言語モデルチャットプロバイダー API
言語モデルチャットプロバイダー API を使用すると、独自の言語モデルを Visual Studio Code のチャットに提供できます。
この API を通じて提供されるモデルは、現在、個別の GitHub Copilot プランのユーザーのみが利用できます。
概要
LanguageModelChatProvider インターフェースは、1 つのプロバイダーが複数のモデルを提供できる「1 プロバイダー対多モデル」の関係に従っています。各プロバイダーは次の責任を負います。
- 利用可能な言語モデルの検出と準備
- そのモデルに対するチャットリクエストの処理
- トークンカウント機能の提供
言語モデル情報
各言語モデルは、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 インターフェースを実装する必要があります。これには 3 つの主要なメソッドがあります。
provideLanguageModelChatInformation: 利用可能なモデルのリストを返します。provideLanguageModelChatResponse: チャットリクエストを処理し、応答をストリーミングします。provideTokenCount: トークンカウント機能を実装します。
言語モデル情報の準備
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."));
}
}
トークン数の提供
provideTokenCount メソッドは、指定されたテキスト入力のトークン数を推定する責任を負います。
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- ツール結果コンテンツ
はじめに
基本的なサンプルプロジェクトから始めることができます。