DEV Community

Cover image for Polhem.Chat: AI Chat Components for Avalonia and Blazor
Jeff Tsai
Jeff Tsai

Posted on Originally published at hackmd.io

Polhem.Chat: AI Chat Components for Avalonia and Blazor

Plug in any IChatClient, and desktop, mobile and web share the same conversation logic

This post is based on version 0.6.0. The packages are still 0.x, so a minor release may still change the API; any change will be noted in the CHANGELOG.

Polhem.Chat is a set of AI chat packages for .NET, with a ChatView for Avalonia and one for Blazor. On the model side it takes an IChatClient from Microsoft.Extensions.AI (the official .NET interface for model clients, implemented for OpenAI, Azure OpenAI, Ollama and others), so it is not tied to any model provider. The view shows:

  • Streamed replies rendered as Markdown
  • A live line that says what the model is doing: thinking, calling tools, the time spent and the tokens
  • A usage summary for each turn
  • Stop, copy, regenerate, and edit the last prompt
  • Approval cards for tool calls, and file attachments

The Polhem framework already uses AI chat in places, such as importing a form from documents in its definition editor, and more parts of the framework will get AI support. Rather than write a chat view in each place, I split it out into a package they all share. The previous post's Polhem.Markdown displays AI replies; this set adds the whole chat view around them: the prompt box, streaming, stopping and tool calls. The framework has both Avalonia and Blazor front ends, so both were built together.

The source is on GitHub under the MIT license. It does not depend on the Polhem framework, so other projects can use it directly.

One turn in the sample: the model thinks, calls a weather tool, streams a Markdown reply, and shows the time and tokens it used


1️⃣ The packages

Package Contents
Polhem.Chat The conversation model: turns the model's streamed updates into conversation entries, runs each turn, and handles the prompt box, sending, stopping and approving. No UI
Polhem.Chat.Avalonia The ChatView control for Avalonia, which renders replies with Polhem.Markdown.Avalonia
Polhem.Chat.Blazor The ChatView component for Blazor, for Interactive Server and WebAssembly, which renders replies with Polhem.Markdown.Blazor

An application references only the package for the front end it uses, and Polhem.Chat and the Markdown packages come along with it:

dotnet add package Polhem.Chat.Avalonia
dotnet add package Polhem.Chat.Blazor
Enter fullscreen mode Exit fullscreen mode

The target framework is net10.0, and the Avalonia side needs Avalonia 12. The core package depends only on Microsoft.Extensions.AI.Abstractions.


2️⃣ How it differs from similar packages

In November 2026, I looked through the AI chat components for Avalonia and Blazor on NuGet.

On Blazor, the mature options mostly belong to commercial component libraries (Syncfusion, DevExpress), and the open-source ones are often tied to a component library of their own (Radzen, for example); Microsoft's Microsoft.AspNetCore.Components.AI is still an experimental preview that supports only .NET 11. On Avalonia, the open-source controls are mostly built for a particular agent or back end (such as Claude Code's output, an agent framework of their own, or a local Ollama), or are one component in a large control library. I did not find one that takes an IChatClient directly.

Here is what this set deliberately does differently.

The conversation logic lives in the core, and each front end only draws

Behind a chat view are quite a few rules that have nothing to do with UI: Enter sends, but the Enter that confirms an input method's candidate must not; a failed send puts the text back in the prompt box; how a stop wraps up the turn, which entries a regenerate replaces, and how to tell the user that an attachment is over the limit. Written once for each front end, these rules would sooner or later drift apart.

So the core package has two layers:

  • ChatConversation, ChatTurn and ChatRunner: turn the streamed updates of an IChatClient into conversation entries (prompts, replies, reasoning, tool calls, summaries, errors), and run each turn.
  • ChatComposer: takes what the user does in the view, including the prompt box, attachments, sending, stopping, regenerating, editing and approving.

The ChatView of each front end only draws the view on top of these two layers. The Blazor version came later: first the parts of the Avalonia version that had nothing to do with UI moved into ChatComposer, and once the Avalonia version used it, all the existing tests passed without changes; the Blazor version then used the same composer directly. The view's texts (ChatStrings, in English, Traditional Chinese, Simplified Chinese and Japanese) also live in the core, so both front ends share the same translations.

Not tied to a component library or a model provider

The Blazor version depends on no component library. Its colors are derived from the page's text color, so it works on light and dark pages, and CSS variables adjust them. The Avalonia version supports the Fluent and Semi base themes, and its colors are brushes in the theme's resources.

