Repository navigation
fix(runtime): keep the LangChain tool message name - #7740
AlemTuzlak wants to merge 3 commits into
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 #6571
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe LangChain adapter now sets the tool name when it converts a result message. Tests check result message fields and user text message conversion. ChangesLangChain message conversion
Priority: ⬇️ Low Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix Merge Risk: ⚪ Minimal · up to Tool results retain their action names, and no actionable merge risk remains after normal checks. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 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 |
@copilotkit/a2ui-renderer
@copilotkit/agentcore-runner
@copilotkit/angular
@copilotkit/channels
@copilotkit/channels-core
@copilotkit/channels-discord
@copilotkit/channels-intelligence
@copilotkit/channels-slack
@copilotkit/channels-teams
@copilotkit/channels-telegram
@copilotkit/channels-ui
@copilotkit/channels-whatsapp
@copilotkit/core
@copilotkit/intelligence-langgraph
@copilotkit/intelligence-mastra
@copilotkit/learning
@copilotkit/mcp-apps-renderer
@copilotkit/react-core
@copilotkit/react-native
@copilotkit/react-textarea
@copilotkit/react-ui
@copilotkit/runtime
@copilotkit/runtime-client-gql
@copilotkit/sdk-js
@copilotkit/shared
@copilotkit/sqlite-runner
@copilotkit/voice
@copilotkit/vue
@copilotkit/web-components
@copilotkit/web-inspector
commit: |
|
Size Change: -572 B (-0.03%) Total Size: 1.79 MB 📦 View Changed
ℹ️ View Unchanged
|
…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 -->
A tool result that was converted to a LangChain ToolMessage dropped the tool name. Consumers could not tell which tool the result belonged to. This branch sets ToolMessage.name from the action name.
What does this PR do?
A tool result that was converted to a LangChain ToolMessage dropped the tool name. Consumers could not tell which tool the result belonged to. This branch sets ToolMessage.name from the action name.
Related PRs and Issues
Checklist
!(for examplefeat(react-core)!: ...) and the description has aBREAKING CHANGE:line with migration steps. See VERSIONING.mdTesting
Risk / rollback
Risk is low. Revert this pull request to stop setting the name.
Public API change
Before
The LangChain tool message had no name.
After
The tool message name is the action name.
Summary by CodeRabbit