Skip to content

Commit a8773dd

Browse files
authored
fix: identify reasoning-first content-plus-tool streams as assistant (#470)
## Fix Identify the assistant on the first reasoning delta of OpenAI content-plus-tool streams, including ordered blocks. LangChain otherwise constructs a generic message and drops the parsed tool calls needed by LangGraph TypeScript MCP Apps. Preserve configured role overrides and later chunks. Scope: two role additions in `src/helpers.ts`, plus four real HTTP regression cases in the existing provider test and an Unreleased changelog entry. No fixture, integration, dependency, or unrelated protocol changes. ## Actual local red → green Unchanged deployed app image `014b6a344a9e42380067bc65dfb5fe6b2e5ff2e2cbd7d1630fc07534aea945f4` and deployed aimock wrapper `0bc93747cefeea3629a64226b20830ff815ddc38055b72fdc3b54a1da5ee9366`: ```json {"key": "d6:langgraph-typescript/mcp-apps", "state": "red", "signal": {"slug": "langgraph-typescript", "featureType": "mcp-apps", "backendUrl": "http://127.0.0.1:11401", "url": "http://127.0.0.1:11401/demos/mcp-apps", "fixtureFile": "mcp-apps.json", "turns_completed": 0, "total_turns": 1, "failure_turn": 1, "turn_durations_ms": [], "errorDesc": "waitForTurnComplete: turn 1 did not complete within 30000ms (reason=surface-missing, runsFinished=1, count=1, attrPresent=true, runningNow=false, runStartCount=1)", "errorClass": "conversation-error", "diagnostics": {"userMsgCount": 1, "apiRequestCount": 3, "apiRequests": [{"url": "http://127.0.0.1:11401/api/copilotkit-mcp-apps", "duration": 12, "transferSize": 747, "status": 200}, {"url": "https://cdn.copilotkit.ai/announcements.json", "duration": 57, "transferSize": 0, "status": 0}, {"url": "http://127.0.0.1:11401/api/copilotkit-mcp-apps", "duration": 1183, "transferSize": 54267, "status": 200}], "pageErrors": [], "chatContainerExists": true, "url": "http://127.0.0.1:11401/demos/mcp-apps", "title": "LangGraph (TypeScript) - MCP Apps", "bodyTextSnippet": "Open Excalidraw and sketch a system diagram with a client, server, and database.\n\nSketching a client \u2192 server \u2192 database diagram in Excalidraw.\n\nDraw a flowchart\nSketch a system diagram\nAI can make mistakes. Please verify important information.", "assistantMsgCount": 1, "consoleLogs": ["[error] Access to fetch at 'https://cdn.copilotkit.ai/announcements.json' from origin 'http://127.0.0.1:11401' has been blocked by CORS policy: Response to preflight request doesn't pass access control check:", "[error] Failed to load resource: net::ERR_FAILED", "[warning] [CopilotKit Inspector] Failed to load announcement TypeError: Failed to fetch\n at g.fetch (<anonymous>:88:31)\n at e.fetchAnnouncement (http://127.0.0.1:11401/_next/static/chunks/8c3ed0a6.b9af3fe", "[error] Access to font at 'https://fonts.gstatic.com/s/plusjakartasans/v12/LDIoaomQNQcsA88c7O9yZ4KMCoOg4Ko20yygg_vb.woff2' from origin 'http://127.0.0.1:11401' has been blocked by CORS policy: Request header ", "[error] Failed to load resource: net::ERR_FAILED"], "requestFailures": ["GET https://cdn.copilotkit.ai/announcements.json => net::ERR_FAILED", "GET https://fonts.gstatic.com/s/plusjakartasans/v12/LDIoaomQNQcsA88c7O9yZ4KMCoOg4Ko20yygg_vb.woff2 => net::ERR_FAILED"]}}, "observedAt": "2026-09-18T13:18:57.163Z"} ``` Same shared D6 MCP Apps probe, unchanged app, freshly built candidate aimock with unchanged deployed wrapper fixtures: ```json {"key": "d6:langgraph-typescript/mcp-apps", "state": "green", "signal": {"slug": "langgraph-typescript", "featureType": "mcp-apps", "backendUrl": "http://127.0.0.1:11403", "url": "http://127.0.0.1:11403/demos/mcp-apps", "fixtureFile": "mcp-apps.json", "turns_completed": 1, "total_turns": 1, "turn_durations_ms": [3793]}, "observedAt": "2026-09-18T13:21:28.289Z"} ``` An isolated two-line overlay on the exact deployed wrapper also passes the same D6, establishing causality separately from newer aimock main. Native Playwright screenshot visually confirms Client → Server → Database in the Excalidraw iframe. Runtime capture contains ACTIVITY_SNAPSHOT and RUN_FINISHED. ## Provider red → green Four new real HTTP tests (legacy/ordered blocks × default/custom role) failed because the first reasoning delta omitted role, then passed. All 85 targeted provider controls pass. Official Dockerfile builds locally with desktop-linux. Typecheck, formatter, lint pass. Full suite: 224 files passed, 1 existing skipped; 7,292 tests passed, 49 existing skipped. Initial suite with a shared dependency symlink failed unrelated adoption entrypoint tests; replacing the symlink with a proper offline lockfile install resolved all failures without code changes. Final test run used Node 22.16.0 and four workers. No staging acceptance or deployment claim. No pinning in staging.
2 parents e23d91f + 51e7d96 commit a8773dd

3 files changed

Lines changed: 62 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535

3636
### Fixed
3737

38+
- Reasoning-first OpenAI chat streams that combine content and tool calls now include the configured role (default `assistant`) in the first reasoning chunk, for both legacy and block fixtures. This lets LangChain recognize the assistant message and preserves tool calls for LangGraph TypeScript MCP rendering (#470)
3839
- Journals and metrics now reflect delivered and interrupted responses, preserve request identity across concurrent calls, and keep route labels bounded. One-shot errors are reserved before asynchronous processing and returned to the queue when unserved, preventing duplicate delivery (#466)
3940
- Nonstreaming OpenAI chat returns authored block text and tools. Across OpenAI, Claude, Gemini, Gemini Interactions, Cohere and Bedrock, text-only blocks now finish normally instead of reporting a tool-call terminal; tool-containing blocks retain their tool outcome (#467)
4041
- AG-UI drift checks read the generated AG-UI 1.0 schemas as well as the legacy layout, and unavailable or malformed comparisons no longer pass silently. BASE and HEAD use the same pinned canonical sources while retaining their own product types. `AGUIRunStartedEvent` now includes optional `protocolVersion?: string` (#469)

‎src/__tests__/openai-chat-toolonly-reasoning-capability.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,3 +248,46 @@ describe("/v1/chat/completions tool-only reasoning capability gating", () => {
248248
expect(warnSpy).not.toHaveBeenCalled();
249249
});
250250
});
251+
252+
describe("reasoning-first tool streams identify the assistant immediately", () => {
253+
for (const ordered of [false, true]) {
254+
for (const role of [undefined, "system"]) {
255+
it(`starts with the configured role (blocks=${ordered}, role=${role ?? "default"})`, async () => {
256+
const toolCall = { name: "get_weather", arguments: '{"city":"SF"}' };
257+
const fixture: Fixture = {
258+
match: { userMessage: "initial-role" },
259+
response: {
260+
content: "Checking weather.",
261+
toolCalls: [toolCall],
262+
reasoning: "Think first.",
263+
...(role !== undefined && { role }),
264+
...(ordered && {
265+
blocks: [
266+
{ type: "text" as const, text: "Checking weather." },
267+
{ type: "toolCall" as const, ...toolCall },
268+
],
269+
}),
270+
},
271+
};
272+
instance = await createServer([fixture], { port: 0, logLevel: "warn", chunkSize: 4 });
273+
const res = await httpPost(
274+
`${instance.url}/v1/chat/completions`,
275+
chatBody("initial-role", "o3-mini", true),
276+
);
277+
expect(res.status).toBe(200);
278+
const events = parseSSEEvents(res.body);
279+
expect(events[0].choices?.[0]?.delta).toMatchObject({
280+
role: role ?? "assistant",
281+
reasoning_content: "Thin",
282+
});
283+
expect(
284+
events
285+
.filter((e) => e.choices?.[0]?.delta?.reasoning_content)
286+
.slice(1)
287+
.every((e) => e.choices?.[0]?.delta?.role === undefined),
288+
).toBe(true);
289+
expect(streamToolCallName(res.body)).toBe("get_weather");
290+
});
291+
}
292+
}
293+
});

‎src/helpers.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,7 +1028,15 @@ export function buildContentWithToolCallsChunks(
10281028
created,
10291029
model: effectiveModel,
10301030
choices: [
1031-
{ index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },
1031+
{
1032+
index: 0,
1033+
delta: {
1034+
...(i === 0 && { role: overrides?.role ?? "assistant" }),
1035+
reasoning_content: slice,
1036+
},
1037+
logprobs: null,
1038+
finish_reason: null,
1039+
},
10321040
],
10331041
...(fingerprint !== undefined && { system_fingerprint: fingerprint }),
10341042
});
@@ -1153,7 +1161,15 @@ export function buildContentWithToolCallsChunks(
11531161
created,
11541162
model: effectiveModel,
11551163
choices: [
1156-
{ index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },
1164+
{
1165+
index: 0,
1166+
delta: {
1167+
...(i === 0 && { role: overrides?.role ?? "assistant" }),
1168+
reasoning_content: slice,
1169+
},
1170+
logprobs: null,
1171+
finish_reason: null,
1172+
},
11571173
],
11581174
...(fingerprint !== undefined && { system_fingerprint: fingerprint }),
11591175
});

0 commit comments

Comments
 (0)