Commit Graph

145 Commits

Author SHA1 Message Date
Martha Schumann 981734fb99 fix: propagate useCopilotReadable context and CopilotKit properties into Python LangGraph agent state
Two silent failures in the Python SDK prevented frontend context from reaching the agent:

1. langgraph_default_merge_state rebuilt copilotkit as {actions} only, dropping the
   useCopilotReadable items the TypeScript runtime had placed in state.copilotkit.context.
2. CopilotKitContext.properties were never forwarded through execute_agent → agent.execute(),
   so <CopilotKit properties={...} /> values never reached state.copilotkit.properties.

Both fields now land cleanly under state["copilotkit"] on every agent invocation.
Also adds tests, a showcase example, and a new docs page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 18:37:51 -07:00
Ran Shem Tov 6986a1c120 fix: use latest agui langgraph packages 2026-04-15 18:11:17 +02:00
Markus Ecker 0f02aae198 fix: align A2UI schema format with v0.9 spec and improve path binding prompts
- Replace custom { name, props } schema format with spec-aligned inline
  catalog format (allOf + properties) so the LLM sees the same flat
  structure it must produce — eliminates "props" nesting confusion.
- Restructure generation prompts: inline literal values are the default,
  path binding is a narrow schema-driven exception for form inputs.
- Export InlineCatalogSchema type from a2ui-renderer.
2026-04-15 12:28:13 +02:00
Markus Ecker abd0d5c11c fix: add path binding schema rule to A2UI generation prompts
LLMs sometimes use path bindings (e.g. {"path": "/chartData"}) on
component properties that only accept literal values, causing silent
render failures. The new guideline tells the LLM to check the schema's
anyOf type before using path bindings.
2026-04-15 11:51:05 +02:00
Jordan Ritter bc4a173751 fix: preserve graph-owned state keys during frontend state merge (#3852)
## Summary
- During frontend state merge in LangGraph agent, preserve keys that are
owned by the graph (not set by the frontend)
- Prevents graph-computed state from being overwritten when frontend
state is merged back

Closes #2893

---
*Split from #3847*
2026-04-14 14:06:10 -07:00
Jordan Ritter de78dfdb68 fix: sanitize NaN/Infinity values in LangGraph state before JSON serialization (#3851)
## Summary
- Add sanitization pass over LangGraph agent state to replace NaN and
Infinity with null before JSON serialization
- Prevents `ValueError: Out of range float values are not JSON
compliant` in Python SDK

Closes #1955

---
*Split from #3847*
2026-04-14 14:06:07 -07:00
Jordan Ritter fe365d3f7f fix: extract all text parts when AIMessage content is a list (#3844)
Partially addresses #1748

When Anthropic models return multi-part content lists, only the first
element was used and the rest discarded. Now iterates all parts and
concatenates text blocks, preserving the full message content.

Split from #3838.
2026-04-14 14:06:04 -07:00
Jordan Ritter 76b1d73bb8 fix: convert Pydantic BaseModel instances to dicts before serialization (#2158) (#3816)
## Summary

Fixes #2158

Pydantic `BaseModel` instances in LangGraph agent state are not
serializable by `langchain_dumps`. This adds a recursive
`_serialize_state` helper that converts `BaseModel` instances to dicts
before serialization, preventing crashes when state contains Pydantic
models.

**Additional fixes (second commit):**
- Also applies `_serialize_state` to the `get_state()` code path, which
was missed in the original fix but has the same bug
- Fixes `filter_state_on_schema_keys` returning `None` implicitly when
schema keys are not set (the `except` branch returned `state` but the
non-matching `if` branch did not)
- Adds 17 tests covering `_serialize_state`, `_emit_state_sync_event`,
and `get_state` with Pydantic models

## Merge order note

This PR and #3851 both modify
`sdk-python/copilotkit/langgraph_agent.py`. Both add a helper function
at module level and call it from `_emit_state_sync_event` and
`get_state`. Whichever merges second will need a trivial rebase. No
semantic conflict — the fixes are complementary (this one handles
Pydantic models, #3851 handles NaN/Infinity).

## Test plan

- [x] 17 unit tests covering both code paths
- [x] Red-green verified: `get_state` tests fail without fix, pass with
it
- [x] Existing test suite (test_emit_filtering) still passes
- [x] Verify LangGraph agent with Pydantic BaseModel state serializes
correctly
- [x] Verify non-Pydantic state is unaffected
2026-04-14 14:06:00 -07:00
Jordan Ritter 6d9efa00a9 test: add comprehensive tests for _sanitize_for_json
27 tests covering:
- Passthrough of valid types (floats, ints, strings, booleans, None)
- NaN and +/-Infinity replacement with None
- Recursive sanitization through dicts, lists, and tuples
- Real-world event structures (on_chain_end, streaming chunks, state sync)
2026-04-13 08:30:07 -07:00
Jordan Ritter e76b7f435e test(sdk-python): replace mock test with integration tests for emit_state merge
The original test only tested the _merge_emit_state helper in isolation
using mocks. Replace with integration tests that simulate the actual
state-tracking loop from _stream_events, including:

- Sequential emits with different keys preserve all keys (core bug)
- Proof that the bug manifests without current_graph_state.update
- Three sequential emits accumulate correctly
- Same key emitted twice uses latest value
- Non-dict emit does not corrupt current_graph_state
- Initial state reference is not mutated
2026-04-13 08:29:15 -07:00
Jordan Ritter 35705db3c7 fix(sdk-python): update current_graph_state after manual emit to persist across iterations
The _merge_emit_state call merges emitted state with current_graph_state
into manually_emitted_state, but the `continue` statement skips the
later current_graph_state.update(updated_state). Without this update,
the next manual emit merges against stale current_graph_state and loses
keys from the previous emit.

Also guards the update call against non-dict values from _merge_emit_state
to prevent TypeError on edge-case non-dict emits.
2026-04-13 08:29:07 -07:00
Jordan Ritter a559406bee fix: also serialize Pydantic state in get_state() and fix implicit None return
The original fix only covered _emit_state_sync_event but missed the
get_state() code path, which also returns state containing Pydantic
BaseModel instances to callers that will JSON-serialize downstream.

Also fixes filter_state_on_schema_keys returning None implicitly when
schema keys are not set (the except branch returned state but the
non-matching if branch did not).

Adds 17 tests covering _serialize_state, _emit_state_sync_event, and
get_state with Pydantic models (nested, lists, plain dicts, empty).
2026-04-13 08:24:10 -07:00
Jordan Ritter d0b7b6981c fix: sanitize raw event stream to prevent NaN/Infinity in JSON output
The _sanitize_for_json function was applied to state sync events and
get_state responses but not to the raw event stream yielded at line 507.
Events with NaN/Infinity float values in their data payloads would
produce invalid JSON (literal NaN) that downstream parsers cannot handle.
2026-04-13 08:19:35 -07:00
Jordan Ritter 2e92fe1bff test: add tests for multi-part AIMessage content extraction
Verifies langchain_messages_to_copilotkit correctly concatenates all text
parts from list-style content blocks (Anthropic models). Includes
regression tests for the exact scenario from #1748 (text + image blocks)
and tests for string lists, mixed content, empty lists, and edge cases.
2026-04-13 08:19:29 -07:00
Jordan Ritter 35ee689652 fix: preserve graph-owned state keys during frontend state merge (#2893) 2026-04-12 15:25:10 -07:00
Jordan Ritter 0e57499664 fix: sanitize NaN/Infinity values in LangGraph state before JSON serialization (#1955) 2026-04-12 15:25:03 -07:00
Jordan Ritter 2f3938036e fix: extract all text parts when AIMessage content is a list (#1748)
When Anthropic models return multi-part content lists, only the first
element was used and the rest discarded. Now iterates all parts and
concatenates text blocks, preserving the full message content.
2026-04-12 15:16:36 -07:00
Jordan Ritter eb5b98f296 fix: convert Pydantic BaseModel instances to dicts before langchain_dumps serialization (#2158) 2026-04-12 14:59:36 -07:00
Jordan Ritter ee9e9c37b8 fix(sdk-python): copilotkit_emit_state merges state instead of replacing (#3138)
Sequential emit_state calls with different keys now preserve all keys
in the snapshot. Previously, each call would replace the entire
manually_emitted_state, losing keys from earlier calls.
2026-04-12 13:21:53 -07:00
Jordan Ritter f5462915c3 ci: fix static_danger matrix bug, python-sdk concurrency and dep pin
- static_danger: removed undefined matrix.node-version, upgraded to
  v4, added concurrency and timeout
- python-sdk: added concurrency and timeout, pinned ag-ui-langgraph
  <0.0.32 (0.0.32 imports non-existent ImageInputContent from ag_ui.core)
2026-04-10 10:37:42 -07: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
Ran Shem Tov a7e3e131d5 chore: loosen up langgraph dependencies on copilotkit and release 2026-04-07 13:14:00 +02:00
Ran Shem Tov aae2c5cee1 chore: use latest ag-ui langgraph version 2026-04-03 14:57:45 +02:00
Alem Tuzlak 79ce60c580 chore: migrate from eslint+prettier to oxlint+oxfmt
Replace eslint and prettier with oxlint and oxfmt for faster linting
and formatting across the monorepo. Remove all eslint and prettier
configs, dependencies, and related packages. Add .oxlintrc.json and
.oxfmtrc.json for the new tooling. Update CI workflows and lefthook
hooks accordingly. Reformat codebase with oxfmt.

https://claude.ai/code/session_01GMkSf29p78HuMR1mbXn8He
2026-04-02 16:39:05 +02: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
Tyler Slaton a33d24496b chore(sdk-python): bump version to 0.1.82
Signed-off-by: Tyler Slaton <tyler@copilotkit.ai>
2026-03-20 16:27:22 -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
Ran Shem Tov 3c98ceab9c chore: release py-sdk 0.1.81 2026-03-19 13:45:33 +01:00
Ran Shem Tov 2f2fdec7ee chore: fix python test ci process 2026-03-19 13:45:10 +01:00
Ran Shem Tov c3adbd4113 chore: release py-sdk 0.1.80 2026-03-19 13:00:14 +01:00
Ran Shem Tov 31a721cdae feat: re-export state streaming langgraph middleware 2026-03-19 12:58:55 +01:00
Ran Shem Tov 82eaf93f11 chore: release lg python sdk 0.1.79 2026-03-13 17:31:15 +01:00
Ran Shem Tov 4506570206 chore: use latest python langgraph ag-ui 2026-03-13 13:49:15 +01: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
Ran Shemtov de02e9cef0 Merge branch 'main' into fix/2667-langgraph-agui-agent-dict-repr 2026-03-11 16:27:00 +01:00
Maxim 46d58ac3bf chore(sdk-python): regenerate poetry.lock
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 15:28:26 +04:00
Maxim c5ec0f8512 fix(sdk-python): guard assistant message with content check
Avoid emitting spurious empty assistant messages for tool-call-only
AIMessages (common with OpenAI models where content is empty string).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 15:28:26 +04:00
Maxim 3b684d914b fix(sdk-python): always emit assistant message for AIMessages with tool_calls
langchain_messages_to_copilotkit previously skipped creating the assistant
message when an AIMessage had tool_calls, causing missing context in chat
history on reconnect. Also adds ActionExecutionMessage type guard in
copilotkit_messages_to_langchain to prevent KeyError on non-tool messages
with parentMessageId.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 15:28:26 +04:00
Jordan Ritter 973b4e460e fix(sdk-python): loosen FastAPI version ceiling from ^0.115.0 to >=0.115.0,<1.0.0 (#3261)
## Problem

The Poetry caret constraint `^0.115.0` in `sdk-python/pyproject.toml`
resolves to `>=0.115.0,<0.116.0` for 0.x versions (per [PEP 440 / Poetry
docs](https://python-poetry.org/docs/dependency-specification/#caret-requirements)).
This blocks installation alongside any FastAPI release since **0.116.0
(June 2025)**.

Current stable FastAPI is **0.129.0** — 14 minor versions ahead of the
ceiling.

## Impact

- Cannot `pip install copilotkit` in any project using FastAPI >=0.116.0
- Multiple users blocked (see #2771 comments)
- Our production project has **~90 tests bypassed** with
`COPILOTKIT_AVAILABLE = False` guards because of this

## Fix

```diff
- fastapi = "^0.115.0"
+ fastapi = ">=0.115.0,<1.0.0"
```

This allows all current and future 0.x FastAPI releases while still
capping at the upcoming 1.0 major version boundary, which may introduce
breaking changes.

## Testing

- The SDK uses standard FastAPI features (routing, dependency injection,
middleware) that have been stable across all 0.11x–0.12x releases
- No FastAPI APIs used by the SDK were deprecated or removed in
0.116.0–0.129.0
- `ag-ui-langgraph` (also in deps) uses `>=0.115.0` without an upper
bound, so this change aligns the two constraints

## Note on `ag-ui-langgraph`

`ag-ui-langgraph[fastapi]` also depends on FastAPI. Its constraint is
already `>=0.115.0` (no ceiling), so this change to `copilotkit` is the
only fix needed.

Fixes #2771
2026-03-06 14:39:52 -04:00
Jordan Ritter 8bad9f30ac test: add unit tests for emit_messages/emit_tool_calls filtering
Tests the two bugs fixed in this PR:
1. Dict raw_event metadata must be read with .get(), not getattr()
2. Filtered events must return None (not ""), and run() strips them

Adds pytest as a dev dependency.
2026-03-06 08:32:06 -08:00
Valen 95fada4490 fix(sdk-python): fix emit_messages and emit_tool_calls config not working
Fixes #2066

## Problem

`copilotkit_customize_config(config, emit_messages=False)` does not work -
TEXT_MESSAGE_* events are still emitted despite the configuration.

## Root Causes

1. **Metadata Reading Bug**: In `langgraph_agui_agent.py`, the code uses
   `getattr(raw_event, 'metadata', {})` to read metadata, but `raw_event`
   is a dict, not an object. This should use `.get()` instead.

2. **Encoder Crash Bug**: When the filtering logic works (after fixing bug #1),
   it returns `""` (empty string) to skip dispatching events. However, this
   empty string gets yielded to the event encoder which expects event objects
   with `model_dump_json()` method, causing an `AttributeError`.

## Fixes

1. Changed metadata reading to handle both dict and object cases.
2. Changed return value from `""` to `None` for filtered events.
3. Added `run()` method override to filter out `None` values before yielding
   to encoder.
2026-03-06 08:29:04 -08:00
Alem Tuzlak f4e8fdf61f Merge branch 'main' into fix/prebuilt-agent-state-streaming 2026-03-02 18:06:02 +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 Shem Tov b21db3a8fc fix: do not override predict state metadata if no cpk prefixed metadata present 2026-03-02 13:30:33 +01:00
BreBryBro 62ba11fe1c fix(sdk-python): loosen FastAPI version ceiling from ^0.115.0 to >=0.115.0,<1.0.0
The Poetry caret constraint `^0.115.0` resolves to `>=0.115.0,<0.116.0` for
0.x versions, blocking installation alongside any FastAPI release since 0.116.0
(June 2025). This prevents adoption of the Python SDK in projects using current
FastAPI versions.

Change to `>=0.115.0,<1.0.0` to allow all 0.x releases while still capping
at the upcoming 1.0 major version boundary.

Fixes #2771
2026-02-23 16:19:04 -06:00
Ran Shemtov c07362d137 chore: release py sdk 0.1.78 (#3158) 2026-02-06 13:01:23 +01:00
Ran Shemtov f0a0ed5e60 feat: add app context readables to prebuilt LG agent middleware (#3155) 2026-02-06 12:49:04 +01:00
Ran Shem Tov 880bdd9907 chore: update all local dependencies of sdk-python 2026-01-29 11:27:08 -07:00
Ran Shem Tov 8ffb56a58e chore: update old dependencies of sdk-python 2026-01-29 11:27:08 -07:00
Ran Shemtov b49277b605 fix: update all agui langgraph dependencies (#3115) 2026-01-28 16:22:04 +01:00