# Quickstart

> Get started with Deep Agents and CopilotKit in minutes.

## Start with your coding agent [#start-with-your-coding-agent]

Use this prompt to connect your Deep Agents agent to CopilotKit and verify a working conversation. Your coding agent will follow this guide in your project, or you can work through the manual steps below.

<PageAgentPrompt />

## Prerequisites [#prerequisites]

Before you begin, you'll need the following:

- An OpenAI API key
- Node.js 20+
- Your favorite package manager
- A LangSmith API key, only if you deploy the agent to LangGraph Platform

## Getting started [#getting-started]

<Steps>
    <Step>
        ### Set up CopilotKit Intelligence [#set-up-copilotkit-intelligence]

        <SignupLink surface="docs_deepagents_quickstart_step1">Sign in to cloud-hosted Intelligence</SignupLink>. Cloud-hosted setup uses a server-side project API key and does not issue `COPILOTKIT_LICENSE_TOKEN`. You will connect the app after you create it below.
    </Step>

    <Step>
        ### Initialize your agent project [#initialize-your-agent-project]

        <Tabs groupId="agent_language" items={['Python', 'TypeScript']} persist>
            <Tab value="Python">
                If you don't already have a Python project set up, create one using `uv`:

                ```bash
                uv init my-agent
                cd my-agent
                ```
            </Tab>
            <Tab value="TypeScript">
                If you don't already have a Node.js project set up, create one using `npm`:

                ```bash
                mkdir my-agent
                cd my-agent
                npm init -y
                ```
            </Tab>
        </Tabs>
    </Step>
    <Step>
        ### Add necessary dependencies [#add-necessary-dependencies]

        <Tabs groupId="agent_language" items={['Python', 'TypeScript']} persist>
            <Tab value="Python">
                Add the `deepagents`, `langchain-openai`, and `copilotkit` packages:

                ```bash
                uv add deepagents copilotkit langchain-openai
                ```
            </Tab>
            <Tab value="TypeScript">
                Add the `deepagents`, `@langchain/langgraph`, `@copilotkit/sdk-js`, `@langchain/openai`, `langchain`, and `zod` packages. `@copilotkit/sdk-js` needs Zod 3:

                ```bash
                npm install deepagents @langchain/langgraph @copilotkit/sdk-js @langchain/openai langchain zod@3
                ```
            </Tab>
        </Tabs>
    </Step>
    <Step>
        ### Create your Deep Agent [#create-your-deep-agent]

        <Tabs groupId="agent_setup" items={['Python', 'TypeScript', 'FastAPI']}>
            <Tab value="Python">
                Create a simple Deep Agent:

                ```python title="main.py"
                from deepagents import create_deep_agent
                from copilotkit import CopilotKitMiddleware

                def get_weather(location: str):
                    """Get weather for a location"""
                    return f"The weather in {location} is sunny."

                agent = create_deep_agent(
                    model="openai:gpt-6-luna",
                    tools=[get_weather],
                    middleware=[CopilotKitMiddleware()], # for frontend tools and context
                    system_prompt="You are a helpful research assistant.",
                )
                ```

                To run the agent with the LangGraph CLI, create a `langgraph.json`:

                ```sh
                touch langgraph.json
                ```

                ```json title="langgraph.json"
                {
                    "python_version": "3.12",
                    "dockerfile_lines": [],
                    "dependencies": ["."],
                    "package_manager": "uv",
                    "graphs": {
                        "sample_agent": "./main.py:agent"
                    },
                    "env": ".env"
                }
                ```
            </Tab>
            <Tab value="TypeScript">
                Create a simple Deep Agent:

                ```ts title="agent.ts"
                import { createDeepAgent } from "deepagents";
                import { copilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
                import { tool } from "langchain";
                import { z } from "zod";

                const getWeather = tool(
                    async ({ location }) => `The weather in ${location} is sunny.`,
                    {
                        name: "get_weather",
                        description: "Get the weather for a given location.",
                        schema: z.object({ location: z.string().describe("The location to get the weather for") }),
                    }
                );

                export const agent = createDeepAgent({
                    model: "openai:gpt-6-luna",
                    tools: [getWeather],
                    middleware: [copilotkitMiddleware],
                    systemPrompt: "You are a helpful research assistant.",
                });
                ```

                To run the agent with the LangGraph CLI, create a `langgraph.json`:

                ```sh
                touch langgraph.json
                ```

                ```json title="langgraph.json"
                {
                    "node_version": "20",
                    "dependencies": ["."],
                    "package_manager": "npm",
                    "graphs": {
                        "sample_agent": "./agent.ts:agent"
                    },
                    "env": ".env"
                }
                ```

                <Callout type="info">
                    When setting up the Copilot Runtime in the next steps, select the **Deep Agent** tab.
                </Callout>
            </Tab>
            <Tab value="FastAPI">
                Add the `ag-ui-langgraph`, `fastapi`, and `uvicorn` packages:

                ```bash
                uv add ag-ui-langgraph fastapi uvicorn
                ```

                Create a Deep Agent and expose it as an AG-UI endpoint:

                ```python title="main.py"
                from ag_ui_langgraph import add_langgraph_fastapi_endpoint
                from copilotkit import CopilotKitMiddleware, LangGraphAGUIAgent
                from deepagents import create_deep_agent
                from fastapi import FastAPI
                from langgraph.checkpoint.memory import MemorySaver

                app = FastAPI()

                def get_weather(location: str):
                    """Get weather for a location"""
                    return f"The weather in {location} is sunny."

                agent = create_deep_agent(
                    model="openai:gpt-6-luna",
                    tools=[get_weather],
                    middleware=[CopilotKitMiddleware()], # for frontend tools and context
                    system_prompt="You are a helpful research assistant.",
                    checkpointer=MemorySaver()
                )

                add_langgraph_fastapi_endpoint(
                    app=app,
                    agent=LangGraphAGUIAgent(
                        name="sample_agent",
                        description="An example agent to use as a starting point for your own agent.",
                        graph=agent,
                    ),
                    path="/",
                )

                def main():
                    """Run the uvicorn server."""
                    import uvicorn
                    uvicorn.run(
                        "main:app",
                        host="0.0.0.0",
                        port=8123,
                        reload=True,
                    )

                if __name__ == "__main__":
                    main()
                ```
            </Tab>
        </Tabs>

        <Callout type="info" title="What is AG-UI?">
            AG-UI is an open protocol for frontend-agent communication. Deep Agents use it to stream state and tool calls to your frontend in real-time.
        </Callout>
    </Step>
    <Step>
        ### Configure your environment [#configure-your-environment]

        Create a `.env` file in your agent directory and add your OpenAI API key:

        ```plaintext title=".env"
        OPENAI_API_KEY=your_openai_api_key
        ```

        <Callout type="info" title="Other models">
        Deep Agents support any model available via LangChain. Change the `model` parameter in `create_deep_agent` to switch providers.
        </Callout>
    </Step>
    <Step>
        ### Create your frontend [#create-your-frontend]

        CopilotKit works with any React-based frontend. We'll use Next.js for this example.

        ```bash
        npx create-next-app@latest frontend
        cd frontend
        ```
    </Step>
    <Step>
        ### Install CopilotKit packages [#install-copilotkit-packages]

        ```npm
        npm install @copilotkit/react-core @copilotkit/runtime @ag-ui/client@1.0.2
        ```

        The **FastAPI** route below imports `HttpAgent` from `@ag-ui/client`.
        Version `1.0.2` matches the one `@copilotkit/runtime` uses.
    </Step>
    <Step>
        ### Setup Copilot Runtime [#setup-copilot-runtime]

        Create an API route to connect CopilotKit to your Deep Agent:

        ```sh
        mkdir -p "app/api/copilotkit/[[...slug]]" && touch "app/api/copilotkit/[[...slug]]/route.ts"
        ```

        <Callout type="info" title="Using Next.js is optional">
            If you'd rather skip the Next.js API proxy, see LangChain's
            [CopilotKit integration guide](https://docs.langchain.com/oss/python/langchain/frontend/integrations/copilotkit)
            for how to add a custom CopilotKit route directly to your LangGraph deployment.
        </Callout>

        <Tabs groupId="deployment_method" items={['Deep Agent', 'FastAPI']}>
            <Tab value="Deep Agent">
                ```tsx title="app/api/copilotkit/[[...slug]]/route.ts" doctest="component"
                import {
                  CopilotKitIntelligence,
                  CopilotRuntime,
                  createCopilotRuntimeHandler,
                } from "@copilotkit/runtime/v2";
                import { LangGraphAgent } from "@copilotkit/runtime/langgraph";

                const runtime = new CopilotRuntime({
                    agents: {
                        sample_agent: new LangGraphAgent({
                            deploymentUrl: process.env.LANGGRAPH_DEPLOYMENT_URL || "http://localhost:8123",
                            graphId: "sample_agent",
                            langsmithApiKey: process.env.LANGSMITH_API_KEY || "",
                        }),
                    },
                    // [!code highlight:8]
                    intelligence: new CopilotKitIntelligence({
                      apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
                    }),
                    // Threads are per-user. Without this, every visitor shares one history.
                    identifyUser: (request) => ({
                      id: request.headers.get("x-user-id") ?? "anonymous",
                      name: request.headers.get("x-user-name") ?? "Anonymous",
                    }),
                });

                const handler = createCopilotRuntimeHandler({
                  runtime,
                  basePath: "/api/copilotkit",
                });

                export const GET = handler;
                export const POST = handler;
                export const PATCH = handler;
                export const DELETE = handler;
                ```
            </Tab>
            <Tab value="FastAPI">
                ```tsx title="app/api/copilotkit/[[...slug]]/route.ts"
                import {
                  CopilotKitIntelligence,
                  CopilotRuntime,
                  createCopilotRuntimeHandler,
                } from "@copilotkit/runtime/v2";
                import { HttpAgent } from "@ag-ui/client";

                const runtime = new CopilotRuntime({
                    agents: {
                        sample_agent: new HttpAgent({
                            url: process.env.LANGGRAPH_DEPLOYMENT_URL || "http://localhost:8123",
                        }),
                    },
                    // [!code highlight:8]
                    intelligence: new CopilotKitIntelligence({
                      apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
                    }),
                    // Threads are per-user. Without this, every visitor shares one history.
                    identifyUser: (request) => ({
                      id: request.headers.get("x-user-id") ?? "anonymous",
                      name: request.headers.get("x-user-name") ?? "Anonymous",
                    }),
                });

                const handler = createCopilotRuntimeHandler({
                  runtime,
                  basePath: "/api/copilotkit",
                });

                export const GET = handler;
                export const POST = handler;
                export const PATCH = handler;
                export const DELETE = handler;
                ```
            </Tab>
        </Tabs>

        From this frontend app directory, connect the runtime to an Intelligence project:

        ```bash title="Terminal"
        npx copilotkit@latest project select
        ```

        The command writes the server-side project API key to `.env`. The runtime reads it here:

        ```plaintext title=".env"
        CPK_INTELLIGENCE_API_KEY=cpk-...
        ```

        <Callout type="info" title="Running without the Intelligence Platform?">
          Drop the `intelligence` and `identifyUser` options and the runtime falls back
          to SSE mode with an in-memory runner. Chat still works, but Threads and the
          Inspector stay locked and the key is never read. See
          [Connect your runtime to Intelligence](/deepagents/intelligence/quickstart) for the
          full constructor and how to confirm the key is in use.
        </Callout>
    </Step>
    <Step>
        ### Configure CopilotKit Provider [#configure-copilotkit-provider]

        Wrap your application with the CopilotKit provider:

        ```tsx title="app/providers.tsx"
        "use client";

        import { CopilotKitProvider } from "@copilotkit/react-core/v2";

        export function Providers({ children }: { children: React.ReactNode }) {
          return (
            <CopilotKitProvider runtimeUrl="/api/copilotkit" agentId="sample_agent" useSingleEndpoint={false}>
              {children}
            </CopilotKitProvider>
          );
        }
        ```

        Render the provider from `app/layout.tsx`:

        ```tsx title="app/layout.tsx"
        import { Providers } from "./providers";
        import "@copilotkit/react-core/v2/styles.css";

        // ...

        export default function RootLayout({ children }: { children: React.ReactNode }) {
            return (
                <html lang="en">
                    <body>
                        <Providers>
                            {children}
                        </Providers>
                    </body>
                </html>
            );
        }
        ```

        <Callout type="info" title="This relative runtimeUrl assumes Next.js serves the runtime">
          `/api/copilotkit` resolves only because Next.js serves your app and the runtime from the
          same origin. A client-only frontend has no shared origin, so it needs a standalone runtime
          server of its own and an absolute `runtimeUrl` such as
          `http://localhost:8200/api/copilotkit`. The per-frontend guides at `/react-spa`, `/vue`,
          `/angular` and `/react-native` each show that setup.
        </Callout>
    </Step>
    <Step>
        ### Add the chat interface [#add-the-chat-interface]

        Add the CopilotSidebar component to your page:

        ```tsx title="app/page.tsx"
        "use client";

        import { CopilotSidebar } from "@copilotkit/react-core/v2";
        import { useDefaultRenderTool } from "@copilotkit/react-core/v2";

        export default function Page() {
            useDefaultRenderTool({
                render: ({ name, status, parameters, result }) => (
                    <details>
                        <summary>
                            {status === "complete" ? `Called ${name}` : `Calling ${name}`}
                        </summary>
                        <p>Status: {status}</p>
                        <p>Args: {JSON.stringify(parameters)}</p>
                        <p>Result: {JSON.stringify(result)}</p>
                    </details>
                ),
            });

            return (
                <main>
                    <h1>Your App</h1>
                    <CopilotSidebar />
                </main>
            );
        }
        ```
    </Step>
    <Step>
        ### Start your agent [#start-your-agent]

        <Tabs groupId="deployment_method" items={['Deep Agent', 'FastAPI']}>
            <Tab value="Deep Agent">
                ```bash
                cd ..
                npx @langchain/langgraph-cli dev --port 8123 --no-browser
                ```
            </Tab>
            <Tab value="FastAPI">
                ```bash
                cd ..
                uv run main.py
                ```
            </Tab>
        </Tabs>

        Your agent will be available at `http://localhost:8123`.

        <Callout type="info">
            If port 8123 is already in use, change the `--port` flag (or the `port=` argument
            in the FastAPI `main.py`) and update `LANGGRAPH_DEPLOYMENT_URL` in the **Setup Copilot Runtime** step to match.
        </Callout>
    </Step>
    <Step>
        ### Start your UI [#start-your-ui]

        In a separate terminal, navigate to your frontend directory and start the development server:

        <Tabs groupId="package-manager" items={['npm', 'pnpm', 'yarn', 'bun']}>
            <Tab value="npm">
                ```bash
                cd frontend && npm run dev
                ```
            </Tab>
            <Tab value="pnpm">
                ```bash
                cd frontend && pnpm dev
                ```
            </Tab>
            <Tab value="yarn">
                ```bash
                cd frontend && yarn dev
                ```
            </Tab>
            <Tab value="bun">
                ```bash
                cd frontend && bun dev
                ```
            </Tab>
        </Tabs>

        Open `http://localhost:3000` and ask the agent: `What is the weather in Paris?` The sidebar shows a **Called get_weather** entry, and the agent replies that the weather in Paris is sunny.
    </Step>
    <Step>
        ### Open Inspector and confirm setup [#open-inspector-and-confirm-setup]

        On localhost, click the Inspector button in the corner of the app.

        1. Open **Inspect**, then **Agent**. Your agent is listed.
        2. Send a chat message. Open **Inspect**, then **AG-UI Events**. Events are moving.
        3. Open **Rich Threads**. The list is unlocked (Intelligence is on), or locked with **Copy setup prompt** (Intelligence is off).

        More detail: [Inspector](/deepagents/inspector).
    </Step>

</Steps>
