Skip to main content

构建你的第一个由 Copilot 提供支持的应用

在本教程中,你将使用 Copilot SDK 生成命令行助手。 你将先从基础内容开始,加入流式响应,然后再添加自定义工具——让 Copilot 能够调用你的代码。

你将生成的内容:

You: What's the weather like in Seattle?
Copilot: Let me check the weather for Seattle...
         Currently 62°F and cloudy with a chance of rain.
         Typical Seattle weather!

You: How about Tokyo?
Copilot: In Tokyo it's 75°F and sunny. Great day to be outside!

先决条件

在开始之前,请确保具备:

  • GitHub Copilot CLI 安装和身份验证 (Installation 指南
  • 首选语言运行时:
    • Node.js 20+ 或 Python 3.11+ 或 Go 1.24+ 或 > Rust 1.94+ 或 Java 17+ 或 .NET 8.0+

验证 CLI 是否正常工作:

copilot --version

步骤 1:安装 SDK

代码语言 navigation

TypeScript

首先,创建新目录并初始化项目:

mkdir copilot-demo && cd copilot-demo
npm init -y --init-type module

然后安装 SDK 和 TypeScript 运行程序:

npm install @github/copilot-sdk tsx

步骤 2:发送第一条消息

创建新文件并添加以下代码。 这是使用 SDK 的最简单方法-大约 5 行代码。

代码语言 navigation

TypeScript

创建 index.ts

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

应会看到:

4

祝贺! 你刚刚创建了你的第一个由 Copilot 提供支持的应用。

步骤 3:添加流式响应

现在,在看到任何内容之前,请等待完整的响应。 让我们在生成响应的同时进行流式传输,让它具有交互性。

代码语言 navigation

TypeScript

更新index.ts

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

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

// Listen for response chunks
session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => {
    console.log(); // New line when done
});

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

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

再次运行代码。 你将看到响应按单词显示。

事件订阅方法

SDK 提供订阅会话事件的方法:

方法Description
on(handler)订阅所有事件;返回取消订阅函数
on(eventType, handler)订阅特定的事件类型(仅限 Node.js/TypeScript);返回取消订阅函数
subscribe()订阅所有事件(Rust);按 event_type 筛选

代码语言 navigation

TypeScript
// Subscribe to all events
const unsubscribeAll = session.on((event) => {
    console.log("Event:", event.type);
});

// Subscribe to specific event type
const unsubscribeIdle = session.on("session.idle", (event) => {
    console.log("Session is idle");
});

// Later, to unsubscribe:
unsubscribeAll();
unsubscribeIdle();

步骤 4:添加自定义工具

现在是强大的部分。 让 Copilot 通过定义自定义工具来调用你的代码。 我们将创建一个简单的天气查找工具。

代码语言 navigation

TypeScript

更新index.ts

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

