Preparing the HTML Shell for Streaming AI Responses
Implementing real-time AI response streaming consists of two distinct phases:
- Initialization: Generating and loading the HTML Shell using C#.
- Streaming: Updating the shell in real-time using JavaScript calls generated by Chilkat.
Phase 1: Creating the HTML Shell (C#)
Before any AI text can be displayed, you must prepare the "stage." The HTML Shell is a complete HTML document that contains the CSS styles (themes), the layout containers, and the necessary JavaScript logic.
Instead of writing this HTML manually, you use Chilkat to generate it dynamically. By setting streamingShell to true, you tell Chilkat to create a shell designed specifically for receiving real-time updates.
C# Code to Generate the Shell
This code configures the visual appearance (themes, syntax highlighting) and generates the empty HTML framework.
// 1. Configure the HTML shell options.
Chilkat.JsonObject htmlOptions = new Chilkat.JsonObject();
// Set the visual theme (e.g., "ChatGPT", "cleanWin", "cleanMac", "custom", or leave empty)
htmlOptions.UpdateString("theme", "ChatGPT");
htmlOptions.UpdateString("ChatGPT.max-width", "80ch"); // ChatGPT theme specific optiony
// Enable PrismJS for code block syntax highlighting
htmlOptions.UpdateBool("usesPrism", true);
htmlOptions.UpdateString("prism.theme", "tomorrow");
htmlOptions.UpdateString("prism.version", "1.29.0");
// IMPORTANT: This tells Chilkat to generate the "HTML Shell" (CSS + JS + Empty Container)
// rather than rendering static Markdown.
htmlOptions.UpdateBool("streamingShell", true);
// 2. Generate the HTML shell.
Chilkat.StringBuilder sbHtml = new Chilkat.StringBuilder();
Chilkat.StringBuilder sbMarkdown = new Chilkat.StringBuilder();
// Passing empty markdown allows Chilkat to output just the shell structure.
sbMarkdown.MarkdownToHtml(htmlOptions, sbHtml);
// 3. Load the generated HTML into your WebView2 control.
// The user will see a styled, empty page ready for input.
await NavigateToStringAndWaitAsync(sbHtml.GetAsString());
What this generates:
The sbHtml string now contains a full HTML document. Crucially, because streamingShell was set to true, Chilkat automatically embedded the specific JavaScript functions required to handle the updates.