You may be wondering why this is important, but a good and effective API contract for a WebSocket or SSE based system matters a lot. It gives both frontend and backend engineers the power to ship features at lightning speed while keeping things reliable.

Let's start with a naive design, then improve it step by step.

1. The naive design

I imagine the most basic events needed to show some sort of conversation with an LLM look like this.

The client sends a request event in this form:

{ "query": "Please pay my bills!" } 

And the LLM or AI agent responds with a series of chunks:

{ "res": "Yes, " } { "res": "Subscribe " } { "res": "to " } { "res": "list " } { "res": "of " } { "res": "videos" } 

Nice, we have built the bare bones of a conversation with AI.

But this has lots of problems when you look deeper. Let's ask it some non-functional questions.

2. Two requests at once: add a crid

What happens when two requests are sent? How will the client know which chunk belongs to which question?

This can be solved very easily by adding a unique id to every request. The client generates it, and the backend echoes it back on every response event. I call it crid in this post, short for client_request_id, which is what the field is called in real code. If the client forgets to send one, the backend generates one (req_<timestamp>), so every event still has it.

Now our contract looks like this.

Request:

{ "query": "Please pay my bills!", "crid": "123" } 

Response:

{ "res": "Yes, ", "crid": "123" } { "res": "Subscribe ", "crid": "123" } { "res": "to ", "crid": "123" } { "res": "list ", "crid": "123" } { "res": "of ", "crid": "123" } { "res": "videos", "crid": "123" } 

Now your client can easily keep track of every query sent to your AI agent, and show the reply under the right question.

3. What happens in case of an error?

There can be many types of errors. To keep this blog from biting your head off, I will only focus on response errors. Like your AI agent starts going haywire. Oops, what to do now?

Let's improve our response event and add a simple type to it. From here on, every event has the same shape: { "type", "crid", ... }.

{ "type": "answer_chunk", "crid": "123", "content": "Yes, " } { "type": "answer_chunk", "crid": "123", "content": "Subscribe " } { "type": "error", "crid": "123", "error_type": "processing_error", "message": "Something went wrong while answering.", "details": "Timeout exceeded", "timestamp": 1730384402.123 } { "type": "response_end", "crid": "123", "status": "error" } 

With the introduction of type, your response events become extensible. The error event now tells the client three useful things:

  • error_type is the category (tool_execution_error, processing_error, validation_error). The client can branch on it.
  • message is for humans. You can show it as is.
  • details is for engineers. Log it, don't show it.

Two rules make errors boring, which is what you want. First, an error can arrive at any point: before the agent thinks, in the middle of a tool call, halfway through the answer. The client must not assume it only comes at the end. Second, an error is always followed by response_end with "status": "error". So the client has one place to stop spinners and close the message, whether things went well or not.

You will see later that every piece of content arrives as a _start, chunks and an _end. error is the one event that stays a single shot, on purpose: it is not content to render bit by bit, it is a control signal that ends the response.

4. Showing thinking and reasoning

Modern agents do work before they answer: they search, call tools, plan. Users hate a blank screen, so show them what is going on.

The pattern I have used in production is a small bracket of events:

{ "type": "processing_start", "crid": "123", "query": "Please pay my bills!", "timestamp": 1730384400.123 } { "type": "thinking_start", "crid": "123" } { "type": "thinking_chunk", "crid": "123", "content": "Looking up your pending bills", "contentType": "str" } { "type": "thinking_chunk", "crid": "123", "content": "Found 3 bills due this week", "contentType": "str" } { "type": "thinking_end", "crid": "123" } { "type": "processing_end", "crid": "123", "duration_ms": 3111, "status": "success" } 

thinking_start opens the thinking, thinking_chunk can arrive zero or many times, and thinking_end closes it. On the UI, render it as a single collapsible status line. While processing is open, the line shows the latest content with a spinner. On processing_end, it collapses into "Thought for 3s" (straight from duration_ms), and the user can expand it to see every step.

Notice content and contentType. Every event that carries something to render uses this same pair. Today contentType is always "str", but the day you want to send markdown or a structured card, the client already knows where to look.

The frontend never has to guess when thinking is over. The backend says so.

5. Tool calls

Thinking is only half of the processing phase. The other half is the agent calling tools: searching bills, fetching a balance, hitting your payments API. Users like to see this too.

Every tool call gets its own bracket inside processing. It opens when the agent fires the call and closes when the result is back:

{ "type": "tool_call_start", "crid": "123", "call_id": "call-1", "tool": "get_pending_bills" } { "type": "tool_call_end", "crid": "123", "call_id": "call-1", "status": "ok", "content": "{\"bills\":3,\"total\":240}", "contentType": "str" } 

