🚀 快速安装

复制以下命令并运行,立即安装此 Skill:

npx @anthropic-ai/skills install github/awesome-copilot/copilot-sdk

💡 提示:需要 Node.js 和 NPM

GitHub Copilot SDK

在任何应用中使用 Python、TypeScript、Go 或 .NET 嵌入 Copilot 的代理工作流。

概述

GitHub Copilot SDK 公开了 Copilot CLI 背后的相同引擎:一个经过生产测试的代理运行时,您可以通过编程方式调用它。无需构建自己的编排——您定义代理行为,Copilot 负责规划、工具调用、文件编辑等。

先决条件

  1. 已安装并验证 GitHub Copilot CLI (安装指南)
  2. 语言运行时:Node.js 18+、Python 3.8+、Go 1.21+ 或 .NET 8.0+

验证 CLI: copilot --version

安装

Node.js/TypeScript

mkdir copilot-demo && cd copilot-demo
npm init -y --init-type module
npm install @github/copilot-sdk tsx

Python

pip install github-copilot-sdk

Go

mkdir copilot-demo && cd copilot-demo
go mod init copilot-demo
go get github.com/github/copilot-sdk/go

.NET

dotnet new console -n CopilotDemo && cd CopilotDemo
dotnet add package GitHub.Copilot.SDK

快速开始

TypeScript

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });

const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
console.log(response?.data.content);

await client.stop();
process.exit(0);

运行: npx tsx index.ts

Python

import asyncio
from copilot import CopilotClient

async def main():
    client = CopilotClient()
    await client.start()

    session = await client.create_session({"model": "gpt-4.1"})
    response = await session.send_and_wait({"prompt": "What is 2 + 2?"})

    print(response.data.content)
    await client.stop()

asyncio.run(main())

Go

package main

import (
    "fmt"
    "log"
    "os"
    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    client := copilot.NewClient(nil)
    if err := client.Start(); err != nil {
        log.Fatal(err)
    }
    defer client.Stop()

    session, err := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"})
    if err != nil {
        log.Fatal(err)
    }

    response, err := session.SendAndWait(copilot.MessageOptions{Prompt: "What is 2 + 2?"}, 0)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(*response.Data.Content)
    os.Exit(0)
}

.NET (C#)

using GitHub.Copilot.SDK;

await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" });

var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2 + 2?" });
Console.WriteLine(response?.Data.Content);

运行: dotnet run

流式响应

启用实时输出以获得更好的用户体验:

TypeScript

import { CopilotClient, SessionEvent } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
});

session.on((event: SessionEvent) => {
    if (event.type === "assistant.message_delta") {
        process.stdout.write(event.data.deltaContent);
    }
    if (event.type === "session.idle") {
        console.log(); // 完成时换行
    }
});

await session.sendAndWait({ prompt: "Tell me a short joke" });

await client.stop();
process.exit(0);

Python

import asyncio
import sys
from copilot import CopilotClient
from copilot.generated.session_events import SessionEventType

async def main():
    client = CopilotClient()
    await client.start()

    session = await client.create_session({
        "model": "gpt-4.1",
        "streaming": True,
    })

    def handle_event(event):
        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
            sys.stdout.write(event.data.delta_content)
            sys.stdout.flush()
        if event.type == SessionEventType.SESSION_IDLE:
            print()

    session.on(handle_event)
    await session.send_and_wait({"prompt": "Tell me a short joke"})
    await client.stop()

asyncio.run(main())

Go

session, err := client.CreateSession(&copilot.SessionConfig{
    Model:     "gpt-4.1",
    Streaming: true,
})

session.On(func(event copilot.SessionEvent) {
    if event.Type == "assistant.message_delta" {
        fmt.Print(*event.Data.DeltaContent)
    }
    if event.Type == "session.idle" {
        fmt.Println()
    }
})

_, err = session.SendAndWait(copilot.MessageOptions{Prompt: "Tell me a short joke"}, 0)

.NET

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    Model = "gpt-4.1",
    Streaming = true,
});

session.On(ev =>
{
    if (ev is AssistantMessageDeltaEvent deltaEvent)
        Console.Write(deltaEvent.Data.DeltaContent);
    if (ev is SessionIdleEvent)
        Console.WriteLine();
});

await session.SendAndWaitAsync(new MessageOptions { Prompt = "Tell me a short joke" });

自定义工具

定义 Copilot 在推理过程中可以调用的工具。当您定义工具时,您告诉 Copilot:

  1. 该工具做什么(描述)
  2. 它需要哪些参数(模式)
  3. 要运行什么代码(处理程序)

TypeScript (JSON Schema)

