Language Model Chat Provider API
Language Model Chat Provider APIを使用すると、Visual Studio Codeでのチャット用に独自の言語モデルを提供できます。
このAPIを通じて提供されるモデルは、現在 GitHub Copilot 個人プラン のユーザーのみが利用可能です。
概要
LanguageModelChatProvider インターフェースは「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 型を通じて、進行状況(progress)コールバックから異なる種類のレスポンスパーツを報告できます。これには以下のいずれかが含まれます。
LanguageModelTextPart- テキストコンテンツLanguageModelToolCallPart- ツール/関数呼び出しLanguageModelToolResultPart- ツール結果コンテンツ
はじめに
基本的なサンプルプロジェクトから始めることができます。