The important field here is call_id. An agent can fire several tools at once, and the results come back in whatever order they finish. crid tells you which question a tool belongs to. call_id tells you which result belongs to which call. Same idea as crid, one level down.

On the UI, tool_call_start adds a row like "Calling get_pending_bills" with a spinner, and the tool_call_end with the same call_id ticks it off. status is ok or error, so one failed tool marks its own row and nothing else. The result travels as stringified JSON in content, so the event shape stays flat and the same as every other content event.

6. Response blocks

A real reply is more than one stream of text. You might have the answer, a follow-up question, a list of videos and a few suggested questions. If you push all of that through one answer_chunk type, the client ends up parsing text to find out what is what. Don't.

Instead, split the reply into blocks, and give every block the same lifecycle:

<block>_start -> <block>_chunk* -> <block>_end 

That is the whole rule. Any block, today or next year, is <name>_start, then zero or more chunks, then <name>_end. thinking and tool_call from the last two sections already follow it. The reply blocks I started with are answer and followup, and the whole reply is wrapped by response_start and response_end:

{ "type": "response_start", "crid": "123" } { "type": "answer_start", "crid": "123" } { "type": "answer_chunk", "crid": "123", "content": "You have ", "contentType": "str" } { "type": "answer_chunk", "crid": "123", "content": "3 bills due.", "contentType": "str" } { "type": "answer_end", "crid": "123", "full_answer": "You have 3 bills due.", "tools_used": ["get_pending_bills"] } { "type": "response_end", "crid": "123", "status": "success" } 

response_start is the very first event the client sees for a request, before processing even begins. response_end is the very last, with a status of success or error. The client keeps the same status on its own message object: streaming while events flow, then whatever response_end says.

Each chunk carries only the new piece in content. The client appends it.

Why the end event carries the full answer

answer_end repeats the whole answer in full_answer. It looks wasteful, but it saves you in two common cases:

  • A dropped chunk. If you only append chunks and one gets lost, the text is corrupt. On answer_end, the client replaces what it built with full_answer, and the screen is correct again.
  • A reconnect. The client comes back halfway through and missed some chunks. It does not need to replay history. It shows what it has, and answer_end fills in the truth.

So the rule on the client is simple: append while streaming, reconcile at the end. Chunks are for the typing effect. The end event is the source of truth. followup_end does the same with a followup field.

tools_used rides along on answer_end too. It is a cheap way to show "Answered using: get_pending_bills" under the message, without the client keeping its own list.

One rule, one reducer

Because every block follows the same pattern, the client never needs a special parser per block. It splits the event type on the last underscore into a block name and a phase, tracks which blocks are open, and lets a single switch fill in the payload. Same shape, same lifecycle, different payload.

The real test of a rule is whether it stretches. So let's add a block that answer text cannot carry: a React component.

Extending it: a block that renders a component

Say the agent searched for videos and wants to show them as cards, not as a markdown list. The backend sends a component block. It names the component, hands it starting props, streams changes to those props, and closes with the final props:

{ "type": "component_start", "crid": "123", "block_id": "block_1", "component": "VideoList", "props": { "videos": [], "loading": true } } { "type": "component_chunk", "crid": "123", "block_id": "block_1", "delta": { "videos": [{ "title": "Sourdough from scratch", "channel": "Slow Kitchen", "duration": "14:02" }] } } { "type": "component_end", "crid": "123", "block_id": "block_1", "props": { "videos": [{ "title": "Sourdough from scratch", "channel": "Slow Kitchen", "duration": "14:02" }], "loading": false } } 

delta is a JSON merge patch onto the current props: keys in the patch overwrite, null deletes, and arrays replace whole instead of merging. That last part keeps the client dumb. It never has to guess whether a list item is new or an edit. And component_end carries the full props, for the same reason answer_end carries full_answer: if a chunk got lost, the end event puts the card right.

block_id does for components what call_id did for tools: two VideoList blocks in one reply stay apart. On the client this is three more cases in the same reducer. Nothing else changes:

const { block, phase } = splitEventType(event.type) // block_id / call_id keep parallel instances of the same block kind apart const instanceId = event.block_id ?? event.call_id const blockKey = instanceId ? `${block}:${instanceId}` : block const setProps = (blockId: string, toProps: (props: Props) => Props, done = false) => next.components.map((rendered) => (rendered.block_id === blockId ? { ...rendered, props: toProps(rendered.props), done } : rendered)) switch (event.type) { case 'component_start': return { ...next, components: [...next.components, { block_id: event.block_id, component: event.component, props: event.props ?? {}, done: false }], } case 'component_chunk': return { ...next, components: setProps(event.block_id, (props) => mergePatch(props, event.delta)) } case 'component_end': // the end props are the truth, same as full_answer return { ...next, components: setProps(event.block_id, () => event.props, true) } } 

