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): bound memory searches per operation so a rephrasing loop stops (#23758)

AmAzing-a52ae3ab50eb
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index 01c81f8fc00..d9cd3ae07ef 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -39,6 +39,7 @@ import {
} from '../utils/operationToolSet';
import { selectSecurityBlacklist, selectUserInterventionConfig } from '../utils/stateSlots';
import { shouldCompress } from '../utils/tokenCounter';
+import { buildToolCallBudgetContent, TOOL_CALL_BUDGET_REASON } from '../utils/toolCallRepeatGuard';
import {
findCurrentTurnPendingToolMessages,
isFoldedAssistantGroup,
@@ -673,7 +674,7 @@ export class GeneralChatAgent implements Agent {
case 'llm_result': {
// LLM response received, check if it contains tool calls
- const { hasToolsCalling, toolsCalling, parentMessageId, result } =
+ const { hasToolsCalling, overBudgetToolCalls, toolsCalling, parentMessageId, result } =
context.payload as GeneralAgentCallLLMResultPayload;
if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {
@@ -705,9 +706,40 @@ export class GeneralChatAgent implements Agent {
} satisfies AgentInstruction);
}
- if (executableCalls.length === 0) return instructions;
+ // Calls past their API's `maxCallsPerOperation` get a rejected row
+ // that tells the model to answer with what it has; the rest of the
+ // batch still runs. The finalizer counted the turn and stops the run
+ // if the model keeps asking anyway (see `updateToolCallBudget`).
+ const budgetLimitByCallId = new Map(
+ (overBudgetToolCalls ?? []).map(({ id, limit }) => [id, limit]),
+ );
+ const overBudgetCalls = executableCalls.filter((call) =>
+ budgetLimitByCallId.has(call.id),
+ );
+ const withinBudgetCalls = executableCalls.filter(
+ (call) => !budgetLimitByCallId.has(call.id),
+ );
+
+ if (overBudgetCalls.length > 0) {
+ instructions.push({
+ payload: {
+ blockedContentByCallId: Object.fromEntries(
+ overBudgetCalls.map((call) => [
+ call.id,
+ buildToolCallBudgetContent(call, budgetLimitByCallId.get(call.id)!),
+ ]),
+ ),
+ blockedReason: TOOL_CALL_BUDGET_REASON,
+ parentMessageId,
+ toolsCalling: overBudgetCalls,
+ },
+ type: 'resolve_blocked_tools',
+ } satisfies AgentInstruction);
+ }
+
+ if (withinBudgetCalls.length === 0) return instructions;
- const { allowedTools, blockedTools } = this.partitionToolsByAllowList(executableCalls);
+ const { allowedTools, blockedTools } = this.partitionToolsByAllowList(withinBudgetCalls);
// Check which tools need human intervention
const [toolsNeedingIntervention, toolsToExecute] = await this.checkInterventionNeeded(
allowedTools,
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.toolCallBudget.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.toolCallBudget.test.ts
new file mode 100644
index 00000000000..68289e1ea15
--- /dev/null
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.toolCallBudget.test.ts
@@ -0,0 +1,263 @@
+import type { ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AgentRuntime } from '../../core/runtime';
+import { finalizeCallLlmTurn } from '../../executors/callLlmFinalizer';
+import type { AgentRuntimeHost, LLMAttemptOutput } from '../../transport';
+import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../../types';
+import {
+ buildToolCallBudgetContent,
+ TOOL_CALL_BUDGET_FEEDBACK_LIMIT,
+ TOOL_CALL_BUDGET_REASON,
+} from '../../utils/toolCallRepeatGuard';
+import { GeneralChatAgent } from '../GeneralChatAgent';
+
+/**
+ * Scenario tests for `maxCallsPerOperation`: a budgeted API called past its
+ * budget is answered with a rejected tool row instead of being dispatched, and
+ * a model that keeps asking is stopped. Pure-helper unit tests live beside the
+ * module in `utils/toolCallRepeatGuard.test.ts`.
+ */
+describe('GeneralChatAgent tool call budget (llm_result phase)', () => {
+ const BUDGET = 20;
+
+ const toolManifestMap = {
+ 'lobe-local-system': {
+ api: [{ name: 'readFile', parameters: { properties: {}, type: 'object' } }],
+ identifier: 'lobe-local-system',
+ },
+ 'lobe-user-memory': {
+ api: [
+ {
+ maxCallsPerOperation: BUDGET,
+ name: 'searchUserMemory',
+ parameters: { properties: {}, type: 'object' },
+ },
+ ],
+ identifier: 'lobe-user-memory',
+ },
+ };
+
+ const createAgent = () =>
+ new GeneralChatAgent({
+ agentConfig: { maxSteps: 1000 },
+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },
+ operationId: 'operation-1',
+ });
+
+ const createState = () =>
+ AgentRuntime.createInitialState({
+ operationId: 'operation-1',
+ status: 'running',
+ toolManifestMap,
+ // Auto-run keeps the scenario on dispatch vs. rejection; approval is a
+ // separate branch with its own tests.
+ userInterventionConfig: { approvalMode: 'auto-run' },
+ });
+
+ const createHost = (): AgentRuntimeHost => ({
+ operation: { operationId: 'operation-1', stepIndex: 0 },
+ transports: {
+ messages: {
+ createAssistantMessage: vi.fn(),
+ createToolMessage: vi.fn(),
+ deleteMessage: vi.fn(),
+ findById: vi.fn(),
+ findToolMessageIdByToolCallId: vi.fn(),
+ getToolMessage: vi.fn(),
+ query: vi.fn(),
+ update: vi.fn().mockResolvedValue(undefined),
+ updatePluginState: vi.fn(),
+ updateToolIntervention: vi.fn(),
+ updateToolMessage: vi.fn(),
+ },
+ stream: {
+ publishChunk: vi.fn(),
+ publishError: vi.fn(),
+ publishEvent: vi.fn().mockResolvedValue(undefined),
+ },
+ },
+ });
+
+ const searchCall = (index: number): ChatToolPayload => ({
+ apiName: 'searchUserMemory',
+ // A new query every call: the argument-keyed repeat guard never sees a repeat.
+ arguments: JSON.stringify({ queries: [`rephrased question ${index}`] }),
+ id: `search-${index}`,
+ identifier: 'lobe-user-memory',
+ type: 'builtin',
+ });
+
+ const readFileCall = (index: number): ChatToolPayload => ({
+ apiName: 'readFile',
+ arguments: JSON.stringify({ path: `/repo/file-${index}.ts` }),
+ id: `read-${index}`,
+ identifier: 'lobe-local-system',
+ type: 'builtin',
+ });
+
+ /** One LLM turn that asks for `toolsCalling` and writes no text. */
+ const runTurn = async (state: AgentState, toolsCalling: ChatToolPayload[], turn: number) => {
+ const output: LLMAttemptOutput = {
+ answerSalvagedFromReasoning: false,
+ content: '',
+ contentParts: [],
+ grounding: null,
+ hasContentImages: false,
+ hasReasoningImages: false,
+ imageList: [],
+ reasoningParts: [],
+ thinkingContent: '',
+ toolCalls: toolsCalling.map((tool) => ({
+ function: { arguments: tool.arguments, name: tool.apiName },
+ id: tool.id,
+ type: 'function' as const,
+ })),
+ toolsCalling,
+ } as LLMAttemptOutput;
+
+ const finalized = await finalizeCallLlmTurn({
+ assistantMessageId: `assistant-${turn}`,
+ events: [],
+ host: createHost(),
+ model: 'gpt-4o-mini',
+ output,
+ provider: 'openai',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+ const instructions = [
+ await createAgent().runner(finalized.nextContext as AgentRuntimeContext, finalized.newState),
+ ].flat() as AgentInstruction[];
+
+ return { finalized, instructions };
+ };
+
+ const dispatchedCalls = (instructions: AgentInstruction[]): ChatToolPayload[] =>
+ instructions.flatMap((instruction) => {
+ if (instruction.type === 'call_tool') return [instruction.payload.toolCalling];
+ if (instruction.type === 'call_tools_batch') return instruction.payload.toolsCalling;
+ return [];
+ });
+
+ const rejectedCalls = (instructions: AgentInstruction[]): ChatToolPayload[] =>
+ instructions.flatMap((instruction) =>
+ instruction.type === 'resolve_blocked_tools' ? instruction.payload.toolsCalling : [],
+ );
+
+ /**
+ * @example
+ * The reported loop: every model response asks for one more memory search
+ * with a rephrased query and never writes an answer. 500 of those ran in one
+ * reply. Now 20 run, the next two are rejected with "answer with what you
+ * have", and the third ignored rejection ends the run.
+ */
+ it('stops a model that searches memory with a new query every turn and never answers', async () => {
+ let state = createState();
+ const dispatched: ChatToolPayload[] = [];
+ const rejected: ChatToolPayload[] = [];
+ let turns = 0;
+ let finished = false;
+
+ // Far above the expected stop, so a missing bound fails the assertions
+ // below instead of hanging the suite.
+ for (let turn = 0; turn < 200 && !finished; turn++) {
+ const { finalized, instructions } = await runTurn(state, [searchCall(turn)], turn);
+ state = finalized.newState;
+ turns += 1;
+ dispatched.push(...dispatchedCalls(instructions));
+ rejected.push(...rejectedCalls(instructions));
+ finished = instructions.some((instruction) => instruction.type === 'finish');
+ }
+
+ expect(finished).toBe(true);
+ expect(dispatched).toHaveLength(BUDGET);
+ expect(rejected).toHaveLength(TOOL_CALL_BUDGET_FEEDBACK_LIMIT);
+ expect(turns).toBe(BUDGET + TOOL_CALL_BUDGET_FEEDBACK_LIMIT + 1);
+ expect(state.toolCallRepeatGuard?.stoppedByRepeatLimit).toBe(true);
+ expect(state.messages.at(-1)).toMatchObject({
+ content: `Stopped after searchUserMemory kept being called past its limit of ${BUDGET} calls.`,
+ role: 'assistant',
+ });
+ });
+
+ it('rejects the call past the budget with guidance to answer, without ending the run', async () => {
+ let state = createState();
+ for (let turn = 0; turn < BUDGET; turn++) {
+ state = (await runTurn(state, [searchCall(turn)], turn)).finalized.newState;
+ }
+
+ const overBudget = searchCall(BUDGET);
+ const { finalized, instructions } = await runTurn(state, [overBudget], BUDGET);
+
+ expect(instructions).toEqual([
+ {
+ payload: {
+ blockedContentByCallId: {
+ [overBudget.id]: buildToolCallBudgetContent(overBudget, BUDGET),
+ },
+ blockedReason: TOOL_CALL_BUDGET_REASON,
+ parentMessageId: `assistant-${BUDGET}`,
+ toolsCalling: [overBudget],
+ },
+ type: 'resolve_blocked_tools',
+ },
+ ]);
+ expect(finalized.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBeUndefined();
+ });
+
+ it('runs the calls that fit the budget and the unbudgeted calls of a turn that overshoots', async () => {
+ const batch = [
+ ...Array.from({ length: BUDGET + 2 }, (_, index) => searchCall(index)),
+ readFileCall(0),
+ ];
+
+ const { instructions } = await runTurn(createState(), batch, 0);
+
+ expect(rejectedCalls(instructions).map((call) => call.id)).toEqual([
+ `search-${BUDGET}`,
+ `search-${BUDGET + 1}`,
+ ]);
+ expect(dispatchedCalls(instructions).map((call) => call.id)).toEqual([
+ ...Array.from({ length: BUDGET }, (_, index) => `search-${index}`),
+ 'read-0',
+ ]);
+ });
+
+ it('keeps the run going when the model moves on after a rejection', async () => {
+ let state = createState();
+ for (let turn = 0; turn < BUDGET; turn++) {
+ state = (await runTurn(state, [searchCall(turn)], turn)).finalized.newState;
+ }
+
+ // Two rejected rounds, a turn on another tool, then two more rejected
+ // rounds: never three in a row, so the run is not stopped.
+ const turns = [
+ [searchCall(100)],
+ [searchCall(101)],
+ [readFileCall(0)],
+ [searchCall(102)],
+ [searchCall(103)],
+ ];
+ for (const [index, toolsCalling] of turns.entries()) {
+ const { finalized, instructions } = await runTurn(state, toolsCalling, BUDGET + index);
+ state = finalized.newState;
+ expect(instructions.some((instruction) => instruction.type === 'finish')).toBe(false);
+ }
+
+ expect(state.toolCallRepeatGuard?.stoppedByRepeatLimit).toBeUndefined();
+ });
+
+ it('never limits an API that declares no budget', async () => {
+ let state = createState();
+
+ for (let turn = 0; turn < BUDGET * 3; turn++) {
+ const call = readFileCall(turn);
+ const { finalized, instructions } = await runTurn(state, [call], turn);
+ state = finalized.newState;
+ expect(dispatchedCalls(instructions)).toEqual([call]);
+ }
+
+ expect(state.toolCallRepeatGuard?.apiCalls).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index 9cd91f9dd50..38a08788b2b 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -19,10 +19,12 @@ import type {
import { serializePartsForStorage } from '../utils/multimodalContent';
import { sanitizeToolCallArguments } from '../utils/sanitizeToolCallArguments';
import {
+ hasIgnoredToolCallBudget,
hasRepeatedToolCall,
hasToolCallBurst,
TOOL_CALL_BURST_LIMIT,
TOOL_CALL_REPEAT_LIMIT,
+ updateToolCallBudget,
updateToolCallRepeatGuard,
} from '../utils/toolCallRepeatGuard';
@@ -342,14 +344,23 @@ export const finalizeCallLlmTurn = async ({
// Same stop for a turn that asks for more calls than the burst limit: the
// calls differ, but nothing legitimate fans out that wide, and dispatching
// them would hit a real service once per call.
+ const burst = hasToolCallBurst(output.toolsCalling);
+ // Calls past an API's `maxCallsPerOperation` are normally answered with a
+ // rejected tool result by the agent (see `overBudgetToolCalls` below), so
+ // the model can still answer. A model that keeps asking after that feedback
+ // gets the same stop as a repeated call.
+ const budget = updateToolCallBudget(state, output.toolsCalling);
+ const budgetIgnored = hasIgnoredToolCallBudget(budget.overBudgetRounds);
const stoppedByRepeatLimit =
- output.finishReason !== 'abort' && (repeated || hasToolCallBurst(output.toolsCalling));
+ output.finishReason !== 'abort' && (repeated || burst || budgetIgnored);
// Carried on the state so the terminal reason can name this stop. Sticky once
// set: later turns emit no tool calls, and `updateToolCallRepeatGuard` resets
// its counts on those, which would otherwise erase the only trace of why the
// run ended.
const toolCallRepeatGuard = {
...repeatCounts,
+ ...(Object.keys(budget.apiCalls).length > 0 && { apiCalls: budget.apiCalls }),
+ ...(budget.overBudgetRounds > 0 && { overBudgetRounds: budget.overBudgetRounds }),
...((stoppedByRepeatLimit || state.toolCallRepeatGuard?.stoppedByRepeatLimit) && {
stoppedByRepeatLimit: true,
}),
@@ -359,7 +370,9 @@ export const finalizeCallLlmTurn = async ({
...output,
content: repeated
? `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`
- : `Stopped after ${output.toolsCalling.length} tool calls were requested in one turn (limit ${TOOL_CALL_BURST_LIMIT}).`,
+ : burst
+ ? `Stopped after ${output.toolsCalling.length} tool calls were requested in one turn (limit ${TOOL_CALL_BURST_LIMIT}).`
+ : `Stopped after ${budget.overBudgetCalls[0].toolCalling.apiName} kept being called past its limit of ${budget.overBudgetCalls[0].limit} calls.`,
finishReason: 'tool_call_repeat_limit',
toolCalls: [],
toolsCalling: [],
@@ -467,6 +480,15 @@ export const finalizeCallLlmTurn = async ({
payload: {
hasToolsCalling: finalizedOutput.toolsCalling.length > 0,
parentMessageId: assistantMessageId,
+ // Only meaningful while the calls are still on the turn: a stop above
+ // already dropped them.
+ ...(!stoppedByRepeatLimit &&
+ budget.overBudgetCalls.length > 0 && {
+ overBudgetToolCalls: budget.overBudgetCalls.map(({ limit, toolCalling }) => ({
+ id: toolCalling.id,
+ limit,
+ })),
+ }),
result: { content: finalizedOutput.content, tool_calls: finalizedOutput.toolCalls },
toolsCalling: finalizedOutput.toolsCalling,
} as GeneralAgentCallLLMResultPayload,
diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.ts
index 56cecc86f2a..91a45186dc6 100644
--- a/packages/agent-runtime/src/types/generalAgent.ts
+++ b/packages/agent-runtime/src/types/generalAgent.ts
@@ -34,6 +34,12 @@ export interface GeneralAgentCallLLMInstructionPayload {
export interface GeneralAgentCallLLMResultPayload {
hasToolsCalling: boolean;
+ /**
+ * The calls in `toolsCalling` that exceed their API's
+ * `maxCallsPerOperation`, with the limit they hit. The agent answers them
+ * with a rejected tool result instead of dispatching them.
+ */
+ overBudgetToolCalls?: Array<{ id: string; limit: number }>;
parentMessageId: string;
result: { content: string; tool_calls: MessageToolCall[] };
toolsCalling: ChatToolPayload[];
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 84c3935aa83..946d21e140b 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -618,7 +618,20 @@ export interface AgentState {
* Only signatures present in the latest tool-calling turn are retained.
*/
toolCallRepeatGuard?: {
+ /**
+ * Calls each budgeted API (`maxCallsPerOperation` on its manifest entry)
+ * was asked for so far in this operation, keyed by tool identity without
+ * arguments. Unlike `counts` it is never reset by a turn that skips the
+ * API: the budget is for the whole operation.
+ */
+ apiCalls?: Record<string, number>;
counts: Record<string, number>;
+ /**
+ * Consecutive LLM turns that asked for a budgeted API past its budget.
+ * Each of those turns got a rejected tool result; the run stops once the
+ * model has ignored that feedback too many turns in a row.
+ */
+ overBudgetRounds?: number;
/**
* Set on the turn the guard cut short. The run still lands in `status:
* 'done'` β€” the turn was finalized without tool calls, which is what
diff --git a/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts b/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
index 494393d16d4..efb0efef609 100644
--- a/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
+++ b/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
@@ -1,11 +1,16 @@
import type { ChatToolPayload } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
+import type { AgentState } from '../types';
import {
+ getToolCallBudget,
+ hasIgnoredToolCallBudget,
hasRepeatedToolCall,
hasToolCallBurst,
+ TOOL_CALL_BUDGET_FEEDBACK_LIMIT,
TOOL_CALL_BURST_LIMIT,
TOOL_CALL_REPEAT_LIMIT,
+ updateToolCallBudget,
updateToolCallRepeatGuard,
} from './toolCallRepeatGuard';
@@ -96,3 +101,108 @@ describe('toolCallRepeatGuard', () => {
).toBe(false);
});
});
+
+describe('tool call budget', () => {
+ const searchCall = (index: number): ChatToolPayload => ({
+ apiName: 'search',
+ arguments: `{"query":"topic ${index}"}`,
+ id: `call-${index}`,
+ identifier: 'memory',
+ type: 'builtin',
+ });
+
+ const createState = (
+ guard?: AgentState['toolCallRepeatGuard'],
+ overrides?: Partial<AgentState>,
+ ): AgentState =>
+ ({
+ toolCallRepeatGuard: guard,
+ toolManifestMap: {
+ files: { api: [{ name: 'read' }], identifier: 'files' },
+ memory: {
+ api: [{ maxCallsPerOperation: 3, name: 'search' }, { name: 'list' }],
+ identifier: 'memory',
+ },
+ },
+ ...overrides,
+ }) as unknown as AgentState;
+
+ it('reads the budget from the API entry and ignores APIs that declare none', () => {
+ const state = createState();
+
+ expect(getToolCallBudget(searchCall(0), state)).toBe(3);
+ expect(getToolCallBudget({ ...searchCall(0), apiName: 'list' }, state)).toBeUndefined();
+ expect(getToolCallBudget({ ...searchCall(0), identifier: 'files' }, state)).toBeUndefined();
+ expect(getToolCallBudget({ ...searchCall(0), identifier: 'unknown' }, state)).toBeUndefined();
+ });
+
+ it('reads the budget of a tool that only exists as a step activation', () => {
+ const state = createState(undefined, {
+ activatedStepTools: [
+ {
+ id: 'web',
+ manifest: { api: [{ maxCallsPerOperation: 5, name: 'search' }], identifier: 'web' },
+ },
+ ],
+ } as unknown as Partial<AgentState>);
+
+ expect(getToolCallBudget({ ...searchCall(0), identifier: 'web' }, state)).toBe(5);
+ });
+
+ it('counts calls with different arguments against one budget across turns', () => {
+ let guard: AgentState['toolCallRepeatGuard'];
+
+ for (let index = 0; index < 3; index++) {
+ const update = updateToolCallBudget(createState(guard), [searchCall(index)]);
+ expect(update.overBudgetCalls).toEqual([]);
+ guard = { apiCalls: update.apiCalls, counts: {} };
+ }
+
+ const update = updateToolCallBudget(createState(guard), [searchCall(3)]);
+ expect(update.overBudgetCalls).toEqual([{ limit: 3, toolCalling: searchCall(3) }]);
+ expect(update.overBudgetRounds).toBe(1);
+ });
+
+ it('keeps the count through a turn that does not call the API', () => {
+ const first = updateToolCallBudget(createState(), [searchCall(0), searchCall(1)]);
+ const idle = updateToolCallBudget(createState({ apiCalls: first.apiCalls, counts: {} }), []);
+ const third = updateToolCallBudget(createState({ apiCalls: idle.apiCalls, counts: {} }), [
+ searchCall(2),
+ searchCall(3),
+ ]);
+
+ expect(third.overBudgetCalls.map(({ toolCalling }) => toolCalling.id)).toEqual(['call-3']);
+ });
+
+ it('flags only the calls past the budget inside one turn, in emission order', () => {
+ const update = updateToolCallBudget(
+ createState(),
+ Array.from({ length: 5 }, (_, index) => searchCall(index)),
+ );
+
+ expect(update.overBudgetCalls.map(({ toolCalling }) => toolCalling.id)).toEqual([
+ 'call-3',
+ 'call-4',
+ ]);
+ });
+
+ it('counts consecutive over-budget turns and starts over once a turn stays within budget', () => {
+ const exhausted = { apiCalls: { '["memory","search"]': 3 }, counts: {} };
+
+ const second = updateToolCallBudget(createState({ ...exhausted, overBudgetRounds: 1 }), [
+ searchCall(9),
+ ]);
+ expect(second.overBudgetRounds).toBe(2);
+
+ const movedOn = updateToolCallBudget(createState({ ...exhausted, overBudgetRounds: 2 }), [
+ { ...searchCall(9), identifier: 'files', apiName: 'read' },
+ ]);
+ expect(movedOn.overBudgetRounds).toBe(0);
+ expect(movedOn.apiCalls).toEqual(exhausted.apiCalls);
+ });
+
+ it('tolerates the feedback limit of rejected turns and stops on the next', () => {
+ expect(hasIgnoredToolCallBudget(TOOL_CALL_BUDGET_FEEDBACK_LIMIT)).toBe(false);
+ expect(hasIgnoredToolCallBudget(TOOL_CALL_BUDGET_FEEDBACK_LIMIT + 1)).toBe(true);
+ });
+});
diff --git a/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts b/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
index 99435cb4b28..c20ca94ebbe 100644
--- a/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
+++ b/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
@@ -1,6 +1,7 @@
import type { ChatToolPayload } from '@lobechat/types';
import type { AgentState } from '../types';
+import { selectEffectiveToolManifestMap } from './operationToolSet';
/**
* Consecutive identical calls allowed before the turn is stopped. High enough
@@ -19,6 +20,15 @@ export const TOOL_CALL_REPEAT_LIMIT = 20;
*/
export const TOOL_CALL_BURST_LIMIT = 50;
+/**
+ * Consecutive LLM turns that may ask for an API past its
+ * `maxCallsPerOperation` budget, each answered with a rejected tool result,
+ * before the run is stopped. The rejection exists so the model can answer with
+ * what it already retrieved; one that keeps asking turn after turn is stuck.
+ */
+export const TOOL_CALL_BUDGET_FEEDBACK_LIMIT = 2;
+export const TOOL_CALL_BUDGET_REASON = 'tool_call_budget_exceeded';
+
const canonicalize = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(canonicalize);
@@ -73,3 +83,63 @@ export const hasRepeatedToolCall = (guard: AgentState['toolCallRepeatGuard']) =>
export const hasToolCallBurst = (toolsCalling: ChatToolPayload[]) =>
toolsCalling.length > TOOL_CALL_BURST_LIMIT;
+
+const getApiKey = ({ apiName, identifier }: ChatToolPayload) =>
+ JSON.stringify([identifier, apiName]);
+
+/**
+ * The API's `maxCallsPerOperation`, read from the same effective manifest map
+ * executors use so a step-activated tool is budgeted like a static one.
+ */
+export const getToolCallBudget = (
+ toolCalling: ChatToolPayload,
+ state: AgentState,
+): number | undefined => {
+ const apis = selectEffectiveToolManifestMap(state)[toolCalling.identifier]?.api as
+ Array<{ maxCallsPerOperation?: number; name?: string }> | undefined;
+ const limit = apis?.find((api) => api.name === toolCalling.apiName)?.maxCallsPerOperation;
+
+ return typeof limit === 'number' && limit > 0 ? limit : undefined;
+};
+
+/**
+ * What the model reads back for a call past the budget. It has to name the way
+ * out: a bare "rejected" reads like a transient failure and invites a retry.
+ */
+export const buildToolCallBudgetContent = (toolCalling: ChatToolPayload, limit: number) =>
+ `Tool call rejected: ${toolCalling.apiName} has reached its limit of ${limit} calls in this reply. The call was not executed, and further calls will be rejected too. Do not call it again: answer now with the results you already have, and say plainly if they do not cover the request.`;
+
+/**
+ * Count this turn's calls against each API's operation-wide budget.
+ *
+ * The repeat guard above keys on arguments, so a model that rephrases its
+ * query every turn never trips it (500 `searchUserMemory` calls in one reply,
+ * each with a new query). The budget ignores arguments and spans the whole
+ * operation, and only applies to APIs that declare one, so file reads, shell
+ * commands and job polling keep running as often as the task needs.
+ */
+export const updateToolCallBudget = (state: AgentState, toolsCalling: ChatToolPayload[]) => {
+ const previousGuard = state.toolCallRepeatGuard;
+ const apiCalls = { ...previousGuard?.apiCalls };
+ const overBudgetCalls: Array<{ limit: number; toolCalling: ChatToolPayload }> = [];
+
+ for (const toolCalling of toolsCalling) {
+ const limit = getToolCallBudget(toolCalling, state);
+ if (limit === undefined) continue;
+
+ const key = getApiKey(toolCalling);
+ apiCalls[key] = (apiCalls[key] ?? 0) + 1;
+ if (apiCalls[key] > limit) overBudgetCalls.push({ limit, toolCalling });
+ }
+
+ return {
+ apiCalls,
+ overBudgetCalls,
+ // Consecutive turns only: a turn that stays within budget (or calls no
+ // tools) means the model took the feedback, so the count starts over.
+ overBudgetRounds: overBudgetCalls.length > 0 ? (previousGuard?.overBudgetRounds ?? 0) + 1 : 0,
+ };
+};
+
+export const hasIgnoredToolCallBudget = (overBudgetRounds: number) =>
+ overBudgetRounds > TOOL_CALL_BUDGET_FEEDBACK_LIMIT;
diff --git a/packages/builtin-tool-memory/src/manifest.test.ts b/packages/builtin-tool-memory/src/manifest.test.ts
index b00854999d2..05b38c8db89 100644
--- a/packages/builtin-tool-memory/src/manifest.test.ts
+++ b/packages/builtin-tool-memory/src/manifest.test.ts
@@ -57,4 +57,17 @@ describe('MemoryManifest', () => {
// genuine user facts inside an assignment can still become memory
expect(boundaries).toContain('genuine facts about the user');
});
+
+ /**
+ * @example
+ * One reply ran 500 memory searches, a rephrased query each time, and never
+ * answered. The search API carries a per-operation budget so the runtime
+ * rejects the calls past it, and the system role names the way out.
+ */
+ it('bounds how many memory searches one operation may run', () => {
+ const search = MemoryManifest.api.find((api) => api.name === MemoryApiName.searchUserMemory);
+
+ expect(search?.maxCallsPerOperation).toBe(20);
+ expect(systemPrompt).toContain('Stop searching once two or three focused searches');
+ });
});
diff --git a/packages/builtin-tool-memory/src/manifest.ts b/packages/builtin-tool-memory/src/manifest.ts
index f8ef260ad3f..bae885ad5c2 100644
--- a/packages/builtin-tool-memory/src/manifest.ts
+++ b/packages/builtin-tool-memory/src/manifest.ts
@@ -93,6 +93,10 @@ export const MemoryManifest: BuiltinToolManifest = {
{
description:
'Retrieve memories using one or more search queries plus optional filters for categories, tags, labels, relationships, and time range. Context memories (ongoing projects, situations, environments) may be left out of default searches depending on the memory effort setting; to be sure to get them, include "context" in layers or set topK.contexts.',
+ // One reply once ran 500 searches, each with a rephrased query, and
+ // never answered. 20 leaves room for a multi-part question searched one
+ // intent at a time; past it the model is told to answer with what it has.
+ maxCallsPerOperation: 20,
name: MemoryApiName.searchUserMemory,
parameters: {
additionalProperties: false,
diff --git a/packages/builtin-tool-memory/src/systemRole.ts b/packages/builtin-tool-memory/src/systemRole.ts
index b99f81c332e..042e8e80196 100644
--- a/packages/builtin-tool-memory/src/systemRole.ts
+++ b/packages/builtin-tool-memory/src/systemRole.ts
@@ -78,6 +78,7 @@ Query construction guidance:
<retrieval_sufficiency>
- A memory result is sufficient only when it directly supports the answer or memory action being considered.
- Topic overlap alone is not sufficient. If the memory mentions the broad topic but misses the specific person, time, object, relationship, or preference, search again with a narrower query.
+- Stop searching once two or three focused searches return nothing new. Answer with what you found, and say plainly when memory holds nothing relevant: rephrasing the same question again will not surface a memory that does not exist.
- Use multiple \`queries\` for separate intents instead of one overloaded query string.
- Use \`queryTaxonomyOptions\` when a category, tag, label, status, role, or relationship vocabulary would make the next search more precise.
- Keep source grounding internal. Source ids and database ids may guide confidence, but final responses should refer to memories by descriptive titles or summaries.
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index bacd659c3db..29469fe81e3 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -166,6 +166,19 @@ export interface LobeChatPluginApi {
*
*/
humanIntervention?: ExtendedHumanInterventionConfig;
+ /**
+ * Calls to this API one operation may run, counted across every LLM turn and
+ * regardless of arguments. Calls past it are answered with a rejected tool
+ * result telling the model to work with what it already has, instead of
+ * being dispatched. Set it on retrieval-style APIs a model can loop on by
+ * rephrasing the query each turn β€” the repeat guard keys on arguments and
+ * never sees that loop. Leave it unset for APIs that legitimately run many
+ * times in one operation (file reads, shell commands, job polling).
+ *
+ * Framework-only config like `humanIntervention`: it never reaches the
+ * LLM-facing tool spec.
+ */
+ maxCallsPerOperation?: number;
name: string;
/**
* Run this API's calls one after another, in the order the model emitted