Nota:
SDK de Copilot actualmente está en versión preliminar pública. La funcionalidad y la disponibilidad están sujetas a cambios.
SDK de GitHub Copilot le permite crear aplicaciones impulsadas por GitHub Copilot en su lenguaje de programación preferido. En esta guía, instalará el SDK usando npm, enviará su primer mensaje y agregará respuestas streaming.
Para obtener más información y pasos para otros lenguajes, consulte Install the SDK en el repositorio de github/copilot-sdk.
Prerrequisitos
Antes de empezar, asegúrese de que tiene Node.js 18 o posterior instalado.
Autenticación
Siga las instrucciones de Instalación de la CLI de GitHub Copilot para instalar y autenticarse con CLI de GitHub Copilot. Esto permitirá que el SDK acceda a su GitHub cuenta y use Copilot.
-
Compruebe que CLI de Copilot está instalado y funcionando:
Bash copilot --version
copilot --version
Installation
-
Cree un nuevo directorio e inicialice el project:
Bash mkdir copilot-demo && cd copilot-demo npm init -y --init-type module
mkdir copilot-demo && cd copilot-demo npm init -y --init-type module -
Instale el SDK y el ejecutor de TypeScript:
Bash npm install @github/copilot-sdk tsx
npm install @github/copilot-sdk tsx
Enviar el primer mensaje
-
Cree un nuevo archivo
index.tsy agregue el código siguiente. Esto envía una sola solicitud a Copilot e imprime la respuesta.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);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); -
Ejecute el código:
Bash npx tsx index.ts
npx tsx index.ts
En este ejemplo:
CopilotClient()crea un nuevo cliente que administra la conexión a CLI de Copilot.createSession()inicia una nueva sesión de conversación con el modelo especificado.sendAndWait()envía un mensaje y espera la respuesta completa antes de devolverla.
Agrega respuestas de streaming
En lugar de esperar la respuesta completa, puede transmitirla a medida que se genera. Esto resulta útil para respuestas largas o aplicaciones interactivas en las que desea mostrar la salida en tiempo real.
-
Actualice
index.tscon el código siguiente para escuchar e imprimir fragmentos de respuesta a medida que llegan:TypeScript 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);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); -
Ejecute el código:
Bash npx tsx index.ts
npx tsx index.ts
Con el streaming habilitado, la respuesta aparece incrementalmente a medida que se genera. Puede suscribirse a eventos para procesar cada fragmento en tiempo real:
assistant.message_deltase activa para cada fragmento de la respuesta a medida que se genera.session.idlese desencadena cuando se completa la respuesta y la sesión está lista para el siguiente mensaje.
Métodos de suscripción de eventos
El SDK proporciona los métodos siguientes para suscribirse a eventos:
- on(handler): suscríbase a todos los eventos. Devuelve la función de cancelación de suscripción.
- on(eventType, handler): suscríbase a un tipo de evento específico. Devuelve la función de cancelación de suscripción.
Agregue el código siguiente para suscribirse a index.ts eventos y cancelar la suscripción cuando ya no los necesite:
// 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();
// 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();
Pasos siguientes
Adición de una herramienta personalizada
Permite que Copilot llame a tu código definiendo una herramienta personalizada. Esta es una herramienta de búsqueda meteorológica:
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);
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);
Para obtener ejemplos de Python, Go, .NET y Rust, consulte Getting started en el repositorio de github/copilot-sdk. Para Java, consulte el github/copilot-sdk-java repositorio.
Cuando defines una herramienta, le estás diciendo a Copilot:
- Qué hace la herramienta (descripción)
- Qué parámetros necesita (esquema)
- Qué código se va a ejecutar (controlador)
Copilot decide cuándo llamar a la herramienta en función de la pregunta del usuario. Cuando lo hace, ejecuta la SDK de Copilot función de controlador y devuelve el resultado a Copilot, que lo incorpora en la respuesta.
Creación de un asistente interactivo
Combine todo en un asistente de chat interactivo:
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();
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();
Ejecute con:
npx tsx weather-assistant.ts
npx tsx weather-assistant.ts
Para obtener ejemplos de Python, Go, .NET y Rust, consulte Getting started en el repositorio de github/copilot-sdk. Para Java, consulte el github/copilot-sdk-java repositorio.
Conexión a servidores MCP
Los servidores MCP (Protocolo de contexto de modelo) proporcionan herramientas pregeneradas. Conéctese al servidor MCP de GitHub para conceder a Copilot acceso a repositorios, incidencias y solicitudes de extracción:
const session = await client.createSession({
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
},
},
});
const session = await client.createSession({
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
},
},
});
Para obtener más información, vea Uso de servidores MCP con el SDK de Copilot.
Creación de agentes personalizados
Defina roles de IA especializados para tareas específicas:
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.",
}],
});
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.",
}],
});
Para obtener más información, vea Agentes personalizados y orquestación de subagentes.
Personalización del mensaje del sistema
Controle el comportamiento y la personalidad de la inteligencia artificial anexando instrucciones:
const session = await client.createSession({
systemMessage: {
content: "You are a helpful assistant for our engineering team. Always be concise.",
},
});
const session = await client.createSession({
systemMessage: {
content: "You are a helpful assistant for our engineering team. Always be concise.",
},
});
Lectura adicional
- Elección de una ruta de instalación para el SDK de Copilot
- Descripción del bucle del agente
- Conexión a un servidor externo de la CLI en el
github/copilot-sdkrepositorio - Telemetría y observabilidad en el
github/copilot-sdkrepositorio