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(model-runtime): keep the prompt cache when GPT models activate tools mid-run (#23629)

AmAzing-eb91a0930e0c
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index ae0fd6182fa..ee1f42103af 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -28,6 +28,7 @@ import {
TaskCallbackMessageProcessor,
TaskMessageProcessor,
TasksFlattenProcessor,
+ ToolActivationAnchorProcessor,
ToolCallProcessor,
ToolMessageReorder,
VerifyMessageProcessor,
@@ -679,6 +680,15 @@ export class MessagesEngine {
new ToolMessageReorder(),
// Force finish summary (when maxSteps exceeded)
new ForceFinishSummaryInjector({ enabled: !!forceFinish }),
+ // Only paired activation results still present in the outgoing conversation can own tools.
+ ...(toolsConfig?.anchorActivatedTools
+ ? [
+ new ToolActivationAnchorProcessor({
+ manifests: injectedToolManifests,
+ variableGenerators,
+ }),
+ ]
+ : []),
// Message cleanup (final step)
new MessageCleanupProcessor(),
];
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.toolActivationAnchor.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.toolActivationAnchor.test.ts
new file mode 100644
index 00000000000..bc6511ec9a0
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.toolActivationAnchor.test.ts
@@ -0,0 +1,190 @@
+import { describe, expect, it } from 'vitest';
+
+import type { UIChatMessage } from '@/types/index';
+
+import type { LobeToolManifest } from '../../tools/types';
+import { MessagesEngine } from '../MessagesEngine';
+import type { MessagesEngineParams } from '../types';
+
+/**
+ * Activating a tool mid-conversation must only append to the request. Anything that
+ * changes ahead of the history (the system message here; the top-level tools on the
+ * transport side) costs the prompt cache for every token after it.
+ */
+
+const CREDS_SYSTEM_ROLE = 'lobe-creds usage: always list before creating.';
+
+const activatorManifest = {
+ api: [{ description: 'Activate tools', name: 'activateTools', parameters: {} }],
+ identifier: 'lobe-activator',
+ meta: { title: 'Activator' },
+ systemRole: 'Activate a tool before calling it.',
+ type: 'builtin',
+} as unknown as LobeToolManifest;
+
+const credsManifest = {
+ api: [{ description: 'List credentials', name: 'listCreds', parameters: {} }],
+ identifier: 'lobe-creds',
+ meta: { title: 'Creds' },
+ systemRole: CREDS_SYSTEM_ROLE,
+ type: 'builtin',
+} as unknown as LobeToolManifest;
+
+const now = 1_700_000_000_000;
+
+const firstTurn = (): UIChatMessage[] =>
+ [
+ { content: 'help me manage creds', createdAt: now, id: 'u1', role: 'user', updatedAt: now },
+ ] as unknown as UIChatMessage[];
+
+const afterActivation = (): UIChatMessage[] =>
+ [
+ ...firstTurn(),
+ {
+ content: '',
+ createdAt: now,
+ id: 'a1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'activateTools',
+ arguments: '{"identifiers":["lobe-creds"]}',
+ id: 'call_activate_1',
+ identifier: 'lobe-activator',
+ type: 'builtin',
+ },
+ ],
+ updatedAt: now,
+ },
+ {
+ content:
+ 'Successfully activated tools: lobe-creds.listCreds.\nUsage instructions for the activated items are in the system prompt.',
+ createdAt: now,
+ id: 't1',
+ plugin: {
+ apiName: 'activateTools',
+ arguments: '{"identifiers":["lobe-creds"]}',
+ identifier: 'lobe-activator',
+ type: 'builtin',
+ },
+ pluginState: {
+ activatedSkills: [],
+ activatedTools: [{ apiCount: 1, identifier: 'lobe-creds', name: 'Creds' }],
+ },
+ role: 'tool',
+ tool_call_id: 'call_activate_1',
+ updatedAt: now,
+ },
+ ] as unknown as UIChatMessage[];
+
+const createParams = (overrides: Partial<MessagesEngineParams>): MessagesEngineParams => ({
+ capabilities: { isCanUseFC: () => true },
+ enableSystemDate: false,
+ messages: [],
+ model: 'gpt-6.1-sol',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ ...overrides,
+});
+
+const run = async (anchorActivatedTools: boolean) => {
+ const before = await new MessagesEngine(
+ createParams({
+ messages: firstTurn(),
+ toolsConfig: {
+ anchorActivatedTools,
+ manifests: [activatorManifest],
+ tools: ['lobe-activator'],
+ },
+ }),
+ ).process();
+ const after = await new MessagesEngine(
+ createParams({
+ messages: afterActivation(),
+ toolsConfig: {
+ anchorActivatedTools,
+ manifests: [activatorManifest, credsManifest],
+ tools: ['lobe-activator', 'lobe-creds'],
+ },
+ }),
+ ).process();
+
+ return { after: after.messages as any[], before: before.messages as any[] };
+};
+
+describe('MessagesEngine tool activation anchoring', () => {
+ it('keeps a canonical request and prepares the append-only variant for the transport', async () => {
+ const { after, before } = await run(true);
+ const result = after.find((message) => message.role === 'tool');
+ const plan = result.toolActivationPlan;
+ expect(result.content).not.toContain(CREDS_SYSTEM_ROLE);
+ expect(after[0].content).toContain(CREDS_SYSTEM_ROLE);
+ expect(plan.results).toEqual([
+ {
+ callId: 'call_activate_1',
+ content: expect.stringContaining(CREDS_SYSTEM_ROLE),
+ toolNames: ['lobe-creds____listCreds'],
+ },
+ ]);
+ expect(after[0].content.replace(plan.system.original, plan.system.replacement)).toEqual(
+ before[0].content,
+ );
+ });
+
+ it('keeps the system-prompt injection and no annotation when the transport cannot anchor', async () => {
+ const { after, before } = await run(false);
+
+ expect(after[0].content).toContain(CREDS_SYSTEM_ROLE);
+ expect(after[0].content).not.toBe(before[0].content);
+
+ const result = after.find((message) => message.role === 'tool');
+ expect(result.content).not.toContain(CREDS_SYSTEM_ROLE);
+ expect(result).not.toHaveProperty('toolActivationPlan');
+ });
+
+ it.each(['truncated caller', 'disabled activator'])(
+ 'retains instructions after a %s',
+ async (scenario) => {
+ const { messages } = await new MessagesEngine(
+ createParams({
+ messages: afterActivation(),
+ enableHistoryCount: scenario === 'truncated caller',
+ historyCount: 1,
+ toolsConfig: {
+ anchorActivatedTools: true,
+ disabledToolIdentifiers: scenario === 'disabled activator' ? ['lobe-activator'] : [],
+ manifests: [activatorManifest, credsManifest],
+ tools: ['lobe-activator', 'lobe-creds'],
+ },
+ }),
+ ).process();
+ expect(messages.some((m) => m.role === 'tool')).toBe(false);
+ expect(messages.find((m) => m.role === 'system')?.content).toContain(CREDS_SYSTEM_ROLE);
+ },
+ );
+
+ it('documents the tool in the system message once its activation left the history', async () => {
+ const messages = [
+ ...afterActivation(),
+ { content: 'thanks', createdAt: now, id: 'a2', role: 'assistant', updatedAt: now },
+ { content: 'now list them', createdAt: now, id: 'u2', role: 'user', updatedAt: now },
+ ] as unknown as UIChatMessage[];
+
+ const result = await new MessagesEngine(
+ createParams({
+ enableHistoryCount: true,
+ historyCount: 1,
+ messages,
+ toolsConfig: {
+ anchorActivatedTools: true,
+ manifests: [activatorManifest, credsManifest],
+ tools: ['lobe-activator', 'lobe-creds'],
+ },
+ }),
+ ).process();
+
+ const payload = result.messages as any[];
+ expect(payload.some((message) => message.role === 'tool')).toBe(false);
+ expect(payload[0].content).toContain(CREDS_SYSTEM_ROLE);
+ });
+});
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 623b0864c89..8b56f2dadb6 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -66,6 +66,8 @@ export interface KnowledgeConfig {
* Tools configuration
*/
export interface ToolsConfig {
+ /** Prepare optional prompt edits for a transport that can declare tools mid-conversation. */
+ anchorActivatedTools?: boolean;
/** Tool identifiers that must be removed from historical tool calls in this runtime scope */
disabledToolIdentifiers?: string[];
/** Tool manifests with systemRole and API definitions */
diff --git a/packages/context-engine/src/processors/ActivationResultTrim.ts b/packages/context-engine/src/processors/ActivationResultTrim.ts
index 4cbecb2effa..90492cd00f8 100644
--- a/packages/context-engine/src/processors/ActivationResultTrim.ts
+++ b/packages/context-engine/src/processors/ActivationResultTrim.ts
@@ -27,6 +27,14 @@ const log = debug('context-engine:processor:ActivationResultTrimProcessor');
const ACTIVATOR_IDENTIFIER = 'lobe-activator';
const SKILLS_IDENTIFIER = 'lobe-skills';
+/**
+ * Closing line of an `activateTools` result, as written by the activator and by this
+ * processor's trimmed form. ToolActivationAnchorProcessor replaces it when the
+ * instructions stay with the result instead.
+ */
+export const ACTIVATION_DOCS_IN_SYSTEM_PROMPT_NOTE =
+ 'Usage instructions for the activated items are in the system prompt.';
+
interface ActivatedToolState {
apiCount?: number;
identifier?: string;
@@ -262,7 +270,7 @@ export class ActivationResultTrimProcessor extends BaseProcessor {
parts.push(`Not found: ${notFound.join(', ')}.`);
}
- parts.push('Usage instructions for the activated items are in the system prompt.');
+ parts.push(ACTIVATION_DOCS_IN_SYSTEM_PROMPT_NOTE);
return parts.join('\n');
}
diff --git a/packages/context-engine/src/processors/MessageCleanup.ts b/packages/context-engine/src/processors/MessageCleanup.ts
index 398b56c4c62..0291d177be9 100644
--- a/packages/context-engine/src/processors/MessageCleanup.ts
+++ b/packages/context-engine/src/processors/MessageCleanup.ts
@@ -87,6 +87,8 @@ export class MessageCleanupProcessor extends BaseProcessor {
role: message.role,
tool_call_id: message.tool_call_id,
...(message.name && { name: message.name }),
+ ...(message.toolsAdded?.length && { toolsAdded: message.toolsAdded }),
+ ...(message.toolActivationPlan && { toolActivationPlan: message.toolActivationPlan }),
};
}
diff --git a/packages/context-engine/src/processors/ToolActivationAnchor.ts b/packages/context-engine/src/processors/ToolActivationAnchor.ts
new file mode 100644
index 00000000000..99fb9eef02b
--- /dev/null
+++ b/packages/context-engine/src/processors/ToolActivationAnchor.ts
@@ -0,0 +1,112 @@
+import { pluginPrompts } from '@lobechat/prompts';
+import type { ToolActivationPlan } from '@lobechat/types';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { LobeToolManifest } from '../engine/tools/types';
+import { generateToolsFromManifest } from '../engine/tools/utils';
+import { toToolPrompt } from '../providers/ToolSystemRole';
+import type { PipelineContext, ProcessorOptions } from '../types';
+import {
+ type ActivateToolsState,
+ isActivateToolsCall,
+ readActivatedToolIds,
+} from '../utils/activatedTools';
+import { ACTIVATION_DOCS_IN_SYSTEM_PROMPT_NOTE } from './ActivationResultTrim';
+import { parsePlaceholderVariables } from './PlaceholderVariables';
+
+export interface ToolActivationAnchorConfig {
+ manifests?: LobeToolManifest[];
+ variableGenerators?: Record<string, () => string>;
+}
+
+/**
+ * Keep the ordinary system and tool messages intact. Prepare an optional edit after
+ * history truncation, role folding, disabled-call filtering and tool pairing. Only the
+ * transport knows its final endpoint, mapped model and effective tool set.
+ */
+export class ToolActivationAnchorProcessor extends BaseProcessor {
+ readonly name = 'ToolActivationAnchorProcessor';
+
+ constructor(
+ private config: ToolActivationAnchorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const { manifests = [], variableGenerators = {} } = this.config;
+ const system = context.messages.find((message) => message.role === 'system');
+ if (!manifests.length || typeof system?.content !== 'string')
+ return this.markAsExecuted(context);
+
+ const render = (tools: LobeToolManifest[]) =>
+ parsePlaceholderVariables(
+ pluginPrompts({ tools: tools.map(toToolPrompt) }),
+ variableGenerators,
+ );
+ const remaining = new Map(manifests.map((manifest) => [manifest.identifier, manifest]));
+ const results: ToolActivationPlan['results'] = [];
+ let firstResultIndex = -1;
+ for (const [index, message] of context.messages.entries()) {
+ if (
+ message.role !== 'tool' ||
+ !message.tool_call_id ||
+ typeof message.content !== 'string' ||
+ !isActivateToolsCall(message.plugin?.identifier, message.plugin?.apiName)
+ )
+ continue;
+ const activated: LobeToolManifest[] = [];
+ for (const id of readActivatedToolIds(message.pluginState)) {
+ const manifest = remaining.get(id);
+ if (!manifest?.api.length) continue;
+ remaining.delete(id);
+ activated.push(manifest);
+ }
+ if (!activated.length) continue;
+ const note = (message.pluginState as ActivateToolsState)?.activatedSkills?.length
+ ? 'Usage instructions for the activated tools follow; skill instructions are in the system prompt.'
+ : 'Usage instructions for the activated tools follow.';
+ const body = message.content.includes(ACTIVATION_DOCS_IN_SYSTEM_PROMPT_NOTE)
+ ? message.content.replace(ACTIVATION_DOCS_IN_SYSTEM_PROMPT_NOTE, note)
+ : [message.content, note].filter(Boolean).join('\n');
+ results.push({
+ callId: message.tool_call_id,
+ content: [body, render(activated)].join('\n\n'),
+ toolNames: activated.flatMap((manifest) =>
+ generateToolsFromManifest(manifest).map((tool) => tool.function.name),
+ ),
+ });
+ if (firstResultIndex < 0) firstResultIndex = index;
+ }
+ if (firstResultIndex < 0) return this.markAsExecuted(context);
+
+ const plan: ToolActivationPlan = { results };
+ // An explicit replacement document owns the whole system prompt. Only the
+ // activation result needs to change when this transport can anchor the tools.
+ if (!context.metadata.agentDocumentSystemReplace?.replaced) {
+ let original = render(manifests);
+ let start = system.content.indexOf(original);
+ // A later injector or a volatile placeholder may have changed this section.
+ // In that case the canonical system message remains the source of instructions.
+ if (start < 0 || system.content.includes(original, start + 1))
+ return this.markAsExecuted(context);
+ const replacement = render([...remaining.values()]);
+ if (!replacement) {
+ if (start >= 2 && system.content.slice(start - 2, start) === '\n\n') {
+ start -= 2;
+ original = '\n\n' + original;
+ } else if (system.content.slice(start + original.length).startsWith('\n\n')) {
+ original += '\n\n';
+ }
+ }
+ plan.system = { original, replacement, start };
+ }
+ const processed = this.cloneContext(context);
+ processed.messages[firstResultIndex] = {
+ ...processed.messages[firstResultIndex],
+ toolActivationPlan: plan,
+ };
+ return this.markAsExecuted(processed);
+ }
+}
diff --git a/packages/context-engine/src/processors/__tests__/ToolActivationAnchor.test.ts b/packages/context-engine/src/processors/__tests__/ToolActivationAnchor.test.ts
new file mode 100644
index 00000000000..ce40bc651a9
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/ToolActivationAnchor.test.ts
@@ -0,0 +1,124 @@
+import { pluginPrompts } from '@lobechat/prompts';
+import { describe, expect, it } from 'vitest';
+
+import type { LobeToolManifest } from '../../engine/tools/types';
+import { toToolPrompt } from '../../providers/ToolSystemRole';
+import type { PipelineContext } from '../../types';
+import { ToolActivationAnchorProcessor } from '../ToolActivationAnchor';
+
+const CREDS_SYSTEM_ROLE = 'Always list credentials before creating one.';
+
+const credsManifest = {
+ api: [
+ { description: 'List credentials', name: 'listCreds', parameters: {} },
+ { description: 'Create a credential', name: 'createCred', parameters: {} },
+ ],
+ identifier: 'lobe-creds',
+ meta: { title: 'Creds' },
+ systemRole: CREDS_SYSTEM_ROLE,
+ type: 'builtin',
+} as unknown as LobeToolManifest;
+
+const notionManifest = {
+ api: [{ description: 'Create a page', name: 'createPage', parameters: {} }],
+ identifier: 'notion',
+ meta: { description: 'Notion workspace', title: 'Notion' },
+ type: 'mcp',
+} as unknown as LobeToolManifest;
+
+const TRIMMED_RESULT =
+ 'Successfully activated tools: lobe-creds.listCreds, lobe-creds.createCred.\nUsage instructions for the activated items are in the system prompt.';
+
+const createContext = (
+ messages: any[],
+ metadata: PipelineContext['metadata'] = {},
+): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata,
+});
+
+const activation = (identifiers: string[], overrides?: Record<string, unknown>) => ({
+ content: TRIMMED_RESULT,
+ id: 'tool-1',
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: {
+ activatedSkills: [],
+ activatedTools: identifiers.map((identifier) => ({ identifier })),
+ },
+ role: 'tool',
+ tool_call_id: 'call-1',
+ ...overrides,
+});
+
+const manifests = [credsManifest, notionManifest];
+const block = pluginPrompts({ tools: manifests.map(toToolPrompt) });
+const system = { role: 'system', content: 'Agent instructions\n\n' + block };
+const process = (messages: PipelineContext['messages']) =>
+ new ToolActivationAnchorProcessor({ manifests }).process(createContext(messages));
+
+describe('ToolActivationAnchorProcessor', () => {
+ it('leaves the canonical messages intact and prepares each tool at its first surviving activation', async () => {
+ const first = activation(['lobe-creds']);
+ const second = activation(['lobe-creds', 'notion'], { tool_call_id: 'call-2' });
+ const result = await process([system, first, second]);
+ expect(result.messages[0]).toEqual(system);
+ expect(result.messages[1].content).toBe(first.content);
+ expect(result.messages[2]).toEqual(second);
+ const plan = result.messages[1].toolActivationPlan;
+ expect(plan.results.map((entry: { toolNames: string[] }) => entry.toolNames)).toEqual([
+ ['lobe-creds____listCreds', 'lobe-creds____createCred'],
+ ['notion____createPage____mcp'],
+ ]);
+ expect(plan.results[0].content).toContain(CREDS_SYSTEM_ROLE);
+ expect(plan.results[0].content).not.toContain('in the system prompt');
+ expect(plan.results[1].content).not.toContain(CREDS_SYSTEM_ROLE);
+ expect(plan.results[1].content).toContain('Notion workspace');
+ expect(system.content.replace(plan.system.original, plan.system.replacement)).toBe(
+ 'Agent instructions',
+ );
+ expect(first).not.toHaveProperty('toolActivationPlan');
+ });
+
+ it('prepares no edit for absent, disabled or unrelated activations', async () => {
+ const messages = [
+ system,
+ activation(['uninstalled']),
+ activation(['notion'], { plugin: { identifier: 'other', apiName: 'run' } }),
+ ];
+ expect((await process(messages)).messages).toEqual(messages);
+ });
+
+ it('leaves a replaced or ambiguous system prompt intact', async () => {
+ for (const content of ['custom agent document', block + '\n\n' + block]) {
+ const messages = [{ role: 'system', content }, activation(['notion'])];
+ expect((await process(messages)).messages).toEqual(messages);
+ }
+ });
+
+ it('keeps an explicit replacement document and prepares guidance at the activation', async () => {
+ const document = { role: 'system', content: 'Custom agent document' };
+ const result = await new ToolActivationAnchorProcessor({ manifests }).process(
+ createContext([document, activation(['lobe-creds'])], {
+ agentDocumentSystemReplace: { replaced: true },
+ }),
+ );
+ expect(result.messages[0]).toEqual(document);
+ expect(result.messages[1].toolActivationPlan).not.toHaveProperty('system');
+ expect(result.messages[1].toolActivationPlan.results[0].content).toContain(CREDS_SYSTEM_ROLE);
+ });
+
+ it('preserves skill guidance in a mixed activation', async () => {
+ const result = await process([
+ system,
+ activation(['notion'], {
+ pluginState: {
+ activatedSkills: [{ name: 'Skill' }],
+ activatedTools: [{ identifier: 'notion' }],
+ },
+ }),
+ ]);
+ expect(result.messages[1].toolActivationPlan.results[0].content).toContain('skill');
+ });
+});
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index 18e2bd4aeb0..34efa88fca4 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -51,6 +51,10 @@ export { SupervisorRoleRestoreProcessor } from './SupervisorRoleRestore';
export { TaskCallbackMessageProcessor } from './TaskCallbackMessage';
export { TaskMessageProcessor } from './TaskMessage';
export { TasksFlattenProcessor } from './TasksFlatten';
+export {
+ type ToolActivationAnchorConfig,
+ ToolActivationAnchorProcessor,
+} from './ToolActivationAnchor';
export { ToolCallProcessor } from './ToolCall';
export { ToolMessageReorder } from './ToolMessageReorder';
export { VerifyMessageProcessor } from './VerifyMessage';
diff --git a/packages/context-engine/src/providers/ToolSystemRole.ts b/packages/context-engine/src/providers/ToolSystemRole.ts
index d9688c85ae9..196027cb915 100644
--- a/packages/context-engine/src/providers/ToolSystemRole.ts
+++ b/packages/context-engine/src/providers/ToolSystemRole.ts
@@ -46,6 +46,22 @@ export interface ToolSystemRoleConfig {
export const selectToolPromptManifests = (manifests?: LobeToolManifest[]): LobeToolManifest[] =>
(manifests ?? []).filter((manifest) => manifest.api.length > 0 || manifest.systemRole);
+/** The prompt entry a manifest contributes to the tool instructions. */
+export const toToolPrompt = (manifest: LobeToolManifest): Tool => {
+ const toolNameResolver = new ToolNameResolver();
+
+ return {
+ apis: manifest.api.map((api): API => ({
+ desc: api.description,
+ name: toolNameResolver.generate(manifest.identifier, api.name, manifest.type),
+ })),
+ description: manifest.meta?.description,
+ identifier: manifest.identifier,
+ name: manifest.meta?.title || manifest.identifier,
+ systemRole: manifest.systemRole,
+ };
+};
+
/**
* Tool System Role Provider
* Responsible for injecting tool-related system roles for models that support tool calling
@@ -53,14 +69,11 @@ export const selectToolPromptManifests = (manifests?: LobeToolManifest[]): LobeT
export class ToolSystemRoleProvider extends BaseSystemRoleProvider {
readonly name = 'ToolSystemRoleProvider';
- private toolNameResolver: ToolNameResolver;
-
constructor(
private config: ToolSystemRoleConfig,
options: ProcessorOptions = {},
) {
super(options);
- this.toolNameResolver = new ToolNameResolver();
}
protected buildSystemRoleContent(_context: PipelineContext): string | null {
@@ -103,16 +116,7 @@ export class ToolSystemRoleProvider extends BaseSystemRoleProvider {
return undefined;
}
- const tools: Tool[] = selectToolPromptManifests(manifests).map((manifest) => ({
- apis: manifest.api.map((api): API => ({
- desc: api.description,
- name: this.toolNameResolver.generate(manifest.identifier, api.name, manifest.type),
- })),
- description: manifest.meta?.description,
- identifier: manifest.identifier,
- name: manifest.meta?.title || manifest.identifier,
- systemRole: manifest.systemRole,
- }));
+ const tools: Tool[] = selectToolPromptManifests(manifests).map(toToolPrompt);
if (tools.length === 0) {
log('No meaningful tools to inject (all manifests have empty APIs and no systemRole)');
diff --git a/packages/context-engine/src/utils/activatedTools.ts b/packages/context-engine/src/utils/activatedTools.ts
new file mode 100644
index 00000000000..89e77f38e82
--- /dev/null
+++ b/packages/context-engine/src/utils/activatedTools.ts
@@ -0,0 +1,22 @@
+/**
+ * Wire-format identifier of the activation tool. Literal copy of
+ * `LobeActivatorIdentifier` (@lobechat/builtin-tool-activator): frozen, persisted in
+ * message rows, and not importable here without a tool-package dependency.
+ */
+const ACTIVATOR_IDENTIFIER = 'lobe-activator';
+const ACTIVATE_TOOLS_API = 'activateTools';
+
+export interface ActivateToolsState {
+ activatedSkills?: unknown[];
+ activatedTools?: Array<{ identifier?: string }>;
+}
+
+export const readActivatedToolIds = (state: unknown): string[] => {
+ const activatedTools = (state as ActivateToolsState | undefined)?.activatedTools;
+ if (!Array.isArray(activatedTools)) return [];
+
+ return activatedTools.flatMap((tool) => (tool?.identifier ? [tool.identifier] : []));
+};
+
+export const isActivateToolsCall = (identifier?: string, apiName?: string) =>
+ identifier === ACTIVATOR_IDENTIFIER && apiName === ACTIVATE_TOOLS_API;
diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts
index dfbe4311b59..45142fea10f 100644
--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts
+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts
@@ -11,6 +11,17 @@ const baseSnapshot = (): ContextSnapshot => ({
});
describe('buildMessagesEngineParams', () => {
+ it('prepares activation proposals for Responses providers even with a logical model alias', () => {
+ const forProvider = (provider: string) =>
+ buildMessagesEngineParams({ ...baseSnapshot(), model: { model: 'my-model', provider } })
+ .toolsConfig?.anchorActivatedTools;
+ expect(forProvider('openai')).toBe(true);
+ expect(forProvider('chatgpt')).toBe(true);
+ expect(forProvider('lobehub')).toBe(true);
+ expect(forProvider('my-openai-relay')).toBe(true);
+ expect(forProvider('anthropic')).toBe(false);
+ });
+
it('hides the page agent system role unless the run enabled the tool', () => {
expect(buildMessagesEngineParams(baseSnapshot()).toolsConfig?.disabledToolIdentifiers).toEqual([
PageAgentIdentifier,
diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
index 9cda00f21c0..cca538b2626 100644
--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
@@ -1,5 +1,6 @@
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import type { LobeToolManifest, MessagesEngineParams } from '@lobechat/context-engine';
+import { ModelProvider } from 'model-bank/modelProvider';
import type { ContextSnapshot } from './types';
import { createVariableGenerators } from './variableGenerators';
@@ -9,6 +10,13 @@ const definedOnly = <T extends Record<string, unknown>>(record: T): Partial<T> =
Object.entries(record).filter(([, value]) => value !== undefined),
) as Partial<T>;
+const builtInProviders = new Set<string>(Object.values(ModelProvider));
+const responsesProviders = new Set<string>([
+ ModelProvider.OpenAI,
+ ModelProvider.ChatGPT,
+ ModelProvider.LobeHub,
+]);
+
const CURRENT_DATE_LINE = /Current date: \d{4}-\d{2}-\d{2}/g;
/**
@@ -99,6 +107,10 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEn
selectedTools: tools?.selectedTools,
toolDiscoveryConfig: tools?.toolDiscoveryConfig,
toolsConfig: {
+ // Custom provider IDs use the OpenAI-compatible runtime. Defer the final
+ // decision until aliases, relays and the effective protocol are resolved.
+ anchorActivatedTools:
+ responsesProviders.has(model.provider) || !builtInProviders.has(model.provider),
disabledToolIdentifiers,
manifests,
tools: enabledToolIds,
diff --git a/packages/mecha/src/contextEngineering/toolActivation.test.ts b/packages/mecha/src/contextEngineering/toolActivation.test.ts
new file mode 100644
index 00000000000..8e2e427b60e
--- /dev/null
+++ b/packages/mecha/src/contextEngineering/toolActivation.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+import { MessagesEngine } from '@lobechat/context-engine';
+import { LobeOpenAI, ModelRuntime } from '@lobechat/model-runtime';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const fn = (name: string) => ({
+ function: { description: name, name, parameters: { properties: {}, type: 'object' } },
+ type: 'function' as const,
+});
+const activator = fn('lobe-activator____activateTools');
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+describe('activation instructions in the outgoing Responses request', () => {
+ it.each([
+ ['official', undefined, undefined, true],
+ ['opt-out', undefined, '0', false],
+ ['relay default', 'https://relay.example.com/v1', undefined, false],
+ ['relay opt-in', 'https://relay.example.com/v1', 'additional_tools', true],
+ ] as const)(
+ 'places instructions with their schemas for %s',
+ async (_name, baseURL, override, anchors) => {
+ vi.stubEnv('OPENAI_RESPONSES_TOOL_ANCHORING', override);
+ interface RequestBody {
+ input: Array<{ content?: string; output?: string; role?: string; type?: string }>;
+ tools: Array<{ name?: string }>;
+ }
+ const requests: RequestBody[] = [];
+ const runtime = new ModelRuntime(
+ new LobeOpenAI({
+ apiKey: 'test',
+ baseURL,
+ fetch: async (_url: RequestInfo | URL, init?: RequestInit) => {
+ requests.push(JSON.parse(String(init?.body)));
+ return new Response('data: [DONE]\n\n', {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ },
+ }),
+ );
+ const model = 'gpt-6.1-sol';
+ const instructions = 'Read the sample record before writing.';
+ const id = 'sample';
+ const dynamicTool = fn('sample____read');
+ const { messages } = await new MessagesEngine({
+ capabilities: { isCanUseFC: () => true },
+ enableSystemDate: false,
+ model,
+ provider: 'openai',
+ systemRole: 'Agent',
+ messages: [
+ { createdAt: 1, updatedAt: 1, id: 'user', role: 'user', content: 'Read the sample' },
+ {
+ createdAt: 2,
+ updatedAt: 2,
+ id: 'assistant',
+ role: 'assistant',
+ content: '',
+ tools: [
+ {
+ id: 'call',
+ identifier: 'lobe-activator',
+ apiName: 'activateTools',
+ type: 'builtin',
+ arguments: '{}',
+ },
+ ],
+ },
+ {
+ createdAt: 3,
+ updatedAt: 3,
+ id: 'result',
+ role: 'tool',
+ content: 'Successfully activated tools.',
+ tool_call_id: 'call',
+ plugin: {
+ arguments: '{}',
+ identifier: 'lobe-activator',
+ apiName: 'activateTools',
+ type: 'builtin',
+ },
+ pluginState: { activatedTools: [{ identifier: id }] },
+ },
+ ],
+ toolsConfig: {
+ anchorActivatedTools: true,
+ tools: ['lobe-activator', id],
+ manifests: [
+ {
+ identifier: 'lobe-activator',
+ meta: {},
+ type: 'builtin',
+ api: [{ name: 'activateTools', description: 'Activate', parameters: {} }],
+ },
+ {
+ identifier: id,
+ meta: {},
+ type: 'builtin',
+ systemRole: instructions,
+ api: [{ name: 'read', description: 'Read', parameters: {} }],
+ },
+ ],
+ },
+ }).process();
+ const response = await runtime.chat({
+ model,
+ messages,
+ tools: [activator, dynamicTool],
+ stream: true,
+ });
+ await response.text();
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ const system = request.input.find((item) => item.role === 'developer');
+ const result = request.input.find((item) => item.type === 'function_call_output');
+ expect(system?.content?.includes(instructions)).toBe(!anchors);
+ expect(result?.output?.includes(instructions)).toBe(anchors);
+ expect(request.tools?.some((t) => t.name === dynamicTool.function.name)).toBe(!anchors);
+ expect(request.input.some((item) => item.type === 'additional_tools')).toBe(anchors);
+ },
+ );
+});
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index 04d5c5cf998..042965c8e7a 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -523,6 +523,19 @@ describe('ModelRuntime', () => {
schema: { name: 'test', schema: { type: 'object' as const, properties: {} } },
};
+ it('keeps internal tool activation metadata outside the provider payload', async () => {
+ const { runtime, mockRuntimeAI } = createMockRuntime();
+ const plan = { results: [{ callId: 'call', content: 'Docs', toolNames: ['lookup'] }] };
+ const message = { role: 'tool' as const, tool_call_id: 'call', content: 'Activated' };
+ const payload = { ...chatPayload, messages: [{ ...message, toolActivationPlan: plan }] };
+ await runtime.chat(payload);
+ expect(mockRuntimeAI.chat).toHaveBeenCalledWith(
+ { ...payload, messages: [message] },
+ expect.objectContaining({ toolActivationPlan: plan }),
+ );
+ expect(payload.messages[0].toolActivationPlan).toBe(plan);
+ });
+
describe('chat hooks', () => {
it('beforeChat is called before runtime.chat', async () => {
const beforeChat = vi.fn();
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index a21651468f5..338ad5cfe3a 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -322,6 +322,22 @@ export class ModelRuntime {
try {
const hooksStartedAt = Date.now();
+ // Messages carry the plan between the context engine and server. Keep it off
+ // vendor payloads, including when a hosted route retries another provider.
+ const plan = payload.messages?.find(
+ (message) => message.toolActivationPlan,
+ )?.toolActivationPlan;
+ if (plan) {
+ payload = {
+ ...payload,
+ messages: payload.messages.map((message) => {
+ if (!message.toolActivationPlan) return message;
+ const { toolActivationPlan: _plan, ...rest } = message;
+ return rest;
+ }),
+ };
+ options = { ...options, toolActivationPlan: plan };
+ }
const finalOptions = await this.applyHooks(payload, options);
if (metadata) {
timing(
diff --git a/packages/model-runtime/src/core/openaiCompatible/factoryOptions.ts b/packages/model-runtime/src/core/openaiCompatible/factoryOptions.ts
index 7970c2d2fe1..e350355f186 100644
--- a/packages/model-runtime/src/core/openaiCompatible/factoryOptions.ts
+++ b/packages/model-runtime/src/core/openaiCompatible/factoryOptions.ts
@@ -22,6 +22,7 @@ import type {
} from '../../types/video';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import type { AssertContextWithinWindowOptions } from '../../utils/resolveSafeMaxTokens';
+import type { ResponsesToolAnchoringMode } from '../protocols/openaiResponses/toolAnchoring';
import type { ChatPayloadForTransformStream } from '../streams/protocol';
import type { DecideConfig } from './decide';
@@ -205,6 +206,17 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
headers?: Record<string, string>;
payload: ResponseCreateParamsWithPromptCacheKey;
};
+ /**
+ * How this provider declares tools that became available mid-conversation
+ * (`OpenAIChatMessage.toolsAdded`), for the model the request targets. Leave it
+ * unset, or return `undefined`, to keep every tool in the top-level list.
+ */
+ toolAnchoring?: (context: {
+ /** Endpoint the request is sent to. */
+ baseURL?: string;
+ /** Upstream model id, after `modelIdMapping`. */
+ model: string;
+ }) => ResponsesToolAnchoringMode | undefined;
};
videoGenerationCapabilities?:
VideoGenerationCapabilities | ((model: string) => VideoGenerationCapabilities);
diff --git a/packages/model-runtime/src/core/openaiCompatible/toolAnchoring.test.ts b/packages/model-runtime/src/core/openaiCompatible/toolAnchoring.test.ts
new file mode 100644
index 00000000000..2d2850582a3
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatible/toolAnchoring.test.ts
@@ -0,0 +1,231 @@
+// @vitest-environment node
+import type OpenAI from 'openai';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { LobeChatGPTAI } from '../../providers/chatGPT';
+import { LobeOpenAI } from '../../providers/openai';
+import type { ChatCompletionTool, OpenAIChatMessage } from '../../types';
+
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+
+const fn = (name: string): ChatCompletionTool => ({
+ function: { description: `${name} tool`, name, parameters: { properties: {}, type: 'object' } },
+ type: 'function',
+});
+
+const activator = fn('lobe-activator____activateTools');
+const search = fn('lobe-web-browsing____search');
+const notion = fn('notion____createPage____mcp');
+
+const closedStream = () =>
+ new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ });
+
+/**
+ * One agent run that activates a tool at step 1 and an MCP tool at step 3. Each entry
+ * is the request the runtime receives at that step: the conversation so far, plus every
+ * tool resolved for the step (the activated ones appended, as `ToolResolver` does).
+ */
+const buildRun = (): Array<{ messages: OpenAIChatMessage[]; tools: ChatCompletionTool[] }> => {
+ const turn1: OpenAIChatMessage[] = [
+ { content: 'You are a helpful assistant.', role: 'system' },
+ { content: 'Find the release notes and file them in Notion.', role: 'user' },
+ ];
+ const turn2: OpenAIChatMessage[] = [
+ ...turn1,
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{"tools":["lobe-web-browsing"]}', name: activator.function.name },
+ id: 'call_activate_search',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'Successfully activated tools: lobe-web-browsing.search.',
+ role: 'tool',
+ tool_call_id: 'call_activate_search',
+ toolsAdded: [search.function.name],
+ },
+ ];
+ const turn3: OpenAIChatMessage[] = [
+ ...turn2,
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{"query":"release notes"}', name: search.function.name },
+ id: 'call_search',
+ type: 'function',
+ },
+ ],
+ },
+ { content: 'Release notes: ...', role: 'tool', tool_call_id: 'call_search' },
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{"tools":["notion"]}', name: activator.function.name },
+ id: 'call_activate_notion',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'Successfully activated tools: notion.createPage.',
+ role: 'tool',
+ tool_call_id: 'call_activate_notion',
+ toolsAdded: [notion.function.name],
+ },
+ ];
+
+ return [
+ { messages: turn1, tools: [activator] },
+ { messages: turn2, tools: [activator, search] },
+ { messages: turn3, tools: [activator, search, notion] },
+ ];
+};
+
+type ResponsesRequest = {
+ input: OpenAI.Responses.ResponseInputItem[];
+ tools?: OpenAI.Responses.Tool[];
+};
+
+const captureRun = async (
+ runtime: LobeOpenAI | LobeChatGPTAI,
+ model: string,
+): Promise<ResponsesRequest[]> => {
+ const create = vi
+ .spyOn((runtime as any).client.responses, 'create')
+ .mockImplementation(async () => closedStream() as never);
+
+ for (const step of buildRun()) {
+ const response = await runtime.chat({ ...step, model, stream: true } as any);
+ await response.text();
+ }
+
+ return create.mock.calls.map(([request]) => request as ResponsesRequest);
+};
+
+/** Each request must only append to the one before it, or the prompt cache is lost. */
+const expectGrowingPrefix = (requests: ResponsesRequest[]) => {
+ for (let index = 1; index < requests.length; index++) {
+ const previous = requests[index - 1];
+ const current = requests[index];
+
+ expect(current.tools).toEqual(previous.tools);
+ expect(current.input.slice(0, previous.input.length)).toEqual(previous.input);
+ }
+};
+
+const toolNames = (tools: OpenAI.Responses.Tool[] | undefined) =>
+ (tools ?? []).map((tool) => (tool as { name?: string }).name);
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe('Responses tool anchoring', () => {
+ it.each(['gpt-5.6-sol', 'gpt-6-luna', 'gpt-6.1-sol', 'gpt-6.2-astra'])(
+ 'keeps the request prefix stable when %s activates tools mid-run',
+ async (model) => {
+ const requests = await captureRun(new LobeOpenAI({ apiKey: 'test' }), model);
+
+ expectGrowingPrefix(requests);
+ for (const request of requests) {
+ expect(toolNames(request.tools)).toEqual([activator.function.name]);
+ }
+
+ const declared = requests
+ .at(-1)!
+ .input.filter((item) => item.type === 'additional_tools')
+ .map((item) =>
+ toolNames((item as OpenAI.Responses.ResponseInputItem.AdditionalTools).tools),
+ );
+ expect(declared).toEqual([[search.function.name], [notion.function.name]]);
+ },
+ );
+
+ it('anchors with a client tool search exchange when the operator asks for it', async () => {
+ vi.stubEnv('OPENAI_RESPONSES_TOOL_ANCHORING', 'tool_search');
+
+ const requests = await captureRun(
+ new LobeOpenAI({ apiKey: 'test', baseURL: 'https://relay.example.com/v1' }),
+ 'gpt-6.1-sol',
+ );
+
+ expectGrowingPrefix(requests);
+ const last = requests.at(-1)!;
+ expect(toolNames(last.tools)).toEqual([activator.function.name]);
+ expect(last.input.some((item) => item.type === 'additional_tools')).toBe(false);
+ expect(
+ last.input
+ .filter((item) => item.type === 'tool_search_output')
+ .map((item) => (item as OpenAI.Responses.ResponseToolSearchOutputItemParam).tools),
+ ).toEqual([
+ [expect.objectContaining({ defer_loading: true, name: search.function.name })],
+ [expect.objectContaining({ defer_loading: true, name: notion.function.name })],
+ ]);
+ // Every output answers the call right before it.
+ const callIds = last.input
+ .filter((item) => item.type === 'tool_search_call' || item.type === 'tool_search_output')
+ .map((item) => (item as { call_id?: string }).call_id);
+ expect(callIds).toEqual([
+ 'lobe_tool_load_call_activate_search',
+ 'lobe_tool_load_call_activate_search',
+ 'lobe_tool_load_call_activate_notion',
+ 'lobe_tool_load_call_activate_notion',
+ ]);
+ });
+
+ it.each([
+ ['a model older than GPT-5.6', 'gpt-5.5', {}, undefined],
+ ['a relay endpoint', 'gpt-6.1-sol', { baseURL: 'https://relay.example.com/v1' }, undefined],
+ ['an operator opt-out', 'gpt-6.1-sol', {}, '0'],
+ ])('keeps every tool in the top-level list for %s', async (_case, model, options, override) => {
+ if (override) vi.stubEnv('OPENAI_RESPONSES_TOOL_ANCHORING', override);
+
+ const requests = await captureRun(new LobeOpenAI({ apiKey: 'test', ...options }), model);
+
+ expect(requests.map((request) => toolNames(request.tools))).toEqual([
+ [activator.function.name],
+ [activator.function.name, search.function.name],
+ [activator.function.name, search.function.name, notion.function.name],
+ ]);
+ const wire = JSON.stringify(requests);
+ expect(wire).not.toContain('additional_tools');
+ expect(wire).not.toContain('tool_search');
+ expect(wire).not.toContain('toolsAdded');
+ });
+
+ it('keeps the Codex backend prefix stable, Responses Lite included', async () => {
+ for (const model of ['gpt-5.6-sol', 'gpt-6.1-sol']) {
+ const requests = await captureRun(
+ new LobeChatGPTAI({ apiKey: 'test', chatgptAccountId: 'test' }),
+ model,
+ );
+
+ expectGrowingPrefix(requests);
+ const declared = requests
+ .at(-1)!
+ .input.filter((item) => item.type === 'additional_tools')
+ .flatMap((item) =>
+ toolNames((item as OpenAI.Responses.ResponseInputItem.AdditionalTools).tools),
+ );
+ // Responses Lite also moves the base tools into a leading additional_tools item.
+ expect(declared.slice(-2)).toEqual([search.function.name, notion.function.name]);
+ expect(declared).not.toHaveLength(0);
+ }
+ });
+});
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts b/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts
index 7495e4590ca..ec6af988c34 100644
--- a/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts
@@ -2,7 +2,7 @@ import debug from 'debug';
import type OpenAI from 'openai';
import type { Stream } from 'openai/streaming';
-import type { ChatMethodOptions, ChatStreamPayload } from '../../../types';
+import type { ChatMethodOptions, ChatStreamPayload, OpenAIChatMessage } from '../../../types';
import { debugPayload, debugResponse, debugStream } from '../../../utils/debugStream';
import { desensitizeUrl } from '../../../utils/desensitizeUrl';
import { getModelPricing } from '../../../utils/getModelPricing';
@@ -26,6 +26,7 @@ import type { OpenAIStreamOptions } from '../openaiChatCompletions/stream';
import { convertOpenAIResponseInputs } from './inputs';
import { transformResponseAPIToStream } from './nonStreamToStream';
import { OpenAIResponsesStream } from './stream';
+import { prepareAnchoredMessages, splitAnchoredTools } from './toolAnchoring';
import { convertChatCompletionToolToResponseTool, stripChatCompletionParameters } from './tools';
export const chatViaResponses = async (
@@ -60,12 +61,26 @@ export const chatViaResponses = async (
'responses',
);
- const input = await convertOpenAIResponseInputs(messages as any, {
+ // Native Responses tools are forwarded verbatim; only function tools of our own
+ // conversation are anchored.
+ const toolAnchoringMode = responsesTools
+ ? undefined
+ : factory.responses?.toolAnchoring?.({ baseURL: runtime.baseURL, model: requestModel });
+ const inputMessages = toolAnchoringMode
+ ? prepareAnchoredMessages(messages as OpenAIChatMessage[], tools, options?.toolActivationPlan)
+ : (messages as OpenAIChatMessage[]);
+ const { anchored, requestTools } = toolAnchoringMode
+ ? splitAnchoredTools(inputMessages, tools, { strictToolPairing: true })
+ : { anchored: undefined, requestTools: tools };
+
+ const input = await convertOpenAIResponseInputs(inputMessages, {
forceImageBase64: factory.chatCompletion?.forceImageBase64,
forceVideoBase64: factory.chatCompletion?.forceVideoBase64,
provider: runtime.id,
reasoningSignatureScope,
strictToolPairing: true,
+ ...(toolAnchoringMode &&
+ anchored && { toolAnchors: { byMessageIndex: anchored, mode: toolAnchoringMode } }),
});
const isStreaming = payload.stream !== false;
@@ -90,7 +105,7 @@ export const chatViaResponses = async (
...(max_tokens && { max_output_tokens: max_tokens }),
store: false,
stream: isStreaming || undefined,
- tools: responsesTools ?? tools?.map(convertChatCompletionToolToResponseTool),
+ tools: responsesTools ?? requestTools?.map(convertChatCompletionToolToResponseTool),
...runtime.resolvePromptCacheKeyParams(
res.model,
options?.user,
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts
index e082c6d04cc..0d30689cd7c 100644
--- a/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts
@@ -8,37 +8,20 @@ import {
isInternalThinkingContentPart,
type OpenAICompatibleContentPart,
} from '../../contextBuilders/openai';
+import { buildAnchoredToolItems, type ResponsesToolAnchors } from './toolAnchoring';
+import { collectToolCallPairing } from './toolPairing';
+
+export interface ConvertOpenAIResponseInputsOptions extends ConvertMessageContentOptions {
+ /** Tools to declare inside the conversation, at the message that introduced them. */
+ toolAnchors?: ResponsesToolAnchors;
+}
export const convertOpenAIResponseInputs = async (
messages: OpenAIChatMessage[],
- options?: ConvertMessageContentOptions,
+ options?: ConvertOpenAIResponseInputsOptions,
) => {
const strictToolPairing = options?.strictToolPairing === true;
- // OpenAI Responses API rejects inputs that keep a function_call without its matching
- // function_call_output. Example from production:
- // "No tool output found for function call call_w5odMFjtXEYBBVyBUAQNMOh5."
- const validToolCallIds = new Set<string>();
- const pairedToolOutputIds = new Set<string>();
- const customToolCallIds = new Set<string>();
-
- for (const message of messages) {
- if (message.role === 'assistant' && message.tool_calls?.length) {
- message.tool_calls.forEach((tool) => {
- if (tool.id) validToolCallIds.add(tool.id);
- if (tool.id && tool.type === 'custom') customToolCallIds.add(tool.id);
- });
- }
- }
-
- for (const message of messages) {
- if (
- message.role === 'tool' &&
- message.tool_call_id &&
- validToolCallIds.has(message.tool_call_id)
- ) {
- pairedToolOutputIds.add(message.tool_call_id);
- }
- }
+ const { customToolCallIds, pairedToolOutputIds } = collectToolCallPairing(messages);
const inputGroups = await Promise.all(
messages.map(async (message) => {
@@ -224,7 +207,8 @@ export const convertOpenAIResponseInputs = async (
}
if (message.role === 'system') {
- items.push({ ...message, role: 'developer' } as OpenAI.Responses.ResponseInputItem);
+ const { toolsAdded: _toolsAdded, ...systemMessage } = message;
+ items.push({ ...systemMessage, role: 'developer' } as OpenAI.Responses.ResponseInputItem);
return items;
}
@@ -299,6 +283,7 @@ export const convertOpenAIResponseInputs = async (
model: _model,
provider: _provider,
reasoning: _reasoning,
+ toolsAdded: _toolsAdded,
...responseMessage
} = message;
const item = {
@@ -311,5 +296,34 @@ export const convertOpenAIResponseInputs = async (
}),
);
- return inputGroups.flat();
+ const toolAnchors = options?.toolAnchors;
+ if (!toolAnchors || toolAnchors.byMessageIndex.size === 0) return inputGroups.flat();
+
+ // Declare anchored tools after the message that introduced them. A tool message waits
+ // for the rest of its batch, so the declaration never splits the outputs of one turn.
+ const input: OpenAI.Responses.ResponseInputItem[] = [];
+ let pendingAnchorItems: OpenAI.Responses.ResponseInputItem[] = [];
+
+ messages.forEach((message, index) => {
+ input.push(...inputGroups[index]);
+
+ const tools = toolAnchors.byMessageIndex.get(index);
+ if (tools?.length) {
+ pendingAnchorItems.push(
+ ...buildAnchoredToolItems(
+ toolAnchors.mode,
+ tools,
+ message.tool_call_id ?? `message_${index}`,
+ ),
+ );
+ }
+
+ const batchContinues = message.role === 'tool' && messages[index + 1]?.role === 'tool';
+ if (pendingAnchorItems.length > 0 && !batchContinues) {
+ input.push(...pendingAnchorItems);
+ pendingAnchorItems = [];
+ }
+ });
+
+ return input;
};
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/toolAnchoring.test.ts b/packages/model-runtime/src/core/protocols/openaiResponses/toolAnchoring.test.ts
new file mode 100644
index 00000000000..3970f24acaf
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/toolAnchoring.test.ts
@@ -0,0 +1,245 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ChatCompletionTool, OpenAIChatMessage } from '../../../types';
+import { convertOpenAIResponseInputs } from './inputs';
+import {
+ buildAnchoredToolItems,
+ INCREMENTAL_TOOLS_NOTICE,
+ prepareAnchoredMessages,
+ resolveOpenAIToolAnchoring,
+ splitAnchoredTools,
+} from './toolAnchoring';
+
+const fn = (name: string): ChatCompletionTool => ({
+ function: { description: `${name} tool`, name, parameters: { properties: {}, type: 'object' } },
+ type: 'function',
+});
+
+const activator = fn('lobe-activator____activateTools');
+const search = fn('lobe-web-browsing____search');
+const crawl = fn('lobe-web-browsing____crawlSinglePage');
+const notion = fn('notion____createPage____mcp');
+
+const activation = (
+ id: string,
+ toolsAdded: string[],
+ extraCalls: string[] = [],
+): OpenAIChatMessage[] => [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [id, ...extraCalls].map((callId) => ({
+ function: { arguments: '{}', name: activator.function.name },
+ id: callId,
+ type: 'function' as const,
+ })),
+ },
+ { content: 'Successfully activated tools.', role: 'tool', tool_call_id: id, toolsAdded },
+ ...extraCalls.map((callId): OpenAIChatMessage => ({
+ content: 'ok',
+ role: 'tool',
+ tool_call_id: callId,
+ })),
+];
+
+describe('prepareAnchoredMessages', () => {
+ it('keeps the canonical prompt when one schema in an activation batch is filtered out', () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'system', content: 'Tool guidance' },
+ ...activation('call', []),
+ ];
+ messages[2].toolActivationPlan = {
+ results: [
+ {
+ callId: 'call',
+ content: 'Activated tools and guidance',
+ toolNames: [search.function.name, crawl.function.name],
+ },
+ ],
+ system: { start: 0, original: 'Tool guidance', replacement: '' },
+ };
+ expect(prepareAnchoredMessages(messages, [search])).toBe(messages);
+ });
+});
+
+describe('splitAnchoredTools', () => {
+ it('keeps every tool at the top level when no message announces one', () => {
+ const tools = [activator, search];
+ const result = splitAnchoredTools([{ content: 'hi', role: 'user' }], tools);
+
+ expect(result.requestTools).toBe(tools);
+ expect(result.anchored.size).toBe(0);
+ });
+
+ it('moves announced tools out of the top-level list, at the message that announced them', () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'find it', role: 'user' },
+ ...activation('call_1', [search.function.name, crawl.function.name]),
+ ];
+
+ const result = splitAnchoredTools(messages, [activator, search, crawl]);
+
+ expect(result.requestTools).toEqual([activator]);
+ expect([...result.anchored]).toEqual([[2, [search, crawl]]]);
+ });
+
+ it('anchors a tool once, at the first message that announces it', () => {
+ const messages: OpenAIChatMessage[] = [
+ ...activation('call_1', [search.function.name]),
+ ...activation('call_2', [search.function.name, notion.function.name]),
+ ];
+
+ const result = splitAnchoredTools(messages, [activator, search, notion]);
+
+ expect([...result.anchored]).toEqual([
+ [1, [search]],
+ [3, [notion]],
+ ]);
+ });
+
+ it('leaves a tool at the top level when its announcing message is dropped as unpaired', () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'orphan', role: 'tool', tool_call_id: 'gone', toolsAdded: [search.function.name] },
+ ];
+
+ const strict = splitAnchoredTools(messages, [activator, search], { strictToolPairing: true });
+ expect(strict.requestTools).toEqual([activator, search]);
+ expect(strict.anchored.size).toBe(0);
+
+ const loose = splitAnchoredTools(messages, [activator, search]);
+ expect(loose.requestTools).toEqual([activator]);
+ });
+
+ it('ignores announced names that are not offered this step', () => {
+ const messages = activation('call_1', [search.function.name, 'removed____tool']);
+
+ const result = splitAnchoredTools(messages, [activator, search]);
+
+ expect([...result.anchored]).toEqual([[1, [search]]]);
+ });
+
+ it('keeps non-function tools at the top level', () => {
+ const webSearch = { type: 'web_search' };
+ const messages = activation('call_1', [search.function.name]);
+
+ const result = splitAnchoredTools(messages, [activator, webSearch, search]);
+
+ expect(result.requestTools).toEqual([activator, webSearch]);
+ });
+});
+
+describe('buildAnchoredToolItems', () => {
+ it('declares additional_tools behind the incremental notice', () => {
+ expect(buildAnchoredToolItems('additional_tools', [search], 'call_1')).toEqual([
+ { content: INCREMENTAL_TOOLS_NOTICE, role: 'developer' },
+ {
+ role: 'developer',
+ tools: [
+ {
+ description: 'lobe-web-browsing____search tool',
+ name: 'lobe-web-browsing____search',
+ parameters: { properties: {}, type: 'object' },
+ type: 'function',
+ },
+ ],
+ type: 'additional_tools',
+ },
+ ]);
+ });
+
+ it('declares a completed client tool search carrying deferred definitions', () => {
+ const [call, output] = buildAnchoredToolItems('tool_search', [search, crawl], 'toolu:01/a b');
+
+ expect(call).toEqual({
+ arguments: {
+ limit: 2,
+ query: 'lobe-web-browsing____search lobe-web-browsing____crawlSinglePage',
+ },
+ call_id: 'lobe_tool_load_toolu_01_a_b',
+ execution: 'client',
+ status: 'completed',
+ type: 'tool_search_call',
+ });
+ expect(output).toMatchObject({
+ call_id: 'lobe_tool_load_toolu_01_a_b',
+ execution: 'client',
+ status: 'completed',
+ tools: [
+ { defer_loading: true, name: 'lobe-web-browsing____search', type: 'function' },
+ { defer_loading: true, name: 'lobe-web-browsing____crawlSinglePage', type: 'function' },
+ ],
+ type: 'tool_search_output',
+ });
+ });
+});
+
+describe('convertOpenAIResponseInputs with tool anchors', () => {
+ it('declares the tools after the tool batch that activated them', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'find it', role: 'user' },
+ ...activation('call_1', [search.function.name], ['call_2']),
+ { content: 'next', role: 'user' },
+ ];
+ const { anchored } = splitAnchoredTools(messages, [activator, search], {
+ strictToolPairing: true,
+ });
+
+ const input = await convertOpenAIResponseInputs(messages, {
+ strictToolPairing: true,
+ toolAnchors: { byMessageIndex: anchored, mode: 'additional_tools' },
+ });
+
+ expect(input.map((item: any) => item.type ?? item.role)).toEqual([
+ 'user',
+ 'function_call',
+ 'function_call',
+ 'function_call_output',
+ 'function_call_output',
+ 'developer',
+ 'additional_tools',
+ 'user',
+ ]);
+ // The annotation is ours; it never reaches the wire.
+ expect(JSON.stringify(input)).not.toContain('toolsAdded');
+ });
+
+ it('emits nothing extra without anchors', async () => {
+ const messages = activation('call_1', [search.function.name]);
+
+ const input = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
+
+ expect(input.map((item: any) => item.type)).toEqual(['function_call', 'function_call_output']);
+ expect(JSON.stringify(input)).not.toContain('toolsAdded');
+ });
+});
+
+describe('resolveOpenAIToolAnchoring', () => {
+ it.each([
+ [undefined, 'additional_tools'],
+ ['https://api.openai.com/v1', 'additional_tools'],
+ ['https://relay.example.com/v1', undefined],
+ ['not a url', undefined],
+ ])('anchors on the official endpoint only by default (%s)', (baseURL, expected) => {
+ expect(resolveOpenAIToolAnchoring({ baseURL, isSupportedModel: true })).toBe(expected);
+ });
+
+ it.each([
+ ['0', undefined],
+ ['off', undefined],
+ ['1', 'additional_tools'],
+ ['additional_tools', 'additional_tools'],
+ ['tool_search', 'tool_search'],
+ ])('lets the operator override the endpoint default (%s)', (override, expected) => {
+ for (const baseURL of ['https://api.openai.com/v1', 'https://relay.example.com/v1']) {
+ expect(resolveOpenAIToolAnchoring({ baseURL, isSupportedModel: true, override })).toBe(
+ expected,
+ );
+ }
+ });
+
+ it('never anchors for a model that cannot take in-conversation tools', () => {
+ expect(
+ resolveOpenAIToolAnchoring({ isSupportedModel: false, override: 'additional_tools' }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/toolAnchoring.ts b/packages/model-runtime/src/core/protocols/openaiResponses/toolAnchoring.ts
new file mode 100644
index 00000000000..0dde2887156
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/toolAnchoring.ts
@@ -0,0 +1,269 @@
+import type { ToolActivationPlan } from '@lobechat/types';
+import type OpenAI from 'openai';
+
+import type { ChatCompletionTool, OpenAIChatMessage } from '../../../types';
+import { collectToolCallPairing } from './toolPairing';
+import { convertChatCompletionToolToResponseTool } from './tools';
+
+/**
+ * How a Responses transport declares a tool that became available mid-conversation.
+ *
+ * OpenAI renders the top-level `tools` list ahead of the whole input, so appending a tool
+ * there changes the first tokens of the prompt and every later token misses the prompt
+ * cache. Both modes leave that list alone and declare the new tools at the message that
+ * introduced them, which only ever appends to the request:
+ *
+ * - `additional_tools`: a developer `additional_tools` input item. A later item adds tools
+ * to the ones already declared.
+ * - `tool_search`: a client-executed tool search exchange (`tool_search_call` answered by
+ * `tool_search_output`) carrying the tools as deferred definitions. For endpoints that
+ * do not pass `additional_tools` through.
+ *
+ * Neither mode can remove a tool or replace a top-level definition, so only additions are
+ * anchored; a tool whose anchor left the conversation falls back to the top-level list.
+ *
+ * @see https://github.com/earendil-works/pi/issues/10940
+ */
+export type ResponsesToolAnchoringMode = 'additional_tools' | 'tool_search';
+
+export interface ResponsesToolAnchors {
+ /** Tools first declared at a message, keyed by that message's index. */
+ byMessageIndex: Map<number, ChatCompletionTool[]>;
+ mode: ResponsesToolAnchoringMode;
+}
+
+export interface AnchoredToolSplit<T> {
+ /** Tools declared inside the conversation, keyed by the index of their message. */
+ anchored: Map<number, ChatCompletionTool[]>;
+ /** Tools that stay in the top-level request field, in their original order. */
+ requestTools: T[] | undefined;
+}
+
+const getFunctionName = (tool: unknown): string | undefined => {
+ const candidate = tool as Partial<ChatCompletionTool> | undefined;
+ return candidate?.type === 'function' ? candidate.function?.name : undefined;
+};
+
+/**
+ * Split the request's tools between the top-level field and the messages that announce
+ * them through `toolsAdded`.
+ *
+ * A name is anchored at the first message that announces it, and only when that message
+ * is actually sent: an unpaired tool message is dropped under strict pairing, and a tool
+ * anchored there would otherwise be declared nowhere. Names that are not in `tools`
+ * (filtered for this step, uninstalled since) are ignored.
+ */
+export const splitAnchoredTools = <T>(
+ messages: OpenAIChatMessage[],
+ tools: T[] | undefined,
+ options?: { strictToolPairing?: boolean },
+): AnchoredToolSplit<T> => {
+ const anchored = new Map<number, ChatCompletionTool[]>();
+ if (!tools?.length || !messages.some((message) => message.toolsAdded?.length)) {
+ return { anchored, requestTools: tools };
+ }
+
+ const toolsByName = new Map<string, ChatCompletionTool>();
+ for (const tool of tools) {
+ const name = getFunctionName(tool);
+ if (name && !toolsByName.has(name)) toolsByName.set(name, tool as ChatCompletionTool);
+ }
+
+ const pairing = options?.strictToolPairing ? collectToolCallPairing(messages) : undefined;
+ const anchoredNames = new Set<string>();
+
+ messages.forEach((message, index) => {
+ if (!message.toolsAdded?.length) return;
+ if (
+ pairing &&
+ message.role === 'tool' &&
+ (!message.tool_call_id || !pairing.pairedToolOutputIds.has(message.tool_call_id))
+ )
+ return;
+
+ const added: ChatCompletionTool[] = [];
+ for (const name of message.toolsAdded) {
+ const tool = toolsByName.get(name);
+ if (!tool || anchoredNames.has(name)) continue;
+ anchoredNames.add(name);
+ added.push(tool);
+ }
+ if (added.length > 0) anchored.set(index, added);
+ });
+
+ if (anchoredNames.size === 0) return { anchored, requestTools: tools };
+
+ const requestTools = tools.filter((tool) => {
+ const name = getFunctionName(tool);
+ return !name || !anchoredNames.has(name);
+ });
+
+ return { anchored, requestTools: requestTools.length > 0 ? requestTools : undefined };
+};
+
+/**
+ * Apply a context-engine plan as one edit, after the runtime has selected its
+ * endpoint and tool set. Revalidate the system span and every target because
+ * callers can filter messages/tools between context assembly and dispatch.
+ */
+export const prepareAnchoredMessages = <T>(
+ messages: OpenAIChatMessage[],
+ tools: T[] | undefined,
+ plan: ToolActivationPlan | undefined = messages.find(
+ (message) => message.role === 'tool' && message.toolActivationPlan,
+ )?.toolActivationPlan,
+) => {
+ if (!plan?.results.length || !tools?.length) return messages;
+ const systemIndex = messages.findIndex((message) =>
+ ['system', 'developer'].includes(message.role),
+ );
+ let editedSystem: string | undefined;
+ if (plan.system) {
+ const system = messages[systemIndex]?.content;
+ const { original, replacement, start } = plan.system;
+ if (
+ typeof system !== 'string' ||
+ !original ||
+ !Number.isInteger(start) ||
+ start < 0 ||
+ !system.startsWith(original, start)
+ )
+ return messages;
+ editedSystem = system.slice(0, start) + replacement + system.slice(start + original.length);
+ }
+ const available = new Set(tools.map(getFunctionName));
+ const byCallId = new Map(plan.results.map((result) => [result.callId, result]));
+ const { pairedToolOutputIds } = collectToolCallPairing(
+ messages.filter((message) => !message.responsesTools && message.responsesOutput === undefined),
+ );
+ for (const result of plan.results) {
+ if (
+ !pairedToolOutputIds.has(result.callId) ||
+ !result.toolNames.length ||
+ !result.toolNames.every((name) => available.has(name))
+ )
+ return messages;
+ }
+ return messages.flatMap((message, index): OpenAIChatMessage[] => {
+ if (index === systemIndex && editedSystem !== undefined)
+ return editedSystem ? [{ ...message, content: editedSystem }] : [];
+ const result =
+ message.role === 'tool' && message.tool_call_id
+ ? byCallId.get(message.tool_call_id)
+ : undefined;
+ return result
+ ? [{ ...message, content: result.content, toolsAdded: result.toolNames }]
+ : [message];
+ });
+};
+
+/**
+ * Precedes every anchored `additional_tools` item. Without it a model can read the item as
+ * the complete tool set and stop calling the tools declared before it; Codex precedes its
+ * incremental tool batches with the same guidance.
+ */
+export const INCREMENTAL_TOOLS_NOTICE =
+ 'This is an incremental tools update. Previously declared tools remain available, and the tools declared next are available in addition to them.';
+
+/**
+ * A tool search call id must be stable across requests, or the anchored items change and
+ * the cached prefix with them. Derive it from the message that introduced the tools.
+ */
+const buildToolSearchCallId = (anchorId: string) =>
+ `lobe_tool_load_${anchorId.replaceAll(/[^\w-]/g, '_').slice(0, 48)}`;
+
+/**
+ * The input items that declare `tools` at their anchor.
+ *
+ * @param anchorId stable id of the message that introduced the tools
+ */
+export const buildAnchoredToolItems = (
+ mode: ResponsesToolAnchoringMode,
+ tools: ChatCompletionTool[],
+ anchorId: string,
+): OpenAI.Responses.ResponseInputItem[] => {
+ const responseTools = tools.map(convertChatCompletionToolToResponseTool);
+
+ if (mode === 'additional_tools') {
+ return [
+ { content: INCREMENTAL_TOOLS_NOTICE, role: 'developer' },
+ { role: 'developer', tools: responseTools, type: 'additional_tools' },
+ ];
+ }
+
+ const names = tools.map((tool) => tool.function.name);
+ const callId = buildToolSearchCallId(anchorId);
+
+ return [
+ {
+ arguments: { limit: names.length, query: names.join(' ') },
+ call_id: callId,
+ execution: 'client',
+ status: 'completed',
+ type: 'tool_search_call',
+ },
+ {
+ call_id: callId,
+ execution: 'client',
+ status: 'completed',
+ // Tool search returns deferred definitions; a result without the flag is rejected.
+ tools: responseTools.map(
+ (tool) => ({ ...tool, defer_loading: true }) as OpenAI.Responses.Tool,
+ ),
+ type: 'tool_search_output',
+ },
+ ];
+};
+
+const OFFICIAL_OPENAI_HOST = 'api.openai.com';
+
+const isOfficialOpenAIEndpoint = (baseURL: string | undefined) => {
+ if (!baseURL) return true;
+
+ try {
+ return new URL(baseURL).hostname === OFFICIAL_OPENAI_HOST;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Tool anchoring for a runtime that talks to OpenAI's public Responses API, possibly
+ * through a relay the user configured.
+ *
+ * A relay may validate or translate the request, and one that does not know the
+ * `additional_tools` item fails the whole chat, so only the official endpoint anchors by
+ * default. `override` (the `OPENAI_RESPONSES_TOOL_ANCHORING` env) is the operator's
+ * answer for everything else: `0` turns anchoring off, `additional_tools` or
+ * `tool_search` forces that mode for any endpoint.
+ */
+export const resolveOpenAIToolAnchoring = ({
+ baseURL,
+ isSupportedModel,
+ override,
+}: {
+ baseURL?: string;
+ isSupportedModel: boolean;
+ override?: string;
+}): ResponsesToolAnchoringMode | undefined => {
+ if (!isSupportedModel) return undefined;
+
+ switch (override?.trim().toLowerCase()) {
+ case '0':
+ case 'false':
+ case 'off': {
+ return undefined;
+ }
+ case '1':
+ case 'true':
+ case 'additional_tools': {
+ return 'additional_tools';
+ }
+ case 'tool_search': {
+ return 'tool_search';
+ }
+ default: {
+ return isOfficialOpenAIEndpoint(baseURL) ? 'additional_tools' : undefined;
+ }
+ }
+};
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/toolPairing.ts b/packages/model-runtime/src/core/protocols/openaiResponses/toolPairing.ts
new file mode 100644
index 00000000000..2a293d92c4b
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/toolPairing.ts
@@ -0,0 +1,42 @@
+import type { OpenAIChatMessage } from '../../../types';
+
+export interface ToolCallPairing {
+ /** Ids of free-form (`custom`) tool calls, whose outputs use the custom output item. */
+ customToolCallIds: Set<string>;
+ /** Ids of tool calls that have a tool message answering them. */
+ pairedToolOutputIds: Set<string>;
+}
+
+/**
+ * Match assistant tool calls with the tool messages that answer them.
+ *
+ * The Responses API rejects an input that keeps a `function_call` without its
+ * `function_call_output`. Example from production:
+ * "No tool output found for function call call_w5odMFjtXEYBBVyBUAQNMOh5."
+ */
+export const collectToolCallPairing = (messages: OpenAIChatMessage[]): ToolCallPairing => {
+ const validToolCallIds = new Set<string>();
+ const pairedToolOutputIds = new Set<string>();
+ const customToolCallIds = new Set<string>();
+
+ for (const message of messages) {
+ if (message.role === 'assistant' && message.tool_calls?.length) {
+ message.tool_calls.forEach((tool) => {
+ if (tool.id) validToolCallIds.add(tool.id);
+ if (tool.id && tool.type === 'custom') customToolCallIds.add(tool.id);
+ });
+ }
+ }
+
+ for (const message of messages) {
+ if (
+ message.role === 'tool' &&
+ message.tool_call_id &&
+ validToolCallIds.has(message.tool_call_id)
+ ) {
+ pairedToolOutputIds.add(message.tool_call_id);
+ }
+ }
+
+ return { customToolCallIds, pairedToolOutputIds };
+};
diff --git a/packages/model-runtime/src/providers/chatGPT/index.ts b/packages/model-runtime/src/providers/chatGPT/index.ts
index 6fc0bfcff3b..d238f9b613e 100644
--- a/packages/model-runtime/src/providers/chatGPT/index.ts
+++ b/packages/model-runtime/src/providers/chatGPT/index.ts
@@ -4,6 +4,7 @@ import OpenAI from 'openai';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatible';
import { params as openAIParams } from '../openai';
+import { isToolAnchoringGPTModel } from '../openai/modelId';
const CHATGPT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex';
const CHATGPT_RESPONSES_LITE_HEADER = 'x-openai-internal-codex-responses-lite';
@@ -150,5 +151,8 @@ export const LobeChatGPTAI = createOpenAICompatibleRuntime<ChatGPTClientOptions>
},
};
},
+ // The Codex backend is the endpoint Codex itself loads tools through with
+ // `additional_tools`, so there is no relay to second-guess.
+ toolAnchoring: ({ model }) => (isToolAnchoringGPTModel(model) ? 'additional_tools' : undefined),
},
});
diff --git a/packages/model-runtime/src/providers/openai/index.ts b/packages/model-runtime/src/providers/openai/index.ts
index 0b33e5313c9..2d0d8c1836c 100644
--- a/packages/model-runtime/src/providers/openai/index.ts
+++ b/packages/model-runtime/src/providers/openai/index.ts
@@ -3,6 +3,7 @@ import { ModelProvider, openaiChatModels } from 'model-bank';
import { pruneReasoningPayload } from '../../core/contextBuilders/openai';
import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatible';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatible';
+import { resolveOpenAIToolAnchoring } from '../../core/protocols/openaiResponses/toolAnchoring';
import type { ChatStreamPayload } from '../../types';
import { processMultiProviderModelList } from '../../utils/modelParse';
import { appendDecisionModels } from '../../utils/postProcessModelList';
@@ -11,6 +12,7 @@ import {
isOpenAIComputerUseModel,
isOpenAIReasoningPayloadModel,
isResponsesAPIModel,
+ isToolAnchoringGPTModel,
supportsOpenAIServiceTierFlex,
} from './modelId';
@@ -139,6 +141,13 @@ export const params = {
tools: openaiTools,
} as any;
},
+ // Read the env per request so an operator's override applies without a rebuild.
+ toolAnchoring: ({ baseURL, model }) =>
+ resolveOpenAIToolAnchoring({
+ baseURL,
+ isSupportedModel: isToolAnchoringGPTModel(model),
+ override: process.env.OPENAI_RESPONSES_TOOL_ANCHORING,
+ }),
},
} satisfies OpenAICompatibleFactoryOptions;
diff --git a/packages/model-runtime/src/providers/openai/modelId.test.ts b/packages/model-runtime/src/providers/openai/modelId.test.ts
index 5ea88eb0dd4..4f759582848 100644
--- a/packages/model-runtime/src/providers/openai/modelId.test.ts
+++ b/packages/model-runtime/src/providers/openai/modelId.test.ts
@@ -6,6 +6,7 @@ import {
isOpenAIComputerUseModel,
isOpenAIReasoningPayloadModel,
isResponsesAPIModel,
+ isToolAnchoringGPTModel,
parseOpenAIModelId,
supportsGPTResponsesReasoningEffortNone,
supportsOpenAIServiceTierFlex,
@@ -235,3 +236,32 @@ describe('supportsOpenAIServiceTierFlex', () => {
expect(supportsOpenAIServiceTierFlex('gpt-4o')).toBe(false);
});
});
+
+describe('isToolAnchoringGPTModel', () => {
+ it.each([
+ 'gpt-5.6-sol',
+ 'gpt-5.6-luna',
+ 'gpt-6-astra',
+ 'gpt-6.1-terra',
+ 'gpt-6.2-sol',
+ 'codex/gpt-6.1-sol',
+ ])('should accept in-conversation tools for %s', (model) => {
+ expect(isToolAnchoringGPTModel(model)).toBe(true);
+ });
+
+ it.each([
+ // Namespaces dynamically loaded tools and rejects replayed calls without it.
+ 'gpt-5.5',
+ 'gpt-5.4-mini',
+ 'gpt-5',
+ 'gpt-4.1',
+ // Chat-tuned snapshots stay on Chat Completions.
+ 'gpt-6-chat-latest',
+ // OpenRouter does not speak the Responses contract for these ids.
+ 'openai/gpt-6.1-sol',
+ 'o3-pro',
+ 'claude-opus-5-5',
+ ])('should keep the top-level tool list for %s', (model) => {
+ expect(isToolAnchoringGPTModel(model)).toBe(false);
+ });
+});
diff --git a/packages/model-runtime/src/providers/openai/modelId.ts b/packages/model-runtime/src/providers/openai/modelId.ts
index 3d55045c230..cda6fd389e4 100644
--- a/packages/model-runtime/src/providers/openai/modelId.ts
+++ b/packages/model-runtime/src/providers/openai/modelId.ts
@@ -180,6 +180,26 @@ export const isGPTResponsesModel = (model: string): boolean => {
return parsed.minorVersion !== undefined && parsed.minorVersion >= 2;
};
+/**
+ * GPT models that take tools declared inside the input (`additional_tools`, client tool
+ * search) and call them like top-level tools.
+ *
+ * GPT-5.5 and older put a tool loaded this way in a namespace named after the tool and
+ * then reject replayed calls that lack it (`Missing namespace for function_call`), which
+ * breaks any history where another model called the same tool. Codex starts dynamic
+ * tool loading at GPT-5.6 for the same reason.
+ *
+ * @see https://github.com/earendil-works/pi/issues/11415
+ */
+export const isToolAnchoringGPTModel = (model: string): boolean => {
+ const parsed = isResponsesEndpointGPTModel(model);
+ if (!parsed || hasModifier(parsed, 'chat')) return false;
+
+ if (parsed.majorVersion >= 6) return true;
+
+ return parsed.minorVersion !== undefined && parsed.minorVersion >= 6;
+};
+
export const isResponsesAPIModel = (model: string): boolean =>
responsesAPIModels.has(model) || isGPTResponsesModel(model);
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index 1c8f440f597..70372f6cd44 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -3,6 +3,7 @@ import type {
ModelReasoning,
ModelTokensUsage,
ModelUsage,
+ ToolActivationPlan,
} from '@lobechat/types';
import type OpenAI from 'openai';
@@ -83,6 +84,17 @@ export interface OpenAIChatMessage {
role: LLMRoleType;
tool_call_id?: string;
tool_calls?: MessageToolCall[];
+ toolActivationPlan?: ToolActivationPlan;
+ /**
+ * Function names that first became callable at this message, e.g. the result of a
+ * mid-conversation tool activation. Their definitions stay in `ChatStreamPayload.tools`.
+ *
+ * A transport that can declare tools inside the conversation moves these definitions
+ * out of the top-level tool list and anchors them here, so activating a tool does not
+ * rewrite the request prefix (and the prompt cache with it). Every other transport
+ * ignores the field and sends the full top-level list.
+ */
+ toolsAdded?: string[];
}
/**
@@ -234,6 +246,8 @@ export interface ChatMethodOptions {
*/
requestHeaders?: Record<string, any>;
signal?: AbortSignal;
+ /** Context edits for a Responses transport that supports inline tool declarations. */
+ toolActivationPlan?: ToolActivationPlan;
/**
* userId for the chat completion
*/
diff --git a/packages/types/src/openai/chat.ts b/packages/types/src/openai/chat.ts
index 8fb549c0960..4444cd9c7fe 100644
--- a/packages/types/src/openai/chat.ts
+++ b/packages/types/src/openai/chat.ts
@@ -53,6 +53,13 @@ export type UserMessageContentPart =
| UserMessageContentPartVideo
| UserMessageContentPartAudio;
+/** Optional prompt edits prepared from the final, paired conversation. The Responses
+ * runtime applies them only when the same request can declare all their tools inline. */
+export interface ToolActivationPlan {
+ results: { callId: string; content: string; toolNames: string[] }[];
+ system?: { original: string; replacement: string; start: number };
+}
+
export interface OpenAIChatMessage {
/**
* @title Content
@@ -76,6 +83,7 @@ export interface OpenAIChatMessage {
role: LLMRoleType;
tool_call_id?: string;
tool_calls?: MessageToolCall[];
+ toolActivationPlan?: ToolActivationPlan;
}
/**