Back to Copilotkit

Quickstart

showcase/shell-docs/src/content/docs/integrations/microsoft-agent-framework/quickstart.mdx

1.57.020.0 KB
Original Source

<video src="https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/chat-example.mp4" className="rounded-lg shadow-xl" loop playsInline controls autoPlay muted />

Prerequisites

Before you begin, you'll need the following:

  • A GitHub Personal Access Token (for GitHub Models API - free AI access)
  • .NET 9.0 SDK or later
  • Node.js 20+
  • Your favorite package manager (npm, pnpm, yarn, or bun)

Getting started

<Steps> <TailoredContent className="step" id="agent" header={ <div> <p className="text-xl font-semibold">Choose your starting point</p> <p className="text-base"> You can either start fresh with our starter template or integrate CopilotKit into your existing Microsoft Agent Framework agent. </p> </div> } > <TailoredContentOption id="starter" title="Start from scratch" description="Get started quickly with our ready-to-go starter application." > <Step> ### Run our CLI
            First, we'll use our CLI to create a new project for us.

            <Tabs groupId="language_microsoft-agent-framework_agent" items={['.NET', 'Python']} persist>
                <Tab value=".NET">
                    ```bash
                    npx copilotkit@latest create -f microsoft-agent-framework-dotnet
                    ```
                </Tab>
                <Tab value="Python">
                    ```bash
                    npx copilotkit@latest create -f microsoft-agent-framework-py
                    ```
                </Tab>
            </Tabs>
        </Step>
        <Step>
            ### 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

            <Tabs groupId="language_microsoft-agent-framework_agent" items={['.NET', 'Python']} persist>
                <Tab value=".NET">
                    The starter template uses GitHub Models API for free access to AI models. Set up your GitHub token:

                    First, get your GitHub token (requires [GitHub CLI](https://github.com/cli/cli)):
                    ```bash
                    gh auth token
                    ```

                    Then navigate to the agent directory and set it as a user secret:
                    ```bash
                    cd agent
                    dotnet user-secrets set GitHubToken "$(gh auth token)"
                    cd ..
                    ```

                    <Callout type="info" title="Want to use a different model provider?">
                      The starter template is configured to use GitHub Models (free), but you can modify it to use:
                      - OpenAI directly
                      - Azure OpenAI
                      - Any other model supported by Microsoft Agent Framework

                      Check the `agent/Program.cs` file to customize the model configuration.
                    </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-5.4-mini
                    ```

                    ```bash title="agent/.env (Azure OpenAI)"
                    AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
                    AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-5.4-mini
                    # If you are not relying on az login:
                    # AZURE_OPENAI_API_KEY=...
                    ```
                </Tab>
            </Tabs>
        </Step>
        <Step>
            ### 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

            Make sure your agent is running and exposing an AG-UI endpoint. Here's a minimal example:

            <Tabs groupId="language_microsoft-agent-framework_agent" items={['.NET', 'Python']} persist>
                <Tab value=".NET">
                    First, setup a new .NET project:
                    ```bash
                    dotnet new web -n AGUIServer
                    cd AGUIServer
                    dotnet add package Microsoft.Agents.AI.Hosting.AGUI.AspNetCore --version 1.0.0-preview.251110.1
                    dotnet add package Microsoft.Extensions.AI.OpenAI --version 9.10.2-preview.1.25552.1
                    dotnet add package OpenAI --version 2.6.0
                    dotnet user-secrets init
                    ```

                    Build a minimal agent and serve it via AG-UI:

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

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

                    // Get your GitHub token for GitHub Models (free)
                    var githubToken = builder.Configuration["GitHubToken"]!;
                    var openAI = new OpenAIClient(
                        new System.ClientModel.ApiKeyCredential(githubToken),
                        new OpenAIClientOptions {
                            Endpoint = new Uri("https://models.inference.ai.azure.com")
                        });

                    var chatClient = openAI.GetChatClient("gpt-5.4-mini").AsIChatClient();
                    var agent = new ChatClientAgent(
                        chatClient,
                        name: "MyAgent",
                        description: "You are a helpful assistant.");

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

                    Then just setup the environment and run your agent:

                    ```bash
                    # Set your GitHub token and run
                    dotnet user-secrets set GitHubToken "$(gh auth token)"
                    dotnet run
                    ```
                </Tab>
                <Tab value="Python">

                    Create a python project

                    ```bash
                    uv init my-agent
                    cd my-agent
                    uv add agent-framework-ag-ui python-dotenv uvicorn agent-framework-openai
                    ```
                    Create a minimal FastAPI server that exposes a Microsoft Agent Framework agent over AG-UI:
                    Replace main.py file with the following 

                    ```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 dotenv import load_dotenv
                    from fastapi import FastAPI

                    load_dotenv()

                    def _build_chat_client():
                        if os.getenv("AZURE_OPENAI_ENDPOINT"):
                            return OpenAIChatClient(
                                model=os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME", "gpt-4o-mini"),
                                api_key=os.getenv("AZURE_OPENAI_API_KEY"),
                                azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
                            )
                        if os.getenv("OPENAI_API_KEY"):
                            return OpenAIChatClient(
                                model=os.getenv("OPENAI_CHAT_MODEL_ID", "gpt-4o-mini"),
                                api_key=os.getenv("OPENAI_API_KEY"),
                            )
                        raise RuntimeError(
                            "Set either AZURE_OPENAI_ENDPOINT + AZURE_OPENAI_API_KEY, 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)
                    ```

                    Then set your environment and run:

                    ```bash
                    # OpenAI (agent/.env)
                    OPENAI_API_KEY=sk-...your-openai-key-here...
                    OPENAI_CHAT_MODEL_ID=gpt-5.4-mini
                    # or Azure OpenAI (agent/.env)
                    AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
                    AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-5.4-mini
                    # (optional) AZURE_OPENAI_API_KEY=...

                    # Run the agent
                    uv run main.py
                    ```
                </Tab>
            </Tabs>

        </Step>
        <Step>
            ### 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

            ```npm
            npm install @copilotkit/react-ui @copilotkit/react-core @copilotkit/runtime @ag-ui/client
            ```
        </Step>
        <Step>
            ### Setup Copilot Runtime

            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/route.ts`:

            ```tsx title="app/api/copilotkit/route.ts"
            import {
              CopilotRuntime,
              ExperimentalEmptyAdapter,
              copilotRuntimeNextJSAppRouterEndpoint,
            } from "@copilotkit/runtime";
            import { HttpAgent } from "@ag-ui/client";
            import { NextRequest } from "next/server";

            // 1. You can use any service adapter here for multi-agent support. We use
            //    the empty adapter since we're only using one agent.
            const serviceAdapter = new ExperimentalEmptyAdapter();

            // 2. Create the CopilotRuntime instance and utilize the Microsoft Agent Framework
            //    AG-UI integration to setup the connection.
            // [!code highlight:5]
            const runtime = new CopilotRuntime({
              agents: {
                my_agent: new HttpAgent({ url: "http://localhost:8000/" }),
              },
            });

            // 3. Build a Next.js API route that handles the CopilotKit runtime requests.
            export const POST = async (req: NextRequest) => {
              const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
                runtime,
                serviceAdapter,
                endpoint: "/api/copilotkit",
              });

              return handleRequest(req);
            };
            ```
        </Step>
        <Step>
            ### 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/layout.tsx"
            import { CopilotKit } from "@copilotkit/react-core/v2"; // [!code highlight]
            import "@copilotkit/react-ui/v2/styles.css";
            import './globals.css';

            export default function RootLayout({ children }: {children: React.ReactNode}) {
              return (
                <html lang="en">
                  <body>
                    <CopilotKit runtimeUrl="/api/copilotkit" agent="my_agent">
                      {children}
                    </CopilotKit>
                  </body>
                </html>
              );
            }
            ```
        </Step>
        <Step>
          ### 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>
                <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
          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>
    ### 🎉 Start chatting!

    Your AI agent is now ready to use! Try asking it some questions:

    ```
    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 C# agent is running on port 8000
              - Your GitHub token is set correctly via user secrets
              - Both servers started successfully (check terminal output)

            **GitHub Token Issues**
            - If the agent fails with "GitHubToken not found":
              ```bash
              cd agent
              dotnet user-secrets set GitHubToken "$(gh auth token)"
              ```

            **.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:
              - `agent/Properties/launchSettings.json` - Update `applicationUrl`
              - `src/app/api/copilotkit/route.ts` - Update the remote endpoint URL
        </Accordion>
    </Accordions>

</Step>
</Steps>

What's 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="/microsoft-agent-framework/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="/microsoft-agent-framework/shared-state" icon={<RepeatIcon />} /> <Card title="Add some generative UI" description="Render your agent's progress and output in the UI." href="/microsoft-agent-framework/generative-ui/tool-rendering" icon={<PaintbrushIcon />} /> <Card title="Setup frontend actions" description="Give your agent the ability to call frontend tools, directly updating your application." href="/microsoft-agent-framework/frontend-tools" icon={<WrenchIcon />} /> </Cards>