State Streaming

Stream partial agent state to your React Native UI while a tool call is still running.

What is this?

By default, agent state only updates between backend checkpoints, so a long tool call (writing a full document, drafting an email) reaches the UI as one burst at the end. In an agent-native app, that feels broken: users expect to watch the output appear.

State streaming copies one tool argument into an agent state key while the model writes the argument. Your screen, subscribed with useAgent, re-renders on every token.

When should I use this?

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

  • A writing agent that produces a document
  • A research agent that collects a list of findings
  • A planning agent that builds a step-by-step plan

The backend: one streaming state mapping

Install the ADK + AG-UI bridge

pip install ag-ui-adk

Declare the predicted state mapping

ADK state streaming uses PredictStateMapping to map the streaming write_document tool argument into state["document"]. Add AGUIToolset() to the agent so CopilotKit can forward the state deltas to the UI.

shared_state_streaming_agent.py
from __future__ import annotations

from ag_ui_adk import AGUIToolset
from ag_ui_adk.config import PredictStateMapping
from google.adk.agents import LlmAgent
from google.adk.tools import ToolContext

from agents.shared_chat import get_model, stop_on_terminal_text


def write_document(tool_context: ToolContext, document: str) -> dict:
    """Write a document into shared state.

    Whenever the user asks you to write or draft anything (essay, poem,
    email, summary, etc.), call this tool with the full content as a
    single string. The UI renders state["document"] live as you type.

    Argument name `document` mirrors langgraph-python's `write_document`
    signature so the shared D5 fixture (`tool_argument="document"`) and
    the LGP-aligned PredictStateMapping below stay in lock-step.
    """
    tool_context.state["document"] = document
    return {"status": "ok", "length": len(document)}


_INSTRUCTION = (
    "You are a collaborative writing assistant. Whenever the user asks "
    "you to write, draft, or revise any piece of text, ALWAYS call the "
    "`write_document` tool with the full content as a single string. "
    "Never paste the document into a chat message directly — the document "
    "belongs in shared state and the UI renders it live as you type."
)

shared_state_streaming_agent = LlmAgent(
    name="SharedStateStreamingAgent",
    model=get_model(),
    instruction=_INSTRUCTION,
    tools=[write_document, AGUIToolset()],
    after_model_callback=stop_on_terminal_text,
)


SHARED_STATE_STREAMING_PREDICT_STATE = [
    PredictStateMapping(
        state_key="document",
        tool="write_document",
        tool_argument="document",
        emit_confirm_tool=False,
        stream_tool_call=True,
    ),
]

Pass the mapping to ADKAgent

The mapping does nothing until it reaches the ADKAgent middleware. Pass it as predict_state, and turn on streaming_function_call_arguments so the middleware receives the tool arguments while the model writes them. The showcase server builds each endpoint this way:

src/agent_server.py
from ag_ui_adk import ADKAgent, add_adk_fastapi_endpoint

middleware = ADKAgent(
    adk_agent=shared_state_streaming_agent,
    user_id="demo_user",
    session_timeout_seconds=3600,
    use_in_memory_services=True,
    predict_state=SHARED_STATE_STREAMING_PREDICT_STATE,
    streaming_function_call_arguments=True,
)
add_adk_fastapi_endpoint(app, middleware, path="/shared-state-streaming")

With predict_state, the frontend gets document while the model writes the document argument of write_document. When the tool runs, tool_context.state stores the final value.

Per-token streaming needs google-adk 1.24.0 or later through Vertex AI. On older versions, or through Gemini in Google AI Studio, the middleware logs a UserWarning at startup and streams in larger chunks. The state still updates, only less often.

Stop after the final model response

The agent above imports stop_on_terminal_text and registers it as its after_model_callback. This prevents Gemini from issuing the same tool call again after its final text response. See the canonical stop_on_terminal_text implementation when adapting the callback for your project.

The backend pattern is always the same: map one streaming tool argument to one shared-state key. Each framework does this in its own way:

  • LangGraph Python: StateStreamingMiddleware with StateItem(...) entries.
  • LangGraph TypeScript: copilotkitCustomizeConfig with an emitIntermediateState mapping.
  • Direct SDK adapters: parse partial tool arguments in the streaming loop, and emit STATE_SNAPSHOT whenever the mapped value changes.
  • LlamaIndex and Pydantic AI: there is no per-token mapping. A backend tool sends a state snapshot after each step or tool call instead (see the setup above).

When the model streams that argument, CopilotKit writes every partial value into shared state before the tool finishes.

shared_state_streaming_agent.py
from __future__ import annotations

from ag_ui_adk import AGUIToolset
from ag_ui_adk.config import PredictStateMapping
from google.adk.agents import LlmAgent
from google.adk.tools import ToolContext

from agents.shared_chat import get_model, stop_on_terminal_text


def write_document(tool_context: ToolContext, document: str) -> dict:
    """Write a document into shared state.

    Whenever the user asks you to write or draft anything (essay, poem,
    email, summary, etc.), call this tool with the full content as a
    single string. The UI renders state["document"] live as you type.

    Argument name `document` mirrors langgraph-python's `write_document`
    signature so the shared D5 fixture (`tool_argument="document"`) and
    the LGP-aligned PredictStateMapping below stay in lock-step.
    """
    tool_context.state["document"] = document
    return {"status": "ok", "length": len(document)}


_INSTRUCTION = (
    "You are a collaborative writing assistant. Whenever the user asks "
    "you to write, draft, or revise any piece of text, ALWAYS call the "
    "`write_document` tool with the full content as a single string. "
    "Never paste the document into a chat message directly — the document "
    "belongs in shared state and the UI renders it live as you type."
)

shared_state_streaming_agent = LlmAgent(
    name="SharedStateStreamingAgent",
    model=get_model(),
    instruction=_INSTRUCTION,
    tools=[write_document, AGUIToolset()],
    after_model_callback=stop_on_terminal_text,
)


SHARED_STATE_STREAMING_PREDICT_STATE = [
    PredictStateMapping(
        state_key="document",
        tool="write_document",
        tool_argument="document",
        emit_confirm_tool=False,
        stream_tool_call=True,
    ),
]

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 tool call the model makes (write_document.document here).
  • Streamed values are previews. When the step ends, the state the agent saves replaces them, so save the final value when the tool finishes. On CrewAI, LlamaIndex, and Pydantic AI, write the final value to the agent state yourself, or it is overwritten when the step returns.

The frontend: useAgent and OnStateChanged

The app side is the same as any other shared-state subscription: useAgent with OnStateChanged gives you a live agent.state. Add OnRunStatusChanged for a "writing" indicator.

src/DocumentView.tsx
import { ActivityIndicator, ScrollView, Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";

export function DocumentView() {
  const { agent } = useAgent({
    agentId: "default",
    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
  });
  const document = (agent.state as { document?: string } | undefined)?.document ?? "";

  return (
    <View style={{ padding: 16, gap: 8 }}>
      {agent.isRunning ? <ActivityIndicator /> : null}
      <ScrollView style={{ maxHeight: 320 }}>
        <Text>{document}</Text>
      </ScrollView>
    </View>
  );
}

agent.state.document is a string that grows on every token, and agent.isRunning tells you whether to show the indicator. The ScrollView with a maxHeight keeps a long document from pushing the rest of the screen away.

If a fast stream re-renders a heavy screen too often, pass throttleMs to useAgent to batch the updates.

Try it

Ask the agent to write a short poem. The document text grows on your screen while the agent writes. When the run ends, agent.isRunning is false, so the indicator goes away.

How is this guide?