On the model side it only knows IChatClient. Changing providers means changing the client, and the chat view stays as it is. Tool calls use UseFunctionInvocation() from Microsoft.Extensions.AI; the package does not define a tool mechanism of its own.

Replies are treated as untrusted input

A chat view shows the model's output, and that output can be steered by a third party, for example through instructions hidden in a document the model read. This is called prompt injection. So the package takes the cautious side by default in a few places:

  • Replies show no images by default. A model can be steered into writing an image whose address carries what the conversation holds, and the moment the view loads it, the data goes to the other party's server. So images in replies show their alternative text by default, and showing them is something the application has to turn on. When it does, a host allow-list (AllowedImageHosts) can allow only the images of its own site, instead of every https address.
  • A tool that needs approval runs only after the user approves it. A tool wrapped in ApprovalRequiredAIFunction shows as a card that lists every argument the tool will receive. There is no default button, no timeout and no "approve all"; stopping the turn counts as rejecting.
  • Hidden characters always show escaped. A bidirectional override (U+202E, for example) can make the order of the text on screen differ from what it really is. Such characters in approval card arguments, replies and reasoning always show in the \u{202E} form, so what the user sees is what is really there.
  • Attachments are checked by content, not by extension. Types are on an allow-list and are identified by the file's first bytes, so an executable named photo.png is not sent; the size is checked before the file is read.

Here is the approval card in the sample: the U+202E in the folder name shows as \u{202E}, long arguments scroll inside the card, and a hint below says there is more:

The delete-notes tool waiting for approval: every argument is listed, the hidden character in the folder name shows escaped, and Reject and Approve buttons are below

You can see what the model is doing

One turn can call the model several times, with tool calls in between, and waiting ten seconds or more is not unusual. While a reply is in progress, an activity line below the conversation shows an animated icon, what the model is doing now, the time spent, which call it is on, and the output tokens so far. Each finished turn leaves a summary line with the time, the tokens and how many of them were cached.

Reasoning and tool calls are folded into the activity line by default, so they take no room in the conversation; the › at the end of the line expands them.

A streaming reply shows as it will look once complete

Markdown that is halfway through streaming often ends with syntax that is still open: bold without its closing marker, a link whose address has not arrived, a table that has only its header row. Shown as is, the view would flicker between raw markers and the formatted result. ChatView tells the Markdown viewer that the reply is still streaming, and the viewer shows such syntax as it will look once the reply is complete; when the reply ends, it renders exactly what the text says.

You can also run the conversation loop yourself

Giving ChatView a ChatRunner is the easiest way to use it. An application that already has its own tool loop or agent can give it a ChatConversation instead and write the streamed updates into it. The view works the same, and approving, stopping and regenerating all have events or methods to hook into.


3️⃣ Features at a glance

Both front ends support every item in this table:

Feature Description
Streamed replies Rendered with Polhem.Markdown, with syntax highlighting, tables, Mermaid and math
Activity line While a reply is in progress: what the model is doing, the time spent, the number of calls and the output tokens
Turn summary Time, tokens and cached tokens; the number of calls when there were several
Stop The stop button or Esc
Copy Appears when the pointer is over a reply
Regenerate, edit Regenerate the last reply, or put the last prompt back in the box to change it and send it again
Tool approval A tool wrapped in ApprovalRequiredAIFunction runs only after it is approved
Templates per tool Draw the calls of one tool, by its name, with a template of your own, such as a weather card
Attachments Attach button and drag and drop; a type allow-list, and size and count limits (AllowsAttachments, off by default)
/ commands Typing / at the start of the prompt box lists the prompts the application provides
Context sent with a prompt Such as the selected text of a document; the view shows only its label
Suggested prompts A few prompts to click while the conversation is still empty
Images in replies Not loaded by default; a host allow-list can allow only the images of your own site
History SaveHistory and LoadHistory save and load it as ChatMessage
Content of your own Above the conversation, and above and below the prompt box
View texts English, Traditional Chinese, Simplified Chinese and Japanese, picked by culture, and replaceable

The two front ends differ in a few places for now:

  • Entry types of the application's own: only the Avalonia version can register templates for them and draw them; the Blazor version does not show such entries.
  • Pasting images: the Blazor version attaches an image pasted into the prompt box; on Avalonia, the application gets the image itself and calls AddAttachmentAsync.
  • The activity line's animated icon: the Avalonia version can replace it with a GIF of its own through ActivityIcon.

4️⃣ Avalonia

Add ChatTheme after the base theme:

<Application xmlns:chat="using:Polhem.Chat.Avalonia">
  <Application.Styles>
    <FluentTheme />
    <chat:ChatTheme />
  </Application.Styles>