mergePatch is the ten-line RFC 7396 function: walk the patch, delete on null, recurse into plain objects, copy everything else as is.

The backend only sends a name. The client owns the mapping from name to component, in a plain registry, with a fallback for names it has never heard of:

export const componentRegistry: Record<string, ComponentType<any>> = { VideoList } export function UnknownComponent({ name }: { name: string }) { return ( <div className="unknown-component" role="note"> No renderer for <code>{name}</code>. The answer above still stands. </div> ) } // in the message bubble {state.components.map((rendered) => { const Renderer = componentRegistry[rendered.component] return Renderer ? <Renderer key={rendered.block_id} {...rendered.props} /> : <UnknownComponent key={rendered.block_id} name={rendered.component} /> })} 

If the backend ships a PriceChart before the frontend knows it, the user sees a quiet note under a correct answer, not a crash.

Suggestions: a second extension

Suggested questions are the same move again. My first draft sent them as one single suggestions event with a questions array, and that broke the one rule this section is built on. So now they get the full lifecycle, one question per chunk:

{ "type": "suggestions_start", "crid": "123", "block_id": "block_3" } { "type": "suggestions_chunk", "crid": "123", "block_id": "block_3", "content": "How do I feed a starter?" } { "type": "suggestions_chunk", "crid": "123", "block_id": "block_3", "content": "Can I bake it the same day?" } { "type": "suggestions_end", "crid": "123", "block_id": "block_3", "questions": ["How do I feed a starter?", "Can I bake it the same day?"] } 

Each chunk adds one button as it arrives. suggestions_end carries the whole list and wins, same reason as full_answer on answer_end. One more block name in the same reducer, one row of buttons under the message.

A harder scenario: the backend picks the layout

The bills example is polite: one tool, one block, everything in order. Real traffic is not. Here is "How did the bakery do this month?", trimmed to the events that matter:

{ "type": "response_start", "crid": "789" } { "type": "processing_start", "crid": "789", "query": "How did the bakery do this month?" } { "type": "tool_call_start", "crid": "789", "call_id": "call-1", "tool": "fetch_sales" } { "type": "tool_call_start", "crid": "789", "call_id": "call-2", "tool": "fetch_products" } { "type": "tool_call_start", "crid": "789", "call_id": "call-3", "tool": "fetch_reviews" } { "type": "tool_call_end", "crid": "789", "call_id": "call-2", "status": "ok", "content": "12 products", "contentType": "str" } { "type": "tool_call_end", "crid": "789", "call_id": "call-3", "status": "error", "content": "reviews timed out", "contentType": "str" } { "type": "tool_call_end", "crid": "789", "call_id": "call-1", "status": "ok", "content": "30 days of sales", "contentType": "str" } { "type": "processing_end", "crid": "789", "status": "success" } { "type": "answer_start", "crid": "789" } { "type": "component_start", "crid": "789", "block_id": "block_1", "component": "SalesDashboard", "props": { "title": "November", "kpis": [], "slots": { "trend": { "component": "LineChart", "props": { "x": "week", "y": "revenue", "data": [] } }, "top": { "component": "BarChart", "props": { "x": "product", "y": "units", "data": [] } } } } } { "type": "answer_chunk", "crid": "789", "content": "Revenue is up 12% on October. ", "contentType": "str" } { "type": "component_chunk", "crid": "789", "block_id": "block_1", "delta": { "kpis": [{ "label": "Revenue", "value": "$18,400", "change": "+12%" }, { "label": "Orders", "value": "1,240", "change": "+8%" }] } } { "type": "component_chunk", "crid": "789", "block_id": "block_1", "delta": { "slots": { "trend": { "props": { "data": [{ "week": "W1", "revenue": 3900 }, { "week": "W2", "revenue": 4300 }] } } } } } { "type": "answer_chunk", "crid": "789", "content": "Week 4 was the best week, and croissants led. ", "contentType": "str" } { "type": "component_chunk", "crid": "789", "block_id": "block_1", "delta": { "slots": { "trend": { "props": { "data": [{ "week": "W1", "revenue": 3900 }, { "week": "W2", "revenue": 4300 }, { "week": "W3", "revenue": 4700 }, { "week": "W4", "revenue...
Source:https://dev.to/ashwani_arya_/how-to-design-a-good-conversational-ui-backend-contract-1nan