Messages & streaming
Handlers are the functions DyUI calls when something happens in a conversation; whatever they yield streams into the reply. Read this page to learn the handler shapes, what you can yield and what chat gives you.
The snippets below are fragments that assume import dyui, from dyui import ui and an app = dyui.App(...). The complete example at the end is a whole file.
Handlers
Section titled “Handlers”@app.on_message is the only required handler. It receives the user’s Message and the conversation’s Chat.
@app.on_messageasync def reply(msg: dyui.Message, chat: dyui.Chat): yield "Hello!"Any of these shapes works for on_message, on_action and on_chat_start:
| Shape | Example |
|---|---|
| async generator | async def reply(msg, chat): yield "hi" |
| sync generator | def reply(msg, chat): yield "hi" (runs in a worker thread) |
| coroutine | async def reply(msg, chat): return ui.Stat("Users", 42) |
| plain function | def reply(msg, chat): return ["Done.", ui.Callout("Saved", level="success")] |
What you can yield
Section titled “What you can yield”| Value | Becomes |
|---|---|
str |
Markdown text, appended to the reply. It is parsed for ```dyui fences, so raw model output works. |
a component (ui.Table(...), your @app.component classes) |
A rendered component part |
dyui.Reasoning("...") |
A delta for the collapsible reasoning block |
{"ui": "stat", ...} |
Validated exactly like model output (so never the developer-only html) |
| a list or tuple | Each item in order |
None |
Ignored |
Anything else is shown as text, and a warning is logged.
Updating a component in place
Section titled “Updating a component in place”Give a component a stable id. Yielding another component with the same id replaces it where it stands, which suits progress bars and live numbers. Inside your handler:
for done in range(0, 101, 20): yield ui.Progress(done, label="Indexing", id="indexing") await asyncio.sleep(0.4)The message
Section titled “The message”Message has id, text, files (a list of File with name, type, size, path and url) and action. action is set when the turn came from an unhandled action; text then holds an LLM-friendly description of it.
@app.on_messageasync def reply(msg: dyui.Message, chat: dyui.Chat): for f in msg.files: yield f"Got **{f.name}** ({f.size} bytes) — saved at `{f.path}`."The chat
Section titled “The chat”| Member | What it is |
|---|---|
chat.history |
[{"role": "user" | "assistant", "content": str}], ready for any chat API. Components the assistant showed are serialized as compact dyui blocks, so the model remembers what it rendered. Steps and reasoning are left out. |
chat.messages |
The stored messages with all their parts (protocol Message dicts). |
chat.session |
A dict persisted with the conversation. See Sessions. |
chat.thread_id, chat.user_id |
The conversation and the anonymous browser identity. |
await chat.send(*items) |
Appends items to the current reply, the same as yielding them. |
chat.step(title, type=) |
A live step. See Steps & reasoning. |
await chat.ask(component) |
Renders an interactive component and waits for the user’s answer. See Actions. |
await chat.set_title(title) |
Sets the conversation title and turns off auto-titling. |
Greeting on a new conversation
Section titled “Greeting on a new conversation”on_chat_start runs when a thread is created. Use chat.send there to post a first assistant message:
@app.on_chat_startasync def start(chat: dyui.Chat): await chat.send("Hi! I can plan trips and book flights.", ui.QuickReplies("Plan a weekend", "Find flights"))Stop, regenerate and edit
Section titled “Stop, regenerate and edit”- Stop: the browser aborts the stream. The server cancels your handler task (
asyncio.CancelledErroris raised inside it) and stores the partial reply ascancelled. - Regenerate: the last assistant reply is deleted and
on_messageruns again for the last user message. - Edit: the user’s last message is replaced, everything after it is deleted, and
on_messageruns again. - Errors: if your handler raises, the user sees an inline error with Retry. The traceback is logged on the server and never sent to the browser. Two errors get a specific message: a missing API key names the variable to set, and a provider rate limit says to wait.
During long silences the server sends an SSE comment every 15 seconds, so proxies don’t time out the stream.
Complete example
Section titled “Complete example”A greeting from on_chat_start, a conversation title, uploaded files, a progress bar updated in place and a list of components yielded at once. No API key needed.
"""Handlers, yields, files, a component updated in place, and a greeting.
Save as app.py, then run: dyui run app.py"""import asyncio
import dyuifrom dyui import ui
app = dyui.App(title="Indexer", description="Attach a file, or send any message.", starters=["Index my notes"])
@app.on_chat_startasync def start(chat: dyui.Chat): # runs when a conversation is created: post a first assistant message await chat.send("Hi! Attach files and I'll index them.", ui.QuickReplies("Index my notes", "What can you do?"))
@app.on_messageasync def reply(msg: dyui.Message, chat: dyui.Chat): if not chat.session.get("titled"): # name the conversation once (turns off auto-titling) await chat.set_title(f"Indexing: {msg.text[:40]}") chat.session["titled"] = True for f in msg.files: yield f"Got **{f.name}** ({f.size} bytes).\n\n" # the same id replaces the component where it stands for done in range(0, 101, 25): yield ui.Progress(done, label="Indexing", id="indexing") await asyncio.sleep(0.2) yield "Done. " yield [ui.Callout("Index is up to date.", level="success"), ui.QuickReplies("Index again")]-
Save it as
app.pyin a new, empty file, or download app.py. -
Run it:
Terminal window pip install dyuidyui run app.py -
Open http://localhost:8000, start a chat, and attach a file with the paperclip.
See also
Section titled “See also”- Steps & reasoning for live progress.
- Generative UI for what changes when a model writes the reply.