</Application>
Enter fullscreen mode Exit fullscreen mode

Put a ChatView in the window:

<Window xmlns:chat="using:Polhem.Chat.Avalonia">
  <chat:ChatView x:Name="Chat" CjkFontFamily="PingFang TC, Microsoft JhengHei UI, Noto Sans CJK TC" />
</Window>
Enter fullscreen mode Exit fullscreen mode

Then give it a runner that wraps the client. This one uses OpenAI; any IChatClient works:

IChatClient client = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))
    .GetChatClient("gpt-4.1-mini")
    .AsIChatClient();

Chat.Runner = new ChatRunner(client);
Enter fullscreen mode Exit fullscreen mode

Enter sends, Shift+Enter starts a new line, and Esc or the stop button stops the reply.

When replies contain Chinese, setting CjkFontFamily is recommended. When Chinese and English are mixed, Avalonia may draw bold Chinese at regular weight; naming a Chinese font keeps it bold (the previous post mentioned this too).

Letting the model call tools

Wrap the client with UseFunctionInvocation() and put the tools in the runner's Options. Wrap a tool that changes data in ApprovalRequiredAIFunction:

var deleteNotes = new ApprovalRequiredAIFunction(AIFunctionFactory.Create(
    (string folder) => DeleteNotes(folder),
    "delete_notes",
    "Deletes the notes in a folder."));

Chat.Runner = new ChatRunner(client.AsBuilder().UseFunctionInvocation().Build())
{
    Options = new ChatOptions { Tools = [deleteNotes] },
};
Enter fullscreen mode Exit fullscreen mode

When the model asks to call delete_notes, the view shows an approval card, and the turn goes on only after the user decides.

A template of its own for one tool

A tool's result often reads better as a card than as a block of JSON. ToolCallTemplate names a template by tool name, and the calls that use it show even when reasoning and tool calls are folded away:

<chat:ChatView.DataTemplates>
  <chat:ToolCallTemplate ToolName="get_weather">
    <DataTemplate x:DataType="pc:ToolCallEntry">
      <local:WeatherCard />
    </DataTemplate>
  </chat:ToolCallTemplate>
</chat:ChatView.DataTemplates>
Enter fullscreen mode Exit fullscreen mode

In the template, ToolCallEntry.TryGetArgument and TryGetResult read the arguments and the result without reflection, so it also works in trimmed and AOT applications.

The sample's weather tool uses such a template. The picture below was taken while the reply was still streaming: the streaming reply is under the weather card, and the activity line is at the bottom.

The weather tool's call drawn as a weather card, with the streaming Markdown reply and the activity line below it

Images in replies

Replies load no images by default. To show images, give the view options of your own and list the allowed hosts in AllowedImageHosts:

var options = new MarkdownOptions();                  // Polhem.Markdown
options.AllowedImageHosts.Add("docs.example.com");    // only images from your own site
Chat.MarkdownOptions = options;
Enter fullscreen mode Exit fullscreen mode

Images from any other host show their alternative text. Put only hosts you control, with no open redirect, on the list: on Blazor the browser loads the images and follows a redirect anywhere. The Blazor version is set up the same way, through the MarkdownOptions parameter of ChatView.

Appearance

The colors are brushes in ChatTheme's resources; declare the same key in your own resources to override one. The view draws no border by default; set BorderBrush, BorderThickness and CornerRadius and it draws one, with the content clipped to the rounded corners.

A reply in the dark theme: a table, lists, a quote, math and a code block


5️⃣ Blazor

Link the Markdown viewer's style sheet in the page's <head>:

<link rel="stylesheet" href="_content/Polhem.Markdown.Blazor/polhem-markdown.css" />
Enter fullscreen mode Exit fullscreen mode

Register the IChatClient with the services (for example with builder.Services.AddChatClient(...)), then put a ChatView in a component with an interactive render mode. The view fills the height of its container, so the container needs a height:

@using Microsoft.Extensions.AI
@using Polhem.Chat
@using Polhem.Chat.Blazor

<div style="height: 600px">
    <ChatView Runner="runner" />
</div>

@code {
    private ChatRunner runner = null!;

    [Inject]
    private IChatClient ChatClient { get; set; } = null!;

    protected override void OnInitialized() => runner = new ChatRunner(ChatClient);
}
Enter fullscreen mode Exit fullscreen mode

One turn in the Blazor sample on the server: the model calls a weather tool, streams a Markdown reply, and shows the time and tokens it used

Server or WebAssembly

