Skip to content

fix: only fetch agent state for langgraph agents - #2093

Merged
ranst91 merged 1 commit into
mainfrom
fix/fetch-agent-state
Jul 3, 2025
Merged

ranst91 merged 1 commit into
mainfrom
fix/fetch-agent-state

Conversation

@ranst91

@ranst91 ranst91 commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

This PR fixes the "eager" state loading, which is still possible for langgraph agents, but not possible for other agents atm, which causes some errors.

Summary by CodeRabbit

  • Refactor
    • Improved internal logic for loading agent state to enhance reliability and prevent potential errors. No visible changes to user-facing features.

@changesets-bot-copilotkit

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: a229224

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel

vercel Bot commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
copilotkit-feature-viewer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 3, 2025 8:04am
demo-viewer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 3, 2025 8:04am
docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 3, 2025 8:04am
examples-coagents-ai-travel-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 3, 2025 8:04am
examples-coagents-research-canvas-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 3, 2025 8:04am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
examples-coagents-ai-researcher-ui ⬜️ Ignored (Inspect) Visit Preview Jul 3, 2025 8:04am

@coderabbitai

coderabbitai Bot commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The loadAgentState method in copilot-runtime.ts has been refactored to improve how the agent client is instantiated and how agent state is retrieved. The logic now includes earlier agent lookup, conditional client creation, and a null check before fetching state, with error handling and public interfaces unchanged.

Changes

File(s) Change Summary
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts Refactored loadAgentState to adjust agent lookup, conditional client instantiation, and null checks before retrieving agent state. No changes to exported/public signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant CopilotRuntime
    participant AgentsRegistry
    participant LangGraphClient

    Caller->>CopilotRuntime: loadAgentState(threadId)
    CopilotRuntime->>AgentsRegistry: Retrieve aguiAgent
    AgentsRegistry-->>CopilotRuntime: aguiAgent or error
    alt aguiAgent found
        CopilotRuntime->>CopilotRuntime: Determine endpoint type
        alt endpoint is LangGraphPlatform
            CopilotRuntime->>LangGraphClient: Instantiate with deploymentUrl, apiKey
        else
            CopilotRuntime->>CopilotRuntime: Use existing client or null
        end
        alt client is not null
            CopilotRuntime->>LangGraphClient: getState(threadId)
            LangGraphClient-->>CopilotRuntime: agentState
        else
            CopilotRuntime->>CopilotRuntime: agentState = {}
        end
    else aguiAgent not found
        CopilotRuntime->>Caller: Throw error
    end
    CopilotRuntime-->>Caller: agentState
Loading

Possibly related PRs

Suggested labels

preview

Suggested reviewers

  • mme
  • suhasdeshpande
  • ataibarkai
  • tylerslaton
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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

🔭 Outside diff range comments (1)
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (1)

1019-1019: Remove unreachable code.

This throw statement is unreachable because all execution paths above it either return or throw an exception. This creates dead code that should be removed.

-    throw new Error(`Agent: ${agent.name} could not be resolved`);

The error handling is already properly covered by the earlier validation at lines 967-969.

🧹 Nitpick comments (1)
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (1)

973-985: Good implementation of conditional state fetching, but address TypeScript error properly.

The conditional client creation and null-safe state fetching logic correctly implements the PR objective of preventing errors when fetching state for non-langgraph agents. However, the @ts-expect-error comment suggests underlying type compatibility issues.

Consider addressing the TypeScript error properly instead of suppressing it:

       } else {
-        // @ts-expect-error -- both clients are the same
-        client = aguiAgent.client ?? null;
+        // Ensure type compatibility between client types
+        client = (aguiAgent.client as LangGraphClient) ?? null;
       }

Alternatively, create a proper type guard or interface to ensure type safety.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 547c7c5 and a229224.

📒 Files selected for processing (1)
  • CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (1)
