语言模型聊天提供程序 API
语言模型聊天提供程序 API 使您可以为 Visual Studio Code 中的聊天贡献自己的语言模型。
通过此 API 提供的模型目前仅对拥有 个人 GitHub Copilot 计划的用户可用。
概述
LanguageModelChatProvider 接口遵循一对多模型的关系,使提供程序能够提供多个模型。每个提供程序负责
- 发现并准备可用的语言模型
- 处理其模型的聊天请求
- 提供 token 计数功能
语言模型信息
每个语言模型都必须通过 LanguageModelChatInformation 接口提供元数据。provideLanguageModelChatInformation 方法返回这些对象的数组,以告知 VS Code 有关可用模型的信息。
interface LanguageModelChatInformation {
readonly id: string; // Unique identifier for the model - unique within the provider
readonly name: string; // Human-readable name of the language model - shown in the model picker
readonly family: string; // Model family name
readonly version: string; // Version string
readonly maxInputTokens: number; // Maximum number of tokens the model can accept as input
readonly maxOutputTokens: number; // Maximum number of tokens the model is capable of producing
readonly tooltip?: string; // Optional tooltip text when hovering the model in the UI
readonly detail?: string; // Human-readable text that is rendered alongside the model
readonly capabilities: {
readonly imageInput?: boolean; // Supports image inputs
readonly toolCalling?: boolean | number; // Supports tool calling
};
}
注册提供程序
-
第一步是在您的
package.json中的contributes.languageModelChatProviders部分注册提供程序。提供一个唯一的vendorID 和一个displayName。{ "contributes": { "languageModelChatProviders": [ { "vendor": "my-provider", "displayName": "My Provider" } ] } } -
接下来,在您的扩展激活函数中,使用
lm.registerLanguageModelChatProvider方法注册您的语言模型提供程序。提供您在
package.json中使用的提供程序 ID 以及您的提供程序类的实例import * as vscode from 'vscode'; import { SampleChatModelProvider } from './provider'; export function activate(_: vscode.ExtensionContext) { vscode.lm.registerLanguageModelChatProvider('my-provider', new SampleChatModelProvider()); } -
可选地,在您的
package.json中提供一个contributes.languageModelChatProviders.managementCommand,以允许用户管理语言模型提供程序。managementCommand属性的值必须是您package.json的contributes.commands部分中定义的命令。在您的扩展中,注册该命令 (vscode.commands.registerCommand) 并实现管理提供程序的逻辑,例如配置 API 密钥或其他设置。{ "contributes": { "languageModelChatProviders": [ { "vendor": "my-provider", "displayName": "My Provider", "managementCommand": "my-provider.manage" } ], "commands": [ { "command": "my-provider.manage", "title": "Manage My Provider" } ] } }
实现提供程序
语言提供程序必须实现 LanguageModelChatProvider 接口,该接口有三个主要方法
provideLanguageModelChatInformation:返回可用模型的列表provideLanguageModelChatResponse:处理聊天请求并流式传输响应provideTokenCount:实现 token 计数功能
准备语言模型信息
provideLanguageModelChatInformation 方法由 VS Code 调用以发现可用模型,并返回 LanguageModelChatInformation 对象列表。
使用 options.silent 参数来控制是否提示用户输入凭据或进行额外配置
async provideLanguageModelChatInformation(
options: { silent: boolean },
token: CancellationToken
): Promise<LanguageModelChatInformation[]> {
if (options.silent) {
return []; // Don't prompt user in silent mode
} else {
await this.promptForApiKey(); // Prompt user for credentials
}
// Fetch available models from your service
const models = await this.fetchAvailableModels();
// Map your models to LanguageModelChatInformation format
return models.map(model => ({
id: model.id,
name: model.displayName,
family: model.family,
version: '1.0.0',
maxInputTokens: model.contextWindow - model.maxOutput,
maxOutputTokens: model.maxOutput,
capabilities: {
imageInput: model.supportsImages,
toolCalling: model.supportsTools
}
}));
}
处理聊天请求
provideLanguageModelChatResponse 方法处理实际的聊天请求。提供程序接收 LanguageModelChatRequestMessage 格式的消息数组,您可以选择将它们转换为语言模型 API 所需的格式(请参阅 消息格式和转换)。
使用 progress 参数来流式传输响应块。响应可以包括文本部分、工具调用和工具结果(请参阅 响应部分)。
async provideLanguageModelChatResponse(
model: LanguageModelChatInformation,
messages: readonly LanguageModelChatRequestMessage[],
options: ProvideLanguageModelChatResponseOptions,
progress: Progress<LanguageModelResponsePart>,
token: CancellationToken
): Promise<void> {
// TODO: Implement message conversion, processing, and response streaming
// Optionally, differentiate behavior based on model ID
if (model.id === "my-model-a") {
progress.report(new LanguageModelTextPart("This is my A response."));
} else {
progress.report(new LanguageModelTextPart("Unknown model."));
}
}
提供 token 计数
provideTokenCount 方法负责估算给定文本输入的 token 数量
async provideTokenCount(
model: LanguageModelChatInformation,
text: string | LanguageModelChatRequestMessage,
token: CancellationToken
): Promise<number> {
// TODO: Implement token counting for your models
// Example estimation for strings
return Math.ceil(text.toString().length / 4);
}
消息格式和转换
您的提供程序会以 LanguageModelChatRequestMessage 格式接收消息,您通常需要将其转换为您的服务的 API 格式。消息内容可以是文本部分、工具调用和工具结果的混合。
interface LanguageModelChatRequestMessage {
readonly role: LanguageModelChatMessageRole;
readonly content: ReadonlyArray<LanguageModelInputPart | unknown>;
readonly name: string | undefined;
}
可选地,为您的语言模型 API 适当地转换这些消息
private convertMessages(messages: readonly LanguageModelChatRequestMessage[]) {
return messages.map(msg => ({
role: msg.role === vscode.LanguageModelChatMessageRole.User ? 'user' : 'assistant',
content: msg.content
.filter(part => part instanceof vscode.LanguageModelTextPart)
.map(part => (part as vscode.LanguageModelTextPart).value)
.join('')
}));
}
响应部分
您的提供程序可以通过 LanguageModelResponsePart 类型通过进度回调报告不同类型的响应部分,该类型可以是以下之一:
LanguageModelTextPart- 文本内容LanguageModelToolCallPart- 工具/函数调用LanguageModelToolResultPart- 工具结果内容
入门
您可以使用 基本示例项目入门。