26 Commits

Author SHA1 Message Date
hata33 963f753f53 fix(sdk-python): strip orphan OpenAI Responses function_call content blocks
after_model strips intercepted frontend tool_calls from the AIMessage but
leaves the equivalent responses/v1 function_call content blocks in
message.content. When a run is cancelled mid-turn the partial turn persists
without a ToolMessage, and on replay langchain-openai serializes the
orphaned block into the Responses API input with no matching
function_call_output, so OpenAI rejects every subsequent turn with
400 "No tool output found for function call call_...".

Extend the checkpoint message sanitizer to treat function_call blocks
like the existing Anthropic tool_use handling: strip blocks whose call_id
is missing from msg.tool_calls, strip all of them when tool_calls is
empty, and strip the ones belonging to unanswered tool_calls.

Fixes #6676
2026-08-29 10:58:40 +08:00
Ben Taylor cd0d38a073 fix(sdk-python): restore frontend tool history faithfully in LangGraph middleware (#5308)
## Description

Fixes the LangGraph middleware "lying" to the agent about frontend tool
execution (#4759). When a model turn calls a `useFrontendTool` handler,
the middleware strips the FE tool calls so the backend `ToolNode` only
runs calls it actually made, then rehydrates them afterward. Previously
the rehydration could leave the restored AI message and its tool history
inconsistent, so providers that require every tool call to have a
matching result would break, and the agent saw an incorrect picture of
what executed.

## Changes

- `_restore_intercepted_tool_call_history` rebuilds the intercepted FE
tool calls with synthetic `ToolMessage` results only for the restored
model history (so providers that require every `tool_call` to have a
result stay valid), and preserves the original AI message's `name`,
`additional_kwargs`, and `response_metadata` on restore.
- Tracks `original_tool_calls` in the CopilotKit private state so the
original call set is restored exactly.

## Testing

`uv run pytest tests/test_copilotkit_lg_middleware.py` — 68 passed,
including new cases asserting the restored AI message keeps its
tool-call ids, name, `additional_kwargs`, and `response_metadata`, and
that tool results line up with their calls.

Closes #4759

AI was used for assistance.
2026-08-17 12:54:26 -05:00
mvanhorn 467d1c5337 fix: implemented the remaining review fix:
Implemented the remaining review fix:
- Sync and async model restoration now operate on copied message lists, preventing synthetic results from entering checkpoint state.
- Removed the obsolete synthesis flag and ineffective result-ID filter.
- `after_agent` restores the frontend call as an orphan.
- Added sync/async regression coverage for request-scoped restoration.
[Middleware changes](/Users/mvanhorn/.osc/workspaces/CopilotKit-CopilotKit-pr5308/sdk-python/copilotkit/copilotkit_lg_middleware.py:450)
[Regression tests](/Users/mvanhorn/.osc/workspaces/CopilotKit-CopilotKit-pr5308/sdk-python/tests/test_copilotkit_lg_middleware.py:618)
```text
2026-08-13 09:39:14 -07:00
Matt Van Horn 9f847a2e47 fix(sdk-python): keep the frontend tool call orphaned in after_agent
Addresses both review concerns on the after_agent half.

after_agent no longer synthesizes a forwarded_to_frontend ToolMessage. That
synthetic result did not match _INTERRUPTED_PAT, so _fix_messages_for_bedrock
and langchain's patch_orphan_tool_calls treated it as a real second result and
skipped the reposition path, which on the Bedrock path could leave the real
frontend result non-adjacent and then stripped as unanswered. The restore helper
now takes synthesize_frontend_tool_results, which after_agent sets to False so
the call stays an orphan for the real result to fill, and any synthetic result
already in history is dropped by id.

The sync wrap_model_call now also runs _fix_messages_for_bedrock, matching
awrap_model_call, so the messages it injects go through the same dedup instead
of risking a duplicate tool_call id on the sync path.
2026-07-25 13:32:24 -07:00
Rod Boev fee7ec237c fix(sdk-python): bridge copilotkit context into LangGraph subgraphs 2026-07-24 16:19:13 -04:00
Rod Boev bb32138e15 fix(sdk-python): read copilotkit context from config when state is empty (subgraph support) 2026-07-24 16:13:05 -04:00
godququ5-code 44c43e4770 fix(python-sdk): fold app context into system prompt 2026-07-03 01:06:09 +03:00
Ran Shem Tov f13865a21f fix(sdk-python): declare ag-ui state channel and add a2ui_params host override
The middleware reads state["ag-ui"]["inject_a2ui_tool"] and
state["ag-ui"]["a2ui_schema"], but "ag-ui" was never declared on the
StateSchema, so create_agent's StateGraph dropped both keys before the
middleware ran — the generate_a2ui tool never injected and the catalog was
lost. Declare the "ag-ui" channel via StateSchema.__annotations__ so the flag
and catalog survive.

Also add an a2ui_params kwarg so a host can steer the auto-injected
generate_a2ui subagent (design/generation guidelines, catalog id, ...). The
middleware still injects the bound model and folds the registered catalog in,
but host-set values win.
2026-06-19 17:50:26 +02:00
Ran Shem Tov 5bb32b9dd5 feat(a2ui): use new ag-ui single-arg A2UIToolParams API (OSS-248)
ag-ui-langgraph's tool factory now takes one A2UIToolParams object (model
inside) and folds composition_guide into the guidelines bag.

- sdk-js middleware: getA2UITools(params) + type A2UIToolParams import;
  pin @ag-ui/langgraph 0.0.40 (the JS release carrying the new API).
- sdk-python middleware: get_a2ui_tools(params) + guarded A2UIToolParams
  import; pin ag-ui-langgraph >=0.0.41 (the py release with the new API).
- Update the a2ui injection test skip-reason wording.
2026-06-09 12:13:51 +02:00
Matt Van Horn 850c74e4b8 fix(sdk-python): keep LangGraph middleware honest about frontend tool execution
The middleware strips FE tool calls so the backend ToolNode only executes
its own calls, then restores them. Restoration now rebuilds the intercepted
calls with synthetic ToolMessage results scoped to the restored model
history (providers that require a result per tool_call stay valid) and
preserves the original AI message's name, additional_kwargs, and
response_metadata. Tracks original_tool_calls in private state so the
original call set is restored exactly.

Closes #4759

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 09:02:34 -07:00
Ran Shem Tov 3ca0f194b8 feat(sdk): gate auto-A2UI injection on injectA2UITool (opt-in)
The A2UI middleware (@ag-ui/a2ui-middleware) forwards injectA2UITool on
forwardedProps; ag-ui-langgraph surfaces it into agent state at
state["ag-ui"]["inject_a2ui_tool"]. The CopilotKit LangGraph middleware
(py + js) now reads that flag and only injects generate_a2ui when it is
truthy (opt-in), drops the runtime's render_a2ui so the model sees one
A2UI tool, and skips if the agent already defines generate_a2ui. The
catalog only binds surfaces; it is no longer the gate.

Reverts the earlier runtime-forward + context-channel approach.

Deps: ag-ui-langgraph>=0.0.38 (py), @ag-ui/langgraph 0.0.37 (sdk-js),
@ag-ui/a2ui-middleware 0.0.6 + @ag-ui/langgraph 0.0.37 (runtime);
.npmrc min-release-age exclude for @ag-ui/a2ui-middleware. Showcase
langgraph pins bumped to copilotkit==0.1.94a3 / sdk-js 1.59.3-alpha.3 /
@ag-ui/langgraph 0.0.37.
2026-06-04 18:37:03 +02:00
Ran Shem Tov 1bd944bd43 feat(sdk): source A2UI catalog wherever the frontend registered it
The auto-injected generate_a2ui tool now resolves the A2UI catalog from
both delivery paths: the CopilotKit runtime proxy (a copilotkit.context
entry) and the AG-UI native endpoint (state["ag-ui"].a2ui_schema). The
registered catalog id is extracted and bound to generated surfaces so
BYOC custom catalogs render their own components instead of the basic
catalog. Covers @copilotkit/sdk-js and the copilotkit Python SDK.
2026-06-04 18:36:12 +02:00
Ran Shem Tov ce4e4142b2 feat(sdk): auto-inject A2UI tool in CopilotKitMiddleware
Prebuilt agents get dynamic A2UI with no extra wiring — adding the
middleware is enough. When the frontend registers an A2UI catalog
(surfaced by the runtime into state["ag-ui"].a2ui_schema), the
middleware infers the agent's own model, advertises the generate_a2ui
tool in the model-call hook, and executes it in the tool-call hook.
No catalog → the tool is never advertised.

Covers both @copilotkit/sdk-js and the copilotkit Python SDK. Bumps
the A2UI tool-factory dependency to where get_a2ui_tools ships
(@ag-ui/langgraph 0.0.35, ag-ui-langgraph >=0.0.37).
2026-06-04 18:36:12 +02:00
github-actions[bot] b2f10f6753 style: auto-fix formatting 2026-05-29 03:58:54 +00:00
Jordan Ritter 59eff59b7f fix(sdk-python): strip copilotkit_forwarded_headers from LLM prompt (App Context + expose_state)
langgraph-api auto-copies the entire config.configurable dict into runtime.context. That dict
carries the CopilotKit-internal transport key `copilotkit_forwarded_headers`, populated solely
to drive the httpx header-forwarding hook (it is not user-visible state). The middleware's
before_agent step then rendered runtime.context into the LLM prompt as an "App Context" system
message, and the expose_state path could surface the same key via the state note — either path
leaks transport headers into the prompt body and, under strict fixture matching (D6/aimock),
changes the request payload and breaks the match.

Fix: hard-exclude `copilotkit_forwarded_headers` from both render paths. The App Context
renderer strips the reserved key before serialization, and the expose_state allowlist applies
the same exclusion so an explicit allow cannot reintroduce the leak. The httpx hook is
unchanged, so the key still reaches aimock as an HTTP header — pure conveyance, no body
pollution.

Adds red-green unit coverage for both paths (App Context strip, expose_state default + allowlist).
2026-05-28 20:57:37 -07:00
Jordan Ritter 7b2f1e9be6 fix(sdk-python): forwarded-header extraction with precedence, normalization, and exception-safe clearing
Extract incoming x-* headers from LangGraph's runtime config and republish
them via the forwarded-headers ContextVar so the httpx hook can attach
them to outbound provider requests. Apply documented precedence
(context > configurable, wrapper-dict > raw x-*) by processing sources
in order with first-write-wins and lowercasing keys at insertion so
mixed-case headers do not silently overwrite each other downstream.

Always clear the ContextVar on early exits so stale headers from a prior
request never leak into the next: explicit set_forwarded_headers({}) on
the RuntimeError no-active-runnable path and on the generic exception
fallback. The happy path already overwrites the ContextVar
unconditionally, even with an empty dict.

The change also installs the httpx event hook once per chat-model client
via a module-level set keyed by id(client), so models reused across
requests pick up fresh per-request headers without re-hooking.
2026-05-22 14:36:43 -07:00
Jordan Ritter 9107e00a9a fix(runtime): close header propagation gap for LangGraphAgent
The if (agent.headers) guard in configureAgentForRequest silently
skipped header forwarding when agent.headers was undefined (the
default for LangGraphAgent). This meant x-aimock-context, x-test-id,
and other x-* headers were never forwarded to agent backends.

Also wires install_httpx_hook in the Python SDK middleware so
forwarded headers propagate to outgoing LLM API calls.

Closes the gap documented in PR #4773 spec as out-of-scope.
2026-05-21 01:39:28 -07:00
Jordan Ritter 2482317ccc style: apply ruff format to Python codebase
320 files reformatted. One-time alignment to match the ruff format
check added to CI in #4812.
2026-05-13 23:10:35 -07:00
Ran Shem Tov 6c14258a39 feat(langgraph): add state injection to copilotkit middleware 2026-04-28 13:24:41 +02:00
Markus Ecker 0a11a05772 feat(sdk-python): A2UI helpers and before_agent ID reuse fix
Add copilotkit.a2ui module with operation builders and prompt helpers,
fix SystemMessage ID reuse in before_agent to prevent LangGraph duplication,
add Pydantic model_dump serialization for app_context.
2026-04-08 12:50:28 -07:00
Tyler Slaton 368663dd08 fix(sdk-python): add missing import re in copilotkit_lg_middleware
The re module was used in _fix_messages_for_bedrock (re.compile) but
never imported, causing NameError at runtime when the middleware is
invoked. Bumps version to 0.1.83.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-20 16:42:56 -07:00
Ran Shem Tov 4073d3d035 fix: deduplicate ToolMessages and tighten adjacent-only validation for Bedrock Converse API 2026-03-20 16:14:49 -07:00
Markus Ecker d6d2e2c96a Fix Bedrock Converse API compatibility in CopilotKitMiddleware
Add _fix_messages_for_bedrock() to handle three issues caused by
after_agent restoring frontend tool_calls to the checkpoint:

1. Strip unanswered tool_calls without matching ToolMessages (Bedrock
   rejects toolUse without a corresponding toolResult)
2. Sync msg.content tool_use blocks with msg.tool_calls
3. Fix tool_use/tool_call blocks with string input/args (must be dict)
2026-03-13 12:02:05 +01:00
Tyler Slaton cc8c945893 refactor(docs): optimize structure, content and navigability
Signed-off-by: Tyler Slaton <tyler@copilotkit.ai>
2026-03-02 11:30:16 -05:00
Ran Shemtov f0a0ed5e60 feat: add app context readables to prebuilt LG agent middleware (#3155) 2026-02-06 12:49:04 +01:00
Ran Shemtov 5a24f28894 feat: create copilotkit langgraph middleware (#2928) 2026-01-09 16:46:40 +01:00