The component works in both render modes; what needs care is where the key lives. A WebAssembly app runs in the browser, and anyone can read an API key out of the files it downloads, so the model client must stay on the server: render with Interactive Server, or have the browser's IChatClient call an endpoint on your own server, which then calls the model.

When a file is attached on Blazor Server, the browser streams it to the server in parts, so there is no need to raise SignalR's message size limit (32 KB by default).

Templates and appearance

Above the conversation, while it is empty, and above and below the prompt box, there is a slot for the application's own content (HeaderContent, EmptyContent, PromptHeaderContent, PromptFooterContent). Each kind of entry can take a template of your own, and ToolCallTemplates names templates by tool:

<ChatView Runner="runner" ToolCallTemplates="toolTemplates">
    <EmptyContent><h2>Ask about your orders</h2></EmptyContent>
</ChatView>

@code {
    private readonly Dictionary<string, RenderFragment<ToolCallEntry>> toolTemplates = new()
    {
        ["get_weather"] = call => @<WeatherCard Call="call" />,
    };
}
Enter fullscreen mode Exit fullscreen mode

The view takes the page's font and text color; its other colors, corner radii and spacing are --pch-* CSS variables, listed in full in the Blazor guide.


6️⃣ Connecting the chat view to the application

A chat view placed in an existing application is usually not a standalone dialog; it has to work with the rest of the application. The following are designed for that.

/ commands

Commands holds prompts the application provides. When the user types / at the start of the prompt box, the commands whose names match are listed, and the arrow keys and Enter choose one; while an input method composes, these keys stay with it:

Chat.Commands = new ObservableCollection<PromptCommand>
{
    new("shorter", "Make this shorter:") { Description = "Cut the text down" },
    new("translate", "Translate the selection to English.") { SendsImmediately = true },
};
Enter fullscreen mode Exit fullscreen mode

A chosen command fills the prompt box with its text for the user to go on writing; with SendsImmediately set, it sends right away.

Context sent with a prompt

An AI assistant in an editor often has to send the text the user selected to the model as well, but that text should not show as a prompt the user typed. That is what PromptContext is for; add it in the MessageSending event:

runner.MessageSending += (_, e) =>
{
    if (!e.ReplacesLastPrompt)
        e.Context.Add(new PromptContext("Selection", selectedText));
};
Enter fullscreen mode Exit fullscreen mode

The model still receives one prompt in one text block, with the context wrapped in <context label="…"> before the prompt's text; the view shows only the label "Selection" next to the prompt. Regenerating or editing brings the context along by itself, so the handler adds it only when ReplacesLastPrompt is false, to avoid adding it twice.

Adding your own entries during a turn

An application that runs the loop itself can insert entries of its own during a turn with ChatTurn.AddEntry, such as a card that asks the user to pick one of a few options, and register a template for that entry type. Such entries only show in the view and are not sent to the model. For now only the Avalonia version can draw the application's own entry types; the Blazor version does not support them yet.


7️⃣ The samples

The repository's samples/ folder has two samples:

  • ChatGallery: the Avalonia version, with desktop, iOS and Android heads. It shows both ways of use, with a runner and with a loop of your own, and switches between Fluent and Semi, light and dark, and the view's language.
  • ChatGallery.Blazor: a Blazor Web App whose first page runs on the server and second page in the browser, both with the same component.

Both samples use replies written in advance by default, so they show reasoning, tool calls, approval cards and errors without a key. The Avalonia sample can also be pointed at an OpenAI-compatible endpoint.

git clone https://github.com/polhem-dev/polhem-chat.git
cd polhem-chat
dotnet run --project samples/ChatGallery.Desktop
dotnet run --project samples/ChatGallery.Blazor
Enter fullscreen mode Exit fullscreen mode

✅ Wrapping up

If your application needs an AI chat view, already uses Microsoft.Extensions.AI, and you do not want to be tied to a component library, or you have both Avalonia and Blazor front ends, give this set a try.

It is not the right fit for every project, though. The known limitations right now:

  • Only IChatClient is supported; an application on another SDK has to find an adapter or write one first.
  • The conversation is a single line with no branches; regenerating replaces only the last reply.
  • The view's texts ship only in English, Traditional Chinese, Simplified Chinese and Japanese; other languages need a ChatStrings of your own.

The packages are still 0.x, and the API may still change. Feel free to try them, and if you have any questions or suggestions, open an issue on GitHub.

Further reading


📘 Original article on HackMD, in Traditional Chinese:
👉 https://hackmd.io/@jeff377/polhem-chat

📢 You are welcome to republish this, please credit the source.
📬 Follow for more engineering notes:
Facebook | HackMD | GitHub | NuGet

Top comments (0)