Repository navigation
Logger sample - #1219
Logger sample#1219
Conversation
WalkthroughAdds logger documentation, introduces a common file-based logger, provides three logging examples (callback, agent filter, custom logger) for GraphAI, and hoists a graph definition in tools to module scope without logic changes. Changes
Sequence Diagram(s)sequenceDiagram
participant Dev
participant GraphAI
participant Logger as Callback Logger
Dev->>GraphAI: run(graph, { onLog: callback })
GraphAI-->>Logger: emit(TransactionLog)
Logger-->>Logger: write via common.logger()
GraphAI-->>Dev: result
sequenceDiagram
participant Dev
participant GraphAI
participant Filter as AgentFilter
Dev->>GraphAI: run(graph, { agentFilters:[Filter] })
Filter->>GraphAI: next(context)
GraphAI-->>Filter: state/response
Filter-->>Filter: log before/after via common.logger()
GraphAI-->>Dev: result
sequenceDiagram
participant Dev
participant GraphAI
participant GALogger as GraphAILogger
participant FileLog as common.logger
Dev->>GALogger: setLogger(consoleAndFileLogger)
Dev->>GraphAI: run(graph)
GraphAI-->>GALogger: emit(log events)
GALogger-->>FileLog: append structured line
GraphAI-->>Dev: result
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (9)
llm_agents/playground/src/tools/run_tools.ts (1)
25-49: Avoid shared-mutable state: reuse of a single graph object across runs can cause subtle bugs.If GraphAI mutates the provided graph object (e.g., normalizing nodes, caching state), reusing the same object across multiple GraphAI instances or runs may leak state between executions. Prefer creating a fresh graph per run or cloning before passing to GraphAI.
Two concrete options:
Option A (factory function, safest): replace the constant graph with a builder and use it when constructing GraphAI.
-const graph = { - version: 0.5, - nodes: { - messages: { - value: [], - }, - text: { - value: "", - }, - llmAgent: {}, - llmModel: {}, - tools: { - isResult: true, - agent: "toolsAgent", - inputs: { - messages: ":messages", - userInput: { text: ":text" }, - tools, - llmAgent: ":llmAgent", - llmModel: ":llmModel", - stream: true, - }, - }, - }, -}; +const buildGraph = () => ({ + version: 0.5, + nodes: { + messages: { value: [] }, + text: { value: "" }, + llmAgent: {}, + llmModel: {}, + tools: { + isResult: true, + agent: "toolsAgent", + inputs: { + messages: ":messages", + userInput: { text: ":text" }, + tools, + llmAgent: ":llmAgent", + llmModel: ":llmModel", + stream: true, + }, + }, + }, +});Outside this hunk, update usages:
- const graphai = new GraphAI(buildGraph(), aagents, { agentFilters });
- const graphai2 = new GraphAI(buildGraph(), aagents, { agentFilters });
Option B (minimal change): clone on use (Node 18+)
- const graphai = new GraphAI(structuredClone(graph), aagents, { agentFilters });
- const graphai2 = new GraphAI(structuredClone(graph), aagents, { agentFilters });
llm_agents/playground/src/loggers/common.ts (2)
5-7: Remove module-load side effect; export the log path instead.Printing the log file path during import is noisy and surprises consumers. Export the path and let callers print it explicitly.
Apply:
const logFile = path.join(os.tmpdir(), "graphai_tmp.log"); -console.log(logFile); +export const logFilePath = logFile;
8-15: Synchronous file I/O can block under heavier logging.appendFileSync is okay for a sample, but will block the event loop if logs are frequent. Consider appendFile (async) or a shared WriteStream if this moves beyond samples or becomes high volume.
I can provide a non-blocking WriteStream-based logger with backpressure handling on request.
llm_agents/playground/README.md (1)
4-6: Add language to fenced code blocks (markdownlint MD040).Specify a language for both code blocks to satisfy lint and improve syntax highlighting.
Apply:
-``` +```bash node --require ts-node/register src/tools/run_tools.ts-
+bash
node --require ts-node/register src/loggers/samples.tsAlso applies to: 9-11
llm_agents/playground/src/loggers/samples.ts (5)
23-26: Mind the volume and sensitivity of callback logs.TransactionLog may include full inputs/outputs, prompts, and intermediate state. Ensure no secrets or PII are included if these samples are run against real data; consider redaction when needed.
I can help add a redaction helper (e.g., masking API keys and emails) if useful.
64-71: Avoid double newlines in custom logger payload.logger() already appends a newline. Dropping the extra "\n" keeps logs single-line per record.
Apply:
- const log = `[${level.toUpperCase()}] ` + util.format(...args) + "\n"; + const log = `[${level.toUpperCase()}] ${util.format(...args)}`; logger(JSON.stringify({ states: "customLogger", log }));
73-74: Global logger side effect; consider restoring previous logger.GraphAILogger.setLogger() affects global logging for the library in the current process. For sample isolation, capture the previous logger (if API allows) and restore it after the example finishes.
If GraphAILogger exposes getLogger() or setLogger returns the previous handler, wrap the demo with try/finally to restore the original logger.
75-89: Validate the agent choice or handle errors.If "pushAgent" is unavailable or misconfigured, customLoggerExample will throw and terminate the sample sequence. Wrap the run in try/catch to demonstrate error logging via your custom logger without aborting other examples.
Apply:
const graphai = new GraphAI(graphInvalid, agents); - - const res = (await graphai.run(true)) as any; - - console.log(JSON.stringify(res, null, 2)); + try { + const res = (await graphai.run(true)) as any; + console.log(JSON.stringify(res, null, 2)); + } catch (err) { + console.error("customLoggerExample failed:", err); + }
97-103: Surface the log file path explicitly in the sample output.With the side-effect removed from common.ts, print the log file path when running the samples.
Apply:
-const main = async () => { +const main = async () => { + console.log(`[graphai] writing logs to: ${logFilePath}`); await callbackLogExample(); await agentFilterLogExample(); await customLoggerExample(); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
llm_agents/playground/README.md(1 hunks)llm_agents/playground/src/loggers/common.ts(1 hunks)llm_agents/playground/src/loggers/samples.ts(1 hunks)llm_agents/playground/src/tools/run_tools.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
llm_agents/playground/src/loggers/common.ts (1)
packages/test_utils/lib/test_runner.js (1)
fs(46-46)
llm_agents/playground/src/loggers/samples.ts (2)
llm_agents/playground/src/loggers/common.ts (1)
logger(8-15)llm_agents/playground/src/tools/run_tools.ts (1)
main(51-80)
🪛 markdownlint-cli2 (0.17.2)
llm_agents/playground/README.md
4-4: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
9-9: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (1)
llm_agents/playground/src/tools/run_tools.ts (1)
25-49: Good refactor: hoisting the graph improves reuse and readability.Centralizing the graph at module scope removes duplication across main and main2. Nice cleanup.
| @@ -0,0 +1,15 @@ | |||
| import fs from "fs"; | |||
There was a problem hiding this comment.
Fix Node built-in import style to avoid runtime breakage.
Default-importing "fs" can fail unless esModuleInterop/synthetic default imports are enabled. Use namespace import for built-ins.
Apply:
-import fs from "fs";
+import * as fs from "fs";📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import fs from "fs"; | |
| import * as fs from "fs"; |
🤖 Prompt for AI Agents
In llm_agents/playground/src/loggers/common.ts around line 1, the file currently
uses a default import for the Node built-in fs which can fail at runtime unless
esModuleInterop or synthetic default imports are enabled; change the import to a
namespace import (import * as fs from "fs") to ensure compatibility with Node's
CommonJS built-ins and update any local references if needed to continue using
fs.* APIs.
| import { logger } from "./common"; | ||
| import util from "util"; |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Fix Node built-in imports to avoid runtime issues.
Default-importing "util" (and only importing logger without the path) may work only with esModuleInterop; use namespace import for util. Also import the exported log path to print it explicitly.
Apply:
-import { logger } from "./common";
-import util from "util";
+import { logger, logFilePath } from "./common";
+import * as util from "util";Optional verification (checks tsconfig flags used by ts-node):
🏁 Script executed:
#!/bin/bash
# Inspect tsconfig files for esModuleInterop/synthetic default imports
fd -a '^tsconfig.*\.json$' | while read -r f; do
echo "== $f =="
jq -r '.compilerOptions.esModuleInterop, .compilerOptions.allowSyntheticDefaultImports' "$f" 2>/dev/null
doneLength of output: 10350
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate and inspect exports in common.ts
common_file="llm_agents/playground/src/loggers/common.ts"
echo "== Contents of $common_file exports =="
rg -nP '^export ' "$common_file" || echo "No exports found."
echo
echo "== Occurrences of logFilePath in $common_file =="
rg -nP 'logFilePath' -n "$common_file" || echo "logFilePath not found."Length of output: 637
🏁 Script executed:
#!/bin/bash
# Display the contents of common.ts to verify exports and log path definitions
common_file="llm_agents/playground/src/loggers/common.ts"
echo "== $common_file =="
sed -n '1,200p' "$common_file" || trueLength of output: 601
Fix Node built‐in import and expose log file path
tsconfig doesn’t enable esModuleInterop or synthetic default imports, so:
-
In
llm_agents/playground/src/loggers/samples.ts, replace the default import ofutilwith a namespace import:// samples.ts -import util from "util"; +import * as util from "util";
-
If you want to print the log file path externally, you must first export it from
common.ts. Inllm_agents/playground/src/loggers/common.ts, add:const logFile = path.join(os.tmpdir(), "graphai_tmp.log"); +export const logFilePath = logFile; console.log(logFile); -
Then update your imports in
samples.tsto include the new export:// samples.ts -import { logger } from "./common"; +import { logger, logFilePath } from "./common";
These changes will prevent runtime/compile‐time errors and allow you to log the path explicitly.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import { logger } from "./common"; | |
| import util from "util"; | |
| import { logger, logFilePath } from "./common"; | |
| import * as util from "util"; |
| import { logger } from "./common"; | |
| import util from "util"; | |
| const logFile = path.join(os.tmpdir(), "graphai_tmp.log"); | |
| export const logFilePath = logFile; | |
| console.log(logFile); |
🤖 Prompt for AI Agents
In llm_agents/playground/src/loggers/samples.ts around lines 3–4, the file
incorrectly uses a default import for Node's util and doesn't access the log
file path; replace the default import with a namespace import (import * as util
from "util") to match tsconfig without esModuleInterop, export the log file path
from llm_agents/playground/src/loggers/common.ts (e.g., export the existing
path/variable as a named export), and then update samples.ts to import that
named export (import { logger, logFilePath } from "./common") so you can log or
expose the path explicitly.
Summary by CodeRabbit
New Features
Documentation
Refactor