# State Streaming

> Stream partial agent state updates to the 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-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? [#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 [#the-backend-one-streaming-state-mapping]

<Steps>
  <Step>
    ### Install the CrewAI AG-UI package

    ```bash
    pip install ag-ui-crewai litellm
    ```

  </Step>
  <Step>
    ### Declare the state key

    ```python title="src/agents/shared_state_streaming.py"
    from ag_ui_crewai import CopilotKitState


    class SharedStateStreamingState(CopilotKitState):
        document: str = ""
    ```

  </Step>
  <Step>
    ### Map the tool argument to the state key

    Call `copilotkit_predict_state` with one `StateItem` before the model
    call. While the model streams `write_document`, CopilotKit copies the
    partial `document` argument into the `document` state key. Wrap the call
    in `copilotkit_stream`, or nothing streams until the turn ends.

    ```python title="src/agents/shared_state_streaming.py"
    from crewai.flow.flow import Flow, start
    from litellm import acompletion

    from ag_ui_crewai import StateItem, copilotkit_predict_state, copilotkit_stream


    class SharedStateStreamingFlow(Flow[SharedStateStreamingState]):
        @start()
        async def write(self) -> None:
            await copilotkit_predict_state(
                [
                    StateItem(
                        state_key="document",
                        tool="write_document",
                        tool_argument="document",
                    )
                ]
            )
            tools = [*self.state.copilotkit.actions, WRITE_DOCUMENT_TOOL]
            response = await copilotkit_stream(
                await acompletion(
                    reasoning_effort="none",
                    allowed_openai_params=["reasoning_effort"],
                    model="openai/gpt-6-luna",
                    messages=[
                        {"role": "system", "content": SYSTEM_PROMPT},
                        *self.state.messages,
                    ],
                    tools=tools,
                    parallel_tool_calls=False,
                    stream=True,
                )
            )
    ```

    `WRITE_DOCUMENT_TOOL` is a plain OpenAI-format tool schema with one
    required `document` string argument.

  </Step>
  <Step>
    ### Persist the final value

    When a Flow method finishes, **its state becomes the single source of
    truth**. The streamed predictions are not written to `self.state`, so
    assign the final value yourself. Otherwise it is overwritten when the
    method completes.

    ```python title="src/agents/shared_state_streaming.py"
            # Still inside write(), after the model call (needs `import json`)
            message = response.choices[0].message
            self.state.messages.append(message)
            calls = message.get("tool_calls") or []
            write_call = next(
                (
                    call
                    for call in calls
                    if call.get("function", {}).get("name") == "write_document"
                ),
                None,
            )
            if write_call is None:
                return

            arguments = json.loads(
                write_call.get("function", {}).get("arguments") or "{}"
            )
            document = arguments.get("document")
            self.state.document = document if isinstance(document, str) else ""
    ```

    The showcase Flow then appends a `role: "tool"` message, calls
    `copilotkit_emit_tool_result`, and asks the model for a one-line
    confirmation. See `src/agents/shared_state_streaming.py`.

  </Step>
</Steps>

<Callout title="Emit progress without a tool argument">
  To show progress that is not a tool argument, assign the value and call
  `copilotkit_emit_state` after each sub-step:

  ```python title="agent.py"
  from ag_ui_crewai import copilotkit_emit_state

  for step in steps:
      self.state.observed_steps = [*self.state.observed_steps, step]
      await copilotkit_emit_state(self.state)
      await asyncio.sleep(1)
  ```
</Callout>

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.

```python title="src/agents/shared_state_streaming.py"
class SharedStateStreamingState(CopilotKitState):
    document: str = ""


class SharedStateStreamingFlow(Flow[SharedStateStreamingState]):
    """Predict write_document arguments into state, then persist the result."""

    @start()
    async def write(self) -> None:
        await copilotkit_predict_state(
            [
                StateItem(
                    state_key="document",
                    tool="write_document",
                    tool_argument="document",
                )
            ]
        )
```

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

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

```vue title="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.

```vue title="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.

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