// Define a tool that Copilot can call
const getWeather = defineTool("get_weather", {
    description: "Get the current weather for a city",
    parameters: {
        type: "object",
        properties: {
            city: { type: "string", description: "The city name" },
        },
        required: ["city"],
    },
    handler: async (args: { city: string }) => {
        const { city } = args;
        // In a real app, you'd call a weather API here
        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("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});

session.on("session.idle", () => {
    console.log(); // New line when done
});

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

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

运行它,你会看到 Copilot 调用你的工具来获取天气数据,然后根据结果作出回应!

步骤 5:生成交互式助手

让我们把这些内容整合成一个实用的交互式助手:

代码语言 navigation

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

const getWeather = defineTool("get_weather", {
    description: "Get the current weather for a city",
    parameters: {
        type: "object",
        properties: {
            city: { type: "string", description: "The city name" },
        },
        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("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});

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

console.log("🌤️  Weather Assistant (type 'exit' to quit)");
console.log("   Try: '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();

运行环境:

npx tsx weather-assistant.ts

示例会话:

🌤️  Weather Assistant (type 'exit' to quit)
   Try: 'What's the weather in Paris?' or 'Compare weather in NYC and LA'

You: What's the weather in Seattle?
Assistant: Let me check the weather for Seattle...
It's currently 62°F and cloudy in Seattle.

You: How about Tokyo and London?
Assistant: I'll check both cities for you:
- Tokyo: 75°F and sunny
- London: 58°F and rainy

You: exit

你已使用Copilot可以调用的自定义工具构建了助手!

工具的工作原理

定义工具时,你将告诉Copilot:

  1. 该工具的作用 (说明)
  2. 它需要哪些参数 (架构)
  3. 要运行的代码 (处理程序)

Copilot根据用户的问题决定何时调用工具。 当这种情况发生时:

  1. Copilot使用参数发送工具调用请求
  2. SDK 运行你的处理函数
  3. 结果被发回给 Copilot
  4. Copilot将结果合并到其响应中

接下来会发生什么?

现在,你已获得基础知识,下面提供了更强大的功能来探索:

连接到 MCP 服务器

MCP(模型上下文协议)服务器提供预构建的工具。 连接到 GitHub 的 MCP 服务器,让 Copilot 能够访问存储库、问题和拉取请求:

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

📖 ** Using MCP servers with the GitHub Copilot SDK** - 了解本地服务器与远程服务器、所有配置选项和故障排除。

创建自定义代理

定义特定任务的专用 AI 角色:

const session = await client.createSession({
    customAgents: [{
        name: "pr-reviewer",
        displayName: "PR Reviewer",
        description: "Reviews pull requests for best practices",
        prompt: "You are an expert code reviewer. Focus on security, performance, and maintainability.",
    }],
});

提示

还可以在会话配置中设置 agent: "pr-reviewer" ,以便从一开始就预先选择此代理。 有关详细信息,请参阅 自定义代理和子代理编排

自定义系统消息

通过追加说明来控制 AI 的行为和个性:

const session = await client.createSession({
    systemMessage: {
        content: "You are a helpful assistant for our engineering team. Always be concise.",
    },
});

若要进行更精细的控制,请使用 mode: "customize" 替代系统提示的各个部分,同时保留其余部分:

const session = await client.createSession({
    systemMessage: {
        mode: "customize",
        sections: {
            tone: { action: "replace", content: "Respond in a warm, professional tone. Be thorough in explanations." },
            code_change_rules: { action: "remove" },
            guidelines: { action: "append", content: "\n* Always cite data sources" },
        },
        content: "Focus on financial analysis and reporting.",
    },
});

可用节 ID:identitytonetool_efficiencyenvironment_contextcode_change_rulesguidelinessafetytool_instructionscustom_instructionsruntime_instructionslast_instructions

每个替代都支持四个操作: replaceremoveappendprepend。 未知的节 ID 会被妥善处理 — 内容会附加到额外说明中并发出警告;对未知节的 remove 会被静默忽略。

有关 TypeScript 中的示例,请参阅特定于语言的 SDK README, PythonGoRustJavaC#

连接到外部 CLI 服务器

默认情况下,SDK 会自动管理Copilot CLI 进程生命周期,根据需要启动和停止 CLI。 但是,还可以单独在服务器模式下运行 CLI,并让 SDK 连接到它。 这可用于:

  • 调试:使 CLI 在 SDK 重启之间保持运行以检查日志
  • 资源共享:多个 SDK 客户端可以连接到同一 CLI 服务器
  • 开发:使用自定义设置或在不同的环境中运行 CLI

在服务器模式下运行 CLI

使用 --headless 标志在服务器模式下启动 CLI,并根据需要指定端口:

copilot --headless --port 4321

如果未指定端口,CLI 将选择随机可用的端口。

默认情况下,无头服务器仅接受来自环回 (127.0.0.1) 的连接,因此 SDK 必须在同一台机器上运行。 若要接受来自其他主机的连接(例如,在容器中或在单独的服务器上运行 CLI 时),请使用 --host以下命令绑定到非环回地址:

# Listen on all interfaces
copilot --headless --host 0.0.0.0 --port 4321

警告

将无头服务器暴露在非回环地址上,会使任何能够路由到该地址的用户都可以访问该服务器。 将其与适合你的环境的网络控制(防火墙、专用网络、反向代理)和身份验证配对。

将 SDK 连接到外部服务器

在服务器模式下运行 CLI 后,使用“cli url”选项将 SDK 客户端配置为连接到它:

代码语言 navigation

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

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

// Use the client normally
const session = await client.createSession({ onPermissionRequest: approveAll });
// ...

注意: 当提供 cli_url / cliUrl / Go 的 UriConnection,或 Rust 使用 Transport::External 时,SDK 不会启动或管理 CLI 进程——它只会连接到指定 URL 处的现有服务器。

遥测和可观测性

Copilot SDK 支持使用 OpenTelemetry 进行分布式跟踪。 向客户端提供配置 telemetry ,以便从 CLI 进程启用跟踪导出,并在 SDK 和 CLI 之间自动传播 W3C 跟踪上下文

启用遥测

创建客户端时,传入 telemetry(或 Telemetry)配置。 这是选择加入 — 无需单独的“enabled”标志。

代码语言 navigation

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

const client = new CopilotClient({
  telemetry: {
    otlpEndpoint: "http://localhost:4318",
  },
});

可选的同级依赖项:@opentelemetry/api

TelemetryConfig 选项

选项Node.jsPythonGoRustJava.NETDescription
OTLP 终结点otlpEndpointotlp_endpointOTLPEndpointotlp_endpointotlpEndpointOtlpEndpointOTLP HTTP 终结点 URL
文件路径filePathfile_pathFilePathfile_pathfilePathFilePathJSON 行跟踪输出的文件路径
导出程序类型exporterTypeexporter_typeExporterTypeexporter_typeexporterTypeExporterType
"otlp-http""file"
源名称sourceNamesource_nameSourceNamesource_namesourceNameSourceName仪器范围名称
捕获内容captureContentcapture_contentCaptureContentcapture_contentcaptureContentCaptureContent是否捕获消息内容

文件导出

若要将追踪数据写入本地文件而不是 OTLP 端点,请执行以下操作:

const client = new CopilotClient({
  telemetry: {
    filePath: "./traces.jsonl",
    exporterType: "file",
  },
});

跟踪上下文传播

自动传播跟踪上下文 - 无需手动检测:

  •           **SDK → CLI**:来自当前跨度/活动的 `traceparent` 和 `tracestate` 标头会包含在 `session.create`、`session.resume` 和 `session.send` RPC 调用中。
    
  • CLI → SDK:当 CLI 调用工具处理程序时,将传播 CLI 范围中的跟踪上下文,以便工具代码在正确的父范围下运行。

📖 ** Copilot SDK 的 OpenTelemetry 检测** — TelemetryConfig 选项、跟踪上下文传播和每种语言依赖项。

了解详细信息

你做到了! 你已了解 GitHub Copilot SDK 的核心概念:

  • ✅ 创建客户端和会话
  • ✅ 发送消息和接收响应
  • ✅ 用于实时输出的流式传输
  • ✅定义Copilot可以调用的自定义工具

现在就去创造精彩的作品吧! 🚀