現已釋出!閱讀關於 11 月新增功能和修復的內容。

語言模型聊天提供商 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
  };
}

註冊提供商

  1. 第一步是在您的 package.jsoncontributes.languageModelChatProviders 部分註冊提供商。提供一個唯一的 vendor ID 和一個 displayName

    {
      "contributes": {
        "languageModelChatProviders": [
          {
            "vendor": "my-provider",
            "displayName": "My Provider"
          }
        ]
      }
    }
    
  2. 接下來,在您的擴充套件啟用函式中,使用 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());
    }
    
  3. 可選地,在您的 package.json 中提供 contributes.languageModelChatProviders.managementCommand,以允許使用者管理語言模型提供商。

    managementCommand 屬性的值必須是您的 package.jsoncontributes.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 - 工具結果內容

入門

您可以從 基本示例專案 開始。

© . This site is unofficial and not affiliated with Microsoft.