# State Streaming

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

## What is this? [#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? [#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

<WhenFrameworkSupports feature="shared-state-streaming" not>

<Callout type="info">
  **Not available on this framework yet.** This framework's showcase doesn't support state streaming. The UI gets the agent's state between checkpoints, which the [Shared State](/react-native/ms-agent-python/shared-state) page covers.
</Callout>

</WhenFrameworkSupports>

## The backend: one streaming state mapping [#the-backend-one-streaming-state-mapping]

<Steps>
  <Step>
    ### Map the tool argument with `predict_state_config`

    `predict_state_config` names the tool and the argument to stream into a
    state key. While the model generates the `write_document` call, the
    adapter sends each partial `document` argument to the UI as a state
    update. Returning `state_update(...)` from the tool commits the final
    value when the call completes:

    ```python title="src/agents/shared_state_streaming.py"
    from typing import Annotated

    from agent_framework import tool
    from agent_framework_ag_ui import state_update
    from pydantic import Field

    # Stream tool-argument deltas straight into `state.document` while
    # `write_document` is still streaming.
    PREDICT_STATE_CONFIG: dict[str, dict[str, str]] = {
        "document": {
            "tool": "write_document",
            "tool_argument": "document",
        }
    }


    @tool(
        name="write_document",
        description=(
            "Write a document for the user. Always call this tool when the "
            "user asks you to write, draft, or revise any text. The "
            "`document` argument is streamed per-token into shared state "
            "under the `document` key so the UI renders the body live."
        ),
    )
    def write_document(
        document: Annotated[
            str,
            Field(description="The full document content as a single string."),
        ],
    ):
        return state_update(
            text="Document written to shared state.",
            state={"document": document},
        )
    ```

  </Step>
  <Step>
    ### Seed the state key before the deltas arrive

    The streamed updates are JSON Patch `replace` operations on
    `/document`. The agent's initial state is `{}`, and a `state_schema`
    defines properties but sets no starting values, so on the first turn the
    path does not exist yet. The
    frontend rejects the patch ("Failed to apply state patch") and the run
    never settles.

    Emit a `STATE_SNAPSHOT` that carries the key right after `RUN_STARTED`,
    keeping any value from an earlier turn:

    ```python title="src/agents/shared_state_streaming.py"
    from collections.abc import AsyncGenerator
    from typing import Any

    from ag_ui.core import BaseEvent, EventType, StateSnapshotEvent
    from agent_framework import Agent, BaseChatClient
    from agent_framework_ag_ui import AgentFrameworkAgent


    class SharedStateStreamingFrameworkAgent(AgentFrameworkAgent):
        async def run(  # type: ignore[override]
            self,
            input_data: dict[str, Any],
        ) -> AsyncGenerator[BaseEvent, None]:
            incoming = input_data.get("state")
            state = incoming if isinstance(incoming, dict) else {}
            document = state.get("document", "")
            seeded = False
            async for event in super().run(input_data):
                yield event
                # RUN_STARTED must be the first event; the seed follows it.
                if not seeded and getattr(event, "type", None) == EventType.RUN_STARTED:
                    yield StateSnapshotEvent(
                        type=EventType.STATE_SNAPSHOT,
                        snapshot={**state, "document": document},
                    )
                    seeded = True


    def create_shared_state_streaming_agent(
        chat_client: BaseChatClient,
    ) -> AgentFrameworkAgent:
        base_agent = Agent(
            client=chat_client,
            name="shared_state_streaming_agent",
            instructions=SYSTEM_PROMPT,  # tells the model to call write_document
            tools=[write_document],
        )

        return SharedStateStreamingFrameworkAgent(
            agent=base_agent,
            name="SharedStateStreamingAgent",
            description=(
                "Per-token state streaming: `write_document` arg deltas land "
                "in `state.document` as the tool call is generated."
            ),
            predict_state_config=PREDICT_STATE_CONFIG,
            require_confirmation=False,
        )
    ```

  </Step>
</Steps>

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.

<WhenFrameworkSupports feature="shared-state-streaming">

```python title="src/agents/shared_state_streaming.py"
# Tells the runtime to stream tool-argument deltas straight into
# `state.document` while `write_document` is still streaming — matches
# LGP's StateStreamingMiddleware setup.
PREDICT_STATE_CONFIG: dict[str, dict[str, str]] = {
    "document": {
        "tool": "write_document",
        "tool_argument": "document",
    }
}
```

</WhenFrameworkSupports>

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-frontend-useagent-and-onstatechanged]

The app side is the same as any other [shared-state](/react-native/ms-agent-python/shared-state) subscription: `useAgent` with `OnStateChanged` gives you a live `agent.state`. Add `OnRunStatusChanged` for a "writing" indicator.

```tsx title="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({ // [!code highlight:4]
    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 [#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.

<IntegrationGrid path="shared-state/streaming" exclude={["agno", "agent-spec", "spring-ai", "langroid"]} />
