跳至主要内容

为后端服务设置 Copilot SDK

在服务器端应用程序中运行 GitHub Copilot SDK,例如 API、Web 后端、微服务和后台工作程序。

谁可以使用此功能?

GitHub Copilot SDK 在所有 Copilot 计划中均可使用。

注意

Copilot SDK 当前处于技术预览阶段。功能和可用性可能会发生变化。

CLI 以无头服务器方式运行,后端代码通过网络与其连接。

适用场景:Web 应用后端、API 服务、内部工具、CI/CD 集成以及任何服务器端工作负载。

它是如何工作的

与其让 SDK 生成 CLI 子进程,你可以独立地以 无头服务器模式 运行 CLI。后端通过 TCP 使用 cliUrl 选项连接它。有关无头服务器架构的详细图示以及它与默认自动管理的 CLI 的对比,请参阅 github/copilot-sdk 仓库

关键特性

  • CLI 作为持久服务器进程运行,而不是每个请求都生成。
  • SDK 通过 TCP 连接——CLI 与应用可以运行在不同的容器中。
  • 多个 SDK 客户端可以共享同一个 CLI 服务器。
  • 支持任何身份验证方式(GitHub 令牌、环境变量、BYOK)。

步骤 1:以无头模式启动 CLI

将 CLI 作为后台服务器运行。

# Start with a specific port
copilot --headless --port 4321

# Or let it pick a random port (prints the URL)
copilot --headless
# Output: Listening on https://:52431

在生产环境中,将其作为系统服务或容器运行

# Docker
docker run -d --name copilot-cli \
    -p 4321:4321 \
    -e COPILOT_GITHUB_TOKEN="$TOKEN" \
    ghcr.io/github/copilot-cli:latest \
    --headless --port 4321
# systemd
[Service]
ExecStart=/usr/local/bin/copilot --headless --port 4321
Environment=COPILOT_GITHUB_TOKEN=YOUR-GITHUB-TOKEN
Restart=always

步骤 2:连接 SDK

Node.js / TypeScript

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

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

const session = await client.createSession({
    sessionId: `user-${userId}-${Date.now()}`,
    model: "gpt-4.1",
});

const response = await session.sendAndWait({ prompt: req.body.message });
res.json({ content: response?.data.content });

Python

from copilot import CopilotClient

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

session = await client.create_session({
    "session_id": f"user-{user_id}-{int(time.time())}",
    "model": "gpt-4.1",
})

response = await session.send_and_wait({"prompt": message})

Go

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

session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
    SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()),
    Model:     "gpt-4.1",
})

response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message})

.NET

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

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    SessionId = $"user-{userId}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}",
    Model = "gpt-4.1",
});

var response = await session.SendAndWaitAsync(
    new MessageOptions { Prompt = message });

后端服务的身份验证

环境变量令牌

最简单的方法——在 CLI 服务器上设置令牌

# All requests use this token
export COPILOT_GITHUB_TOKEN="YOUR-SERVICE-ACCOUNT-TOKEN"
copilot --headless --port 4321

YOUR-SERVICE-ACCOUNT-TOKEN 替换为你的 GitHub 个人访问令牌或服务账户的 OAuth 令牌。

每用户令牌(OAuth)

创建会话时传递单个用户的令牌

// Your API receives user tokens from your auth layer
app.post("/chat", authMiddleware, async (req, res) => {
    const client = new CopilotClient({
        cliUrl: "localhost:4321",
        githubToken: req.user.githubToken,
        useLoggedInUser: false,
    });

    const session = await client.createSession({
        sessionId: `user-${req.user.id}-chat`,
        model: "gpt-4.1",
    });

    const response = await session.sendAndWait({
        prompt: req.body.message,
    });

    res.json({ content: response?.data.content });
});

BYOK(无 GitHub 身份验证)

为模型提供商使用你自己的 API 密钥

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

const session = await client.createSession({
    model: "gpt-4.1",
    provider: {
        type: "openai",
        baseUrl: "https://api.openai.com/v1",
        apiKey: process.env.OPENAI_API_KEY,
    },
});

常见后端模式

使用 Express 的 Web API

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

const app = express();
app.use(express.json());

// Single shared CLI connection
const client = new CopilotClient({
    cliUrl: process.env.CLI_URL || "localhost:4321",
});

app.post("/api/chat", async (req, res) => {
    const { sessionId, message } = req.body;

    // Create or resume session
    let session;
    try {
        session = await client.resumeSession(sessionId);
    } catch {
        session = await client.createSession({
            sessionId,
            model: "gpt-4.1",
        });
    }

    const response = await session.sendAndWait({ prompt: message });
    res.json({
        sessionId,
        content: response?.data.content,
    });
});

app.listen(3000);

后台工作程序

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

const client = new CopilotClient({
    cliUrl: process.env.CLI_URL || "localhost:4321",
});

// Process jobs from a queue
async function processJob(job: Job) {
    const session = await client.createSession({
        sessionId: `job-${job.id}`,
        model: "gpt-4.1",
    });

    const response = await session.sendAndWait({
        prompt: job.prompt,
    });

    await saveResult(job.id, response?.data.content);
    await session.disconnect(); // Clean up after job completes
}

Docker Compose 部署

version: "3.8"

services:
  copilot-cli:
    image: ghcr.io/github/copilot-cli:latest
    command: ["--headless", "--port", "4321"]
    environment:
      - COPILOT_GITHUB_TOKEN=${COPILOT_GITHUB_TOKEN}
    ports:
      - "4321:4321"
    restart: always
    volumes:
      - session-data:/root/.copilot/session-state

  api:
    build: .
    environment:
      - CLI_URL=copilot-cli:4321
    depends_on:
      - copilot-cli
    ports:
      - "3000:3000"

volumes:
  session-data:

健康检查

监控 CLI 服务器的健康状况

// Periodic health check
async function checkCLIHealth(): Promise<boolean> {
    try {
        const status = await client.getStatus();
        return status !== undefined;
    } catch {
        return false;
    }
}

会话清理

后端服务应主动清理会话,以防资源泄漏

// Clean up expired sessions periodically
async function cleanupSessions(maxAgeMs: number) {
    const sessions = await client.listSessions();
    const now = Date.now();

    for (const session of sessions) {
        const age = now - new Date(session.createdAt).getTime();
        if (age > maxAgeMs) {
            await client.deleteSession(session.sessionId);
        }
    }
}

// Run every hour
setInterval(() => cleanupSessions(24 * 60 * 60 * 1000), 60 * 60 * 1000);

限制

限制详细信息
单个 CLI 服务器 = 单点故障在生产部署时请考虑高可用性模式。
SDK 与 CLI 之间没有内置身份验证确保网络路径安全(同一主机、VPC 等)。
会话状态存储在本地磁盘上为容器重启挂载持久存储。
30 分钟空闲超时无活动的会话将被自动清理。

后续步骤

  • 有关安装和首条消息的内容,请参阅 Copilot SDK 入门指南
  • 有关跨重启恢复会话的信息,请参阅 github/copilot-sdk 仓库中的 会话持久化
  • 有关添加用户身份验证的信息,请参阅 github/copilot-sdk 仓库中的 GitHub OAuth
© . This site is unofficial and not affiliated with GitHub, Inc.