import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk";

const getWeather = defineTool("get_weather", {
    description: "获取指定城市的当前天气", // 翻译
    parameters: {
        type: "object",
        properties: {
            city: { type: "string", description: "城市名称" }, // 翻译
        },
        required: ["city"],
    },
    handler: async (args: { city: string }) => {
        const { city } = args;
        // 在实际应用中,这里调用天气API
        const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
        const temp = Math.floor(Math.random() * 30) + 50;
        const condition = conditions[Math.floor(Math.random() * conditions.length)];
        return { city, temperature: `${temp}°F`, condition };
    },
});

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
    tools: [getWeather],
});

session.on((event: SessionEvent) => {
    if (event.type === "assistant.message_delta") {
        process.stdout.write(event.data.deltaContent);
    }
});

await session.sendAndWait({
    prompt: "What's the weather like in Seattle and Tokyo?",
});

await client.stop();
process.exit(0);

Python (Pydantic)

import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field

class GetWeatherParams(BaseModel):
    city: str = Field(description="要获取天气的城市名称") # 翻译

@define_tool(description="获取指定城市的当前天气") # 翻译
async def get_weather(params: GetWeatherParams) -> dict:
    city = params.city
    conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
    temp = random.randint(50, 80)
    condition = random.choice(conditions)
    return {"city": city, "temperature": f"{temp}°F", "condition": condition}

async def main():
    client = CopilotClient()
    await client.start()

    session = await client.create_session({
        "model": "gpt-4.1",
        "streaming": True,
        "tools": [get_weather],
    })

    def handle_event(event):
        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
            sys.stdout.write(event.data.delta_content)
            sys.stdout.flush()

    session.on(handle_event)

    await session.send_and_wait({
        "prompt": "What's the weather like in Seattle and Tokyo?"
    })

    await client.stop()

asyncio.run(main())

Go

type WeatherParams struct {
    City string `json:"city" jsonschema:"城市名称"` // 翻译
}

type WeatherResult struct {
    City        string `json:"city"`
    Temperature string `json:"temperature"`
    Condition   string `json:"condition"`
}

getWeather := copilot.DefineTool(
    "get_weather",
    "获取指定城市的当前天气", // 翻译
    func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {
        conditions := []string{"sunny", "cloudy", "rainy", "partly cloudy"}
        temp := rand.Intn(30) + 50
        condition := conditions[rand.Intn(len(conditions))]
        return WeatherResult{
            City:        params.City,
            Temperature: fmt.Sprintf("%d°F", temp),
            Condition:   condition,
        }, nil
    },
)

session, _ := client.CreateSession(&copilot.SessionConfig{
    Model:     "gpt-4.1",
    Streaming: true,
    Tools:     []copilot.Tool{getWeather},
})

.NET (Microsoft.Extensions.AI)

using GitHub.Copilot.SDK;
using Microsoft.Extensions.AI;
using System.ComponentModel;

var getWeather = AIFunctionFactory.Create(
    ([Description("城市名称")] string city) => // 翻译
    {
        var conditions = new[] { "sunny", "cloudy", "rainy", "partly cloudy" };
        var temp = Random.Shared.Next(50, 80);
        var condition = conditions[Random.Shared.Next(conditions.Length)];
        return new { city, temperature = $"{temp}°F", condition };
    },
    "get_weather",
    "获取指定城市的当前天气" // 翻译
);

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    Model = "gpt-4.1",
    Streaming = true,
    Tools = [getWeather],
});

工具工作原理

当 Copilot 决定调用您的工具时:

  1. Copilot 发送带有参数的工具调用请求
  2. SDK 运行您的处理程序函数
  3. 结果被发送回 Copilot
  4. Copilot 将结果整合到其响应中

Copilot 根据用户的问题和您工具的描述来决定何时调用您的工具。

交互式 CLI 助手

构建一个完整的交互式助手:

TypeScript

import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk";
import * as readline from "readline";

const getWeather = defineTool("get_weather", {
    description: "获取指定城市的当前天气", // 翻译
    parameters: {
        type: "object",
        properties: {
            city: { type: "string", description: "城市名称" }, // 翻译
        },
        required: ["city"],
    },
    handler: async ({ city }) => {
        const conditions = ["sunny", "cloudy", "rainy", "partly cloudy"];
        const temp = Math.floor(Math.random() * 30) + 50;
        const condition = conditions[Math.floor(Math.random() * conditions.length)];
        return { city, temperature: `${temp}°F`, condition };
    },
});

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
    tools: [getWeather],
});

session.on((event: SessionEvent) => {
    if (event.type === "assistant.message_delta") {
        process.stdout.write(event.data.deltaContent);
    }
});

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

