DEV Community

Cover image for One prompt layer, many models: keeping a multi-model chat UI stable when providers differ
ChatMax AI
ChatMax AI

Posted on AI-assisted

One prompt layer, many models: keeping a multi-model chat UI stable when providers differ

Shipping a chat product that lets people pick between frontier models looks like a UI problem. It is not. It is a normalization problem: every provider streams a slightly different event shape, reports usage at a different moment, and encodes tool calls its own way. If you let those differences leak into the UI, you end up with a dozen if (provider === ...) branches that break every time someone ships a new model.

This is the adapter layout we use to keep a multi-model chat interface stable, and the pitfalls that cost us the most debugging time.

The differences that actually bite

Most of the pain comes from five places:

Concern Typical variance across providers
Stream framing newline-delimited data: chunks; a final sentinel chunk (e.g. [DONE]); or whole-JSON chunks with their own envelope
System prompt a message with role system; or a separate top-level field outside the message array
Tool / function calls incremental JSON fragments spread across chunks; or one complete object per event
Usage accounting only in the final chunk; or in every chunk; or only via a separate endpoint
Stop reasons stop / end_turn / STOP / absent until the stream closes

None of these are hard individually. The problem is combinatorial: five axes multiplied by N providers, multiplied by every place in the client that reads the stream.

Normalize at the edge, once

The fix is a single internal event type. Everything downstream — the store, the renderer, the usage meter — only ever sees these four events:

type ChatEvent =
  | { type: "delta"; text: string }
  | { type: "tool_call"; id: string; name: string; args: unknown }
  | { type: "usage"; input: number; output: number }
  | { type: "done"; reason: "stop" | "length" | "tool" | "error" };

interface ModelAdapter {
  readonly id: string;
  readonly capabilities: Capabilities;
  stream(req: NormalizedRequest): AsyncIterable<ChatEvent>;
}

interface Capabilities {
  images: boolean;
  tools: boolean;
  maxOutputTokens: number;
  streaming: "sse" | "ndjson";
}
Enter fullscreen mode Exit fullscreen mode

Each provider gets one file that speaks its dialect and nothing else. The UI never learns the provider's name; it reads capability flags instead.

That last part matters more than it sounds. if (model.startsWith("claude")) is how a codebase rots. if (model.capabilities.images) is how it survives a model you have never heard of.

The SSE parser is where you will lose a day

Provider SSE streams do not respect chunk boundaries. A single network read can contain half an event, three events, or a comment line. The parser must buffer and only emit on a blank-line delimiter:

export function sseEvents(stream: ReadableStream<Uint8Array>) {
  const decoder = new TextDecoder();
  let buffer = "";

  return new ReadableStream<string>({
    async start(controller) {
      const reader = stream.getReader();
      for (;;) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        let boundary: number;
        while ((boundary = buffer.indexOf("\n\n")) !== -1) {
          const raw = buffer.slice(0, boundary);
          buffer = buffer.slice(boundary + 2);
          for (const line of raw.split("\n")) {
            if (!line.startsWith("data:")) continue;      // ignore comments / id fields
            const payload = line.slice(5).trim();
            if (payload === "[DONE]") return controller.close();
            if (payload) controller.enqueue(payload);
          }
        }
      }
      controller.close();
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

Two details that are easy to get wrong:

  • Comments keep connections alive. Providers send : ping lines to hold the socket open. A parser that treats every line as JSON will throw on them.
  • The sentinel is not always JSON. Some providers end with data: [DONE], others simply close the connection. Handle both, and treat "stream ended without done" as an error path, not a success.

Treat usage and latency as first-class

If you bill, rate-limit, or show a cost estimate, you cannot wait for the last chunk. Three rules that saved us a lot of support tickets:

  1. Emit usage as its own event, even if the provider reports it at the end. It keeps the UI decoupled from "how this provider happens to report tokens this quarter".
  2. Track time-to-first-token separately from total time. They fail differently: a slow first token is a routing problem, a slow total is a long generation.
  3. Record the raw stream in tests. Capture a real response per provider into a fixture file, then replay it through the parser in CI. Provider schema changes are silent otherwise — you find out from a user, not a test.
const fixture = await readFile(`fixtures/${provider}.sse`, "utf8");
const events = await collect(parseStream(new Response(fixture).body!));
expect(events.at(-1)).toEqual({ type: "done", reason: "stop" });
Enter fullscreen mode Exit fullscreen mode

Fallbacks belong in the registry, not the view

Models go down, get deprecated, or silently change behaviour. Keep a registry that maps a logical task ("fast chat", "long-form writing", "vision") to an ordered list of concrete models, and let the router walk that list on hard failures only:

const registry = {
  fastChat: ["small-model", "mid-model"],
  vision:   ["vision-model", "mid-model"],
  writing:  ["large-model", "mid-model"],
} as const;
Enter fullscreen mode Exit fullscreen mode

Two guardrails keep this honest:

  • Fall back on infrastructure errors only. Retrying on a content refusal produces the same refusal from the next model, twice as slowly.
  • Surface the substitution in the UI. Users who picked a specific model should know when they got a different one.

What this buys you

With the adapter in place, adding a model is one file and one registry line. A provider changing its stream envelope is one fixture failing in CI. The UI never sees a provider name, and the code path for "images not supported" is a capability check rather than a guess.

We build ChatMax AI — a workspace that puts chat and image models from several providers behind one interface — and this is the layer that keeps it from falling apart every time a new model ships. It runs in the browser and on iOS, which adds one more constraint worth mentioning: the same normalized event stream has to drive both an SSE connection on the web and a URLSession stream on mobile, so keep the adapters free of anything platform-specific.

If you are building something similar, the cheapest investment is the fixture set. Capture real streams early, and let the tests tell you when a provider quietly changes its dialect.

Top comments (0)