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.

🐛 fix(agent-runtime): stop repeated tool call loops (#18965)

Arvin Xuf6e47529f355
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index 39ab3bb016c..5c3b4a43f06 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -61,6 +61,134 @@ const createOutput = (overrides: Partial<LLMAttemptOutput> = {}): LLMAttemptOutp
});
describe('callLlmFinalizer', () => {
+ it('blocks the fifth consecutive identical tool call before it can execute', async () => {
+ const messages = createMessageTransport();
+ const stream = createStreamSink();
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+ state.toolCallRepeatGuard = {
+ counts: {
+ '["credentials","inject","{\\"keys\\":[\\"github\\"],\\"scope\\":\\"repo\\"}"]': 4,
+ },
+ };
+ const output = createOutput({
+ content: '',
+ toolCalls: [
+ {
+ function: {
+ arguments: '{"scope":"repo","keys":["github"]}',
+ name: 'inject',
+ },
+ id: 'call-5',
+ type: 'function',
+ },
+ ],
+ toolsCalling: [
+ {
+ apiName: 'inject',
+ arguments: '{"scope":"repo","keys":["github"]}',
+ id: 'call-5',
+ identifier: 'credentials',
+ type: 'default',
+ },
+ ],
+ });
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-5',
+ events: [],
+ host: createHost(messages, stream),
+ model: 'glm',
+ output,
+ provider: 'lobehub',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(result.nextContext).toMatchObject({
+ payload: {
+ hasToolsCalling: false,
+ result: {
+ content: 'Stopped after the same tool call was requested 5 consecutive times.',
+ tool_calls: [],
+ },
+ toolsCalling: [],
+ },
+ phase: 'llm_result',
+ });
+ expect(result.events).toContainEqual(
+ expect.objectContaining({
+ result: expect.objectContaining({ finishReason: 'tool_call_repeat_limit' }),
+ type: 'llm_result',
+ }),
+ );
+ expect(messages.update).toHaveBeenCalledWith(
+ 'assistant-5',
+ expect.objectContaining({
+ content: 'Stopped after the same tool call was requested 5 consecutive times.',
+ tools: undefined,
+ }),
+ );
+ expect(stream.publishEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ toolsCalling: [] }),
+ type: 'stream_end',
+ }),
+ );
+ });
+
+ it('preserves user cancellation when an aborted stream emits the fifth repeated tool call', async () => {
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+ state.toolCallRepeatGuard = {
+ counts: {
+ '["credentials","inject","{\\"keys\\":[\\"github\\"]}"]': 4,
+ },
+ };
+ const toolCalling = {
+ apiName: 'inject',
+ arguments: '{"keys":["github"]}',
+ id: 'call-5',
+ identifier: 'credentials',
+ type: 'default' as const,
+ };
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-5',
+ events: [],
+ host: createHost(),
+ model: 'glm',
+ output: createOutput({
+ content: '',
+ finishReason: 'abort',
+ toolCalls: [
+ {
+ function: { arguments: toolCalling.arguments, name: toolCalling.apiName },
+ id: toolCalling.id,
+ type: 'function',
+ },
+ ],
+ toolsCalling: [toolCalling],
+ }),
+ provider: 'lobehub',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(result.nextContext).toMatchObject({
+ payload: {
+ hasToolsCalling: true,
+ reason: 'user_cancelled',
+ toolsCalling: [toolCalling],
+ },
+ phase: 'human_abort',
+ });
+ expect(result.events).toContainEqual(
+ expect.objectContaining({
+ result: expect.objectContaining({ finishReason: 'abort' }),
+ type: 'llm_result',
+ }),
+ );
+ });
+
it('persists, builds replay-safe state and usage, and preserves finalization order', async () => {
const messages = createMessageTransport();
const stream = createStreamSink();
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index 822cf234cff..beb2dff9ba9 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -17,6 +17,11 @@ import type {
GeneralAgentCallLLMResultPayload,
InstructionExecutionResult,
} from '../types';
+import {
+ hasRepeatedToolCall,
+ TOOL_CALL_REPEAT_LIMIT,
+ updateToolCallRepeatGuard,
+} from '../utils/toolCallRepeatGuard';
export const VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY =
'visibleOutputEndPublishedStepIndex';
@@ -212,13 +217,16 @@ const buildFinalState = ({
shouldReplayAssistantReasoning,
state,
stepLabel,
+ toolCallRepeatGuard,
visibleOutputEndPublishedStepIndex,
finalReasoning,
}: Omit<FinalizeCallLlmTurnInput, 'events' | 'host' | 'recordResult'> & {
finalReasoning?: ModelReasoning;
+ toolCallRepeatGuard: NonNullable<AgentState['toolCallRepeatGuard']>;
visibleOutputEndPublishedStepIndex?: number;
}): AgentState => {
const newState = structuredClone(state);
+ newState.toolCallRepeatGuard = toolCallRepeatGuard;
newState.messages.push({
content: output.content,
id: assistantMessageId,
@@ -268,27 +276,41 @@ export const finalizeCallLlmTurn = async ({
stepLabel,
}: FinalizeCallLlmTurnInput): Promise<InstructionExecutionResult> => {
const { operation, transports } = host;
+ const toolCallRepeatGuard = updateToolCallRepeatGuard(
+ state.toolCallRepeatGuard,
+ output.toolsCalling,
+ );
+ const finalizedOutput =
+ output.finishReason !== 'abort' && hasRepeatedToolCall(toolCallRepeatGuard)
+ ? {
+ ...output,
+ content: `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`,
+ finishReason: 'tool_call_repeat_limit',
+ toolCalls: [],
+ toolsCalling: [],
+ }
+ : output;
events.push({
result: {
- content: output.content,
- finishReason: output.finishReason,
- reasoning: output.thinkingContent,
- tool_calls: output.toolCalls,
- usage: output.usage,
+ content: finalizedOutput.content,
+ finishReason: finalizedOutput.finishReason,
+ reasoning: finalizedOutput.thinkingContent,
+ tool_calls: finalizedOutput.toolCalls,
+ usage: finalizedOutput.usage,
},
type: 'llm_result',
});
await transports.stream.publishEvent({
data: {
- finalContent: output.content,
- grounding: output.grounding,
+ finalContent: finalizedOutput.content,
+ grounding: finalizedOutput.grounding,
...(stepLabel && { stepLabel }),
- imageList: output.imageList.length > 0 ? output.imageList : undefined,
- reasoning: output.thinkingContent || undefined,
- toolsCalling: output.toolsCalling,
- usage: output.usage,
+ imageList: finalizedOutput.imageList.length > 0 ? finalizedOutput.imageList : undefined,
+ reasoning: finalizedOutput.thinkingContent || undefined,
+ toolsCalling: finalizedOutput.toolsCalling,
+ usage: finalizedOutput.usage,
},
stepIndex: operation.stepIndex,
type: 'stream_end',
@@ -299,9 +321,9 @@ export const finalizeCallLlmTurn = async ({
operation.allowEarlyFinalAnswerVisibleOutputEnd ?? true;
if (
canPublishEarlyFinalAnswerVisibleEnd &&
- output.finishReason !== 'abort' &&
- output.toolsCalling.length === 0 &&
- output.toolCalls.length === 0
+ finalizedOutput.finishReason !== 'abort' &&
+ finalizedOutput.toolsCalling.length === 0 &&
+ finalizedOutput.toolCalls.length === 0
) {
try {
await transports.stream.publishEvent({
@@ -315,32 +337,38 @@ export const finalizeCallLlmTurn = async ({
}
}
- const finalReasoning = await persistFinalMessage({ assistantMessageId, host, output, state });
+ const finalReasoning = await persistFinalMessage({
+ assistantMessageId,
+ host,
+ output: finalizedOutput,
+ state,
+ });
const newState = buildFinalState({
assistantMessageId,
finalReasoning,
model,
- output,
+ output: finalizedOutput,
provider,
shouldReplayAssistantReasoning,
state,
stepLabel,
+ toolCallRepeatGuard,
visibleOutputEndPublishedStepIndex,
});
- await recordResult?.(output);
+ await recordResult?.(finalizedOutput);
- if (output.finishReason === 'abort') {
+ if (finalizedOutput.finishReason === 'abort') {
return {
events,
newState,
nextContext: {
payload: {
- hasToolsCalling: output.toolsCalling.length > 0,
+ hasToolsCalling: finalizedOutput.toolsCalling.length > 0,
parentMessageId: assistantMessageId,
reason: 'user_cancelled',
- result: { content: output.content, tool_calls: output.toolCalls },
- toolsCalling: output.toolsCalling,
+ result: { content: finalizedOutput.content, tool_calls: finalizedOutput.toolCalls },
+ toolsCalling: finalizedOutput.toolsCalling,
},
phase: 'human_abort',
session: {
@@ -350,7 +378,7 @@ export const finalizeCallLlmTurn = async ({
status: 'running',
stepCount: state.stepCount + 1,
},
- stepUsage: output.usage,
+ stepUsage: finalizedOutput.usage,
},
};
}
@@ -360,10 +388,10 @@ export const finalizeCallLlmTurn = async ({
newState,
nextContext: {
payload: {
- hasToolsCalling: output.toolsCalling.length > 0,
+ hasToolsCalling: finalizedOutput.toolsCalling.length > 0,
parentMessageId: assistantMessageId,
- result: { content: output.content, tool_calls: output.toolCalls },
- toolsCalling: output.toolsCalling,
+ result: { content: finalizedOutput.content, tool_calls: finalizedOutput.toolCalls },
+ toolsCalling: finalizedOutput.toolsCalling,
} as GeneralAgentCallLLMResultPayload,
phase: 'llm_result',
session: {
@@ -373,7 +401,7 @@ export const finalizeCallLlmTurn = async ({
status: 'running',
stepCount: state.stepCount + 1,
},
- stepUsage: output.usage,
+ stepUsage: finalizedOutput.usage,
},
};
};
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index db097e63715..4c01ff8fe2f 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -163,6 +163,14 @@ export interface AgentState {
stepCount: number;
systemRole?: string;
+ /**
+ * Consecutive LLM turns that emitted the same normalized tool calls.
+ * Only signatures present in the latest tool-calling turn are retained.
+ */
+ toolCallRepeatGuard?: {
+ counts: Record<string, number>;
+ };
+
/** Tool executor map for routing tool execution between server and client */
toolExecutorMap?: Record<string, ToolExecutor>;
diff --git a/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts b/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
new file mode 100644
index 00000000000..d339d6f355d
--- /dev/null
+++ b/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
@@ -0,0 +1,40 @@
+import type { ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { hasRepeatedToolCall, updateToolCallRepeatGuard } from './toolCallRepeatGuard';
+
+const createToolCall = (argumentsValue: string): ChatToolPayload => ({
+ apiName: 'inject',
+ arguments: argumentsValue,
+ id: 'call-1',
+ identifier: 'credentials',
+ type: 'default',
+});
+
+describe('toolCallRepeatGuard', () => {
+ it('allows four consecutive calls and blocks the fifth with canonically equivalent arguments', () => {
+ let guard: ReturnType<typeof updateToolCallRepeatGuard> | undefined;
+
+ for (let index = 0; index < 4; index++) {
+ guard = updateToolCallRepeatGuard(guard, [
+ createToolCall('{"keys":["github"],"scope":"repo"}'),
+ ]);
+ expect(hasRepeatedToolCall(guard)).toBe(false);
+ }
+
+ guard = updateToolCallRepeatGuard(guard, [
+ createToolCall('{"scope":"repo","keys":["github"]}'),
+ ]);
+ expect(hasRepeatedToolCall(guard)).toBe(true);
+ });
+
+ it('resets the consecutive count when a call is absent from the next LLM turn', () => {
+ const repeatedGuard = updateToolCallRepeatGuard({ counts: { previous: 4 } }, [
+ createToolCall('{}'),
+ ]);
+ const resetGuard = updateToolCallRepeatGuard(repeatedGuard, []);
+
+ expect(resetGuard).toEqual({ counts: {} });
+ expect(hasRepeatedToolCall(resetGuard)).toBe(false);
+ });
+});
diff --git a/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts b/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
new file mode 100644
index 00000000000..18c901aaebf
--- /dev/null
+++ b/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
@@ -0,0 +1,53 @@
+import type { ChatToolPayload } from '@lobechat/types';
+
+import type { AgentState } from '../types';
+
+export const TOOL_CALL_REPEAT_LIMIT = 5;
+
+const canonicalize = (value: unknown): unknown => {
+ if (Array.isArray(value)) return value.map(canonicalize);
+
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, nestedValue]) => [key, canonicalize(nestedValue)]),
+ );
+ }
+
+ return value;
+};
+
+const normalizeArguments = (argumentsValue: string) => {
+ try {
+ return JSON.stringify(canonicalize(JSON.parse(argumentsValue)));
+ } catch {
+ return argumentsValue.trim();
+ }
+};
+
+const getToolCallSignature = ({
+ apiName,
+ arguments: argumentsValue,
+ identifier,
+}: ChatToolPayload) => JSON.stringify([identifier, apiName, normalizeArguments(argumentsValue)]);
+
+export const updateToolCallRepeatGuard = (
+ previousGuard: AgentState['toolCallRepeatGuard'],
+ toolsCalling: ChatToolPayload[],
+) => {
+ if (toolsCalling.length === 0) return { counts: {} };
+
+ const previousCounts = previousGuard?.counts ?? {};
+ const counts: Record<string, number> = {};
+
+ for (const toolCalling of toolsCalling) {
+ const signature = getToolCallSignature(toolCalling);
+ counts[signature] = (previousCounts[signature] ?? 0) + 1;
+ }
+
+ return { counts };
+};
+
+export const hasRepeatedToolCall = (guard: AgentState['toolCallRepeatGuard']) =>
+ Object.values(guard?.counts ?? {}).some((count) => count >= TOOL_CALL_REPEAT_LIMIT);