Skip to content

Commit 49d715b

Browse files
Pick-catvincentkoc
authored andcommitted
fix(ai): keep OpenAI tool call id truncation UTF-16 safe
1 parent ac6cc33 commit 49d715b

2 files changed

Lines changed: 50 additions & 1 deletion

File tree

‎packages/ai/src/openai-completions-messages.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,52 @@ describe("convertMessages assistant text replay", () => {
4949
const replayed = converted.find((message) => message.role === "assistant");
5050
expect(replayed?.content).toBe("Let me check the file.\nThe file contains X.");
5151
});
52+
53+
it("keeps paired OpenAI tool call ids UTF-16 safe when truncating", () => {
54+
const prefix = "a".repeat(39);
55+
const oversizedId = `${prefix}🐱`;
56+
const targetModel: Model<"openai-completions"> = {
57+
...model,
58+
id: "target-model",
59+
provider: "openai",
60+
};
61+
const assistant: AssistantMessage = {
62+
role: "assistant",
63+
api: targetModel.api,
64+
provider: targetModel.provider,
65+
model: "source-model",
66+
content: [{ type: "toolCall", id: oversizedId, name: "lookup", arguments: {} }],
67+
usage: emptyUsage,
68+
stopReason: "toolUse",
69+
timestamp: 1,
70+
};
71+
const context: Context = {
72+
messages: [
73+
assistant,
74+
{
75+
role: "toolResult",
76+
toolCallId: oversizedId,
77+
toolName: "lookup",
78+
content: [{ type: "text", text: "ok" }],
79+
isError: false,
80+
timestamp: 2,
81+
},
82+
],
83+
};
84+
85+
const converted = convertMessages(
86+
targetModel,
87+
context,
88+
resolveOpenAICompletionsCompat(targetModel),
89+
);
90+
const assistantParam = converted.find((message) => message.role === "assistant");
91+
const toolParam = converted.find((message) => message.role === "tool");
92+
const normalizedAssistantId =
93+
assistantParam?.role === "assistant" ? assistantParam.tool_calls?.[0]?.id : undefined;
94+
const normalizedToolResultId = toolParam?.role === "tool" ? toolParam.tool_call_id : undefined;
95+
96+
expect(oversizedId.slice(0, 40).charCodeAt(39)).toBe(0xd83d);
97+
expect(normalizedAssistantId).toBe(prefix);
98+
expect(normalizedToolResultId).toBe(prefix);
99+
});
52100
});

‎packages/ai/src/openai-completions-messages.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
12
import type {
23
ChatCompletionAssistantMessageParam,
34
ChatCompletionContentPart,
@@ -57,7 +58,7 @@ export function convertMessages(
5758
}
5859

5960
if (model.provider === "openai") {
60-
return id.length > 40 ? id.slice(0, 40) : id;
61+
return id.length > 40 ? truncateUtf16Safe(id, 40) : id;
6162
}
6263
return id;
6364
};

0 commit comments

Comments
 (0)