Chapter 13. Chat Components
The previous ten blocks were all “one question, one answer” UIs: fill in a few inputs, click a button, look at one result. A chat is not like that. It accumulates, one message after another, and users act on what has already been said — they like it, retry it, undo it, or edit a line and say it again.
One value holds the whole history, not the single numbers or files from earlier chapters; the UI also has a set of buttons that the component generates itself.
The sample adds an eleventh block to the workbench. The chat module: a starting conversation of four messages, an input box, an input with an attachment, and a script for two speakers. Replies are hardcoded: this chapter does not call a model service.
First, draw a boundary. This chapter is about “how to use the chat as a UI”, not “how to hook up a large model”. The line between the two is clear. Replace the line in the handler function that builds a string with one HTTP request, and the chat is connected to a model. No UI code has to change in between. The other way round, if the UI is set up wrong, connecting a model only gives you a box you can talk to. So get the UI right first.
13.1 Chatbot Message Structure
The value of Chatbot is a list of ChatMessage. One message has four fields.
Figure 13-1 The four fields of one message, and the history as an array of those messages
role is who is speaking, and there are only three: user, assistant, and system. Write a fourth and it throws; the front end aligns messages by role. content is an array, not a string; this is the structural basis of the chapter, expanded in 13.2. metadata and options can be absent.
This is what the four fields look like when sent to the front end.
{"role": "user", "metadata": null, "content": [{"text": "Explain the file module from Chapter 12.", "type": "text"}], "options": null}
This JSON explains several things that come later. content is an array, so one message can hold several things; each block has a type, and the front end picks a renderer by it; metadata and options are there even when empty, so code reading this JSON never has to write “this field might not exist”. When you build JSON by hand to call the API, build it in this structure.
Figure 13-2 shows the sample’s four messages. The first two are a question and an answer; a small collapsible “thought” floats above the second assistant message; the third is a follow-up question; the fourth has a file card hanging below the answer.
Figure 13-2 Four messages: bubbles, a collapsed thought, a file block, and a toolbar under each message
Where does the history live? In the component’s value. The sample does not use state (that is Chapter 14’s business); instead it has the handler function receive the whole list and return the whole list.
(IReadOnlyList<ChatMessage>, string, string) Send(IReadOnlyList<ChatMessage> history, string text)
{
var next = (history ?? []).ToList();
if (string.IsNullOrWhiteSpace(text))
{
return (next, text, "**Send** the input is empty, nothing was sent.");
}
next.Add(new ChatMessage(text.Trim(), ChatRole.User));
next.Add(new ChatMessage(ChatDesk.Reply(text, next.Count), ChatRole.Assistant));
return (next, "", $"**Send** now {Summary(next)}");
}
The sample also binds Submit to the input box, so Enter and clicking Send go to the same handler function. Without that binding, Enter does nothing and the user has to reach for the button. And pressing Enter to send in a chat box is muscle memory; without feedback people assume it has frozen.
Three return values: the new conversation, the cleared input box, and one line in the panel. Where does Chatbot’s value come from? The front end sends the current conversation along with the request. It always remembers which messages it is showing. So “multiple turns” needs no extra storage. The user sends a line, the front end sends it together with the history, and the handler function appends two messages at the end and writes them back to Chatbot.
The order is guaranteed by this way of writing too. The sample adds the user’s line first, then the answer, so the array is always “question, answer, question, answer”; add them the other way round and the UI shows “answer first, question after”. In a multi-turn chat, “is the order right” is a matter of array indexes. Undo, retry, and edit all work by index; get the order wrong and all of them land in the wrong place.
The second return value is an empty string, and you cannot leave it out. After sending, the input box has to be cleared, or the user sees the line they just typed still sitting there and assumes it was not sent. The sample’s empty-input branch hands the original text back (return (next, text, ...)) on purpose. When nothing was sent, do not wipe out what the user typed.
This approach has a cost, and 13.8 spells it out. The history travels with every request, and one page refresh wipes it. To keep it across refreshes you need state; to keep it on the server you have to store it yourself. This chapter is about understanding the value you already have in hand.
One note about the system role. It is neither “user” nor “assistant”; it usually holds an opening instruction, who this assistant is and what rules it speaks by. The front end draws it as a centered or marked notice, and it does not take part in the question-and-answer alignment.
Once the handler function has the history, besides appending to it, it commonly does two more things: read it and trim it. Reading is for context — what the last line asked, which words came up earlier. Trimming is because the history keeps growing until one request can no longer hold it. Trimming usually keeps the most recent rounds, or keeps by word count. The sample does not trim, because four messages are far from the limit; when you really connect a model, “how many rounds of history to carry over” is a number you have to decide yourself.
Every entry in history is a ChatMessage. The Text property is all of its text blocks joined together; Content is those blocks themselves. Code that only cares about “what was said” reads Text; code that has to handle files or components reads Content. Both are there, and which one you pick depends on whether you need anything beyond the blocks.
13.2 Content Blocks and Message Metadata
content is an array because a message can hold more than one piece of text. Three kinds of block.
ChatContent.TextBlock(text), a piece of text, the most common;ChatContent.FileBlock(file, alt). A file; the front end draws it as an image, audio, or a file card according to its type;ChatContent.ComponentBlock(...). A component; the front end draws it with that component’s own renderer.
The last message in Figure 13-2 is exactly “a piece of text + a file”: the text gives the conclusion, the file card carries the attachment. The file card shows the file name and extension, clicking it downloads, and allowFileDownloads is on by default.
The sample puts these two kinds of block together.
// The content of one message is an array of blocks: a piece of text, plus (optionally) a file.
static IReadOnlyList<ChatContent> Blocks(Turn turn)
{
var blocks = new List<ChatContent> { ChatContent.TextBlock(turn.Text) };
if (turn.Attachment is { } name)
{
blocks.Add(ChatContent.FileBlock(
new FileData { Path = Path.Combine(AppContext.BaseDirectory, "assets", name), OrigName = name },
"Attachment"));
}
return blocks;
}
FileData is the file object from Chapter 12: path, name, size, type. Once the component has it, it moves the file into the cache just like a file block, and the front end fetches it from the file endpoint. So what Chapter 12 said about “paths go stale” holds here too.
What a file block is drawn as is decided by the file’s type. Images become thumbnails, audio becomes a playback bar, video becomes a player, and everything else becomes a card with a name and extension. The txt file in Figure 13-2 is the last kind. That decision is made on the front end; the server only sends the file address, so “whether it can be displayed” depends on the file itself, not on which parameters you wrote.
The third kind of block (component) is used less often but is powerful. Put a table or a chart in a message and the front end draws it with that component. It needs four things: the component’s name (the spelling used in configuration, for example "dataframe"), the value it carries, the parameters used to construct it, and its properties. The last two travel with the message, because the front end uses them to rebuild the component. Give only the value and no properties and you get the component in its default shape. The sample does not use it, because there is no reason yet to put a table into a chat.
metadata decides what a message “looks like”. It governs a few things meant for the UI, not labels for a machine to read.
Title. Give the message a title and it becomes a collapsible block. The “Thought for 3 seconds” in Figure 13-2 is one;LogandDuration. Extra notes shown beside the title; the sample writes “Looked through two screenshots from Chapter 12” and3.2seconds;IdandParentId. Let one message hang under another for multi-level thinking. A child message’sParentIdis the parent’sId, and the front end indents it one level;Status.Pendingmakes the front end spin and expand;Donecollapses.
The sample gives the second assistant message the first three.
new("assistant", "First see where it lands, then when it disappears.", "Thought for 3 seconds", "Looked through two screenshots from Chapter 12", 3.2),
This line is business data in core; the UI turns it into MessageMetadata. The value of that collapse is that “the process beyond the answer” can be folded away on its own. The user sees the conclusion first, and opens it only if they want to know why.
Whether to use metadata depends on whether the message needs “layers”. A one-line conclusion does not; a process of “what was checked first, how long the thinking took, and what came out at the end” does. Fold the process away and the main text holds only the conclusion, which makes the chat cleaner to read. The other way round, if every message carries a title, the user has to click once more every time to see the answer, which turns a convenience into an obstacle. The sample gives only the second of its four messages a thought; that is the sense of proportion.
Status deserves its own note. Write Pending and the front end spins on that message and expands it; write Done and it collapses. This is not decoration. With streaming output you first put down a Pending assistant message, fill it in piece by piece, and finally change it to Done; what the user sees is “thinking” rather than “stuck”. That is Chapter 16’s subject; here you only need to know the field exists, and that it governs “process”, not “content”.
options is the fourth thing. A message can carry a few clickable options, so the user clicks one instead of typing. It takes a series of ChatOption, each with a value and display text; when one is picked the app receives that value. When should you use it? When the answer is not unique but there are few choices — “Expand further?” with “Yes” and “No” is less work than making the user type two words. The sample does not use it: in a chat with only fixed replies, options would have nothing to reply with.
13.3 Layout, Height, and Rendering Options
layout has only two values, and you can see the difference at a glance. bubble splits the two sides left and right, each a rounded bubble; panel puts both sides into full rows, left-aligned, more like a record.
Figure 13-3 On the left, panel layout; on the right, Markdown rendering turned off
The right-hand panel in Figure 13-3 has one more switch, renderMarkdown: false. With the same line “Cleanup checks every 20 seconds, right?”, rendering on gives bold and monospace; off shows the asterisks and backticks as they are. When should you turn it off? When the message content is itself “source text meant to be seen”. A chat that teaches Markdown, a chat that pastes logs. It is on by default.
height is the block’s height: write a number and it is pixels, write a string and it is a CSS length. It decides “how many messages you see at once”. The sample writes 480, which fits four messages exactly; after ten rounds you have to scroll. There is no standard answer for how tall to make it, but there is a rule of thumb: keep “the last two rounds” fully visible. One round is a little over a hundred pixels (one message each for question and answer), so two rounds are around 300; taller wastes the page, shorter makes the user scroll back every time.
placeholder is the line shown in the middle when the chat is empty; there is none by default. Its position overlaps with examples (both appear only when the chat is empty), so you generally pick one. Either give a hint (“Ask something to start”), or give a few clickable examples. Give both and the examples push the hint upward.
autoscroll decides whether a new message scrolls to the bottom. The sample turns it on. After sending a line, your eyes follow to the newest one. Turn it off and, in a long chat, the user stays put after sending and has to scroll down themselves. That is actually right for a “log stream” style UI.
resizable, minHeight, and maxHeight are a group. The first lets the user drag the block’s bottom edge to change the height; the other two give it lower and upper bounds. Write none of the three and the block’s height is fixed by height. If you write resizable: true, write minHeight along with it. Otherwise a user can drag the chat down to a slit and then cannot find a bottom edge to drag it back. maxHeight governs “how tall it can get at most”, used together with height. height is the initial height, maxHeight is where it stops growing.
There is one more inconspicuous parameter that bites: groupConsecutiveMessages, true by default. Two adjacent messages of the same role are merged into one bubble. Usually that is a good thing — when the model says two segments in a row, they look like one. But once you delete the user message in between, two assistant messages sit together and merge into one (the undo in 13.4 runs into this). To tell them apart one by one, write false.
examples appear only when the chat is empty. The sample gives the main chat two, and they surface only after you click “Clear chat” (in a chat with content, like Figure 13-2, they take up no space). Clicking one fires example_select and brings back Index (which one) and Value (the example itself, a dictionary with a text key). But it does not fill the example into the chat by itself — you have to write that step.
This one is easy to trip over. In ChatInterface, clicking an example means “send this question straight away”, because it does the sending for you; with a handwritten Chatbot, the example buttons only tell you “which one the user clicked”, and turning the example into a question and an answer is still your job. The sample’s handler function therefore has two extra lines. It treats the example’s text as one user message, pairs it with an answer, and puts both back into the chat. Without those two lines, clicking an example does nothing: the button stays, the chat stays empty.
An example can also carry an icon and files. Besides Text, ChatExample has DisplayText (what to show), Icon (the small image beside it), and Files (attachments the example brings). You use these for prompts like “Upload an image and try”.
13.4 Feedback, Retry, and Undo
Chatbot has ten events; this section covers four of them: like, retry, undo, and edit. They are all triggered by buttons the component brings with it, in that row of small icons under each message.
These buttons live under each message, not in a toolbar at the top of the page. The position is the design. Like, retry, and undo all target “this one”, so put them beside it and the user does not have to select first and then say “yes, that one”. The cost is one more row of icons per message, and a long chat starts to look dense. If that feels noisy, buttons can drop the copy ones and editable set to null removes the pencil, but retry and undo cannot be dropped — they are part of this round of the conversation.
First, a counterintuitive one: if you don’t bind like, there are no thumbs-up and thumbs-down. In that row of icons under a message, copy, retry, and undo are all there, and only the two thumbs are missing; they appear once you bind it (the lit thumb in Figure 13-4). The component is waiting for someone who can catch the rating.
Figure 13-4 A like: message 1 is liked, and the callback carries the position and that message’s text
like brings back three things. Index is which message, Liked is “like or dislike” (a Boolean with the default two options, the value of the chosen option with custom ones), and Value is that message’s text. The sample joins them into one line.
string OnChatLike(LikeData data)
{
var said = data.Value switch
{
object[] blocks => string.Join(" ", blocks.Select(block => block?.ToString())),
null => "",
_ => data.Value.ToString(),
};
return data.Liked is true
? $"**Like** message {data.Index}: \"{said}\""
: $"**Dislike** message {data.Index}: \"{said}\"";
}
The type of Value is object, but what you actually get is an array of strings, one entry per text block in that message. So handle it as an array here; writing data.Value is string will never be true.
What do you do after getting the rating? The sample skips this step, because it needs to “remember”: which messages were liked, and by whom. Without state, a rating can only be written to a log, sent to an external service, or shown once as the sample does. To really “remember which one was liked last time”, you store the rating in state (Chapter 14) and then write it into the component through feedbackValue at render time, so the thumb stays lit.
feedbackOptions decides how many options there are and what they are called. Two by default (like, dislike); write custom strings and you get custom buttons; more than two options are folded into a menu. Whatever value you write is what Liked brings back. So “like/dislike” is a Boolean check, while “Accurate / Inaccurate / Off-topic” has to be checked by value.
retry is “answer this one again”. Its button appears only in the last round, because “answer again” means “a different answer to that last question”. It brings back Indices (which messages this retry covers), Index (the first of them), and Value (that question’s text).
The sample’s retry only rephrases; it does not call a model.
(IReadOnlyList<ChatMessage>, string) OnChatRetry(IReadOnlyList<ChatMessage> history, RetryData data)
{
var next = (history ?? []).ToList();
var at = data.Indices.LastOrDefault();
if (at < 0 || at >= next.Count)
{
return (next, "**Retry** that message was not found.");
}
Answer(next, at);
return (next, $"**Retry** the answer after message {at} was replaced.");
}
Answer is that small function in the sample. It replaces the answer after message at, and inserts one if there is no assistant message after it. Editing uses the same one. “Replacing the answer to a question” is the same job in retry and in edit.
Figure 13-5 shows it after the click: the last answer is replaced with a different phrasing (the sample picks one at random), and the first three rounds are untouched. Random.Shared is the sample simulating “asking again gives a different answer”; with a real model, that line becomes one request.
Indices is an array rather than a single number because one retry can cover the two messages of “a question and an answer”. The sample uses only the last position (answer the last question again, replace its answer), which is also the most common use. If you want “start from this question and redo everything after it”, truncate at the first item of Indices and generate again from there.
The retry button appears only in the last round, and that cannot be changed: the component decides it, it is not a parameter. To “re-answer a round in the middle”, you have to make your own button and send that question again.
Figure 13-5 Retry: only the last answer is replaced, the history is unchanged
undo is “take this round back”. It brings back Indices and Index. It gives only the position of the user’s message; the assistant’s is not included. So undo has to delete two messages itself.
(IReadOnlyList<ChatMessage>, string) OnChatUndo(IReadOnlyList<ChatMessage> history, UndoData data)
{
var next = (history ?? []).ToList();
var at = data.Indices.LastOrDefault();
if (at < 0 || at >= next.Count)
{
return (next, "**Undo** that round was not found.");
}
next.RemoveAt(at);
if (at < next.Count && next[at].Role == ChatRole.Assistant)
{
next.RemoveAt(at);
}
return (next, $"**Undo** removed one question and one answer, now {Summary(next)}");
}
What happens if you delete only the user’s message? The two remaining assistant messages sit together, groupConsecutiveMessages merges them into one bubble, and the answer looks longer — that is the wrong deletion. This is where mistakes happen. Undo is “a question and an answer”, not “one message”.
One more thing to be clear about. What the UI looks like after undo is decided by the array you return; the component does not touch it again. So “how many to delete” is entirely up to you. Delete a pair, delete a pair and add an apology, or delete nothing and just make a note — all are fine. The component only tells you that the user clicked undo.
Figure 13-6 Undo: four messages become two, and the callback reads “now 2 messages: 1 user, 1 assistant”
edit requires editable to be on first. Write "user" and every user message gets a pencil; write "all" and the assistant’s can be edited too; write null (the default) and there are none. Click the pencil, the message becomes an input box, and after editing you click its own “Send”; the edit event brings back Indices, PreviousValue (before the change), and Value (after the change).
On receiving it, the sample rewrites that question’s answer. This is the most common use of editing. If the user changed what they asked, the answer should not still be the old one.
The handler functions of the three events can all return a new conversation — that is what they are really for. They can also return just one line and leave the conversation alone; that becomes “make a note”, the kind in Figure 13-4.
Editing has one consequence that is easy to overlook. After the change, the original answer no longer stands. The sample rewrites the answer along with it; change only the user’s line and leave the answer, and the UI shows “asks A, answers B”. So an edit handler usually looks just like retry: replace that question, then generate a new answer.
Use editable: "all" with care. It lets the assistant’s message be edited too, so the user can change the model’s answer into anything. If the chat is going to be exported and treated as a record, you can no longer tell who said what in edited content. The case for open editing is usually “make the question clearer”, and "user" covers that.
All four events go through the queue, like an ordinary button: click first queues, then executes. So click retry twice quickly and both run, with the later one overwriting the earlier result. To prevent that, use triggerMode from Chapter 15.
13.5 What ChatInterface Saves You
Across the four sections above you wrote the chat block, the input box, the send button, the send handler function, four event handler functions, plus clearing and examples. ChatInterface packs that whole set into one function.
// ChatInterface builds an app of its own: the whole page is one chat and it cannot be placed inside another layout.
var demo = gr.ChatInterface(
Reply,
title: "Chat-only app",
description: "One function, one input box, one chat; it builds everything else for you.",
examples: new[] { "What does Chapter 12 cover", "Where do the files land" });
demo.Launch(serverPort: 7862);
// The message and the history are both handed over by the framework: you do not append them yourself, and you do not clear the input box yourself.
static string Reply(string message, IReadOnlyList<ChatMessage> history)
=> $"Round {history.Count / 2 + 1}: you asked \"{message}\".";
Figure 13-7 shows it running: a title, a description, one chat, and an input box at the bottom. The handler function has only two inputs (this line and the history), returns only one line, and takes care of nothing else.
Figure 13-7 One function buys a whole chat page: title, description, chat, input box
The things it does for you can be counted one by one: the input box and its Enter-to-send, the send button and the stop button, appending the user’s line to the history, passing the history to the handler function, appending the answer, clearing the input box, wiring retry and undo, editing and regeneration, the examples bar, and caching the answers for the examples. In the handwritten version, every one of those has to be wired up by hand.
Its sending also happens to solve a failure case. When the handler function throws, the user’s line should still be in the chat and the input box should be empty, rather than both kept or both lost. ChatInterface gets that order right. You can get it right by hand too, but you have to think first about “what the UI should look like on failure”.
Its toolbar comes built in as well. The chat block has three icons in the top-right corner (share, copy the conversation, copy all) and a clear button beside them; under each message are copy and (only when bound) retry, undo, and like/dislike. To change that top-right row, the buttons parameter can subtract but not add. It takes names, not components.
It has a few more parameters worth knowing. multimodal: true swaps the input box for MultimodalTextbox, and the handler function takes MultimodalText instead of a string. additionalInputs adds a collapsible block of extra inputs below the chat (for example a “Tone” dropdown), and the handler function receives those values after the history and the message. additionalOutputs lets the handler function’s result fill a few more components, such as a companion image.
But there are two things it does not give you.
The first is layout. gr.ChatInterface returns a Blocks. It builds an app of its own. You cannot tuck it into one column of the workbench. It does not recognize an outside layout, and you cannot drop it in as a component. So choose it only when “the whole app is one chat”; if you already have a workbench, you have to handwrite Chatbot.
The second is detail. Its chat block, input box, and buttons are all in their default shape; you can only fine-tune them with parameters (chatbot and textbox can be swapped for ones you build yourself), you cannot change the structure. Like and dislike are off by default. flaggingMode defaults to never; to turn it on you write "manual". That is why the assistant message in Figure 13-7 has only copy, retry, and undo beneath it, and no thumbs.
There is one less obvious thing it withholds: it gives you only one chat. If you want two chats side by side on a page (say “Ask the docs” and “Ask the code”), ChatInterface cannot do it. The app it builds has exactly one chat block. Here too you have to handwrite it.
The choice starts with this question: first ask “does this app have anything besides the chat?”. No — use ChatInterface, done in twenty lines. Yes — handwrite Chatbot and treat the chat as one block in the workbench. There is a middle case too: only one chat, but you want to change the structure (a custom toolbar, a live result panel beside the chat). Start from Chatbot there as well, because ChatInterface does not expose its structure.
The sample gives you both. samples-en/chapter13 is the handwritten version (inside the workbench shell), and samples-en/chapter13/interface is the twenty lines of ChatInterface. Launching both and comparing them is faster than reading two pages of explanation.
The difference in code size is an order of magnitude. The handwritten version: one chat block, an input box and a button, seven handler functions (send, like/dislike, retry, undo, edit, examples, read attachment), plus ten lines of bindings to wire them together. The ChatInterface version: one gr.ChatInterface call and one handler function. The former gives you control (what each block looks like, what each button does when clicked, how the UI changes on failure; the latter gives you speed) — twenty minutes and you have a working chat.
Which one to pick is not a question of “more advanced or less”. Use the handwritten version for an app that is only a chat, and every extra line repeats work the framework already got right; a workbench that already has ten blocks has no room for ChatInterface, which builds an app of its own.
13.6 Text and Attachments in MultimodalTextbox
Sending an image or a file in a chat uses MultimodalTextbox. The name says it all: one input box that you can both type into and attach files to.
Its value is MultimodalText: a Text and a Files. The sample reads it out.
string ReadMultimodal(MultimodalText? value)
{
if (value is null)
{
return "**Attachment** no value.";
}
var files = value.Files?.Count ?? 0;
var names = files == 0 ? "" : string.Join(" / ", value.Files!.Select(file => Path.GetFileName(file.Path)));
return $"""
**Attachment** Text "{value.Text}", {files} files
{names}
""";
}
Figure 13-8 shows it with an image attached and a line typed: the input box holds the thumbnail and the text, and after clicking “Read attachment” the panel shows the text, the file count, and the file names.
Figure 13-8 An input with an attachment: text and files travel to the server together with the request
The three parameters are the same set as File. sources governs the entry points (upload, microphone, camera), fileTypes which types are accepted, and fileCount how many. The sample enables only upload and accepts only images, so opening the attachment button shows just a file picker.
Attached files land in the cache just like uploaded ones, and each item in Files carries a path, a name, and a size. So Chapter 12’s rule “don’t treat the path as storage” still applies. If the handler function needs this image, use it now or copy it away yourself.
There is no automatic relationship between it and Chatbot. The sample treats it as a standalone block: fill it in, click “Read attachment”, read the value. In a real chat you usually use it as ChatInterface’s input box (multimodal: true, with a handler function taking MultimodalText), or wire its value to a send button yourself.
When you wire it yourself, that step is the same pattern as the send in 13.1, with one extra job: turn the attachments into file blocks in the message. Text goes into a text block, each file into a file block, together they form one user message, and then you append an answer. The sample does not wire this up (its send button is paired with an ordinary input box), but the way to assemble it is the Blocks function from 13.2: one block for the text, one for the file.
The difference between MultimodalTextbox and Textbox is more than “one extra attachment button”. It has no type (no password box, no email box), lines and maxLines decide how tall the input box grows, and maxPlainTextLength limits the length of the plain-text part. It also draws attachments as thumbnails lined up inside the input box. The small image on the left of Figure 13-8 is one: the user can see what they attached and can click it away.
How many attachments one message can carry is decided by fileCount. Write "single" and you can attach only one; "multiple" allows several, and each one attached becomes a separate file block in the message. Figure 13-8 has only one image, so it reads out as “1 file”; attach three and you get three file blocks in a row, each with its own thumbnail drawn by the front end.
Size and type limits carry over from Chapter 12. fileTypes goes into the picker and is checked again on the front end, and Blocks.MaxFileSize blocks once more on the server. Attached files land in the cache the same way and are deleted by the cleanup job the same way. To keep one in the handler function, the same advice applies: copy it away on the spot.
13.7 Dialogue Speaker Structure
Dialogue is a script: a record with speakers and lines, each line marked with who said it and colored by speaker. It suits “reading” cases such as interview transcripts, meeting notes, and two-person walkthroughs; it does not suit “back-and-forth Q&A” — it has no input box and no toolbar.
Figure 13-9 A script: two speakers each with their own background color, four lines in order
Three parameters decide how it looks. speakers lists who is present (and also fixes the order of the colors), type written as "list" gives one line per sentence (the default "text" is one whole block of text), and colorMap gives each person a color.
Be careful with the structure of the value. Pass in new[] { new DialogueTurn("Editor", "...") } and the UI displays a string of DialogueTurn { Speaker = Editor, ... } literals. That is because this component’s value does not go through a type — it only understands JSON. The sample therefore hands over JSON directly.
public static JsonArray Script() =>
[
new JsonObject { ["speaker"] = "Editor", ["text"] = "Is the example in this section too long?" },
new JsonObject { ["speaker"] = "Author", ["text"] = "Longer is fine, but you should be able to tell at a glance what it does." },
new JsonObject { ["speaker"] = "Editor", ["text"] = "Then keep the callback panel so readers can compare side by side." },
new JsonObject { ["speaker"] = "Author", ["text"] = "Keep it." },
];
DialogueTurn is for reading. When a handler function receives a script, the framework reads it into a list of DialogueTurn, with both the Speaker and Text fields present. Write JSON on the way in, take records on the way out; don’t get the two directions mixed up.
colorMap is the background color of the whole row, not the color of the speaker label. The sample first used dark blue and dark green, and the text blurred into the background; switching to light blue and light green brought the text back. That is the difference. Choose colors as “backgrounds”, not as “theme colors”.
The other value of type is "text", which is also the default. The whole script becomes one text area, and the user can edit it like a piece of text. That suits “let someone write a dialogue record”, not “edit line by line”. The sample writes "list", because it wants one line per sentence with the speakers kept apart.
formatter and unformatter are a pair. The former turns “your value” into the script the front end shows; the latter turns an edited script back into “your value”. Give neither and the defaults are used. The default writes one line as [speaker] line. The sample gives neither. Its value already has that structure, so there is nothing to convert.
interactive decides whether this script can be edited. It can by default. Each row has a speaker dropdown plus a text box, so the user can add, change, and delete lines. The left cell of each row in Figure 13-9 is the speaker. Write false and it is read-only, which suits “put a cleaned-up record on display”. An edited script comes back as the new value, still that same JSON array, so the code reading it does not need two versions for “edited” and “not edited”.
When should you use Dialogue rather than Chatbot? Look for a “there” and a “back”. If there is back-and-forth and the user will keep talking, it is a conversation — use Chatbot. A fixed record laid out by person is a script — use Dialogue. The former has an input box and a toolbar, the latter does not; the former splits left and right by role, the latter colors by speaker. Both are called “dialogue”, but one can grow and the other can only be read (or edited as a whole).
13.8 Chapter Summary
A message is four fields: role (three values), content (an array of blocks), metadata, and options. There are three kinds of content block: text, file, and component. So one message can hold a passage plus an attachment, or hold a table. Metadata is for the UI. Title makes it collapsible, Id/ParentId lets it nest, and Log and Duration show beside it.
The history lives in the component’s value. The handler function receives the whole list and returns the whole list, so “multiple turns” needs no extra storage; the cost is that the history travels with every request and is gone on refresh. To keep it across refreshes, you need state (Chapter 14).
Presentation has four switches. layout toggles between bubbles and full rows, renderMarkdown decides whether asterisks become bold or are shown as-is, height decides how many messages you see at once, and autoscroll governs whether a new message scrolls into view. There is also groupConsecutiveMessages, on by default and easy to forget: adjacent messages of the same role merge into one bubble.
Of the four events, like has to be bound before there are thumbs-up and thumbs-down; retry and undo appear only in the last round; edit needs editable on first. like’s Value is an array of text blocks, not a string; undo gives only the position of the user’s message, and you have to delete the assistant’s yourself. Leave it and you will see two assistant messages merge into one. All three events can return a new conversation, and all three can also just make a note.
ChatInterface buys a complete chat page in twenty lines, but it builds its own Blocks and cannot be fitted into an existing layout; like and dislike are off by default. There is only one test: if the whole app is a chat, use it; if you already have a workbench, handwrite Chatbot.
The value of MultimodalTextbox is text plus files, and its three parameters are the same set as File. Dialogue is a script, not a conversation: speakers, lines, and colors, with the value written as JSON, and DialogueTurn appearing only when you read it.
The chat block differs from the previous ten in one more fundamental way. Its value is “history”, not “a value”. That has three consequences; go over them once more before you close the book.
First, the value keeps growing. A four-message chat and a forty-message chat send data on a different scale with each request; at forty, one request has to carry the entire history. So “how many rounds to bring along” sooner or later becomes a decision you state explicitly, rather than “bring everything”.
Second, values are nested inside the value. A message holds blocks, a block holds a file, and behind the file is a cache path. Chapter 12’s rule that “paths go stale” still holds one layer of message down. That is also why a file block’s handler function has to copy the file away early.
Third, some of the buttons on the UI are not ones you placed. Like, dislike, retry, undo, and edit all come with the component; the only decision you get is “whether to bind them”. Don’t bind them and they do not appear (like/dislike) or appear with no effect (retry); bind them and you have to think through what to return.
With that, the part on interface building blocks is done. Eleven blocks sit on one page, each minding only its own value. But one page refresh leaves nothing behind, and two blocks cannot share a piece of data. The chat magnifies the problem: one refresh and the whole history is gone. The next chapter solves it — state.