Skip to content

feat(agent): add debug logging / enhance chat history handling in com…#15

Merged
Ryanakml merged 2 commits intomainfrom
feature/agent-memory
Mar 19, 2026
Merged

feat(agent): add debug logging / enhance chat history handling in com…#15
Ryanakml merged 2 commits intomainfrom
feature/agent-memory

Conversation

@Ryanakml
Copy link
Copy Markdown
Owner

@Ryanakml Ryanakml commented Mar 19, 2026

…position chain

Summary by CodeRabbit

  • Refactor

    • Restructured error handling and control flow in the composition chain for more consistent fallback behavior.
    • Enhanced chat history integration into message composition with clearer formatting and sensible defaults.
  • Chores

    • Added temporary debug logging for formatted chat history to aid troubleshooting.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 19, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
chat-fuse-dashboard Ready Ready Preview, Comment Mar 19, 2026 2:08pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 19, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ed12b2c0-d98c-4b97-a053-53a9ec83c6ac

📥 Commits

Reviewing files that changed from the base of the PR and between 5ef1837 and c08336a.

📒 Files selected for processing (1)
  • packages/llm/src/langchain/chains/composition.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/llm/src/langchain/chains/composition.ts

📝 Walkthrough

Walkthrough

Restructured composition chain error handling into a single outer try/catch, added chat history formatting to the composition prompt inputs, and added a debug console.log for the formatted chat history in the worker runner.

Changes

Cohort / File(s) Summary
Worker runner debug
apps/worker/src/agent/runner.ts
Added a console.log that prints the stringified formattedHistory for debugging immediately after it's derived from rawHistory.
Composition chain & prompts
packages/llm/src/langchain/chains/composition.ts
Added chatHistory to the prompt template and to chainInput (derived from state.context?.history with type mapping and fallback). Restructured error handling: consolidated outer try/catch and limited inner catch to only handle LLM-specific retry (Gemini) for rate/quota OpenAI errors; other errors are rethrown to the outer fallback. Also switched some defaults to nullish coalescing.

Sequence Diagram(s)

sequenceDiagram
  participant Agent as Agent
  participant Composition as CompositionChain
  participant LLM as OpenAI LLM
  participant Gemini as GeminiFallback

  Agent->>Composition: invoke with AgentState (includes context.history)
  Composition->>Composition: format chatHistory from state.context?.history
  Composition->>LLM: call primary LLM invocation with prompt (includes chatHistory)
  alt LLM rate/quota error
    LLM-->>Composition: error (rate/quota)
    Composition->>Gemini: retry with Gemini model
    Gemini-->>Composition: response
  else success
    LLM-->>Composition: response
  end
  Composition-->>Agent: return composed safe-fallback or LLM response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped through lines of code tonight,
Printed histories glowing bright.
Prompts now carry tales from before,
Errors caught once, then out the door.
A tiny log — a rabbit's delight! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title partially covers the main changes—it mentions debug logging and chat history handling—but is truncated and appears incomplete or vague about the specific enhancements made. Complete the title with specific details about what was enhanced (e.g., 'feat(agent): add debug logging and improve chat history handling in composition chain with message type support').
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/agent-memory
📝 Coding Plan
  • Generate coding plan for human review comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

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 (2)
apps/worker/src/agent/runner.ts (2)

80-81: Remove debug logging before merging or replace with structured logger.

Debug console.log statements with emojis and mixed-language text should not be committed to production code. The comment acknowledges this is for debugging.

Consider either:

  1. Removing before merge
  2. Using a proper logger with configurable log levels (e.g., logger.debug())
♻️ Option 1: Remove debug log
-  // Debug log to verify history formatting - can be removed in production
-  console.log('🔥 [DEBUG] HISTORY DARI DATABASE:', JSON.stringify(formattedHistory, null, 2));
-
   const { processMessage } = await import('@wa-chat/llm');