console.log("天气助手 (输入 'exit' 退出)"); // 翻译
console.log("试试: 'What's the weather in Paris?'\n");

const prompt = () => {
    rl.question("You: ", async (input) => {
        if (input.toLowerCase() === "exit") {
            await client.stop();
            rl.close();
            return;
        }

        process.stdout.write("Assistant: ");
        await session.sendAndWait({ prompt: input });
        console.log("\n");
        prompt();
    });
};

prompt();

Python

import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field

class GetWeatherParams(BaseModel):
    city: str = Field(description="要获取天气的城市名称") # 翻译

@define_tool(description="获取指定城市的当前天气") # 翻译
async def get_weather(params: GetWeatherParams) -> dict:
    conditions = ["sunny", "cloudy", "rainy", "partly cloudy"]
    temp = random.randint(50, 80)
    condition = random.choice(conditions)
    return {"city": params.city, "temperature": f"{temp}°F", "condition": condition}

async def main():
    client = CopilotClient()
    await client.start()

    session = await client.create_session({
        "model": "gpt-4.1",
        "streaming": True,
        "tools": [get_weather],
    })

    def handle_event(event):
        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
            sys.stdout.write(event.data.delta_content)
            sys.stdout.flush()

    session.on(handle_event)

    print("天气助手 (输入 'exit' 退出)") # 翻译
    print("试试: 'What's the weather in Paris?'\n")

    while True:
        try:
            user_input = input("You: ")
        except EOFError:
            break

        if user_input.lower() == "exit":
            break

        sys.stdout.write("Assistant: ")
        await session.send_and_wait({"prompt": user_input})
        print("\n")

    await client.stop()

asyncio.run(main())

MCP 服务器集成

连接到 MCP(模型上下文协议)服务器以使用预构建的工具。连接到 GitHub 的 MCP 服务器以访问仓库、议题和 PR:

TypeScript

const session = await client.createSession({
    model: "gpt-4.1",
    mcpServers: {
        github: {
            type: "http",
            url: "https://api.githubcopilot.com/mcp/",
        },
    },
});

Python

session = await client.create_session({
    "model": "gpt-4.1",
    "mcp_servers": {
        "github": {
            "type": "http",
            "url": "https://api.githubcopilot.com/mcp/",
        },
    },
})

Go

session, _ := client.CreateSession(&copilot.SessionConfig{
    Model: "gpt-4.1",
    MCPServers: map[string]copilot.MCPServerConfig{
        "github": {
            Type: "http",
            URL:  "https://api.githubcopilot.com/mcp/",
        },
    },
})

.NET

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    Model = "gpt-4.1",
    McpServers = new Dictionary<string, McpServerConfig>
    {
        ["github"] = new McpServerConfig
        {
            Type = "http",
            Url = "https://api.githubcopilot.com/mcp/",
        },
    },
});

自定义代理

为特定任务定义专门的 AI 角色:

TypeScript

const session = await client.createSession({
    model: "gpt-4.1",
    customAgents: [{
        name: "pr-reviewer",
        displayName: "PR 审查员", // 翻译
        description: "根据最佳实践审查拉取请求", // 翻译
        prompt: "你是一名代码审查专家。关注安全性、性能和可维护性。", // 翻译
    }],
});

Python

session = await client.create_session({
    "model": "gpt-4.1",
    "custom_agents": [{
        "name": "pr-reviewer",
        "display_name": "PR 审查员", # 翻译
        "description": "根据最佳实践审查拉取请求", # 翻译
        "prompt": "你是一名代码审查专家。关注安全性、性能和可维护性。", # 翻译
    }],
})

系统消息

自定义 AI 的行为和个性:

TypeScript

const session = await client.createSession({
    model: "gpt-4.1",
    systemMessage: {
        content: "你是我工程团队的得力助手。务必保持简洁。", // 翻译
    },
});

Python

session = await client.create_session({
    "model": "gpt-4.1",
    "system_message": {
        "content": "你是我工程团队的得力助手。务必保持简洁。", # 翻译
    },
})

外部 CLI 服务器

单独以服务器模式运行 CLI,并将 SDK 连接到它。便于调试、资源共享或自定义环境。

以服务器模式启动 CLI

copilot --server --port 4321

连接 SDK 到外部服务器

TypeScript

const client = new CopilotClient({
    cliUrl: "localhost:4321"
});

const session = await client.createSession({ model: "gpt-4.1" });

Python

client = CopilotClient({
    "cli_url": "localhost:4321"
})
await client.start()

session = await client.create_session({"model": "gpt-4.1"})

