fix(sdk): keep tool names on Vercel tool-result parts through the OpenAI round trip (#3883)

## Description

`openAIToVercel()` emits every `tool-result` part with `toolName:
"unknown"`, because an OpenAI `tool` message only carries the
`tool_call_id`. So after any successful compression through
`headroomMiddleware()` / `compressVercelMessages()`, every tool result
in the prompt reaches the AI SDK provider with the wrong tool name.

That is not cosmetic for providers that put the name on the wire. In the
AI SDK source, `packages/google/src/convert-to-google-messages.ts`
builds `functionResponse: { name: toolName, … }` and
`packages/mistral/src/convert-to-mistral-chat-messages.ts` sends `name:
part.toolName` — both receive `"unknown"` today, which no longer matches
the preceding function call.

The name is recoverable: the assistant message that precedes the tool
result carries `tool_calls[].function.name` for the same id. This
records the `id → name` mapping while converting and uses it for the
matching `tool-result`, keeping `"unknown"` only as the fallback when no
call matches (the existing lone-tool-message test stays valid
unchanged).

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- **`sdk/typescript/src/utils/format.ts`** — `openAIToVercel`: a
`toolNames` map filled from each assistant `tool_calls` entry as it is
converted; the `tool-result` part uses `toolNames.get(msg.tool_call_id)
?? "unknown"`. Three lines net.
- **`sdk/typescript/test/utils/format.test.ts`** — `openAIToVercel`
carries the name from the matching tool-call onto the tool-result; a
Vercel → OpenAI → Vercel round trip preserves `toolName`.
- **`sdk/typescript/test/adapters/vercel-ai.test.ts`** —
`compressVercelMessages` keeps tool names on tool-result parts after a
(mocked) compression that returns the assistant tool call and the tool
message.

## Testing

- [x] Unit tests pass (`npm test` — vitest, incl. typecheck)
- [x] Type checking passes (`npm run typecheck` — tsc --noEmit)
- [x] Build passes (`npm run build` — tsup)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ cd sdk/typescript && npx vitest run test/utils/format.test.ts test/adapters/vercel-ai.test.ts
 Test Files  2 passed (2)
      Tests  47 passed (47)

$ npm test                       # full suite
 Test Files  19 passed | 5 skipped (24)
      Tests  337 passed | 33 skipped (370)
Type Errors  no errors

$ npm run typecheck              # tsc --noEmit
(clean, no errors)

$ npm run build                  # tsup
CJS / ESM / DTS Build success
```

## Real Behavior Proof

- Environment: macOS (Apple silicon), Node v22.16.0, npm 10.9.2; `cd
sdk/typescript && npm ci`.
- Exact command / steps: a `node --input-type=module` script calling the
built `toOpenAI` / `fromOpenAI` from `dist/index.js` on `main` with a
user → assistant `tool-call` (`getWeather`) → `tool-result`
conversation; then the three new tests on `main` and on this branch;
then `npm test`, `npm run typecheck`, `npm run build`.
- Observed result: On `main` the round-tripped tool-result part is `{
"type": "tool-result", "toolCallId": "call_1", "toolName": "unknown", …
}` while the tool-call part keeps `"getWeather"`; the three new tests
fail with `Expected: "getWeather" / Received: "unknown"`. With the
change they pass and the round trip yields `toolName: "getWeather"`;
full suite 337 passed | 33 skipped; typecheck and build clean.
- Not tested: a live provider call. The conversion is pure; the AI SDK
provider code cited above is what consumes the name.

## Runtime Rollout Safety

- Rollout-managed feature(s): None. Client-side TypeScript SDK
conversion fix; no server/runtime feature flag or rollout channel
involved.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: Only the buggy path — tool-result
parts now carry the real tool name when the matching tool call is
present; everything else is byte-identical, and the `"unknown"` fallback
is unchanged for unmatched results.
- Kill switch / disable path: N/A — correctness fix, not a gated
feature.
- Unsafe override required: No.
- Qualification impact: None — existing conversion tests unchanged and
green.
- Rollback path: Revert this PR; no persisted state, migrations, or
config to unwind.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

- A tool result whose matching assistant call was compressed away (or
never present) still gets `"unknown"`; recovering a name in that case is
impossible from the OpenAI shape and out of scope.
- CHANGELOG left untouched — the `no-manual-changelog` CI guard owns it;
the Conventional Commit title drives the entry.
This commit is contained in:
Shubham Srivastava
2026-09-30 09:27:09 -05:00
committed by GitHub
parent 1512c06235
commit b7156714ac
3 changed files with 78 additions and 1 deletions
+4 -1
View File
@@ -328,6 +328,8 @@ export function vercelToOpenAI(messages: any[]): OpenAIMessage[] {
export function openAIToVercel(messages: OpenAIMessage[]): any[] {
const result: any[] = [];
// tool_call id -> function name, so tool-result parts carry the name the AI SDK expects.
const toolNames = new Map<string, string>();
for (const msg of messages) {
if (msg.role === "system") {
@@ -354,6 +356,7 @@ export function openAIToVercel(messages: OpenAIMessage[]): any[] {
if (msg.content) parts.push({ type: "text", text: msg.content });
if (msg.tool_calls) {
for (const tc of msg.tool_calls) {
toolNames.set(tc.id, tc.function.name);
let input: any;
try { input = JSON.parse(tc.function.arguments); } catch { input = tc.function.arguments ?? {}; }
parts.push({
@@ -380,7 +383,7 @@ export function openAIToVercel(messages: OpenAIMessage[]): any[] {
content: [{
type: "tool-result",
toolCallId: msg.tool_call_id,
toolName: "unknown",
toolName: toolNames.get(msg.tool_call_id) ?? "unknown",
output,
}],
});
@@ -171,6 +171,39 @@ describe("compressVercelMessages", () => {
expect(result.messages[1].role).toBe("user");
expect(result.messages[1].content[0].type).toBe("text");
});
it("keeps tool names on tool-result parts after compression", async () => {
mockFetch.mockResolvedValueOnce(
mockCompressResponse([
{
role: "assistant",
content: null,
tool_calls: [
{ id: "call_1", type: "function", function: { name: "getWeather", arguments: '{"city":"Paris"}' } },
],
},
{ role: "tool", content: '{"tempC":21}', tool_call_id: "call_1" },
]),
);
const result = await compressVercelMessages(
[
{
role: "assistant",
content: [{ type: "tool-call", toolCallId: "call_1", toolName: "getWeather", input: { city: "Paris" } }],
},
{
role: "tool",
content: [
{ type: "tool-result", toolCallId: "call_1", toolName: "getWeather", output: { type: "json", value: { tempC: 21 } } },
],
},
],
{ model: "gpt-4o", baseUrl: "http://localhost:8787" },
);
expect(result.messages[1].content[0].toolName).toBe("getWeather");
});
});
describe("withHeadroom", () => {
+41
View File
@@ -638,3 +638,44 @@ describe("round-trip conversion", () => {
});
});
});
describe("openAIToVercel tool names", () => {
it("carries the tool name from the matching tool-call onto the tool-result part", () => {
const msgs: OpenAIMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "tc_1", type: "function", function: { name: "getWeather", arguments: '{"city":"Paris"}' } },
],
},
{ role: "tool", content: '{"tempC":21}', tool_call_id: "tc_1" },
];
const result = openAIToVercel(msgs);
expect(result[1].content[0]).toEqual({
type: "tool-result",
toolCallId: "tc_1",
toolName: "getWeather",
output: { type: "json", value: { tempC: 21 } },
});
});
it("preserves tool names through a Vercel -> OpenAI -> Vercel round trip", () => {
const original = [
{ role: "user", content: [{ type: "text", text: "weather in Paris?" }] },
{
role: "assistant",
content: [{ type: "tool-call", toolCallId: "call_1", toolName: "getWeather", input: { city: "Paris" } }],
},
{
role: "tool",
content: [
{ type: "tool-result", toolCallId: "call_1", toolName: "getWeather", output: { type: "json", value: { tempC: 21 } } },
],
},
];
const back = openAIToVercel(vercelToOpenAI(original));
expect(back[2].content[0].toolName).toBe("getWeather");
});
});