♻️ Option 2: Use structured logging
-  // Debug log to verify history formatting - can be removed in production
-  console.log('🔥 [DEBUG] HISTORY DARI DATABASE:', JSON.stringify(formattedHistory, null, 2));
+  // Use DEBUG level so this only appears when explicitly enabled
+  logger.debug('Formatted chat history for agent pipeline', { 
+    conversationId: input.conversationId,
+    historyLength: formattedHistory.length 
+  });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/worker/src/agent/runner.ts` around lines 80 - 81, Remove the development
console.log in runner.ts that prints formattedHistory (console.log('🔥 [DEBUG]
HISTORY DARI DATABASE:', JSON.stringify(formattedHistory, null, 2))); either
delete the line or replace it with a structured logger call (e.g., logger.debug)
that respects log levels; locate the statement referencing formattedHistory in
the agent/runner.ts file and switch to the project's logger utility or remove
the debug output prior to merging so no informal console output remains in
production.

75-78: Unsafe type cast is misleading but doesn't cause runtime failures as claimed.

The as unknown as BaseMessage[] cast creates plain objects {role, content} that don't implement the BaseMessage class. However, composition.ts (line 73) re-casts this data back to { role?: string; content?: string }[] and only accesses the role and content properties—it never calls BaseMessage methods. The code works despite the unsafe cast.

That said, the cast is deceptive and bypasses type checking unnecessarily. Using HumanMessage and AIMessage constructors would be clearer and more maintainable:

🔧 Suggested improvement
+import { HumanMessage, AIMessage } from '@langchain/core/messages';
-  const formattedHistory = rawHistory.map((message) => ({
-    role: message.direction === 'inbound' ? 'user' : 'assistant',
-    content: message.body,
-  })) as unknown as BaseMessage[];
+  const formattedHistory: BaseMessage[] = rawHistory.map((message) =>
+    message.direction === 'inbound'
+      ? new HumanMessage(message.body)
+      : new AIMessage(message.body)
+  );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/worker/src/agent/runner.ts` around lines 75 - 78, The current unsafe
cast creating plain objects as BaseMessage[] is misleading; replace the mapping
that creates formattedHistory from rawHistory so it constructs proper message
instances using the HumanMessage and AIMessage constructors (e.g., new
HumanMessage(message.body) or new AIMessage(message.body)) based on
message.direction, remove the "as unknown as BaseMessage[]" cast, and ensure
formattedHistory remains typed as BaseMessage[]; update imports to include
HumanMessage and AIMessage and keep downstream usage (e.g., composition.ts)
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/llm/src/langchain/chains/composition.ts`:
- Around line 121-125: Replace the grammatically incorrect user-facing fallback
message in the safeFallback object (variable safeFallback in composition.ts)
with a correct, clear sentence; update the content string from "System have some
trouble." to a proper phrasing such as "The system is experiencing an issue." or
"The system is having trouble." so end users see a professional message while
keeping the other fields (confidence, escalate_flag) unchanged.
- Around line 73-81: The chat history mapping uses a non-existent msg.role which
causes every message to be labeled "Assistant"; update the logic in the
composition chain where history and formattedChatHistory are computed to read
BaseMessage.type instead of role (map 'human' -> 'User', 'ai' -> 'Assistant',
'system' -> 'System' and default to a safe label), ensure the history variable
is typed as BaseMessage[] (or the appropriate type from
`@langchain/core/messages`) so TypeScript catches misuse, and defensively handle
non-string content values as the existing code does.

---

Nitpick comments:
In `@apps/worker/src/agent/runner.ts`:
- Around line 80-81: Remove the development console.log in runner.ts that prints
formattedHistory (console.log('🔥 [DEBUG] HISTORY DARI DATABASE:',
JSON.stringify(formattedHistory, null, 2))); either delete the line or replace
it with a structured logger call (e.g., logger.debug) that respects log levels;
locate the statement referencing formattedHistory in the agent/runner.ts file
and switch to the project's logger utility or remove the debug output prior to
merging so no informal console output remains in production.
- Around line 75-78: The current unsafe cast creating plain objects as
BaseMessage[] is misleading; replace the mapping that creates formattedHistory
from rawHistory so it constructs proper message instances using the HumanMessage
and AIMessage constructors (e.g., new HumanMessage(message.body) or new
AIMessage(message.body)) based on message.direction, remove the "as unknown as
BaseMessage[]" cast, and ensure formattedHistory remains typed as BaseMessage[];
update imports to include HumanMessage and AIMessage and keep downstream usage
(e.g., composition.ts) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9d163476-4030-4825-a545-a1f5f09f7e54

📥 Commits

Reviewing files that changed from the base of the PR and between 42700b7 and 5ef1837.

📒 Files selected for processing (2)
  • apps/worker/src/agent/runner.ts
  • packages/llm/src/langchain/chains/composition.ts

Comment on lines +121 to +125
const safeFallback = {
content: 'System have some trouble.',
confidence: 0,
escalate_flag: true,
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix grammatical error in user-facing fallback message.

The message "System have some trouble." is grammatically incorrect and will be shown to end users.

✏️ Proposed fix
     const safeFallback = {
-      content: 'System have some trouble.',
+      content: 'The system is experiencing some trouble. Please try again later.',
       confidence: 0,
       escalate_flag: true,
     };
📝 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
const safeFallback = {
content: 'System have some trouble.',
confidence: 0,
escalate_flag: true,
};
const safeFallback = {
content: 'The system is experiencing some trouble. Please try again later.',
confidence: 0,
escalate_flag: true,
};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/llm/src/langchain/chains/composition.ts` around lines 121 - 125,
Replace the grammatically incorrect user-facing fallback message in the
safeFallback object (variable safeFallback in composition.ts) with a correct,
clear sentence; update the content string from "System have some trouble." to a
proper phrasing such as "The system is experiencing an issue." or "The system is
having trouble." so end users see a professional message while keeping the other
fields (confidence, escalate_flag) unchanged.

@Ryanakml Ryanakml merged commit 3b76644 into main Mar 19, 2026
12 checks passed
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