sdk-python/copilotkit/langgraph_agent.py (1)
  • LangGraphAgent (85-700)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Build Images (coagents-qa-native, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-research-canvas, agent, python, local-deps)
  • GitHub Check: Build Images (next-openai, next-openai)
  • GitHub Check: Build Images (coagents-qa-text, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-qa-text, ui)
  • GitHub Check: Build Images (coagents-qa-native, ui)
  • GitHub Check: Build Images (coagents-research-canvas, ui)
  • GitHub Check: Build Images (coagents-routing, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-routing, ui)
  • GitHub Check: Test (20.x)
  • GitHub Check: Test (18.x)

Comment on lines +966 to 969
const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent;
if (!aguiAgent) {
throw new Error(`Agent: ${agent.name} could not be resolved`);
}

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.

🛠️ Refactor suggestion

Replace unsafe type assertion with proper type checking.

The type assertion as LangGraphAgent is potentially unsafe and could lead to runtime errors if the agent isn't actually a LangGraphAgent instance. This could cause issues when accessing LangGraphAgent-specific properties later.

-    const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent;
+    const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
     if (!aguiAgent) {
       throw new Error(`Agent: ${agent.name} could not be resolved`);
     }
+    
+    // Verify it's a LangGraphAgent if we need LangGraph-specific functionality
+    if (!(aguiAgent instanceof LangGraphAgent)) {
+      throw new Error(`Agent: ${agent.name} is not a LangGraphAgent instance`);
+    }
📝 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
const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent;
if (!aguiAgent) {
throw new Error(`Agent: ${agent.name} could not be resolved`);
}
// Early lookup without assertion
const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
if (!aguiAgent) {
throw new Error(`Agent: ${agent.name} could not be resolved`);
}
// Verify it's a LangGraphAgent before using lang-graph–specific APIs
if (!(aguiAgent instanceof LangGraphAgent)) {
throw new Error(`Agent: ${agent.name} is not a LangGraphAgent instance`);
}
🤖 Prompt for AI Agents
In CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts around lines
966 to 969, replace the unsafe type assertion 'as LangGraphAgent' with a proper
type check to ensure the retrieved agent is indeed an instance of
LangGraphAgent. Use a runtime type guard or instanceof check before accessing
LangGraphAgent-specific properties, and throw an error if the type does not
match to prevent runtime errors.

@github-actions

github-actions Bot commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

Preview environments destroyed for this pull request.

@github-actions

github-actions Bot commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

Test Results

Status: ✅ Passed (View Run)

Commit: 01e3b14

Duration: 242.2s

Total Tests: 20

Pass Rate: 100.0%

Failed Tests: 0

🔍 Detailed Results

coagents-research-canvas

CoAgents Research Canvas (UI) - Local Depenencies

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
CrewAI chromium ✅ PASSED -

coagents-qa-native

CoAgents QA Native (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -

coagents-qa-text

CoAgents QA Text (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
OpenAI (LGC Python) chromium ✅ PASSED -
Anthropic (LGC Python) chromium ✅ PASSED -
OpenAI (LGC JS) chromium ✅ PASSED -
Anthropic (LGC JS) chromium ✅ PASSED -

coagents-routing

CoAgents Routing (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -

next-openai

Next OpenAI - Self Hosted

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
Google Generative AI chromium ✅ PASSED -
LangChain (OpenAI) chromium ✅ PASSED -
LangChain (Anthropic) chromium ✅ PASSED -
LangChain (Gemini) chromium ✅ PASSED -
Groq chromium ✅ PASSED -

This branch was successfully deployed

5 active deployments
Preview – docs — a2292242 Deployed Jul 3, 2025 by vercel[bot]
Preview – examples-coagents-research-canvas-ui — a2292242 Deployed Jul 3, 2025 by vercel[bot]
Preview – copilotkit-feature-viewer — a2292242 Deployed Jul 3, 2025 by vercel[bot]
Preview – demo-viewer — a2292242 Deployed Jul 3, 2025 by vercel[bot]
Preview – examples-coagents-ai-travel-app — a2292242 Deployed Jul 3, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant