Skip to content

Logger sample - #1219

Merged
isamu merged 3 commits into
receptron:mainfrom
isamu:loggerSample
Aug 18, 2025
Merged

isamu merged 3 commits into
receptron:mainfrom
isamu:loggerSample

Conversation

@isamu

@isamu isamu commented Aug 18, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added a simple file-based logger that writes timestamped entries to the system temp directory.
    • Introduced logging examples showcasing callback-based, agent-filter, and custom logger integrations, with a sample runner that prints results.
  • Documentation

    • Updated README with a new “Logger examples” section, including a command to run the samples.
  • Refactor

    • Consolidated a shared graph definition in the tools playground to reduce duplication, with no functional changes.

@coderabbitai

coderabbitai Bot commented Aug 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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

Cohort / File(s) Summary
Docs update
llm_agents/playground/README.md
Adds “Logger examples” section with command to run logger samples; no code changes.
Logging utility
llm_agents/playground/src/loggers/common.ts
New module writing timestamped lines to a temp log file; logs file path on load; basic error handling.
Logger samples
llm_agents/playground/src/loggers/samples.ts
New examples showcasing: callback-based logging, agent-filter logging, and custom GraphAILogger integration; includes a main runner.
Tools refactor
llm_agents/playground/src/tools/run_tools.ts
Hoists shared graph to module scope; main and main2 reuse it; no API 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
Loading
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
Loading
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
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • Play ground #1216 — Also edits llm_agents/playground/src/tools/run_tools.ts, adding flow logic and an exported filter; overlaps in the same area as the graph hoisting.

Poem

I tap my paws, log lines in a row,
Timestamps twinkle, as the workflows flow.
Filters nibble state before and after,
Callbacks squeak with structured chatter.
A file burrows in /tmp to stay—
Carrots for logs, hip-hop hooray! 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts

Also 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 2f5e044 and 7b4086c.

📒 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";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

Suggested change
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.

Comment on lines +3 to +4
import { logger } from "./common";
import util from "util";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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
done

Length 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" || true

Length 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 of util with 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. In llm_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.ts to 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.

Suggested change
import { logger } from "./common";
import util from "util";
import { logger, logFilePath } from "./common";
import * as util from "util";
Suggested change
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.

@isamu
isamu merged commit f36af1a into receptron:main Aug 18, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Sep 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant