Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

Streaming from a model

Since 0.1.0-alpha.22
Stream a model's reply into the last entry, with Stop and Retry.

Chat takes plain values, so it works with any model client, and with no dependency of its own. With Microsoft.Extensions.AI, keep the conversation as ChatMessage items and map each to a ChatEntry: Mine for the user's, Markdown for the assistant's. Send the history to IChatClient.GetStreamingResponseAsync and append each update's text to the last message.

Set Status to Waiting until the first piece, then Streaming, and Pending on the entry being written. Render at most every 50 milliseconds or so (each render on an interactive page crosses the circuit), and once more at the end. Stop cancels the request through a CancellationToken; what arrived stays. On an error, set Failed on the entry and Status to Failed; OnRetry asks again.

On a static page, put [StreamRendering] on the page and stream only when OnSend's CanStream is true; with JavaScript off, send the reply whole.

A cooking assistant

This site's IChatClient is a stand-in with canned answers; register your own (OpenAI, Azure OpenAI, Ollama) and the page stays the same.

Always Interactive

Preview

Code

Streaming.razor
@* A cooking assistant streaming from a model through Microsoft.Extensions.AI's IChatClient.
   This site registers a stand-in client with canned answers; an app registers its own
   (OpenAI, Azure OpenAI, Ollama), and this page doesn't change. *@
@using System.Text
@using Microsoft.Extensions.AI
@inject IChatClient Client

<Chat Label="Cooking assistant" FormName="cooking" OnSend="SendAsync" OnStop="Stop" Status="_status"
      Suggestions="@(_history.Count == 1 ? Ideas : null)" Placeholder="Ask about rice, eggs or substitutions">
    @foreach (var message in _history.Where(m => m.Role != ChatRole.System))
    {
        @if (message.Role == ChatRole.User)
        {
            <ChatEntry Mine Text="@message.Text" />
        }
        else
        {
            <ChatEntry Author="Assistant" Initials="IB" Markdown="@message.Text" Pending="message == _streaming" Failed="message == _failed" OnRetry="RetryAsync" />
        }
    }
</Chat>

Connection lost

Rejoining the server…