State Streaming

Stream partial agent state updates to the UI while a tool call is still running.

Not available for Langchain DeepAgents yet

The code on this page comes from the showcase's shared-state-streaming demo, and Langchain DeepAgents doesn't have it yet. See this page for CopilotKit's Built-in Agent, LangGraph (Python), LangGraph (TypeScript).

What is this?

By default, agent state only updates between backend checkpoints, so a long-running tool call, such as writing a full document or drafting an email, appears to the UI as one big burst at the end. For agent-native apps, that feels broken: users expect to watch the output materialize.

State streaming copies the value of one tool argument into an agent state key while the model writes it. The UI, subscribed through useAgent, re-renders every token.

When should I use this?

Use state streaming whenever a tool's output is long-form text or a growing structured value and you want the user to see it assemble in real time. Common shapes:

  • A collaborative writing agent that emits a document
  • A research agent that accumulates a list of findings
  • A planning agent that builds up a step-by-step plan

Without streaming, the user stares at a spinner. With streaming, they see the answer grow token-by-token.

The backend: one streaming state mapping

Build an agent that streams a tool argument into state

Deep Agents has no live demo on this page yet, so the demo code on this page does not show for it. Define the state key, add a tool that saves the completed value, and add StateStreamingMiddleware with one StateItem that maps the tool argument to the state key. This example streams a searches list:

agent.py
from typing import Any, TypedDict

from copilotkit import (
    CopilotKitMiddleware,
    CopilotKitState,
    StateItem,
    StateStreamingMiddleware,
)
from deepagents import create_deep_agent
from langchain_openai import ChatOpenAI
from langchain.agents.middleware import AgentMiddleware
from langchain.messages import ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.types import Command

class Search(TypedDict):
    query: str
    done: bool

class AgentState(CopilotKitState):
    searches: list[Search]

class SearchesStateMiddleware(AgentMiddleware[AgentState, Any, Any]):
    state_schema = AgentState

@tool
def report_research_progress(
    searches: list[Search],
    runtime: ToolRuntime[None, AgentState],
) -> Command:
    """Report the current research tasks and completion status."""
    return Command(
        update={
            "searches": searches,
            "messages": [
                ToolMessage(
                    content="Research progress saved.",
                    tool_call_id=runtime.tool_call_id,
                )
            ],
        }
    )

agent = create_deep_agent(
    model=ChatOpenAI(model="gpt-6-luna", reasoning_effort="none"),
    tools=[report_research_progress],
    middleware=[
        SearchesStateMiddleware(),
        CopilotKitMiddleware(),
        StateStreamingMiddleware(
            StateItem(
                state_key="searches",
                tool="report_research_progress",
                tool_argument="searches",
            )
        ),
    ],
    system_prompt=(
        "You are a research assistant. Use report_research_progress "
        "to show each task and mark it done when complete."
    ),
)

Understand the two update phases

The state-streaming middleware sends the partial searches argument while the model writes it. The frontend can show each partial value at once.

The tool then returns a Command that saves the completed list. Its ToolMessage closes the active tool call.

When the run finishes, the agent's final state is the single source of truth. A streamed value that the tool does not also save in its Command disappears at the end of the run, with no error.

Each setting must match your code. A mismatch sends updates to the wrong state field, or to none:

  • state_key (stateKey): the state field.
  • tool: the name of the tool.
  • tool_argument (toolArgument): the argument of the tool.

Render the state in the UI

Use useAgent to read the state anywhere in your app: in the chat, in a dashboard, in a sidebar.

app/page.tsx
import { useAgent } from "@copilotkit/react-core/v2";

function YourMainContent() {
  const { agent } = useAgent({
    agentId: "sample_agent",
  });

  const state = (agent.state ?? {}) as {
    searches?: { query: string; done: boolean }[];
  };
  const searches = state.searches ?? [];

  return (
    <div>
      {searches.map((search, index) => (
        <div key={index}>
          {search.done ? "✅" : "⏳"} {search.query}
        </div>
      ))}
    </div>
  );
}

Ask the agent to research a topic. The search items appear and update while the agent works.

The backend pattern is always the same: map one streaming tool argument to one shared-state key. Middleware-backed frameworks usually expose this as a declarative mapping. Direct SDK adapters do the same work in their streaming loop by parsing partial tool arguments and emitting STATE_SNAPSHOT whenever the mapped value changes. When the LLM streams that argument, CopilotKit writes every partial value into shared state before the tool finishes executing. The sample below is the LangGraph (Python) version.

A few things to note:

  • The state key must exist in your agent state (document in this example).
  • The tool and argument names must match the exact LLM-facing tool call you want to forward.
  • When the tool call completes, its final return value is written to the same key, so the streamed partial eventually becomes the authoritative final value.

The frontend: useAgent + OnStateChanged

The UI side is identical to any other shared-state subscription: useAgent with OnStateChanged gives you a reactive agent.value.state. Add OnRunStatusChanged if you want a live/done indicator.

src/components/StreamingDocument.vue
<script setup lang="ts">
import { computed } from "vue";
import { useAgent, UseAgentUpdate } from "@copilotkit/vue/v2";

type DocumentState = { document?: string };

const { agent } = useAgent({
  agentId: "writer",
  updates: [
    UseAgentUpdate.OnStateChanged,
    UseAgentUpdate.OnRunStatusChanged,
  ],
});
const state = computed(
  () => (agent.value?.state ?? {}) as DocumentState,
);
</script>

<template>
  <article aria-live="polite">
    <span v-if="agent?.isRunning">LIVE</span>
    <p>{{ state.document ?? "Waiting for a draft…" }}</p>
  </article>
</template>

From there, state.document is a string that grows on every token, and agent.isRunning tells you whether to show a streaming indicator.

src/App.vue
<script setup lang="ts">
import { CopilotChat, CopilotKitProvider } from "@copilotkit/vue/v2";
import StreamingDocument from "./components/StreamingDocument.vue";
</script>

<template>
  <CopilotKitProvider runtime-url="/api/copilotkit">
    <StreamingDocument />
    <CopilotChat agent-id="writer" />
  </CopilotKitProvider>
</template>

Ask the writer agent to draft a short document. The LIVE badge shows, and the text grows while the agent writes.

If the runtime does not emit partial state snapshots, the UI sees only the final state. The Vue frontend cannot invent updates the backend never sends.

How is this guide?