Repository navigation
fix(runtime): carry the tool name onto LangChain ToolMessage - #7327
Conversation
convertMessageToLangChainMessage built a ToolMessage from a ResultMessage with only content and tool_call_id, dropping actionName. ToolMessage.name is the field LangChain consumers route on, so any chain behind LangChainAdapter that matched on tool identity fell through silently: the gated branch never ran, and nothing errored. ResultMessage already carries actionName, and the sibling branch for ActionExecutionMessage already passes name through, so the two halves of the same round trip disagreed. Pass it through on the result side too. Adds utils.test.ts: two specs pin the name (they fail with this change reverted) and two guard tool_call_id, content and the text-message branch against regressing. Refs CopilotKit#6571
|
Understand this PR’s impact Explore downstream dependencies and potential security impact with Blast Radius. Important Review skippedReview was skipped as selected files did not have any reviewable changes. ⚙️ Run configurationConfiguration used: Repository: CopilotKit/CopilotKit/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository: CopilotKit/CopilotKit/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe LangChain adapter now assigns ChangesLangChain message conversion
Priority: ⬇️ Low Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…in (#7756) Closes #3217. Refs #6408 (item 11). ## Problem Since v1.50.0, `handleServiceAdapter` turns a v1 service adapter into a `BuiltInAgent`. That works only when the adapter can name a model through `getLanguageModel()` or a `provider/model` pair that BuiltInAgent can resolve. `serviceAdapter.process()` has no callers on `main`, so any adapter whose behavior lives in `process()` had no execution path: - `LangChainAdapter`: the custom `chainFn` never runs. On `main` the runtime advertises **no agents** (`/info` returns `"agents":{}`), and a v1 app's page crashes with `useAgent: Agent 'default' not found after runtime sync`. - `BedrockAdapter` extends `LangChainAdapter` and sets `provider = "bedrock"`. It reached the `provider/model` branch, and BuiltInAgent has no `bedrock` provider. - User-written `CopilotServiceAdapter`s failed the same way. v1 is deprecated, but it will not be deleted. The deprecation exists to stop new adoption, not to strand existing users. Runtime telemetry (`oss.runtime.instance_created`, last 30 days) shows about 3,400 distinct IDs that use `LangChainAdapter` on 1.10.x, and about 30 on 1.50+ that hit the error. **A second regression is fixed here too (commit `e7434e7`).** Since #7157 (v1.73.1), no v1 `actions` or `mcpServers` tool reaches *any* agent, BuiltInAgent included, through a documented v1 endpoint. Every endpoint calls `getRuntimeInstanceTelemetryInfo` before `handleServiceAdapter`, and that function read `runtime.instance.agents`. Reading it built the v2 runtime early, so the per-request factory that attaches the tools was never used. The tests in #7157 and #6931 wired the endpoint by hand, so they never ran that call first. I found it in the real app below. It can be split into its own PR if you prefer. ## Fix `LegacyServiceAdapterAgent` (`lib/runtime/legacy-service-adapter-agent.ts`) is an `AbstractAgent` that runs the adapter's own `process()`: - **Input:** AG-UI messages become v1 messages through the runtime's `aguiToGQL`. `input.tools` become `ActionInput[]`. `input.context` becomes a leading system message, which is where the v1 frontend put readable context. - **Events:** the bridge captures the `eventSource.stream` callback (its consumer was deleted in v1.50.0) and maps runtime events to AG-UI `TEXT_MESSAGE_*`, `TOOL_CALL_*` and `TOOL_CALL_RESULT`, inside `RUN_STARTED`/`RUN_FINISHED`. A failure becomes `RUN_ERROR`. - **Server-side v1 `actions` and `mcpServers`** arrive as `config.tools`, as on BuiltInAgent. The bridge advertises them to the adapter, executes them, and calls `process()` again with the results, up to 10 steps. A frontend tool call ends the run. - **Stop:** `abortRun()` aborts the run, as on BuiltInAgent. No further step or server tool runs, and the LangChain model stream is cancelled so that it does not keep streaming and billing. LangChain fixes that the bridge makes reachable (the GraphQL path never ran `verifyEvents`, so the old defects did not fail a turn): - A plain `string` returned by `chainFn` always threw, because the code read `actionExecution.id` off `undefined`. This was already the case in 1.10.6. - With parallel tool calls on the streaming path, the code ended the *new* call's id instead of the open one, so the run failed with `RUN_ERROR`. A stream that ended inside a tool call ended `undefined`. - After a parallel tool call, OpenAI rejected the next model call with a 400. Each call had become its own `AIMessage`, and an assistant tool-call message must be followed directly by its results. `LangChainAdapter` now folds each assistant turn back into one message. - Anthropic-style array content reached `TEXT_MESSAGE_CONTENT` as an array. Only the text parts are sent now. Routing in `ensureDefaultAgent` changes only for cases that fail today: | Adapter exposes | Before | After | |---|---|---| | `getLanguageModel()` | BuiltInAgent | unchanged | | `provider/model` that `resolveModel` accepts | BuiltInAgent | unchanged | | `provider/model` that `resolveModel` rejects (`bedrock`) | BuiltInAgent that throws on first run | bridge | | neither | `CopilotKitMisuseError` | bridge | | `OpenAIAssistantAdapter` | `CopilotKitMisuseError` | a clear `CopilotKitMisuseError` | `OpenAIAssistantAdapter` stays on an error on purpose. Its `process()` needs OpenAI thread and run ids carried between requests, and OpenAI shut down the Assistants API on 2026-08-26. `copilot-runtime.ts` does not import `LangChainAdapter`, because `@langchain/core` is an optional peer. No public API is added. `RuntimeEventSubject` gains an optional `signal` constructor argument, and the public API manifest check passes. `agentsAmount` in v1 endpoint telemetry now reports the configured count; it was always 0 before. ## Testing ### Real app, before and after `examples/v1/next-openai`, the v1 `CopilotSidebar` page with `copilotRuntimeNextJSAppRouterEndpoint`, driven in a browser. I added a local-only `langchain_openai` case (not committed) that uses the documented `model.bindTools(tools).stream(messages)` with `gpt-4o-mini`. - **`main` runtime:** `/info` returns `"agents":{}`. The page crashes with `useAgent: Agent 'default' not found after runtime sync … No agents registered`. - **This branch:** `/info` lists `default` as a `LegacyServiceAdapterAgent`. - **Parallel server-side actions:** prompt "get image urls for lighthouse and mountain (one call per topic, in parallel)". `chainFn` call 1 received `getImageUrl`, both calls ran on the server, and call 2 received a 5-message history (user, one merged assistant turn, two tool results). The model answered with both URLs. - **Frontend tool:** "Add Lisbon to the new destinations". `AddNewDestination` ran in the browser, the row appeared, and the follow-up run answered "Lisbon, Portugal has been added". No loop. ### Stop, through the real endpoint A model stream produces one chunk every 100 ms. `agent/stop` is called after 1 s: ``` before the cancel fix: response ended at 1020ms | model chunks at stop: 9, 1.5s later: 24 | stream cancelled: false after: response ended at 1019ms | model chunks at stop: 9, 1.5s later: 10 | stream cancelled: true ``` ### Live OpenAI runs (`gpt-4o-mini`, local only, not committed) ``` ✓ parallel server-side tools, then a second step (failed before the fix: 400 "An assistant message with 'tool_calls' must be followed by tool messages…") ✓ follow-up after parallel frontend tool results (failed before the fix: same 400) ✓ single server tool still works ✓ text / server action loop / frontend tool / follow-up (first round) ``` ### Unit and end-to-end tests The end-to-end tests send a real `LangChainAdapter` through `POST agent/run` on the single-route endpoint and parse the SSE stream. `v1-endpoint-order.test.ts` copies the real endpoints' order (telemetry first, then `handleServiceAdapter`). I wrote each new test before its fix and confirmed it fails without the fix: | Test | Fails when | |---|---| | parallel tool calls close in order; stream ends inside a call | the end uses the chunk's id | | parallel tool calls reach `chainFn` as one `AIMessage` | there is no merge | | array content streams its text | content is cast to string | | Stop completes a run whose stream never ends | `abortRun` does nothing, or there is no abort listener | | Stop cancels the LangChain model stream | there is no cancel on abort | | telemetry does not build the instance; v1 actions reach the agent | telemetry reads `runtime.instance` | | routing: LangChain / Bedrock / provider without model → bridge; Assistant → clear error | routing is reverted | ``` nx run @copilotkit/runtime:test Test Files 199 passed | Tests 2933 passed nx run @copilotkit/runtime:check-types exit 0 nx run @copilotkit/runtime:build exit 0 pnpm check:public-api-manifest manifest.v1.json is current ``` ## Review An adversarial review of the first version found the parallel-tool-call, Stop, array-content, and OpenAIAssistantAdapter defects. I reproduced each one before fixing it. The browser run then found the #7157 telemetry regression, and a probe found the stream that was not cancelled. ## Not verified - I did not run `BedrockAdapter` live (no AWS credentials). It routes through the same LangChain path that I tested. - Agent-state and LangGraph meta events are not mapped. Only remote agent endpoints emitted them. - When v1 `actions` are in use, the suggestion feature runs through the bridge. It ignores `forwardedProps.toolChoice`, as v1's `LangChainAdapter` always did, because `chainFn` owns the model call. ## Seen while testing, not caused by this PR `examples/v1/next-openai` sends hundreds of runtime POSTs per minute on `main` with *any* adapter (689 in 25 s with `OpenAIAdapter`). `/multi` throws `Invalid action configuration`, and `runtimeUrl` with a query string produces `…?serviceAdapter=x/info` (405). Worth a separate look. ## Overlap #7327 and #7740 change `convertMessageToLangChainMessage` in `langchain/utils.ts`, in a different function. Both #7740 and #7327 merge cleanly with the current head. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for running legacy service adapters through the agent runtime, including frontend and server-side tools. * Added improved handling for tool arguments, context, streaming, and cancellation. * **Bug Fixes** * Improved compatibility with adapters that do not specify a model. * Fixed LangChain tool calls, message content, streamed responses, and parallel tool-call ordering. * Aborting a run now cancels active streams and prevents further processing. * Requests using the retired OpenAI Assistants API now receive a clear shutdown error. * Improved endpoint action handling, telemetry counts, validation, and error reporting. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Picks up the second half of #6571, the part #6586 deliberately left alone.
The bug
convertMessageToLangChainMessagebuilds aToolMessagefrom aResultMessageand drops the tool's identity on the floor:ResultMessagealready carriesactionName. It just never gets passed.The two halves of the same round trip disagree about this. The
ActionExecutionMessagebranch twenty lines up already passesnamethrough onto theAIMessage's tool call, so a chain sees the name on the way out and then loses it on the way back.Why it matters
ToolMessage.nameis the field LangChain consumers route on. With it unset, a chain behindLangChainAdapterthat matches on tool identity falls through silently. Nothing throws, nothing logs, the branch just never runs and the model carries on as if it had. That is the same failure shape #6571 describes: the evidence of a working gate and the evidence of a gate that never fired are identical from inside the app.The only workaround available to a consumer is to walk back through the message list to the
ActionExecutionMessagewhose id matchestool_call_idand read the name off that. That is work the adapter is better placed to do, and it is exactly the lookupsdk-python/copilotkit/copilotkit_lg_middleware.py:840already does on the Python side, wherenameis set correctly from the matching tool call. This brings the TypeScript adapter in line with it.The fix
One field, plus a comment saying why it's there.
Tests
New
utils.test.ts, four specs. Two pin the name, two guard against collateral damage:ToolMessagetool_call_idandcontentare untouchedconvertedResult.nameequals thenameon theAIMessage's tool call produced from the matchingActionExecutionMessageHumanMessageReverting only
utils.tsand keeping the specs fails the two that pin the name (expected undefined to be 'request_page_oncall') and passes the other two, so they bind to the mechanism rather than to themselves.Differential full-suite run on
packages/runtime, with and without the change: identical failure set either way (105 files / 8 tests, all pre-existing and all from workspace deps that aren't built in a fresh checkout —Cannot find module '@copilotkit/shared/...'and friends). The change adds exactly one passing file and four passing tests and moves nothing else.tsc --noEmitreports no errors in either touched file; the 35 it does report are the same unbuilt-dependency errors and are present on cleanmain.Scope
convertMessageToLangChainMessagehas one caller,langchain-adapter.ts:106. Nothing readsToolMessage.nameinside this repo, so nothing here depended on it being unset.This is a behavior change for anyone downstream who had worked around the gap by reading the name out of the message list themselves. Their workaround keeps working, since it reads the
ActionExecutionMessage, not this field. Worth a release note anyway.Still not addressed
The upstream half.
@ag-ui/langgraph'saguiMessagesToLangChain()omitsnamein itscase "tool", and the root cause is thatToolMessageSchemain@ag-ui/coreis the only message role without anamefield. That is not fixed in0.0.43— that release only addedstatus— so bumping the0.0.42pin inpackages/runtime/package.jsonandpackages/sdk-js/package.jsonwill not help. It needs a change in those packages, not this one.One correction to a note I left on #6586: I flagged
examples/showcases/scene-creator/agent/agent.py:743as a live instance of this bug. It isn't. The tools it routes on are backend tools executed by LangGraph'sToolNode, which setsnameitself, so that read is fine. My mistake.Summary by CodeRabbit