By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The agent loop ends when it has produced a final answer. The chat surface is what the customer actually uses, and it has its own contract: text has to appear while it is being generated, every claim that came from a document has to link to that document, and a thumbs-down has to arrive attached to enough evidence to reproduce the failure.
Earlier lessons covered streaming and the trace fields. This lesson treats those outputs as an interface with a version, a small set of events and a written rule for every failure. The event list in the snippet is a scripted fixture, so you can assemble it without a model call and without an API key.
Do not render raw provider chunks. Translate them once, on the server, into a small versioned stream that the client can consume without knowing which model ran. Six event types cover Harbor Helper's surface.
| Event | What it carries | What the surface must do |
|---|---|---|
message_start | The trace id and prompt version for the new answer | Create the message bubble, keep the trace id and show a stop control |
token | A piece of visible text | Append it in order and keep a plain-text buffer for copy and screen readers |
citation | A document id and the span the model claims it supports | Resolve the id server-side; render a link only when it resolves |
tool_call | A read-only or approval-gated tool call in progress | Show a neutral status and never echo raw arguments that may contain PII |
message_end | The final status: complete, stopped or truncated | Freeze the text, persist the message id and attach the feedback controls |
error | A failure after some text has already been sent | Keep the partial text marked incomplete and offer one retry, not a loop |
The stream is versioned and additive: /v1/chat/stream may gain a field, but an existing event never changes shape. That is what lets the web and mobile clients ship independently of a backend deploy.
A citation is a claim about provenance, so it is only worth showing if the server can check it. The model proposes a document id and a span; the server confirms that the document was retrieved for this request and that the span exists. An id that does not resolve is a signal, not a link.
Three failures are worth handling explicitly. The model can cite a real document that was not retrieved (a provenance lie), cite a plausible id that does not exist (a fabrication), or give the right document with the wrong span (a sloppy quote). Resolution catches the first two; storing the span and highlighting only matched text catches the third.
"""Assemble a scripted event stream into a chat-surface message."""
import json
SOURCES = {
"doc-returns": "Returns and refunds policy",
"doc-shipping": "Shipping windows",
}
EVENTS = [
'{"seq": 1, "type": "message_start", "trace_id": "tr-9f2a"}',
'{"seq": 2, "type": "token", "text": "Orders "}',
'{"seq": 3, "type": "token", "text": "ship in "}',
'{"seq": 4, "type": "citation", "doc_id": "doc-shipping", "span": "2-3 days"}',
'{"seq": 5, "type": "token", "text": "2-3 business days."}',
'{"seq": 6, "type": "citation", "doc_id": "doc-invented", "span": "free returns"}',
'{"seq": 7, "type": "message_end", "status": "complete"}',
]
def assemble(events):
text, citations, trace_id = "", [], None
for raw in events:
event = json.loads(raw)
kind = event["type"]
if kind == "message_start":
trace_id = event["trace_id"]
elif kind == "token":
text += event["text"]
elif kind == "citation":
citations.append(
{"doc_id": event["doc_id"], "resolved": SOURCES.get(event["doc_id"])}
)
return trace_id, text, citations
trace_id, text, citations = assemble(EVENTS)
print("trace:", trace_id)
print("text:", text)
print("citations:", len(citations), "received")
for citation in citations:
label = citation["resolved"] or "UNRESOLVED - do not render a link"
print(f" {citation['doc_id']}: {label}")
print("feedback:", {"trace_id": trace_id, "rating": "up", "prompt_version": "v12"})The fixture contains one invented citation. The assembler keeps it in the diagnostic list but marks it unresolved, and a client would render no link for it. Silently dropping it hides a model defect; rendering it as a link teaches the customer to trust a source that never existed.
A thumbs-down on its own is an anecdote. A thumbs-down with the trace id, the prompt version, the message id and the citation resolution list is a bug report. Collect the same identifiers the trace has, keep the comment optional, and route negative feedback the same day.
A dropped connection is normal on mobile. Sequence numbers on events let the client ask for a resume; the server re-sends the missing events from a short-lived buffer, or returns the final message by id if the run already finished. Never re-run the agent to recover a display problem: that can repeat a tool call and a cost.
seq, and the client reconnects with the last one it applied.Read the output as a checklist: the trace id arrives on the first event, the text is the concatenation of every token event in order, and the unresolved citation is visible in diagnostics but would not be rendered as a link. Those three checks are exactly the assertions a chat-surface test should make against the same fixture, which keeps the surface testable with no provider and no browser.
Key takeaways
A chat surface is an interface with its own contract: versioned events, resolvable citations and feedback that carries the trace id.
Translate provider chunks into a small event stream once, on the server, so clients never depend on a model wire format.
Resolve citations against the retrieved set before rendering; an unresolved id is evidence of a model defect, not a link.
Store feedback with the message id, trace id and prompt version, and treat it as triage evidence rather than training data.
Resume a dropped stream from sequence numbers and fetch the final message by id instead of re-running the agent.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.