# State Inputs and Outputs

> Decide which state properties are received and returned to the frontend.

## What is this? [#what-is-this]

Not all state properties are relevant for frontend-backend sharing.

## When should I use this? [#when-should-i-use-this]

Depending on your implementation, some properties are meant to be processed internally, while some others are the way for the UI to communicate user input.
In addition, some state properties contain a lot of information. Syncing them back and forth between the agent and UI can be costly, while it might not have any practical benefit.

## Implementation [#implementation]

<Steps>
  <Step>
    ### Examine your state structure [#examine-your-state-structure]
    LlamaIndex agents using the AG-UI workflow router are stateful. As you execute tools and process messages, that state is updated and available throughout the session. For this example,
    assume that the agent's state looks like this:

    ```python title="agent.py"
    # Shared state: the router sends these keys to the UI
    initial_state = {
        "question": "",         # Input from user
        "answer": "",           # Output to user
    }
    # Internal use only: the agent keeps "resources" under its own context key
    ```
  </Step>
  <Step>
    ### Organize state by purpose [#organize-state-by-purpose]
    Our example case lists several state properties, each with its own purpose:
      - **question**: the user asks it, and the LLM answers it.
      - **answer**: the LLM returns it.
      - **resources**: the LLM uses this list to answer. The user cannot see or set it.

    Here's a complete example showing how to structure your agent with these considerations:

    ```python title="agent.py"
    from typing import Annotated, List
    from fastapi import FastAPI
    from llama_index.llms.openai import OpenAI
    from llama_index.core.workflow import Context
    from llama_index.protocols.ag_ui.router import get_ag_ui_workflow_router
    from llama_index.protocols.ag_ui.events import StateSnapshotWorkflowEvent

    async def answerQuestion(
        ctx: Context,
        answer: Annotated[str, "The answer to store in state."]
    ) -> str:
        """Stores the answer to the user's question in shared state.

        Args:
            ctx: The workflow context for state management.
            answer: The answer to store in state.

        Returns:
            str: A message indicating the answer was stored.
        """
        async with ctx.store.edit_state() as global_state:
            state = global_state.get("state", {})
            if state is None:
                state = {}
            
            state["answer"] = answer
            
            # Emit state update to frontend
            ctx.write_event_to_stream(
                StateSnapshotWorkflowEvent(snapshot=state)
            )
            
            global_state["state"] = state
        
        return f"Answer stored: {answer}"

    async def addResource(
        ctx: Context,
        resource: Annotated[str, "The resource URL or reference to add."]
    ) -> str:
        """Adds a resource to the internal resources list.

        Args:
            ctx: The workflow context for state management.
            resource: The resource URL or reference to add.

        Returns:
            str: A message indicating the resource was added.
        """
        # The router sends only the "state" key to the UI, so a separate
        # context key keeps the resources on the server.
        resources = await ctx.store.get("resources", default=[])
        await ctx.store.set("resources", [*resources, resource])

        return f"Resource added: {resource}"

    # Initialize the LLM
    llm = OpenAI(model="gpt-6-luna")

    # Create the AG-UI workflow router
    agentic_chat_router = get_ag_ui_workflow_router(
        llm=llm,
        system_prompt="""
        You are a helpful assistant. When the user asks a question:
        1. Think through your answer
        2. Optionally use addResource to track any sources you reference
        3. Use answerQuestion to provide your final answer - this stores it in state for the user to see
        
        Always use the answerQuestion tool to provide your response so it appears in the UI.
        """,
        backend_tools=[answerQuestion, addResource],
        initial_state={
            "question": "",       # Input: received from frontend
            "answer": "",         # Output: sent to frontend
        },
    )

    # Create FastAPI app
    app = FastAPI(
        title="LlamaIndex Agent",
        description="A LlamaIndex agent integrated with CopilotKit",
        version="1.0.0"
    )

    # Include the router
    app.include_router(agentic_chat_router)

    # Health check endpoint
    @app.get("/health")
    async def health_check():
        return {"status": "healthy", "agent": "llamaindex"}

    if __name__ == "__main__":
        import uvicorn
        uvicorn.run(app, host="localhost", port=8000)
    ```
  </Step>
  <Step>
    ### Use the state in your frontend [#use-the-state-in-your-frontend]
    Now that we know which state properties our agent uses, we can work with them in the UI:
    - **question**: Set by the UI to ask the agent something
    - **answer**: Read from the agent's response
    - **resources**: Not accessible to the UI. The agent keeps it under its own context key.

    <Callout type="warn" title="Important">
      The `agentId` that you pass to `useAgent` must match the agent name in your CopilotRuntime `agents` configuration (for example, `my_agent` from the quickstart).
    </Callout>
  </Step>
  <Step>
    ### Give it a try [#give-it-a-try]
    Start the agent and the app. Then click **Ask Question** in the React sample, or **Ask agent** in the Angular sample. The answer that the agent stored in state appears on the page, and the agent state has no `resources` key.
  </Step>
</Steps>
