Chat: AgentInterface and the message protocol
A chat app has to do four things around a generated interface: send the thread to your server, decode the streamed reply, store each reply so it can be shown again with the user's choices intact, and run the interface's actions. OpenUI's chat pieces do the first two, define a stored format for the third, and leave one gap in the fourth that you fill with a small custom component.
By the end of this lesson you can
- name the layers between the AgentInterface component and your model call, and say what each one is responsible for;
- configure
fetchLLMwith a stream adapter and a message format that match your route's wire format; - write and read a stored message with
buildMessageandparseMessage, and explain why the model never sees the marker lines; - make a reload restore a changed
$variable, usingonStateUpdateandinitialState; - explain why a chat that uses
Queryneeds its ownAssistantMessage, and what that component must re-implement.
From the chat window to the model and back
AgentInterface from @openuidev/react-ui is a complete chat surface: sidebar, composer, message list, and generated UI rendering. It talks to your backend through exactly one object, the llm prop, and the usual way to build that object is fetchLLM from @openuidev/react-headless. The headless package also holds the chat state (ChatProvider, useThread), which AgentInterface wraps for you. Step through one round trip.
One chat round trip
AgentInterfacerenders the chat and creates aChatProvideraround it, which holds the threads and the current thread's messages. You pass itllm, acomponentLibraryfor generated UI, and optionally your owncomponents. When the user presses send, the provider callsllm.send(...)with the thread.fetchLLMturns that call into afetch: a JSONPOSTtourl. The body is{ threadId, runId, messages, tools: [], context: [] }, withmessagesconverted by yourmessageFormat. The request goes to your route, never to a model provider.- Your route validates the body, adds the system prompt itself (a client must not choose it), and calls the model. The reference file shows this server half for one-shot generation, with a body of
{prompt, messages}. A chat route does the same with theUIMessages thatfetchLLMsends:convertToModelMessageson the way in,toUIMessageStreamResponse()on the way out. Which model and which SDK is entirely your choice. - The model streams its reply and your route forwards it in whatever wire format you picked, for example an AI SDK UI message stream.
fetchLLMhands the rawResponseto thestreamAdapter. - The adapter decodes the wire format into AG-UI events, a common vocabulary (text messages, tool calls and their results, run errors). The thread state applies each event, so the assistant message's
contentgrows andisRunningis true until the run ends. - Each growth of the message re-renders the
AssistantMessagecomponent, which gives the text so far to<Renderer isStreaming>. That is the same streaming parse from the pipeline lesson, now inside a thread.
Key idea
Everything OpenUI-specific happens at the two ends of this picture: your server writes the prompt and streams OpenUI Lang, and the assistant message component renders it. The layers in between (fetchLLM, adapters, thread state) are ordinary chat plumbing that would be the same for a markdown chat.
fetchLLM, adapters and message formats
Three settings connect the chat to your route, and they must agree with what the route actually sends and receives.
urlis your own chat route. Customheaders, a customfetchand extrabodyfields are optional. Anything you put inheadersis visible in the browser.streamAdapterreads theResponseyour route returns and yields AG-UI events. It must match your route's stream format. Choose from the bundled adapters below. They are factory functions, so call them:vercelAIAdapter().messageFormatconverts the thread's messages into the shape your route expects (and back, for stored threads). The default is the identity format. Pair the adapter and the format from the same family.
| Your route streams | streamAdapter | messageFormat |
|---|---|---|
| AG-UI events directly | agUIAdapter() | identity (default) |
| AI SDK UI message stream (what the reference route sends) | vercelAIAdapter() | vercelAIMessageFormat |
| OpenAI chat completions stream (SSE) | openAIAdapter() | openAIMessageFormat |
| OpenAI chat completions as a readable stream | openAIReadableStreamAdapter() | openAIMessageFormat |
| OpenAI Responses API stream | openAIResponsesAdapter() | openAIConversationMessageFormat |
| LangGraph | langGraphAdapter({…}) | langGraphMessageFormat |
| Vercel Eve session stream | eveAdapter(), as the streamProtocol of a hand-written ChatLLM | none: Eve keeps the conversation server-side |
The adapter and format names are those listed in the AgentInterface adapters reference for these package versions. Check the reference for the exact options each adapter takes.
OpenUI rule
The adapter is how the chat stays independent of your provider. Underneath, ChatLLM is just { send(...): Promise<Response>, streamProtocol }, and a stream protocol is anything with parse(response): AsyncIterable<AGUIEvent>. If none of the bundled adapters fits your route, you can write that one method yourself.
The message protocol
A reply is stored as the program text, but a chat also needs to keep something next to it: the values the user typed, a toggle they flipped. The message protocol stores both in one string, separated by marker lines that start with ]]>openui:. You write it with buildMessage and read it with parseMessage, both exported from @openuidev/react-lang. Edit the fields on the left, then edit the stored string itself and watch the decoder.
1. Encode: buildMessage
2. The stored string (editable)
3. Decode: parseMessage
The encoder and decoder here are the course simulator's OUI.buildMessage and OUI.parseMessage, which follow the same rules as the real ones in @openuidev/react-lang, including moving a content marker found in the middle of a line onto its own line, and the { streaming: true } option (next sections).
Three parties touch a stored message, and the division of labour is the point of the protocol:
- Your app writes it, with
buildMessage, whenever the response or its state changes. - The Renderer reads it. You can pass a stored message as
response: the Renderer removes the marker lines and renders the content. It ignores the context. - The model never sees the markers. Before history goes back to the model, strip them with
parseMessage(stored).content. If you want the model to know the user's form values, put them in plain words in the next user turn.
Break it
Predict first. Click Add a second content section. Which content does the decoder return, and what happens to the context? Then click Remove all markers.
What should happen
With several content sections, the last one wins, and a context section that came before the winning content section is ignored. After Remove all markers the whole text comes back as content, with no context and no attributes: plain text is a valid message, which is how responses stored before you adopted the protocol keep working. These are the reading rules in the OpenUI docs for the message protocol.
OpenUI rule
"The model never sees the markers." A chat that stores messages in this format must strip the markers before it sends history to the model. A leaked ]]>openui:context line is text the model may imitate.
State that survives a reload
Reactive state lives in the Renderer's store. Reload the page and the store starts again from the values the model wrote, so a user who switched to Fahrenheit is back on Celsius. The fix uses two Renderer props and the protocol above. onStateUpdate fires with a snapshot every time a $variable or field changes; the chat writes it into the stored message as context. On reload, the chat reads the context back and passes it to initialState. Flip the unit, then press Reload.
The assistant message, rendered
The stored message, as updateMessage keeps it
Simulated: the weather comes from the course's in-page get_weather, and the Renderer is the teaching subset. The stored context holds the inputs ($city, $units), never the weather itself, so after a reload the Query runs again with the restored inputs.
Common misconception
"The Renderer remembers state for me." It keeps state in memory only. Persisting it is the chat app's job, and the stock AgentInterface message already does it by storing [state] as the context. Because the Renderer ignores stored context, you must read it yourself and pass it as initialState.
A marker cut in half
The stored message is assembled from a stream, and a chunk can end anywhere, including in the middle of a marker line. Without care, the half marker ]]>open is the last line of the content, and it flashes on screen as program text (or, worse, breaks the parse). The fix is parseMessage(text, { streaming: true }): a last line that is, or could still become, a marker line is held back until its newline arrives. Drag the slider to cut the message at any point.
Received so far
Content passed to the Renderer
Without the guard (parseMessage(text)), last line:
With { streaming: true }, last line:
OpenUI rule
Pass { streaming: true } to parseMessage while the response is still arriving, and the same isStreaming flag to the Renderer. The stock chat message and the reference RuntimeAssistantMessage both do this.
Why a custom AssistantMessage
When you give AgentInterface a componentLibrary and no components.AssistantMessage, it renders each reply with react-ui's stock GenUIAssistantMessage. That component does the right things for plain generated UI: it strips the markers, restores and saves state, and sends @ToAssistant clicks back as new user turns. It renders <Renderer> without a toolProvider. Any Query or Mutation in a chat reply therefore never calls anything, and the card shows its defaults with no error (the previous lesson's silent failure).
The way out is the components prop. A replacement AssistantMessage receives { message, isStreaming } and renders whatever you like. Because it replaces the stock one, it must do again everything the stock one did for you:
| Job | Stock message | Your replacement |
|---|---|---|
| Strip markers, honour streaming | yes | parseMessage(message.content, { streaming: isStreaming }) |
| Restore saved state | yes | pass context[0] as initialState |
| Save state on change | yes | onStateUpdate → updateMessage(…buildMessage(…)) |
Send @ToAssistant as a user turn | yes | onAction → processMessage |
Run Query and Mutation | no | toolProvider={…} |
OpenUI rule
Define the components object (and any extend()ed library) at module scope. AgentInterface memoizes on the identity of what you pass, so a new object on every render remounts every message and throws away its state. Also wrap AgentInterface in a sized container: its CSS assumes a full viewport.
The server-tool timeline (the rows that show which tools the model called while it worked) is drawn by AgentInterface outside the assistant message, so replacing the message component does not remove it.
Key idea
The toolProvider you pass here is what runs from the browser. Its tools are public endpoints: see the previous lesson for why they need their own authorization.
A whole thread, replayed Simulated
No model runs here. The replies are two recorded OpenUI Lang programs, streamed character by character, and the "server" is a script that picks the next recording. Everything else follows the chat flow of this lesson: the user turn goes in the thread, the reply streams into a Renderer, state changes are saved into the stored message, and a button with @ToAssistant adds a new user turn whose stored form carries the click and the form state as context. Press Send, switch to Fahrenheit, change the city, then click the button in the reply.
Thread
Stored messages
Simulated: replies are recordings, the tool is an in-page function, and rendering uses the course's teaching subset of @openuidev/react-lang. The real chat streams over HTTP through fetchLLM and an adapter, and real stored user turns for @ToAssistant are buildMessage({content: message, context: ["User clicked: …", formState]}), a two-element context.
Break it
Predict first. Tick Use the stock message and look at the weather card in the first reply. Then untick it. What differs, and which error do you get?
What should happen
With the stock message the card keeps its defaults (an empty city and 0°) while the controls still work. Nothing is reported: with no toolProvider the Query never runs, and no error is raised. Unticking remounts the thread with a provider and the card fills in. The second recorded reply (a comparison table) looks the same either way because its numbers are typed into the program, which is the server-tool snapshot from the previous lesson.
Quick check
What does the stream adapter in fetchLLM({ url, streamAdapter, messageFormat }) do?
messageFormat's job, and parsing OpenUI Lang belongs to the Renderer. The adapter only translates your route's wire format into the chat's common event vocabulary.A user switches a card to Fahrenheit and reloads the page. The chat uses the stock message format, but the card is back on Celsius. What was missing?
buildMessage, and on the next mount it reads the context back with parseMessage and passes it as initialState.Why does the reference chat replace the stock AssistantMessage?
toolProvider.Recap
- The chain is
AgentInterface→ChatProvider→fetchLLM(url, streamAdapter, messageFormat)→ your route → the model, and back through the stream adapter, which turns your wire format into AG-UI events. - Your route owns the system prompt and the model. The browser only posts the thread.
- A stored message is the program plus optional context behind
]]>openui:marker lines.buildMessagewrites it,parseMessagereads it, and the model never sees the markers. - State survives a reload when
onStateUpdatewrites the snapshot into the context and the next mount passes it asinitialState. While streaming, pass{ streaming: true }so a half-written marker is held back. - The stock assistant message gives the Renderer no
toolProvider. A customAssistantMessage, defined at module scope, adds it and must repeat the stock message's marker, state and action handling.