# Quickstart

> Turn your Microsoft Agent Framework agent into an agent-native application in 10 minutes.

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

Use this prompt to connect your Microsoft Agent Framework 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](https://platform.openai.com/api-keys) for the .NET starter
- .NET 9.0 SDK or later, for a .NET agent
- Python 3.12 or later and [uv](https://docs.astral.sh/uv/), for a Python agent
- Node.js 20+
- Your favorite package manager (npm, pnpm, yarn, or bun)

## Getting started [#getting-started]

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

        <SignupLink surface="docs_microsoft_agent_framework_quickstart_step1">Sign in to cloud-hosted Intelligence</SignupLink>. You will connect the app after you create it below.
    </Step>

    <Step>
        ### Choose your starting point [#choose-your-starting-point]

        You can either start fresh with our starter template or integrate CopilotKit into your existing Microsoft Agent Framework agent.

        <TailoredContent
            className="step"
            id="agent"
        >
        <TailoredContentOption
            id="starter"
            title="Start from scratch"
            description="Get started quickly with our ready-to-go starter application."
        >
            <Step>
                ### Run our CLI [#run-our-cli]

                ```bash
                npx copilotkit@latest create
                ```

                The CLI walks you through:

                - **Project name**
                - **CopilotKit Intelligence**: persistent threads and the Inspector. Choose **Yes** for a project that is wired to Intelligence. Choose **No** for a standard Microsoft Agent Framework setup.
                - **Framework**: pick **Microsoft Agent Framework (.NET)** or **Microsoft Agent Framework (Python)**.
            </Step>
            <Step>
                ### Install dependencies [#install-dependencies]

                The starter includes a `postinstall` script that automatically installs both your npm and agent dependencies.

                ```npm
                npm install
                ```

                <Callout type="info" title="Manual setup">
                  <Tabs groupId="language_microsoft-agent-framework_agent" items={['.NET', 'Python']} persist>
                    <Tab value=".NET">
                      If you have issues with automatic .NET package installation, you can manually restore them:
                      ```bash
                      npm run install:agent
                      ```
                    </Tab>
                    <Tab value="Python">
                      If you have issues with automatic Python setup, you can manually install the agent dependencies:
                      ```bash
                      npm run install:agent
                      # or manually:
                      cd agent
                      uv sync
                      ```
                    </Tab>
                  </Tabs>
                </Callout>
            </Step>
            <Step>
                ### Configure your environment [#configure-your-environment]

                <Tabs groupId="language_microsoft-agent-framework_agent" items={['.NET', 'Python']} persist>
                    <Tab value=".NET">
                        The .NET starter uses OpenAI. Save your API key as a .NET user secret:

                        ```bash
                        cd agent
                        dotnet user-secrets set OPENAI_API_KEY "<your-openai-api-key>"
                        cd ..
                        ```

                        <Callout type="info" title="Want to use a different model provider?">
                          Edit `agent/Program.cs` to use Azure OpenAI or another
                          [Microsoft Agent Framework model provider](https://learn.microsoft.com/en-us/agent-framework/integrations/by-component/model-providers/).
                        </Callout>
                    </Tab>
                    <Tab value="Python">
                        Create a `.env` file inside the `agent` folder with one of the following configurations:

                        ```bash title="agent/.env (OpenAI)"
                        OPENAI_API_KEY=sk-...your-openai-key-here...
                        OPENAI_CHAT_MODEL_ID=gpt-6-luna
                        ```

                        ```bash title="agent/.env (Azure OpenAI)"
                        AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
                        AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-6-luna
                        # Optional when az login is unavailable:
                        # AZURE_OPENAI_API_KEY=...
                        ```
                    </Tab>
                </Tabs>
            </Step>
            <Step>
                ### Start the development server [#start-the-development-server]

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

                This will start both the Next.js UI (port 3000) and agent server (port 8000) concurrently.
            </Step>
        </TailoredContentOption>
        <TailoredContentOption
            id="bring-your-own"
            title="Use an existing agent"
            description="I already have a Microsoft Agent Framework agent and want to add CopilotKit."
        >
            <Step>
                ### Start your Microsoft Agent Framework agent [#start-your-microsoft-agent-framework-agent]

                Serve your agent over an AG-UI endpoint. This is a minimal example:

                <Tabs groupId="language_microsoft-agent-framework_agent" items={['.NET', 'Python']} persist>
                    <Tab value=".NET">
                        1. Create the project and add the packages:

                        ```bash
                        dotnet new web -n AGUIServer
                        cd AGUIServer
                        dotnet add package Microsoft.Agents.AI.Hosting.AGUI.AspNetCore --version 1.19.0-preview.260822.1
                        dotnet add package Microsoft.Agents.AI.OpenAI --version 1.19.0
                        dotnet user-secrets init
                        ```

                        2. Write `Program.cs`. It builds a minimal agent and serves it over AG-UI:

                        ```csharp title="Program.cs"
#pragma warning disable OPENAI001
using Microsoft.Extensions.AI;
                        using Microsoft.Agents.AI;
                        // [!code highlight:1]
                        using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
                        using OpenAI;
                        using OpenAI.Chat;

                        var builder = WebApplication.CreateBuilder(args);
                        // [!code highlight:1]
                        builder.Services.AddAGUIServer();
                        var app = builder.Build();

                        var openAiApiKey = builder.Configuration["OPENAI_API_KEY"]
                            ?? throw new InvalidOperationException("Set OPENAI_API_KEY");
                        var openAI = new OpenAIClient(openAiApiKey);

                        var agent = openAI.GetChatClient("gpt-6-luna")
    .AsIChatClient().AsBuilder()
    .ConfigureOptions(options => options.RawRepresentationFactory = _ =>
        new OpenAI.Chat.ChatCompletionOptions { ReasoningEffortLevel = new("none") })
    .Build().AsAIAgent(
                            name: "MyAgent",
                            instructions: "You are a helpful assistant.");

                        // [!code highlight:1]
                        app.MapAGUIServer("/", agent);
                        app.Run("http://localhost:8000");
                        ```

                        3. Set the API key:

                        ```bash
                        dotnet user-secrets set OPENAI_API_KEY "<your-openai-api-key>"
                        ```

                        4. Run the agent:

                        ```bash
                        dotnet run
                        ```
                    </Tab>
                    <Tab value="Python">

                        1. Create the project and add the packages:

                        ```bash
                        uv init my-agent
                        cd my-agent
                        uv add agent-framework-ag-ui python-dotenv uvicorn agent-framework-openai azure-identity
                        ```

                        2. Replace the contents of `main.py` with this FastAPI server. It serves a Microsoft Agent Framework agent over AG-UI:

                        ```python title="main.py"
                        from __future__ import annotations
                        import os
                        import uvicorn
                        from agent_framework import Agent
                        from agent_framework.openai import OpenAIChatClient
                        from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
                        from azure.identity import DefaultAzureCredential
                        from dotenv import load_dotenv
                        from fastapi import FastAPI

                        load_dotenv()

                        def _build_chat_client():
                            if os.getenv("AZURE_OPENAI_ENDPOINT"):
                                azure_api_key = os.getenv("AZURE_OPENAI_API_KEY")
                                return OpenAIChatClient(
                                    model=os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME", "gpt-6-luna"),
                                    api_key=azure_api_key,
                                    credential=None if azure_api_key else DefaultAzureCredential(),
                                    azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
                                )
                            if os.getenv("OPENAI_API_KEY"):
                                return OpenAIChatClient(
                                    model=os.getenv("OPENAI_CHAT_MODEL_ID", "gpt-6-luna"),
                                    api_key=os.getenv("OPENAI_API_KEY"),
                                )
                            raise RuntimeError(
                                "Set AZURE_OPENAI_ENDPOINT (uses az login unless AZURE_OPENAI_API_KEY is set) or OPENAI_API_KEY."
                            )

                        chat_client = _build_chat_client()

                        agent = Agent(
                            name="MyAgent",
                            instructions="You are a helpful assistant.",
                            client=chat_client,
                        )

                        app = FastAPI(title="Microsoft Agent Framework - Quickstart")
                        add_agent_framework_fastapi_endpoint(app=app, agent=agent, path="/")

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

                        3. Create a `.env` file in `my-agent` with your OpenAI key:

                        ```plaintext title=".env"
                        OPENAI_API_KEY=sk-...your-openai-key-here...
                        OPENAI_CHAT_MODEL_ID=gpt-6-luna
                        ```

                        For Azure OpenAI, set `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME` instead. If you do not use `az login`, also set `AZURE_OPENAI_API_KEY`.

                        4. Run the agent:

                        ```bash
                        uv run main.py
                        ```
                    </Tab>
                </Tabs>

            </Step>
            <Step>
                ### Frontend Setup [#frontend-setup]
                CopilotKit works with any React-based frontend. We'll use Next.js for this example.

                In a new terminal window, run the following commands:

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

                ```npm
                npm install @copilotkit/react-ui @copilotkit/react-core @copilotkit/runtime @ag-ui/client@1.0.2
                ```
            </Step>
            <Step>
                ### Add the Copilot Runtime route [#add-the-copilot-runtime-route]

                CopilotKit requires a Copilot Runtime endpoint to safely communicate with your agent. This can be served
                anywhere that Node.js can run, but for this example we'll use Next.js.

                Create a new API route at `app/api/copilotkit/[[...slug]]/route.ts`:

                ```tsx title="app/api/copilotkit/[[...slug]]/route.ts" doctest="component"
                import {
                  CopilotKitIntelligence,
                  CopilotRuntime,
                  createCopilotRuntimeHandler,
                } from "@copilotkit/runtime/v2";
                import { HttpAgent } from "@ag-ui/client";

                // [!code highlight:5]
                const runtime = new CopilotRuntime({
                  agents: {
                    my_agent: new HttpAgent({ url: "http://localhost:8000/" }),
                  },
                  // [!code highlight:9]
                  intelligence: new CopilotKitIntelligence({
                    apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
                  }),
                  // Demo only: the browser sends no x-user-id header, so all visitors share
                  // one "anonymous" history. Before you deploy, return the verified session user.
                  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;
                ```

                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 and the Inspector still work, but
                  Rich Threads stay locked and the key is never read. See
                  [Connect your runtime to Intelligence](/ms-agent-dotnet/intelligence/quickstart) for the
                  full constructor and how to confirm the key is in use.
                </Callout>
            </Step>
            <Step>
                ### Configure CopilotKit Provider [#configure-copilotkit-provider]

                Next, wrap your application with the CopilotKit provider so that CopilotKit can take control across your application
                via the Microsoft Agent Framework agent.

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

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

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

                Render `Providers` around your app in `app/layout.tsx`:

                ```tsx title="app/layout.tsx"
                import { Providers } from "./providers"; // [!code highlight]
                import "@copilotkit/react-core/v2/styles.css";
                import './globals.css';

                export default function RootLayout({ children }: {children: React.ReactNode}) {
                  return (
                    <html lang="en">
                      <body>
                        {/* [!code highlight:3] */}
                        <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`. See the [React SPA](/ms-agent-dotnet/react-spa), [Vue](/vue),
                  [Angular](/angular), and [React Native](/react-native) guides for 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";

              // [!code highlight:1]
              import { CopilotSidebar } from "@copilotkit/react-core/v2";

              export default function Page() {
                return (
                  <main>
                    {/* [!code highlight:6] */}
                    <CopilotSidebar
                      labels={{
                        modalHeaderTitle: "Your Assistant",
                        welcomeMessageText: "Hi! How can I help you today?",
                      }}
                    />
                    <h1>Your App</h1>
                  </main>
                );
              }
              ```
            </Step>
            <Step>
              ### Run and start your Next.js app [#run-and-start-your-nextjs-app]
              To run the Next.js app we just created, use the following command:

              <Tabs groupId="package-manager" items={['npm', 'pnpm', 'yarn', 'bun']}>
                  <Tab value="npm">
                      ```bash
                      npm run dev
                      ```
                  </Tab>
                  <Tab value="pnpm">
                      ```bash
                      pnpm dev
                      ```
                  </Tab>
                  <Tab value="yarn">
                      ```bash
                      yarn dev
                      ```
                  </Tab>
                  <Tab value="bun">
                      ```bash
                      bun dev
                      ```
                  </Tab>
              </Tabs>
            </Step>
        </TailoredContentOption>
    </TailoredContent>
    </Step>
    <Step>
        ### Start chatting [#start-chatting]

        Open http://localhost:3000 and open the sidebar. Send one of these messages, and the agent replies in the sidebar:

        - Can you tell me a joke?
        - Can you help me understand AI?
        - What do you think about .NET?

        <Accordions className="mb-4">
            <Accordion title="Troubleshooting">
                **Agent Connection Issues**
                - If you see "I'm having trouble connecting to my tools", make sure:
                  - The agent is running on port 8000
                  - Your OpenAI API key is set: in .NET user secrets for a .NET agent, or in the `.env` file of a Python agent
                  - Both servers started successfully (check terminal output)

                **OpenAI API Key Issues**
                - If the .NET agent fails with "OPENAI_API_KEY not found":
                  ```bash
                  cd agent
                  dotnet user-secrets set OPENAI_API_KEY "<your-openai-api-key>"
                  ```

                **.NET SDK Issues**
                - Verify .NET SDK is installed:
                  ```bash
                  dotnet --version  # Should be 9.0.x or higher
                  ```
                - Restore packages manually if needed:
                  ```bash
                  cd agent
                  dotnet restore
                  dotnet run
                  ```

                **Port Conflicts**
                - If port 8000 is already in use, you can change it in:
                  - .NET agent: `agent/Properties/launchSettings.json` - Update `applicationUrl`
                  - Python agent: `agent/.env` - Set `AGENT_PORT`
                  - Frontend: `.env` - Set `AGENT_URL` to the new agent URL (read in `src/agent.ts`)
            </Accordion>
        </Accordions>

    </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](/ms-agent-dotnet/inspector).
    </Step>

</Steps>

## What's next? [#whats-next]

Now that you have your basic agent setup, explore these advanced features:

<Cards>
  <Card
    title="Implement Human in the Loop"
    description="Allow your users and agents to collaborate together on tasks."
    href="/ms-agent-dotnet/human-in-the-loop"
    icon={<UserIcon />}
  />
  <Card
    title="Utilize Shared State"
    description="Learn how to synchronize your agent's state with your UI's state, and vice versa."
    href="/ms-agent-dotnet/shared-state"
    icon={<RepeatIcon />}
  />
  <Card
    title="Add some generative UI"
    description="Render your agent's progress and output in the UI."
    href="/ms-agent-dotnet/generative-ui/tool-rendering"
    icon={<PaintbrushIcon />}
  />
  <Card
    title="Add frontend tools"
    description="Give your agent the ability to call frontend tools, directly updating your application."
    href="/ms-agent-dotnet/frontend-tools"
    icon={<WrenchIcon />}
  />
</Cards>
