언어 모델 채팅 공급자 API
언어 모델 채팅 공급자 API를 사용하면 Visual Studio Code에서 자체 언어 모델을 채팅에 기여할 수 있습니다.
이 API를 통해 제공되는 모델은 현재 개인 GitHub Copilot 플랜 사용자만 사용할 수 있습니다.
개요
LanguageModelChatProvider 인터페이스는 하나의 공급자가 여러 모델을 제공할 수 있도록 하는 '하나의 공급자-다수의 모델' 관계를 따릅니다. 각 공급자는 다음을 담당합니다.
- 사용 가능한 언어 모델 검색 및 준비
- 자체 모델에 대한 채팅 요청 처리
- 토큰 계산 기능 제공
언어 모델 정보
각 언어 모델은 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: 토큰 계산 기능을 구현합니다.
언어 모델 정보 준비
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- 도구 결과 내용
시작하기
여기서 기본 예제 프로젝트로 시작할 수 있습니다.