# Agent App Context

> Share app specific context with your agent.

Your agent can answer only about data it can see. The signed-in user and the rows on screen live in your React app. Register them with `useAgentContext`, and CopilotKit sends them to your LangGraph agent on every run.

## Implementation [#implementation]

<Callout type="warn" title="Context values arrive as JSON strings">
  The AG-UI protocol defines a context value as a string. Therefore
  `useAgentContext` calls `JSON.stringify` on any `value` that is not already a
  string, and your agent receives the JSON text instead of the object or the
  array.

  Parse the value before you read a field from it. Use `json.loads(item["value"])`
  in Python, or `JSON.parse(item.value)` in TypeScript. If you skip the parse
  step, an index such as `colleagues[0]` returns a single character, and a shape
  check such as `isinstance(value, list)` can never pass.

  Do not stringify the value again, because that produces double encoding. A
  `value` that is already a string is sent unchanged, so no parse step is needed
  for it.
</Callout>

<TailoredContent
    className="step"
    id="impl"
>
    <TailoredContentOption
        id="graph"
        title="Custom graph"
        description="I'm using a custom graph, where I define the nodes and edges myself."
    >
        <Steps>
            <Step>
                ### Add the data to the Copilot [#add-the-data-to-the-copilot]

                The `useAgentContext` hook adds data as context to the agent.

                ```tsx title="YourComponent.tsx"
                "use client" // only necessary if you are using Next.js with the App Router. // [!code highlight]
                import { useAgentContext } from "@copilotkit/react-core/v2"; // [!code highlight]
                import { useState } from 'react';

                export function YourComponent() {
                  // Create colleagues state with some sample data
                  const [colleagues, setColleagues] = useState([
                    { id: 1, name: "John Doe", role: "Developer" },
                    { id: 2, name: "Jane Smith", role: "Designer" },
                    { id: 3, name: "Bob Wilson", role: "Product Manager" }
                  ]);

                  // Share context with the agent
                  // [!code highlight:4]
                  useAgentContext({
                    description: "The current user's colleagues",
                    value: colleagues,
                  });
                  return (
                    // Your custom UI component
                    <>...</>
                  );
                }
                ```
            </Step>

            <Step>
                ### Set up your agent state [#set-up-your-agent-state]
                Make sure that your agent state includes the CopilotKit state: inherit from `CopilotKitState` in Python, or spread `CopilotKitStateSchema.fields` in TypeScript.

                <Tabs groupId="language_langgraph_agent" items={['Python', 'TypeScript']} default="Python" persist>
                    <Tab value="Python">
                        ```python title="agent.py"
                        # ...
                        from copilotkit import CopilotKitState # extends MessagesState
                        # ...

                        # This is the state of the agent.
                        # It inherits from the CopilotKitState properties from CopilotKit.
                        class AgentState(CopilotKitState):
                            # ... Your defined state properties
                        ```
                    </Tab>
                    <Tab value="TypeScript">
                        ```typescript title="agent-js/src/agent.ts"
                        // ...
                        import { StateSchema } from "@langchain/langgraph";
                        import { CopilotKitStateSchema } from "@copilotkit/sdk-js/langgraph";
                        // ...

                        // This is the state of the agent.
                        // It inherits from the CopilotKitState properties from CopilotKit.
                        export const AgentStateSchema = new StateSchema({
                          // ... Your defined state properties
                          ...CopilotKitStateSchema.fields,
                        });
                        export type AgentState = typeof AgentStateSchema.State;
                        ```
                    </Tab>
                </Tabs>

            </Step>

            <Step>
                ### Consume the data in your LangGraph agent [#consume-the-data-in-your-langgraph-agent]
                CopilotKit writes the context entries to `copilotkit.context` in your agent state. Read them from there.

                <Tabs groupId="language_langgraph_agent" items={['Python', 'TypeScript']} default="Python" persist>
                    <Tab value="Python">
                        ```python title="agent.py"
                        import json # [!code highlight]

                        from langchain_core.runnables import RunnableConfig
                        from langchain_core.messages import SystemMessage
                        from langchain_openai import ChatOpenAI
                        from copilotkit import CopilotKitState

                        # add the agent state definition from the previous step
                        class AgentState(CopilotKitState):
                            # ... Your defined state properties

                        def chat_node(state: AgentState, config: RunnableConfig):
                            # Extract the colleagues from CopilotKit context
                            colleagues_context_item = next(
                                (item for item in state["copilotkit"]["context"] if item.get("description") == "The current user's colleagues"),
                                None
                            )

                            # [!code highlight:7]
                            # The value is a JSON string, so parse it to read the fields
                            colleagues = []
                            if colleagues_context_item:
                                colleagues = json.loads(colleagues_context_item["value"])

                            # Now each entry is a dict, so colleague["name"] works
                            colleague_list = ", ".join(f"{c['name']} ({c['role']})" for c in colleagues)

                            # Provide the list of colleagues to the LLM
                            system_message = SystemMessage(
                                content=f"""You are a helpful assistant that can help emailing colleagues.
                                The user's colleagues are: {colleague_list}"""
                            )

                            response = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none").invoke(
                                [system_message, *state["messages"]],
                                config
                            )

                            return {
                                **state,
                                "messages": response,
                            }
                        ```
                    </Tab>
                    <Tab value="TypeScript">
                        ```typescript title="agent-js/src/agent.ts"
                        import { SystemMessage } from "@langchain/core/messages";
                        import { ChatOpenAI } from "@langchain/openai";

                        // add the agent state definition from the previous step
                        export const AgentStateSchema = new StateSchema({
                          // ... Your defined state properties
                          ...CopilotKitStateSchema.fields,
                        });
                        export type AgentState = typeof AgentStateSchema.State;

                        async function chat_node(state: AgentState, config: RunnableConfig) {
                          // Extract the colleagues from CopilotKit context
                          const copilotKitContext = state.copilotkit.context
                          const colleaguesContextItem = copilotKitContext.find(contextItem => contextItem.description === "The current user's colleagues")

                          // [!code highlight:5]
                          // The value is a JSON string, so parse it to read the fields
                          const colleagues = colleaguesContextItem ? JSON.parse(colleaguesContextItem.value) : [];

                          // Now each entry is an object, so colleague.name works
                          const colleagueList = colleagues.map((c) => `${c.name} (${c.role})`).join(", ");

                          // Provide the list of colleagues to the LLM
                          const systemMessage = new SystemMessage({
                            content: `
                              You are a helpful assistant that can help emailing colleagues.
                              The user's colleagues are: ${colleagueList}
                            `,
                          });

                          const response = await new ChatOpenAI({ modelKwargs: { reasoning_effort: "none" }, model: "gpt-6-luna" }).invoke(
                            [systemMessage, ...state.messages],
                            config
                          );

                          return {
                            ...state,
                            messages: response,
                          };
                        }
                        ```
                    </Tab>
                </Tabs>
            </Step>

            <Step>
                ### Give it a try [#give-it-a-try]
                Ask "Who are my colleagues?". The agent names John Doe, Jane Smith, and Bob Wilson with their roles.
            </Step>
        </Steps>
    </TailoredContentOption>
    <TailoredContentOption
        id="prebuilt"
        title="Prebuilt agent"
        description={`I'm using a prebuilt agent like "create_agent" by LangGraph`}
    >
        <Steps>
            <Step>
                ### Add the data to the Copilot [#add-the-data-to-the-copilot-1]

                The `useAgentContext` hook adds data as context to the agent.

                ```tsx title="YourComponent.tsx"
                "use client" // only necessary if you are using Next.js with the App Router. // [!code highlight]
                import { useAgentContext } from "@copilotkit/react-core/v2"; // [!code highlight]
                import { useState } from 'react';

                export function YourComponent() {
                  // Create colleagues state with some sample data
                  const [colleagues, setColleagues] = useState([
                    { id: 1, name: "John Doe", role: "Developer" },
                    { id: 2, name: "Jane Smith", role: "Designer" },
                    { id: 3, name: "Bob Wilson", role: "Product Manager" }
                  ]);

                  // Share context with the agent
                  // [!code highlight:4]
                  useAgentContext({
                    description: "The current user's colleagues",
                    value: colleagues,
                  });
                  return (
                    // Your custom UI component
                    <>...</>
                  );
                }
                ```
            </Step>

            <Step>
                ### Consume the data in your LangGraph agent [#consume-the-data-in-your-langgraph-agent-1]
                CopilotKit writes the context entries to `copilotkit.context` in your agent state. Add the CopilotKit middleware, and it adds these entries to the system message of the model.

                <Tabs groupId="language_langgraph_agent" items={['Python', 'TypeScript']} default="Python" persist>
                    <Tab value="Python">
                        ```python title="agent.py"
                        from langchain_openai import ChatOpenAI
                        from langchain.agents import create_agent
                        from copilotkit import CopilotKitMiddleware, CopilotKitState # [!code highlight]

                        graph = create_agent(
                            model="openai:gpt-6-luna",
                            tools=[],  # Backend tools go here
                            middleware=[CopilotKitMiddleware()], # [!code highlight]
                            system_prompt="You are a helpful assistant.",
                            state_schema=CopilotKitState # [!code highlight]
                        )
                        ```
                    </Tab>
                    <Tab value="TypeScript">
                        ```typescript title="agent-js/src/agent.ts"
                        import { createAgent } from "langchain";
                        import { copilotkitMiddleware } from "@copilotkit/sdk-js/langgraph"; // [!code highlight]

                        export const agenticChatGraph = createAgent({
                          model: "openai:gpt-6-luna",
                          tools: [],  // Backend tools go here
                          middleware: [copilotkitMiddleware], // [!code highlight]
                          systemPrompt: "You are a helpful assistant.",
                        });
                        ```
                    </Tab>
                </Tabs>
            </Step>

            <Step>
                ### Serve the agent with FastAPI (Python) [#serve-the-agent-with-fastapi-python]

                If you deploy with LangSmith, skip this step. The LangGraph API server supplies persistence, so do not pass a `checkpointer`.

                If you run the agent in your own FastAPI app, nothing supplies persistence. `ag-ui-langgraph` reads thread state with `graph.aget_state(...)`, which raises `ValueError: No checkpointer set` without a checkpointer. Pass one to `create_agent`.

                `create_agent` comes from `langchain` 1.x. Install it explicitly, together with the FastAPI packages:

                ```bash
                uv add "langchain>=1" langchain-openai ag-ui-langgraph fastapi uvicorn copilotkit python-dotenv
                ```

                ```python title="main.py" doctest="server"
                from langchain_openai import ChatOpenAI
                from dotenv import load_dotenv
                from ag_ui_langgraph import add_langgraph_fastapi_endpoint
                from copilotkit import CopilotKitMiddleware, CopilotKitState, LangGraphAGUIAgent
                from fastapi import FastAPI
                from langchain.agents import create_agent
                from langgraph.checkpoint.memory import MemorySaver
                import uvicorn

                load_dotenv()

                graph = create_agent(
                    model=ChatOpenAI(model="gpt-6-luna", reasoning_effort="none"),
                    tools=[],  # Backend tools go here
                    middleware=[CopilotKitMiddleware()],
                    system_prompt="You are a helpful assistant.",
                    state_schema=CopilotKitState,
                    checkpointer=MemorySaver(), # [!code highlight]
                )

                app = FastAPI()

                add_langgraph_fastapi_endpoint(
                    app=app,
                    agent=LangGraphAGUIAgent(
                        name="sample_agent",
                        description="An agent that reads context from the app.",
                        graph=graph,
                    ),
                    path="/",
                )

                if __name__ == "__main__":
                    uvicorn.run("main:app", host="0.0.0.0", port=8123, reload=True)
                ```

                `MemorySaver` keeps state in process memory only. For production, use a durable saver, for example Postgres. The [quickstart](/langgraph-python/quickstart) shows the runtime route and provider that connect to this server on port `8123`.
            </Step>

            <Step>
                ### Give it a try [#give-it-a-try-1]
                Ask "Who are my colleagues?". The agent names John Doe, Jane Smith, and Bob Wilson with their roles.
            </Step>
        </Steps>
    </TailoredContentOption>
</TailoredContent>
