Skip to content

fix: update thread_state with each state update - #2516

Closed
eaocx wants to merge 1 commit into
CopilotKit:mainfrom
eaocx:fix/2200-fix-thread-state
Closed

eaocx wants to merge 1 commit into
CopilotKit:mainfrom
eaocx:fix/2200-fix-thread-state

Conversation

@eaocx

@eaocx eaocx commented Sep 26, 2025 •

Copy link
Copy Markdown

What does this PR do?

Updates LangGraphAgent.thread_state anytime current_graph_state is updated. This allows the thread_state to be persisted for each thread_id as a chat is occurring.

Related PRs and Issues

Checklist

  • I have read the Contribution Guide
  • If the PR changes or adds functionality, I have updated the relevant documentation

Summary by CodeRabbit

  • Bug Fixes
    • Resolved an issue where thread-specific context could be lost between calls, leading to inconsistent behavior. Thread state now persists reliably across interactions.
  • Stability
    • Improved reliability for multi-threaded use, reducing intermittent context loss and state resets during consecutive operations.

@changesets-bot-copilotkit

Copy link
Copy Markdown

⏭️ Changeset Not Required

Latest commit: e231658

No changes in this PR affected the @copilitkit/* packages. Merging this PR will not cause a version bump for any packages.

Changeset is not required for this PR.

@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Updated sdk-python/copilotkit/langgraph_agent.py to persist thread-local state by synchronizing thread_state with current_graph_state at three update points. No changes to public APIs.

Changes

Cohort / File(s) Change summary
Thread state persistence updates
sdk-python/copilotkit/langgraph_agent.py
Added assignments to update thread_state after current_graph_state changes in three places to ensure state persists across calls.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant A as LangGraphAgent
  participant S as current_graph_state
  participant T as thread_state (per-thread)

  C->>A: invoke()
  A->>S: update state
  A->>T: mirror S into T[thread_id]
  Note right of A: Persist thread-local state for subsequent calls

  C->>A: invoke() again
  A->>T: read T[thread_id]
  A->>S: initialize/merge from T
  A-->>C: result
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

preview

Suggested reviewers

  • mme
  • suhasdeshpande
  • tylerslaton

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title clearly states that the thread_state is being updated with each state update, directly matching the main change of persisting thread-local state during graph state updates as described in the PR summary.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel

vercel Bot commented Sep 26, 2025

Copy link
Copy Markdown
Contributor

@eaocx is attempting to deploy a commit to the CopilotKit Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 799582f and e231658.

📒 Files selected for processing (1)
  • sdk-python/copilotkit/langgraph_agent.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
{sdk-python/**,sdk-python/copilotkit/crewai/**,sdk-python/copilotkit/openai/**}

📄 CodeRabbit inference engine (.cursor/rules/copilotkit-architecture.mdc)

Python SDK and its integrations should be implemented in sdk-python/, with CrewAI agents in sdk-python/copilotkit/crewai/ and OpenAI integrations in sdk-python/copilotkit/openai/

Files:

  • sdk-python/copilotkit/langgraph_agent.py

Comment on lines 232 to 236
current_graph_state.update(state)
self.thread_state[thread_id] = current_graph_state
lg_interrupt_meta_event = next((ev for ev in (meta_events or []) if ev.get("name") == "LangGraphInterruptEvent"), None)
has_active_interrupts = active_interrupts is not None and len(active_interrupts) > 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix thread_state assignment before generating a new thread_id

We’re storing current_graph_state under the pre-normalized thread_id, but a few lines later we replace a falsey thread_id with a freshly generated UUID. For first-time threads this writes the state under "", while the rest of the flow (and get_state) looks up the newly generated UUID, so the persisted state is never found. Move the assignment to occur after the UUID fallback to keep the keys aligned.

-        current_graph_state.update(state)
-        self.thread_state[thread_id] = current_graph_state
+        current_graph_state.update(state)
         lg_interrupt_meta_event = next((ev for ev in (meta_events or []) if ev.get("name") == "LangGraphInterruptEvent"), None)
@@
-        thread_id = thread_id or str(uuid.uuid4())
-        config["configurable"]["thread_id"] = thread_id
+        thread_id = thread_id or str(uuid.uuid4())
+        config["configurable"]["thread_id"] = thread_id
+        self.thread_state[thread_id] = current_graph_state
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
current_graph_state.update(state)
self.thread_state[thread_id] = current_graph_state
lg_interrupt_meta_event = next((ev for ev in (meta_events or []) if ev.get("name") == "LangGraphInterruptEvent"), None)
has_active_interrupts = active_interrupts is not None and len(active_interrupts) > 0
# update the graph state first
current_graph_state.update(state)
# only assign after we’ve ensured thread_id is finalized
lg_interrupt_meta_event = next(
(ev for ev in (meta_events or []) if ev.get("name") == "LangGraphInterruptEvent"),
None
)
has_active_interrupts = active_interrupts is not None and len(active_interrupts) > 0
# ensure we have a real thread_id before persisting state
thread_id = thread_id or str(uuid.uuid4())
config["configurable"]["thread_id"] = thread_id
self.thread_state[thread_id] = current_graph_state
🤖 Prompt for AI Agents
In sdk-python/copilotkit/langgraph_agent.py around lines 232 to 236, the code
assigns current_graph_state to self.thread_state using the original (possibly
falsey) thread_id before the code later generates a new UUID fallback; move the
self.thread_state[thread_id] = current_graph_state assignment to after the logic
that sets thread_id = thread_id or new_uuid so that the state is stored under
the normalized (non-empty) thread_id used elsewhere (and ensure thread_id is
used consistently thereafter).

@ddovbii

ddovbii commented Oct 6, 2025

Copy link
Copy Markdown

Nice!
My team faced a bug related to this (that the thread_state was never updated and we didn't see the fresh message history) and this fix is something we require

@eaocx

eaocx commented Oct 10, 2025

Copy link
Copy Markdown
Author

@ranst91 Any chance you or one of the other maintainers take a look at this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants