返回源码地图

packages/ai/src/api/transform-messages.ts

v1.3.0 · 71023aec1546 · 04:逐段读取跨模型thinking、工具ID映射、错误响应和缺失结果修复

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type {
2 Api,
3 AssistantMessage,
4 ImageContent,
5 Message,
6 Model,
7 TextContent,
8 ToolCall,
9 ToolResultMessage,
10} from "../types.ts";
11
12const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
13const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
14const ERROR_TOOL_IMAGE_PLACEHOLDER = "(image attached after the tool results)";
15
16/** An error tool result split into a text-only result and the images to send after the tool results. */
17export interface SplitErrorToolResult {
18 /** The result content with each run of images replaced by a note. */
19 content: TextContent[];
20 /** Text naming the tool call, to send before `images`. */
21 caption: string;
22 images: ImageContent[];
23}
24
25/**
26 * Split the images out of an error tool result, for APIs that reject images in error results
27 * (Anthropic, and Claude on Bedrock). Send the returned content as the tool result and the caption and
28 * images after all tool results of the turn, in the same user message. Returns undefined for results
29 * that need no split (#10794).
30 */
31export function splitErrorToolResultImages(msg: ToolResultMessage): SplitErrorToolResult | undefined {
32 if (!msg.isError) return undefined;
33 const images = msg.content.filter((block): block is ImageContent => block.type === "image");
34 if (images.length === 0) return undefined;
35 return {
36 content: replaceImagesWithPlaceholder(msg.content, ERROR_TOOL_IMAGE_PLACEHOLDER),
37 caption: `Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,
38 images,
39 };
40}
41
42function replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {
43 const result: TextContent[] = [];
44 let previousWasPlaceholder = false;
45
46 for (const block of content) {
47 if (block.type === "image") {
48 if (!previousWasPlaceholder) {
49 result.push({ type: "text", text: placeholder });
50 }
51 previousWasPlaceholder = true;
52 continue;
53 }
54
55 result.push(block);
56 previousWasPlaceholder = block.text === placeholder;
57 }
58
59 return result;
60}
61
62function downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {
63 if (model.input.includes("image")) {
64 return messages;
65 }
66
67 return messages.map((msg) => {
68 if (msg.role === "user" && Array.isArray(msg.content)) {
69 return {
70 ...msg,
71 content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),
72 };
73 }
74
75 if (msg.role === "toolResult") {
76 return {
77 ...msg,
78 content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),
79 };
80 }
81
82 return msg;
83 });
84}
85
86/**
87 * Normalize tool call ID for cross-provider compatibility.
88 * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.
89 * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).
90 */
91export function transformMessages<TApi extends Api>(
92 messages: Message[],
93 model: Model<TApi>,
94 normalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,
95): Message[] {
96 // Build a map of original tool call IDs to normalized IDs
97 const toolCallIdMap = new Map<string, string>();
98 // Normalize null/undefined content from untyped callers (custom tools, hand-built
99 // histories, old session files) so downstream code can rely on the type contract.
100 const normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));
101 const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);
102
103 // First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)
104 const transformed = imageAwareMessages.map((msg) => {
105 // System and user messages pass through unchanged
106 if (msg.role === "system" || msg.role === "user") {
107 return msg;
108 }
109
110 // Handle toolResult messages - normalize toolCallId if we have a mapping
111 if (msg.role === "toolResult") {
112 const normalizedId = toolCallIdMap.get(msg.toolCallId);
113 if (normalizedId && normalizedId !== msg.toolCallId) {
114 return { ...msg, toolCallId: normalizedId };
115 }
116 return msg;
117 }
118
119 // Assistant messages need transformation check
120 if (msg.role === "assistant") {
121 const assistantMsg = msg as AssistantMessage;
122 const isSameModel =
123 assistantMsg.provider === model.provider &&
124 assistantMsg.api === model.api &&
125 assistantMsg.model === model.id;
126
127 const transformedContent = assistantMsg.content.flatMap((block) => {
128 if (block.type === "thinking") {
129 // Thinking from another model is dropped. Signatures and encrypted reasoning are
130 // only valid for the model that produced them, and sending readable thinking as
131 // plain text makes the new model treat it as part of the visible reply.
132 if (!isSameModel) return [];
133 // Keep redacted and signed blocks even if the thinking text is empty
134 // (OpenAI encrypted reasoning); they are needed for replay.
135 if (block.redacted || block.thinkingSignature) return block;
136 if (!block.thinking || block.thinking.trim() === "") return [];
137 return block;
138 }
139
140 if (block.type === "text") {
141 if (isSameModel) return block;
142 return {
143 type: "text" as const,
144 text: block.text,
145 };
146 }
147
148 if (block.type === "toolCall") {
149 const toolCall = block as ToolCall;
150 let normalizedToolCall: ToolCall = toolCall;
151
152 if (!isSameModel && toolCall.thoughtSignature) {
153 normalizedToolCall = { ...toolCall };
154 delete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;
155 }
156
157 if (!isSameModel && normalizeToolCallId) {
158 const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);
159 if (normalizedId !== toolCall.id) {
160 toolCallIdMap.set(toolCall.id, normalizedId);
161 normalizedToolCall = { ...normalizedToolCall, id: normalizedId };
162 }
163 }
164
165 return normalizedToolCall;
166 }
167
168 return block;
169 });
170
171 return {
172 ...assistantMsg,
173 content: transformedContent,
174 };
175 }
176 return msg;
177 });
178
179 // Second pass: insert synthetic empty tool results for orphaned tool calls
180 // This preserves thinking signatures and satisfies API requirements
181 const result: Message[] = [];
182 let pendingToolCalls: ToolCall[] = [];
183 let existingToolResultIds = new Set<string>();
184 // System messages are transparent to tool-call accounting: one that lands between a tool
185 // call and its results is held back and emitted after the results (synthetic ones
186 // included), so it never causes a duplicate result for a call that is answered later.
187 const heldSystemMessages: Message[] = [];
188 const closePendingToolCalls = () => {
189 if (pendingToolCalls.length > 0) {
190 for (const tc of pendingToolCalls) {
191 if (!existingToolResultIds.has(tc.id)) {
192 result.push({
193 role: "toolResult",
194 toolCallId: tc.id,
195 toolName: tc.name,
196 content: [{ type: "text", text: "No result provided" }],
197 isError: true,
198 timestamp: Date.now(),
199 } as ToolResultMessage);
200 }
201 }
202 pendingToolCalls = [];
203 existingToolResultIds = new Set();
204 }
205 result.push(...heldSystemMessages);
206 heldSystemMessages.length = 0;
207 };
208
209 for (let i = 0; i < transformed.length; i++) {
210 const msg = transformed[i];
211
212 if (msg.role === "assistant") {
213 // If we have pending orphaned tool calls from a previous assistant, insert synthetic results now
214 closePendingToolCalls();
215
216 // Skip errored/aborted assistant messages entirely.
217 // These are incomplete turns that shouldn't be replayed:
218 // - May have partial content (reasoning without message, incomplete tool calls)
219 // - Replaying them can cause API errors (e.g., OpenAI "reasoning without following item")
220 // - The model should retry from the last valid state
221 const assistantMsg = msg as AssistantMessage;
222 if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
223 continue;
224 }
225
226 // Track tool calls from this assistant message
227 const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall") as ToolCall[];
228 if (toolCalls.length > 0) {
229 pendingToolCalls = toolCalls;
230 existingToolResultIds = new Set();
231 }
232
233 result.push(msg);
234 } else if (msg.role === "toolResult") {
235 existingToolResultIds.add(msg.toolCallId);
236 result.push(msg);
237 } else if (msg.role === "system") {
238 if (pendingToolCalls.length > 0) {
239 heldSystemMessages.push(msg);
240 } else {
241 result.push(msg);
242 }
243 } else if (msg.role === "user") {
244 // A new user turn interrupts tool flow - insert synthetic results for orphaned calls
245 closePendingToolCalls();
246 result.push(msg);
247 } else {
248 result.push(msg);
249 }
250 }
251
252 // If the conversation ends with unresolved tool calls, synthesize results now.
253 closePendingToolCalls();
254
255 return result;
256}