Skip to content

Latest commit

 

History

History
183 lines (148 loc) · 5.92 KB

File metadata and controls

183 lines (148 loc) · 5.92 KB
title Reading agent state
icon lucide/ArrowLeft
description Read the realtime agent state in your native application.

What is this?

You can easily use the realtime agent state not only in the chat UI, but also in the native application UX.

CopilotKit consumes AG-UI protocol events streamed by AG2 over /chat. See the AG2 AG-UI integration docs.

When should I use this?

You can use this when you want to provide the user with feedback about your agent's state. As your agent's state updates, you can reflect these updates natively in your application.

Implementation

### Run and connect your agent Start your AG2 backend and connect your CopilotKit frontend to the AG-UI `/chat` endpoint. ### Define the Agent State
Create your AG2 backend with `ContextVariables` and emit `StateSnapshotEvent` whenever the state changes:

```python title="agent.py"
from typing import Annotated

from ag_ui.core import EventType, StateSnapshotEvent
from fastapi import FastAPI, Header
from fastapi.responses import StreamingResponse
from autogen import ConversableAgent, LLMConfig
from autogen.agentchat import ContextVariables
from autogen.ag_ui import AGUIStream, RunAgentInput

def read_state(context: ContextVariables) -> dict:
    return context.get("agent_state", {"language": "english"})

def write_state(context: ContextVariables, state: dict) -> StateSnapshotEvent:
    context["agent_state"] = state
    return StateSnapshotEvent(type=EventType.STATE_SNAPSHOT, snapshot=state)

agent = ConversableAgent(
    name="assistant",
    system_message=(
        "You are a helpful assistant for tracking language. "
        "Always respond in the current language."
    ),
    llm_config=LLMConfig({"model": "gpt-5.4-mini"}),
    human_input_mode="NEVER",
)

@agent.register_for_llm(description="Update the language in shared state.")
def set_language(
    context: ContextVariables,
    language: Annotated[str, "language such as english or spanish"],
) -> StateSnapshotEvent:
    return write_state(context, {"language": language.lower()})

agent.register_for_execution(name="set_language")(set_language)

stream = AGUIStream(agent)
app = FastAPI()

@app.post("/chat")
async def run_agent(
    message: RunAgentInput,
    accept: str | None = Header(None),
):
    return StreamingResponse(
        stream.dispatch(message, accept=accept),
        media_type=accept or "text/event-stream",
    )
```
### Use the `useAgent` Hook With your agent connected and running all that is left is to call the [useAgent](/reference/v1/hooks/useAgent) hook, pass the agent's ID, and optionally provide an initial state.
```tsx title="ui/app/page.tsx"
import { useAgent } from "@copilotkit/react-core/v2"; // [!code highlight]

// Define the agent state type, should match the actual state of your agent
type AgentState = {
  language: "english" | "spanish";
}

function YourMainContent() {
  // [!code highlight:4]
  const { agent } = useAgent({
    agentId: "my_agent", // MUST match the agent name in CopilotRuntime
    initialState: { language: "english" }  // optionally provide an initial state
  });

  // ...

  return (
    // style excluded for brevity
    <div>
      <h1>Your main content</h1>
      {/* [!code highlight:1] */}
      <p>Language: {agent.state.language}</p>
    </div>
  );
}
```

<Callout type="warn" title="Important">
  The `agentId` parameter must exactly match the agent name you defined in your CopilotRuntime configuration (e.g., `my_agent` from the quickstart).
</Callout>

<Callout type="info">
  The `agent.state` in `useAgent` is reactive and will automatically update when the agent's state changes.
</Callout>
### Give it a try As the agent state updates, your `state` variable will automatically update with it. In this case, you'll see the language set to "english" as that's the initial state we set.

Rendering agent state in the chat

You can also render the agent's state in the chat UI. This is useful for informing the user about the agent's state in a more in-context way. To do this, you can use the useAgent hook with a render function.

import { useAgent } from "@copilotkit/react-core/v2"; // [!code highlight]

// Define the agent state type, should match the actual state of your agent
type AgentState = {
  language: "english" | "spanish";
};

function YourMainContent() {
  // ...
  // [!code highlight:7]
  useAgent({
    agentId: "my_agent",
    render: ({ state }) => {
      if (!state.language) return null;
      return <div>Language: {state.language}</div>;
    },
  });
  // ...
}
The `name` parameter must exactly match the agent name you defined in your CopilotRuntime configuration (e.g., `my_agent` from the quickstart). The `agent.state` in `useAgent` is reactive and will automatically update when the agent's state changes.

Intermediately Stream and Render Agent State

By default, AG2 state updates are visible to CopilotKit whenever your backend emits StateSnapshotEvent. For smoother long-running workflows, emit additional intermediate snapshots from your backend tools.