Skip to content

fix(memory): preserve tool calls and results in chat memory - #703

Merged
haiphucnguyen merged 3 commits into
mainfrom
feature/fix-lost-tool-tracking-in-messages
Sep 6, 2026
Merged

haiphucnguyen merged 3 commits into
mainfrom
feature/fix-lost-tool-tracking-in-messages

Conversation

@haiphucnguyen

Copy link
Copy Markdown
Collaborator
  • Retain tool execution requests and results when converting messages
  • Keep paired tool calls and results together during truncation
  • Include tool result content in token budget calculations
  • Add coverage for memory serialization and message transformation behavior

- Retain tool execution requests and results when converting messages
- Keep paired tool calls and results together during truncation
- Include tool result content in token budget calculations
- Add coverage for memory serialization and message transformation behavior
Copilot AI lite review requested due to automatic review settings September 6, 2026 20:01

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Tool result reconstruction can produce invalid/unsafe ToolExecutionResultMessage instances when legacy persisted records lack toolCallId/toolName, which can break session reloads or cause provider request failures.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR updates Askimo’s chat request transformation + session memory serialization to correctly preserve tool call (tool_use) metadata and tool results (tool_result) across deduplication, persistence, and token-budget truncation—preventing provider-side rejections caused by orphaned tool ids.

Changes:

  • Prevent tool result messages from being dropped incorrectly during deduplication and ensure tool call/result sequences are kept atomic during truncation.
  • Persist/restore assistant tool execution requests and tool result id/toolName through MemoryMessage serialization.
  • Improve token estimation for memory management by including tool result text content, and add regression tests for tool call/result round-trips and truncation behavior.
File summaries
File Description
shared/src/main/kotlin/io/askimo/core/providers/ChatRequestTransformers.kt Updates dedup + token-budget truncation to respect tool call/result pairing.
shared/src/main/kotlin/io/askimo/core/memory/TokenAwareSummarizingMemory.kt Keeps tool-related messages during reload and counts tool result text in token estimation.
shared/src/main/kotlin/io/askimo/core/memory/MemoryMessage.kt Adds serialized tool-call metadata and reconstructs LangChain4j messages accordingly.
cli/src/test/kotlin/io/askimo/core/providers/ChatRequestTransformersTest.kt Adds coverage for dedup + truncation invariants around tool calls/results.
cli/src/test/kotlin/io/askimo/core/memory/MemoryMessageTest.kt Adds round-trip tests ensuring tool ids/toolName survive persistence/JSON serialization.
Review details
  • Files reviewed: 5/5 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +118 to +122
MessageRole.TOOL_EXECUTION_RESULT_MESSAGE.value ->
ToolExecutionResultMessage.builder().text(this.content).build()
ToolExecutionResultMessage.from(
this.toolCallId,
this.toolName ?: "",
this.content,
Comment on lines +117 to +121
val deduplicatedNonSystem = nonSystemMessages.fold(mutableListOf<ChatMessage>()) { acc, msg ->
val lastSameType = acc.lastOrNull { it.type() == msg.type() }
if (lastSameType != null && getMessageText(lastSameType) == getMessageText(msg)) {
log.debug("Dropping consecutive duplicate {} message: {}", msg.type(), getMessageText(msg).take(100))
acc
} else {
if (msg is ToolExecutionResultMessage) {
acc.also { it.add(msg) }
} else {
val lastSameType = acc.lastOrNull { it.type() == msg.type() }

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

There are remaining edge cases where orphan/invalid tool_result messages can still be produced (e.g., leading tool_result grouping and reconstructing tool results with blank toolName), which can trigger provider request rejection.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

shared/src/main/kotlin/io/askimo/core/providers/ChatRequestTransformers.kt:291

  • groupIntoToolCallUnits() can leave a leading ToolExecutionResultMessage as its own group (when groups.isEmpty()), which allows truncation to keep an orphan tool_result without its preceding tool_use. That contradicts the function’s guarantee and can still produce provider-rejected requests.
  • Files reviewed: 5/5 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment on lines 127 to +136
MessageRole.TOOL_EXECUTION_RESULT_MESSAGE.value ->
ToolExecutionResultMessage.builder().text(this.content).build()
if (this.toolCallId.isNullOrBlank()) {
null
} else {
ToolExecutionResultMessage.from(
this.toolCallId,
this.toolName ?: "",
this.content,
)
}

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Token-budget estimation still substantially undercounts tool_use payload size (tool name/arguments), which can undermine the new truncation guarantees in tool-heavy conversations.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

shared/src/main/kotlin/io/askimo/core/providers/ChatRequestTransformers.kt:264

  • Token budgeting/dedup uses getMessageText(), but for AiMessage tool-use messages it currently appends only tool-call ids. The actual request payload also includes tool name + arguments; omitting those can drastically undercount tokens for tool-heavy turns (especially when AiMessage.text is blank), making enforceTokenBudget() much less reliable and increasing the chance of provider context-length errors.
  • Files reviewed: 6/6 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@haiphucnguyen
haiphucnguyen merged commit 4219ddf into main Sep 6, 2026
11 checks passed
@haiphucnguyen
haiphucnguyen deleted the feature/fix-lost-tool-tracking-in-messages branch September 6, 2026 22:44
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.

2 participants