Language

Windows ML Tasks を使用したチャット補完

Important

チャット完了タスクは試験段階であり、運用環境での使用は サポートされていません 。

「チャット補完タスク」は、テキスト生成セッションを備えた構造化された会話フォーマッタを提供するトークナイザーを構成します。 ロールタグ付きメッセージの一覧を送信します。 タスクは、モデル独自のチャット テンプレートを適用し、生成を開始し、コンテンツ、推論、およびツール呼び出しイベントとして応答をストリーム配信します。

アプリが会話を管理します。 各応答をメッセージ リストに追加し、次のターンでリスト全体を送信します。 テキスト生成セッションは、 タスクがモデルを実行する方法を選択する任意の方法から取得でき、チャット セッション、イベント、結果はそれぞれ同じように動作します。

会話を完了する

次の例では、テキスト生成タスク、構成、トークナイザーが既にあることを前提としています。 チャット セッションはテキスト生成セッションをラップし、セッションが保持するトークンは 1 ターンから次のターンに引き継がれます。

テキスト生成タスク、構成、トークナイザーから 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;
}

各質問につきそれを1回呼び出し、各ターンの後に応答を履歴に追加します。

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を呼び出します。

次のステップ