跳到正文
FunCoding

搜索

搜索文档、Skill 和 MCP

SDK 快速开始

安装 SDK,以 TypeScript 发起会话、订阅流式事件,并接入自定义工具。

官方快速开始列出的语言运行时为 Node.js 20+、Python 3.11+、Go 1.24+、Rust 1.94+、Java 17+ 或 .NET 8.0+。选择语言后,再按对应 SDK README 核对当前版本前提;这不是独立 CLI npm 包的 Node.js 安装要求。

安装与认证

以 TypeScript 为例,在独立示例目录执行:

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

Node.js 与 .NET 随包提供 runtime;Python 推荐预下载,Go、Java 与 Rust 的 CLI 分发方式需单独核对,见自动管理 CLI。使用 GitHub 托管模型时准备有效的 Copilot 认证;自有模型可按BYOK配置。

发送第一条消息

保存为 index.ts:

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

const client = new CopilotClient();
const session = await client.createSession({ model: "auto" });
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

这会实际创建会话并请求模型。sendAndWait 等待完整回答;完成后停止 client,释放其管理的运行资源。

显示流式响应

创建会话时加入 streaming: true,在发送前订阅增量事件:

const session = await client.createSession({
    model: "auto",
    streaming: true,
});
session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => {
    console.log();
});
await session.sendAndWait({ prompt: "Tell me a short joke" });

这是替换前面会话创建与发送部分的片段。Node.js/TypeScript 可用 on(eventType, handler) 订阅指定事件,也可用 on(handler) 订阅全部事件;返回函数用于取消订阅。其他语言的订阅接口不必与此重载相同。

添加自定义工具

官方教程使用 defineTool 声明工具名称、description、参数 schema 和 handler,然后把工具放进会话的 tools 数组。模型决定何时调用,SDK 执行 handler,把结果返回给模型继续回答。

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

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;
        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 };
    },
});

该片段沿用官方教学工具,返回随机模拟天气,不会查询真实天气服务。在 createSession 中配置 tools: [getWeather],再发送相关问题即可练习调用流程;实际产品需接入自己的数据源并实现业务授权。

扩展为交互助手

保留同一 session,在每次用户输入后调用 sendAndWait,等本次完成后再接收下一条输入。退出时停止 client 并关闭输入接口。官方 TypeScript 完整例子使用 readline;生产后端的并发、认证与恢复不能直接套用单用户循环,见后端服务。