語言

使用 Windows ML 任務的聊天完成功能

Important

聊天完成任務仍屬實驗性質, 不支援 在生產環境中使用。

聊天完成任務會組合一個分詞器,公開一個結構化的對話格式化工具,搭配 文字生成 工作階段。 你傳送一份帶有角色標籤的訊息清單。 任務會套用模型自有的聊天範本,開始生成,並將回覆以內容、推理及工具呼叫事件的形式串流。

你的應用程式掌控了對話。 它會將每則回覆附加到訊息清單,並在下一回合發送整個清單。 文字生成會話可透過 選擇 Task 如何執行你的模型的任何方式產生,而聊天會話、事件和結果對每個工作階段的運作方式都一樣。

完成對話

以下範例假設您已擁有文字產生任務、設定及分詞器。 聊天工作階段會封裝文字生成工作階段,而該工作階段持有的權杖會從一個回合延續到下一個回合。

使用文字生成任務、設定與分詞器建立一個 ChatGenerator。 它會建立文字生成工作階段和基於其上的聊天工作階段,並將兩者都維持在各自專用的同一個執行緒上,因為工作階段屬於建立它的執行緒。 它會以 IAsyncEnumerable<T> 串流回覆:

// Temporary: ChatGenerator and the other wrapper types in the WinMLSamples.Runtime
// namespaces aren't in the Windows ML package yet. Copy the wrapper files from
// https://github.com/microsoft/WindowsML/tree/main/Samples/Runtime/shared/csharp
// into your project. A future update will include the C# APIs natively.
using WinMLSamples.Runtime;
using WinMLSamples.Runtime.Tasks;

// The chat session wraps the text generation session, and the tokens that
// session holds carry over from one turn to the next.
await using ChatGenerator chat = await ChatGenerator.CreateAsync(tasks, task, configuration, tokenizer);

每一回合都會傳送完整的歷史:

// Send the conversation, stream the reply, and return it so that
// the caller can add it to the history.
static async Task<string> CompleteTurnAsync(
    ChatGenerator chat,
    TextGenerationOptions options,
    List<ConversationMessage> history,
    CancellationToken cancellationToken)
{
    ConversationRequest request = new()
    {
        FormatterMode = ConversationFormatterMode.ModelDefault,
        Messages = [.. history],
        AddGenerationPrompt = true,
    };

    // Content events carry the reply as the model generates it.
    await foreach (ChatCompletionUpdate update in chat.GenerateAsync(request, options, cancellationToken))
    {
        if (update.Type == ConversationOutputEventType.ContentDelta)
        {
            Console.Write(update.Text);
        }
        else if (update.Type == ConversationOutputEventType.Error)
        {
            throw WinMLException.GetExceptionForHResult(update.ErrorCode);
        }
    }

    // The outcome has the reply, the token counts, and how many prompt tokens
    // the session reused from the previous turn.
    ChatCompletionOutcome outcome = chat.LastOutcome!;
    Console.WriteLine(
        $"\n  Tokens: prompt={outcome.PromptTokenCount} " +
        $"(reused={outcome.PromptCacheUse.CachedPromptTokenCount}) " +
        $"completion={outcome.CompletionTokenCount}");

    return outcome.Content;
}

每次提問時呼叫一次,然後每回合後將回覆加入歷史紀錄:

string[] questions =
[
    "Name three primary colors.",
    "Which of those is the color of the sky?",
];

using TextGenerationOptions options = tasks.TextGeneration.CreateTextGenerationOptions(48);
List<ConversationMessage> history = [];
foreach (string question in questions)
{
    history.Add(new ConversationMessage { Role = "user", Content = question });
    Console.Write($"User: {question}\nAssistant: ");
    string reply = await CompleteTurnAsync(chat, options, history, CancellationToken.None);
    history.Add(new ConversationMessage { Role = "assistant", Content = reply });
}

// Closing the sessions reports a failure that disposing them would not.
await chat.CloseAsync();

在執行環境中,取消 CancellationToken 會停止生成。

重複使用對話內容

當格式化提示以會話保留的權杖序列開始時,生成程序會以新後綴繼續,而非重新評估整個提示。 結果內容無論如何都是一樣的。 只有提示工作量不同。 結果會回報完整的提示數量、保留前綴數,以及評估的標記數,讓您可以看到重用情況:

User: Name three primary colors.
Assistant: Three primary colors are red, blue, and yellow.
  Tokens: prompt=34 (reused=0) completion=11
User: Which of those is the color of the sky?
Assistant: The color of the sky is blue.
  Tokens: prompt=65 (reused=45) completion=8

結果與取消

終端結果會回報最終內容、推理、工具呼叫次數、提示與完成令牌數、完成理由,以及底層的文字生成結果。 將 IWinMLCancellationSource 傳遞給 Generate,並可從任意執行緒呼叫 Cancel 以停止生成。

會話與串流屬於創建它們的執行緒。 來自其他執行緒的呼叫會回傳 RPC_E_WRONG_THREAD。

影像輸入

聊天會話可以將圖片傳遞給支援圖片的模型。 設定一個媒體編碼器,SetMediaEncoder,然後呼叫 GenerateWithMedia,並使用將每個影像內容部分對應到張量的繫結。

下一步