Go

client := copilot.NewClient(&copilot.ClientOptions{
    CLIUrl: "localhost:4321",
})

if err := client.Start(); err != nil {
    log.Fatal(err)
}

session, _ := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"})

.NET

using var client = new CopilotClient(new CopilotClientOptions
{
    CliUrl = "localhost:4321"
});

await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" });

注意: 当提供 cliUrl 时,SDK 不会生成或管理 CLI 进程——它仅连接到现有服务器。

事件类型

事件 描述
user.message 已添加用户输入
assistant.message 完整模型响应
assistant.message_delta 流式响应片段
assistant.reasoning 模型推理(取决于模型)
assistant.reasoning_delta 流式推理片段
tool.execution_start 工具调用已开始
tool.execution_complete 工具执行已完成
session.idle 无活动处理
session.error 发生错误

客户端配置

选项 描述 默认值
cliPath Copilot CLI 可执行文件的路径 系统 PATH
cliUrl 连接到现有服务器(例如 “localhost:4321″)
port 服务器通信端口 随机
useStdio 使用 stdio 传输而非 TCP true
logLevel 日志详细程度 “info”
autoStart 自动启动服务器 true
autoRestart 崩溃时重启 true
cwd CLI 进程的工作目录 继承

会话配置

选项 描述
model 要使用的 LLM(”gpt-4.1″、”claude-sonnet-4.5″ 等)
sessionId 自定义会话标识符
tools 自定义工具定义
mcpServers MCP 服务器连接
customAgents 自定义代理角色
systemMessage 覆盖默认系统提示
streaming 启用增量响应片段
availableTools 允许的工具白名单
excludedTools 禁用的工具黑名单

会话持久化

在重启之间保存和恢复对话:

使用自定义 ID 创建

const session = await client.createSession({
    sessionId: "user-123-conversation",
    model: "gpt-4.1"
});

恢复会话

const session = await client.resumeSession("user-123-conversation");
await session.send({ prompt: "What did we discuss earlier?" });

列出和删除会话

const sessions = await client.listSessions();
await client.deleteSession("old-session-id");

错误处理

try {
    const client = new CopilotClient();
    const session = await client.createSession({ model: "gpt-4.1" });
    const response = await session.sendAndWait(
        { prompt: "Hello!" },
        30000 // 超时时间(毫秒)
    );
} catch (error) {
    if (error.code === "ENOENT") {
        console.error("未安装 Copilot CLI"); // 翻译
    } else if (error.code === "ECONNREFUSED") {
        console.error("无法连接到 Copilot 服务器"); // 翻译
    } else {
        console.error("错误:", error.message); // 翻译
    }
} finally {
    await client.stop();
}

优雅关闭

process.on("SIGINT", async () => {
    console.log("正在关闭..."); // 翻译
    await client.stop();
    process.exit(0);
});

常见模式

多轮对话

const session = await client.createSession({ model: "gpt-4.1" });

await session.sendAndWait({ prompt: "My name is Alice" });
await session.sendAndWait({ prompt: "What's my name?" });
// 响应: "Your name is Alice"

文件附件

await session.send({
    prompt: "分析这个文件", // 翻译
    attachments: [{
        type: "file",
        path: "./data.csv",
        displayName: "销售数据" // 翻译
    }]
});

中止长时间操作

const timeoutId = setTimeout(() => {
    session.abort();
}, 60000);

session.on((event) => {
    if (event.type === "session.idle") {
        clearTimeout(timeoutId);
    }
});

可用模型

在运行时查询可用模型:

const models = await client.getModels();
// 返回: ["gpt-4.1", "gpt-4o", "claude-sonnet-4.5", ...]

最佳实践

  1. 始终清理资源:使用 try-finallydefer 确保调用 client.stop()
  2. 设置超时:对长时间操作使用带超时的 sendAndWait
  3. 处理事件:订阅错误事件以实现稳健的错误处理
  4. 使用流式:在长响应上启用流式以获得更好的用户体验
  5. 持久化会话:对多轮对话使用自定义会话 ID
  6. 定义清晰的工具:编写描述性的工具名称和描述

架构

您的应用程序
       |
  SDK 客户端
       | JSON-RPC
  Copilot CLI (服务器模式)
       |
  GitHub (模型、认证)

SDK 自动管理 CLI 进程的生命周期。所有通信通过基于 stdio 或 TCP 的 JSON-RPC 进行。

资源

状态

此 SDK 处于技术预览版,可能会有重大更改。尚不建议用于生产环境。

📄 原始文档

完整文档(英文):

https://skills.sh/github/awesome-copilot/copilot-sdk

💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。