Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(context engine): tool message normalization (#13359)

Rylan Cai5e1738ad4baa
diff --git a/packages/context-engine/src/processors/ToolMessageReorder.ts b/packages/context-engine/src/processors/ToolMessageReorder.ts
index e7b95b6afcd..0b9ca7ea77f 100644
--- a/packages/context-engine/src/processors/ToolMessageReorder.ts
+++ b/packages/context-engine/src/processors/ToolMessageReorder.ts
@@ -15,6 +15,12 @@ declare module '../types' {
const log = debug('context-engine:processor:ToolMessageReorder');
+const DEFAULT_TOOL_FAILURE_CONTENT = JSON.stringify({
+ error: 'Tool call failed',
+ success: false,
+ synthetic: true,
+});
+
/**
* Reorder tool messages to ensure that tool messages are displayed in the correct order.
* see https://github.com/lobehub/lobe-chat/pull/3155
@@ -30,7 +36,9 @@ export class ToolMessageReorder extends BaseProcessor {
const clonedContext = this.cloneContext(context);
// Reorder messages
- const reorderedMessages = this.reorderToolMessages(clonedContext.messages);
+ const { reorderedMessages, removedInvalidTools } = this.reorderToolMessages(
+ clonedContext.messages,
+ );
const originalCount = clonedContext.messages.length;
const reorderedCount = reorderedMessages.length;
@@ -40,14 +48,14 @@ export class ToolMessageReorder extends BaseProcessor {
// Update metadata
clonedContext.metadata.toolMessageReorder = {
originalCount,
- removedInvalidTools: originalCount - reorderedCount,
+ removedInvalidTools,
reorderedCount,
};
- if (originalCount !== reorderedCount) {
+ if (removedInvalidTools > 0) {
log(
'Tool message reordering completed, removed',
- originalCount - reorderedCount,
+ removedInvalidTools,
'invalid tool messages',
);
} else {
@@ -60,63 +68,109 @@ export class ToolMessageReorder extends BaseProcessor {
/**
* Reorder tool messages
*/
- private reorderToolMessages(messages: any[]): any[] {
- // 1. First collect all valid tool_call_ids from assistant messages
+ private reorderToolMessages(messages: any[]): {
+ removedInvalidTools: number;
+ reorderedMessages: any[];
+ } {
+ let removedInvalidTools = 0;
const validToolCallIds = new Set<string>();
- messages.forEach((message) => {
- if (message.role === 'assistant' && message.tool_calls) {
- message.tool_calls.forEach((toolCall: any) => {
- validToolCallIds.add(toolCall.id);
- });
+ const toolMessages = new Map<string, any>();
+
+ // 1. First collect all valid tool_call_ids from assistant messages
+ for (const message of messages) {
+ if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) continue;
+
+ const seenToolCallIds = new Set<string>();
+ for (const toolCall of message.tool_calls) {
+ if (!toolCall?.id) continue;
+
+ if (seenToolCallIds.has(toolCall.id)) continue;
+
+ seenToolCallIds.add(toolCall.id);
+ validToolCallIds.add(toolCall.id);
}
- });
+ }
// 2. Collect all valid tool messages
- const toolMessages: Record<string, any> = {};
- messages.forEach((message) => {
- if (
- message.role === 'tool' &&
- message.tool_call_id &&
- validToolCallIds.has(message.tool_call_id)
- ) {
- toolMessages[message.tool_call_id] = message;
+ for (const message of messages) {
+ if (message.role !== 'tool') continue;
+
+ // Skip invalid tool messages
+ if (!message.tool_call_id || !validToolCallIds.has(message.tool_call_id)) {
+ removedInvalidTools++;
+ continue;
+ }
+
+ if (toolMessages.has(message.tool_call_id)) {
+ // Check if this tool message has already been added
+ removedInvalidTools++;
+ continue;
}
- });
+
+ toolMessages.set(message.tool_call_id, message);
+ }
// 3. Reorder messages
const reorderedMessages: any[] = [];
- messages.forEach((message) => {
- // Skip invalid tool messages
- if (
- message.role === 'tool' &&
- (!message.tool_call_id || !validToolCallIds.has(message.tool_call_id))
- ) {
- log('Skipping invalid tool message:', message.id);
- return;
+
+ for (const [index, message] of messages.entries()) {
+ if (message.role === 'tool') continue;
+
+ if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) {
+ reorderedMessages.push(message);
+ continue;
}
- // Check if this tool message has already been added
- const hasPushed = reorderedMessages.some(
- (m) => !!message.tool_call_id && m.tool_call_id === message.tool_call_id,
- );
+ const seenToolCallIds = new Set<string>();
+ const normalizedToolCalls = [];
+
+ for (const toolCall of message.tool_calls) {
+ if (!toolCall?.id) continue;
+
+ if (seenToolCallIds.has(toolCall.id)) continue;
- if (hasPushed) return;
+ seenToolCallIds.add(toolCall.id);
+ normalizedToolCalls.push(toolCall);
+ }
- reorderedMessages.push(message);
+ reorderedMessages.push(
+ normalizedToolCalls.length === message.tool_calls.length
+ ? message
+ : { ...message, tool_calls: normalizedToolCalls },
+ );
// If assistant message with tool_calls, add corresponding tool messages
- if (message.role === 'assistant' && message.tool_calls) {
- message.tool_calls.forEach((toolCall: any) => {
- const correspondingToolMessage = toolMessages[toolCall.id];
- if (correspondingToolMessage) {
- reorderedMessages.push(correspondingToolMessage);
- delete toolMessages[toolCall.id];
- }
+ for (const toolCall of normalizedToolCalls) {
+ const matchedToolMessage = toolMessages.get(toolCall.id);
+
+ if (matchedToolMessage) {
+ const pluginErrorMessage =
+ typeof matchedToolMessage.pluginError?.message === 'string'
+ ? matchedToolMessage.pluginError.message
+ : undefined;
+
+ reorderedMessages.push({
+ ...matchedToolMessage,
+ content:
+ typeof matchedToolMessage.content === 'string' &&
+ (matchedToolMessage.content.length > 0 || !pluginErrorMessage)
+ ? matchedToolMessage.content
+ : pluginErrorMessage || DEFAULT_TOOL_FAILURE_CONTENT,
+ });
+ toolMessages.delete(toolCall.id);
+ continue;
+ }
+
+ reorderedMessages.push({
+ content: DEFAULT_TOOL_FAILURE_CONTENT,
+ ...(toolCall.function?.name && { name: toolCall.function.name }),
+ role: 'tool',
+ tool_call_id: toolCall.id,
});
}
- });
+ }
- return reorderedMessages;
+ return { reorderedMessages, removedInvalidTools };
}
// Simplified: removed validation/statistics helper methods
diff --git a/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts b/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts
index 19d4753b3f7..a1e03394160 100644
--- a/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts
+++ b/packages/context-engine/src/processors/__tests__/ToolMessageReorder.test.ts
@@ -158,7 +158,7 @@ describe('ToolMessageReorder', () => {
role: 'tool',
tool_call_id: 'tool_call_1',
name: 'test-plugin____testApi',
- content: 'Tool result',
+ content: '',
},
{
role: 'assistant',
@@ -175,12 +175,135 @@ describe('ToolMessageReorder', () => {
const { messages: output } = await proc.process(ctx);
- // Verify reordering logic works and covers line 688 hasPushed check
- // In this test, tool messages are duplicated but the second occurrence is skipped
- expect(output.length).toBe(4); // Original has 3, assistant will add corresponding tool message again
+ expect(output.length).toBe(3);
expect(output[0].role).toBe('system');
- expect(output[1].role).toBe('tool');
- expect(output[2].role).toBe('assistant');
- expect(output[3].role).toBe('tool'); // Tool message added by assistant's tool_calls
+ expect(output[1].role).toBe('assistant');
+ expect(output[2]).toEqual(
+ expect.objectContaining({
+ role: 'tool',
+ content: '',
+ tool_call_id: 'tool_call_1',
+ }),
+ );
+ });
+
+ it('should generate a synthetic tool result when a tool message is missing', async () => {
+ const proc = new ToolMessageReorder();
+ const ctx = createContext([
+ { id: 'u1', role: 'user', content: 'hi' },
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'calling',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'test-plugin____testApi' },
+ id: 'call_missing',
+ type: 'function',
+ },
+ ],
+ },
+ ]);
+
+ const result = await proc.process(ctx);
+
+ expect(result.messages).toEqual([
+ { id: 'u1', role: 'user', content: 'hi' },
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'calling',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'test-plugin____testApi' },
+ id: 'call_missing',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: '{"error":"Tool call failed","success":false,"synthetic":true}',
+ name: 'test-plugin____testApi',
+ role: 'tool',
+ tool_call_id: 'call_missing',
+ },
+ ]);
+ });
+
+ it('should dedupe duplicate tool calls and keep the first real tool result', async () => {
+ const proc = new ToolMessageReorder();
+ const ctx = createContext([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'calling',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' },
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' },
+ { function: { arguments: '{}', name: 'test2' }, id: 'call_2', type: 'function' },
+ ],
+ },
+ { id: 't2', role: 'tool', content: '{"ok":2}', tool_call_id: 'call_2' },
+ { id: 't1-first', role: 'tool', content: '{"ok":1}', tool_call_id: 'call_1' },
+ { id: 't1-second', role: 'tool', content: '{"ok":3}', tool_call_id: 'call_1' },
+ { id: 'orphan', role: 'tool', content: '{"ok":4}', tool_call_id: 'call_3' },
+ ]);
+
+ const result = await proc.process(ctx);
+
+ expect(result.messages).toEqual([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'calling',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' },
+ { function: { arguments: '{}', name: 'test2' }, id: 'call_2', type: 'function' },
+ ],
+ },
+ { id: 't1-first', role: 'tool', content: '{"ok":1}', tool_call_id: 'call_1' },
+ { id: 't2', role: 'tool', content: '{"ok":2}', tool_call_id: 'call_2' },
+ ]);
+ });
+
+ it('should prefer a real error tool result over a synthetic fallback', async () => {
+ const proc = new ToolMessageReorder();
+ const ctx = createContext([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'calling',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' },
+ ],
+ },
+ {
+ id: 't1',
+ role: 'tool',
+ content: '',
+ pluginError: { message: 'Manifest not found for tool: test' },
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await proc.process(ctx);
+
+ expect(result.messages).toEqual([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'calling',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' },
+ ],
+ },
+ {
+ id: 't1',
+ role: 'tool',
+ content: 'Manifest not found for tool: test',
+ pluginError: { message: 'Manifest not found for tool: test' },
+ tool_call_id: 'call_1',
+ },
+ ]);
});
});