Skip to content
← All writing
2026-06-11 · 24 min read ai-sdkarchitectureprovideragent

Build Your Own Mini Vercel AI SDK

Calling two providers' raw protocols hurts. Feel the pain first, then open the real SDK's layered design, then build a mini version with the same interface.

What you'll get from this article

This article was born out of two production incidents (a 50-second streaming freeze and a json_schema direct-call blowup). Both had the same class of root cause: not knowing what the SDK was doing for us beneath the abstraction. The fastest way to truly learn an abstraction layer is to hand-write the problem it solves. All code in this article runs for real in ai-sdk-streaming-lab.

One experimental setup note up front: DeepSeek officially exposes both an OpenAI-protocol endpoint (/chat/completions) and an Anthropic-protocol endpoint (/anthropic/v1/messages), and the same API key works for both. That means you can empirically test "two vendor dialects" without buying keys from two companies — every comparison experiment in this article relies on this.


Act One: streaming a model call without an SDK

Start with the most basic question: strip away every library — what does it actually take to stream a single LLM call with fetch?

Let's build it up step by step. Step one, sending the request, is easy:

const res = await fetch("https://api.deepseek.com/chat/completions", {
  method: "POST",
  headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
  body: JSON.stringify({
    model: "deepseek-v4-flash",
    stream: true, // ← the key bit: ask for streaming
    messages: [{ role: "user", content: "Explain what a protocol adapter layer is in one sentence" }],
  }),
});

Step two: with stream: true, you don't get JSON back — you get an SSE (Server-Sent Events) stream. SSE isn't mysterious: it's a text framing convention on top of HTTP chunked transfer, with events separated by blank lines. But "not mysterious" doesn't mean "no code to write" — you have to decode bytes yourself, split on newlines, and handle a line getting cut in half at a chunk boundary:

const reader = res.body!.getReader();
const decoder = new TextDecoder();
let buffer = "";
let text = "";
outer: while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  let i: number;
  while ((i = buffer.indexOf("\n")) >= 0) {        // split on newlines
    const line = buffer.slice(0, i).trim();
    buffer = buffer.slice(i + 1);
    if (!line.startsWith("data:")) continue;        // only accept data: lines
    const data = line.slice(5).trim();
    if (data === "[DONE]") break outer;             // end sentinel: a magic string
    const delta = JSON.parse(data).choices?.[0]?.delta;
    if (delta?.content) text += delta.content;      // the increments hide in choices[0].delta.content
  }
}
console.log(text);

Forty lines, just to stream one sentence. It works (this is exactly dialect A in lab experiment 05), and you can live with it — it's a one-time cost, right?


Act Two: a second provider = a second dialect

Now wire up a second provider. Send the same question to the Anthropic-protocol endpoint, and every layer changes:

const res = await fetch("https://api.deepseek.com/anthropic/v1/messages", {
  method: "POST",
  headers: {
    "content-type": "application/json",
    "x-api-key": apiKey,                  // ← auth changed: no Bearer, it's a custom header
    "anthropic-version": "2023-06-01",    // ← and you need a version header
  },
  body: JSON.stringify({
    model: "deepseek-v4-flash",
    stream: true,
    max_tokens: 512,                      // ← required here; omit it and you get an instant 400
    messages: [{ role: "user", content: "Explain what a protocol adapter layer is in one sentence" }],
  }),
});

The parsing layer needs a rewrite too. Anthropic's SSE uses named event: lines, and the content comes in a three-part shape — content_block_start opens a block, several content_block_delta events carry the increments, content_block_stop closes it. Text deltas hide in delta.text_delta.text, and the stream ends not with a [DONE] sentinel but with a message_stop event.

Run both dialects side by side (full code: npm run 05):

npm run 05 — same question, two dialects (real output excerpt)
# # Dialect A: OpenAI protocol
Raw frame: {"id":"05b2…","object":"chat.completion.chunk","choices":[{"delta":{"content":"A protocol"}}…
# # Dialect B: Anthropic protocol
Raw frame (message_start): {"type":"message_start","message":{"id":"278a…
Raw frame (content_block_delta): {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"A protocol"}}

The list of differences — and keep in mind, this is just for the single feature "stream one sentence":

SemanticsOpenAI dialectAnthropic dialect
AuthAuthorization: Bearerx-api-key + version header
Required params(none)max_tokens is mandatory
System prompta regular message with role:"system"top-level system parameter
SSE framingbare data: + [DONE] sentinelnamed event: + three-part content_block
Text deltaschoices[0].delta.contentcontent_block_delta.delta.text
Reasoning textreasoning_content (a field DeepSeek invented)protocol-native thinking content blocks

That last row deserves a pause. Dialects aren't just renamed fields — some semantics have no standard home at all in one dialect. The OpenAI protocol has no concept of "streaming reasoning text", so every vendor invents its own field (one of our production incidents crashed on exactly this).


Act Three: add tool calling, and the pain squares itself

Text streaming is just the appetizer. The real watershed is tool calling (a.k.a. function calling).

Key Concept

What tool calling really is

Models can't execute code. When a model "calls a tool", it is merely saying, in its output, "I'd like to invoke this tool with these arguments" — a structured statement of intent. Execution always happens in your code: you parse the intent → run the function → splice the result back into the conversation as a new message → call the model again. That model → tool → model cycle is the agent loop. The model makes decisions; you do the executing and the looping.

Once you see that, you can count the hand-written workload. For every provider, you write four things:

(1) Tool definitions are formatted differently. The same "check inventory" tool:

// OpenAI dialect: wrapped in a function shell, the schema field is called parameters
{ "type": "function", "function": { "name": "get_inventory", "description": "Look up product inventory", "parameters": { /* JSON Schema */ } } }

// Anthropic dialect: flat, the schema field is called input_schema
{ "name": "get_inventory", "description": "Look up product inventory", "input_schema": { /* JSON Schema */ } }

(2) Streaming argument assembly works differently. The arguments of a call intent stream out token by token, and the two sides fragment them in completely different shapes (these are real captured frames):

The same call intent get_inventory({sku:'MML-001'}), two fragmentations
# # OpenAI dialect: accumulate delta.tool_calls[].function.arguments by index
{"delta":{"tool_calls":[{"index":0,"id":"call_00_37Cv…","function":{"name":"get_inventory","arguments":""}}]}}
{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]}}
{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"sku"}}]}}
# # Anthropic dialect: three-part content_block + input_json_delta.partial_json
{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_00_UUI9…","name":"get_inventory"}}
{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\""}}

(3) Tool results go back in different places. OpenAI takes results as standalone role:"tool" messages (linked via tool_call_id); Anthropic has no tool role — results must masquerade as tool_result content blocks inside a user message.

(4) The loop itself. Maintaining conversation history, splicing model output and tool results back in each vendor's format, deciding "does the model want to continue?", guarding against infinite loops — this logic is vendor-agnostic, but you still have to write it.

Do the math: N providers × M features (streaming, tools, reasoning, multimodal, structured output...) means every combination is its own adapter. Three providers supporting four features is twelve copies of "Act One + Act Two + Act Three". That's the Tower of Babel.


Act Four: the AI SDK's answer — a few lines of code, and the architecture decision behind them

The same "check inventory → restock if below 10 → report" agent, written with the real SDK:

import { streamText, tool, stepCountIs } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
import { z } from "zod";

const deepseek = createOpenAI({ baseURL: "https://api.deepseek.com", apiKey });

const result = streamText({
  model: deepseek.chat("deepseek-v4-flash"), // ← swapping providers means changing only this value
  system: "You are an inventory assistant. Check stock first; if below 10 units, create a purchase order to restock to 50, then report back.",
  prompt: "Check the stock for MML-001; if it's below 10 units, restock to 50",
  tools: {
    get_inventory: tool({
      description: "Get the current stock count for a given SKU",
      inputSchema: z.object({ sku: z.string() }), // ← write it once, the SDK translates it into each dialect
      execute: async ({ sku }) => ({ sku, stock: 3 }),
    }),
  },
  stopWhen: stepCountIs(5), // ← step cap for the agent loop
});

The SSE parsing is gone, the dialects are gone, the loop is gone. Where did they go? Look at how the packages are layered:

The Vercel AI SDK's layers: one contract, translators on both sides

@ai-sdk/react
useChat / useObject: consume the stream on the frontend

UI layer (optional)

↓

ai (the core)
streamText / streamObject / agent loop / fixJson

The core only ever sees the unified intermediate representation; it knows no vendor

↓

@ai-sdk/provider
the LanguageModelV3 contract (almost pure type definitions)

The IR's definition: unified messages / unified tools / unified stream events

↓

@ai-sdk/openai
OpenAI dialect ↔ IR
→
@ai-sdk/anthropic
Anthropic dialect ↔ IR
→
@ai-sdk/deepseek …
one translator per vendor

Provider layer: each package = one bidirectional translator

This architecture rests on a single core decision: an intermediate representation.

Key Concept

Intermediate representation (IR)

In plain terms: a "relay format" that only circulates inside the system. Think of an interpreting team at an international conference. Instead of staffing one interpreter for every language pair — Chinese-to-French, German-to-Japanese — they agree that every speech gets translated into English first, then out of English. English is that team's intermediate representation. The unified messages, unified tools, and unified stream events defined by @ai-sdk/provider in the third layer above are, together, the AI SDK's "internal English".

Why does this deserve its own name? Do the math and it's obvious — compiler folks did this math decades ago. Compiling N programming languages to M CPU architectures with one bespoke compiler per combination is N×M units of work; switch to N "language → IR" frontends plus M "IR → machine code" backends, and it's only N+M. Same with the AI SDK: core features (the loop, stream transforms, JSON repair) are written once, against the IR; onboarding a new vendor only requires one "dialect ↔ IR" translator. That Act Three bill of 3 providers × 4 features = 12 adapters? This is how it gets erased.

The limits of unification: an IR unifies "phrasing", not "capability"

By now you should have a nagging question: some models can see images and some can't — if you stuff an image into the unified message format, can a contract conjure up a capability that doesn't exist?

It can't. What an IR can unify is different phrasings of the same semantics: reasoning and tool calling exist everywhere, they just look different, so translation flattens the difference. But whether a capability exists at all is beyond any format design. The real SDK is honest about this and handles it in three tiers:

SituationMechanismExample
Capability exists, only the phrasing differstranslate normallyimages: unified file parts → the OpenAI dialect's image_url content blocks
Capability missing, but not fataldegrade + warna model doesn't support system messages → drop it, and attach a warning to the stream's stream-start event, telling you openly
Capability simply doesn't existthrow on the spotfeed audio to a model with no audio support → throws UnsupportedFunctionalityError, never silently swallows it and pretends success

The contract even requires every model to declare its own capability boundary: the supportedUrls field announces which URLs the model can fetch itself; everything else gets downloaded to bytes by the SDK first. There's also an escape hatch — every layer of the contract (messages, tools, content blocks) carries a providerOptions passthrough field, so vendor-specific semantics the IR hasn't absorbed (say, one vendor's cache-control parameters) reach the right provider directly without polluting the unified format.

One sentence for this boundary: a translator can change the phrasing, but it can't grow new organs for the model. Our mini version cuts this entire layer (text-only support). The acceptance tests later pass only because the demo scenario happens to dodge capability differences — production won't, which is one more reason to use the real SDK there.


Act Five: opening the source — what the contract looks like

Don't take my word for it. Here are the real types from the @ai-sdk/provider package (excerpted, comments stripped):

// @ai-sdk/provider — a "provider" is simply an object implementing this interface
type LanguageModelV3 = {
  readonly specificationVersion: 'v3';
  readonly provider: string;
  readonly modelId: string;
  doGenerate(options: LanguageModelV3CallOptions): PromiseLike<LanguageModelV3GenerateResult>;
  doStream(options: LanguageModelV3CallOptions): PromiseLike<{
    stream: ReadableStream<LanguageModelV3StreamPart>; // ← the key: unified stream events
  }>;
};

// Unified stream events (excerpt): every vendor's output gets translated into these types
type LanguageModelV3StreamPart =
  | { type: 'text-start' | 'text-delta' | 'text-end'; /* … */ }
  | { type: 'reasoning-start' | 'reasoning-delta' | 'reasoning-end'; /* … */ }   // reasoning has a standard home!
  | { type: 'tool-input-start' | 'tool-input-delta' | 'tool-input-end'; /* … */ }
  | { type: 'finish'; usage: LanguageModelV3Usage; finishReason: /* … */ }
  | /* tool-call, error, source… */;

// Unified tool definition: standard JSON Schema, translated by each provider into its own field names
type LanguageModelV3FunctionTool = {
  type: 'function';
  name: string;
  description?: string;
  inputSchema: JSONSchema7;
};

Hold this against the Act Three pain list — every item is caught by this contract:

Pain (1) (tool formats): the core only knows inputSchema: JSONSchema7. @ai-sdk/openai's convertToOpenAIChatMessages plus its request builder wrap it into function.parameters; the Anthropic provider puts it into input_schema — translation in the request direction.

Pain (2) (argument fragments): translation in the response direction. Inside @ai-sdk/openai there's a TransformStream that accumulates the delta.tool_calls[].function.arguments fragments by index and emits unified tool-input-delta events; the moment the accumulated string becomes JSON.parse-able, it immediately emits a complete tool-call event (without waiting for the stream to end — saving a few hundred milliseconds). In the dist source this logic is called isParsableJson, and it's worth a read.

Pain (3) (result passback): the conversation history the core maintains is in unified format (role:"tool" + tool-result content blocks); before each request, the provider translates it into each vendor's splice format.

Pain (4) (the loop): inside the core's streamText / generateText is just a do-while (the skeleton, with telemetry and timeouts peeled away):

// the real loop from the ai package's dist source (simplified, skeleton preserved)
do {
  // call the model once; collect text / tool calls
  // execute client tools; splice assistant output + tool results back into responseMessages
} while (
  // there are tool calls and all of them have finished executing, and
  (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length) &&
  // the stop condition (default stepCountIs(1)) hasn't triggered yet
  !await isStopConditionMet({ stopConditions, steps })
);
💡

The loop is off by default — an easy design to trip over

The default value of stopWhen is stepCountIs(1): the model called a tool, the tool executed, but the SDK will not automatically feed the result back to the model. To get the full agent behavior — "model sees the tool result and continues" — you must explicitly allow more steps. Almost everyone using tools for the first time gets stuck here.


Act Six: write your own

With the architecture understood, write it once to verify the understanding. Goal: the same interface as the real SDK (streamText, stepCountIs, provider factory functions — same names, same shapes), with the edge handling cut and the full skeleton kept. Five files, about 400 lines:

FileReal SDK counterpartResponsibility
types.ts@ai-sdk/providerthe contract: unified messages / unified tools / unified stream events / doStream
sse.ts@ai-sdk/provider-utilsSSE parser (eats both framings)
openai-compatible.ts@ai-sdk/openaiOpenAI dialect ↔ IR
anthropic.ts@ai-sdk/anthropicAnthropic dialect ↔ IR
stream-text.tsai's streamTextthe core: the agent loop

The contract: 30 lines define the whole system

// mini-ai-sdk/types.ts (the core parts)
export type MiniMessage =
  | { role: "system"; content: string }
  | { role: "user"; content: string }
  | { role: "assistant"; content: Array<
      | { type: "text"; text: string }
      | { type: "tool-call"; toolCallId: string; toolName: string; input: unknown }
    > }
  | { role: "tool"; content: Array<{ type: "tool-result"; toolCallId: string; toolName: string; output: unknown }> };

export interface MiniToolDef {
  name: string;
  description: string;
  inputSchema: Record<string, unknown>; // standard JSON Schema, written once
}

export type MiniStreamPart =
  | { type: "text-delta"; delta: string }
  | { type: "reasoning-delta"; delta: string }   // reasoning has a standard home in the IR
  | { type: "tool-call"; toolCallId: string; toolName: string; input: unknown }
  | { type: "finish"; finishReason: "stop" | "tool-calls" | "length" | "other" }
  | { type: "error"; error: unknown };

export interface MiniLanguageModel {
  readonly provider: string;
  readonly modelId: string;
  doStream(options: { prompt: MiniMessage[]; tools?: MiniToolDef[]; maxTokens?: number }): AsyncGenerator<MiniStreamPart>;
}

Two notes. First, MiniStreamPart covers events a provider can produce; the core loop appends two events of its own on top — tool-result (the tool's execution result) and step-finish (end of a step) — together called MiniLoopPart. The contract covers "what the model said"; loop events cover "what we did on the model's behalf". Clean separation. Second, the real SDK uses ReadableStream instead of AsyncGenerator — it can tee (clone one stream into two independently consumed copies: one for the UI, one for the database) and it has backpressure (slow consumers throttle the producer instead of piling deltas up in memory until it blows). The mini version trades that for readability with generators.

Provider: one provider = two translations

Take the Anthropic version. The skeleton is just two passes. Translation (1), request direction — unified format → dialect:

// mini-ai-sdk/anthropic.ts (translation 1, excerpt)
const system = prompt.filter((m) => m.role === "system").map((m) => m.content).join("\n");
const messages = prompt.flatMap((msg) => {
  switch (msg.role) {
    case "system": return [];        // Anthropic's system is a top-level parameter, not a message
    case "user":   return [{ role: "user", content: msg.content }];
    case "assistant": return [{ role: "assistant", content: msg.content.map((p) =>
      p.type === "text"
        ? { type: "text", text: p.text }
        : { type: "tool_use", id: p.toolCallId, name: p.toolName, input: p.input }) }];
    case "tool":   // no tool role: results masquerade as tool_result blocks in a user message
      return [{ role: "user", content: msg.content.map((p) => ({
        type: "tool_result", tool_use_id: p.toolCallId, content: JSON.stringify(p.output) })) }];
  }
});
// tools translation: { name, description, input_schema: t.inputSchema }

Translation (2), response direction — dialect → unified stream events:

// mini-ai-sdk/anthropic.ts (translation 2, excerpt)
for await (const frame of parseSse(res.body)) {
  const ev = JSON.parse(frame.data);
  switch (ev.type) {
    case "content_block_start":
      blocks[ev.index] = { type: ev.content_block.type, id: ev.content_block.id, name: ev.content_block.name, json: "" };
      break;
    case "content_block_delta":
      if (ev.delta.type === "text_delta")        yield { type: "text-delta", delta: ev.delta.text };
      else if (ev.delta.type === "thinking_delta") yield { type: "reasoning-delta", delta: ev.delta.thinking };
      else if (ev.delta.type === "input_json_delta") blocks[ev.index].json += ev.delta.partial_json; // accumulate argument fragments
      break;
    case "content_block_stop": {
      const b = blocks[ev.index];
      if (b?.type === "tool_use")
        yield { type: "tool-call", toolCallId: b.id!, toolName: b.name!, input: JSON.parse(b.json || "{}") };
      break;
    }
  }
}

The OpenAI version (openai-compatible.ts) has the exact same structure, just with the OpenAI dialect in both translation passes. It also does one thing generic adapters don't: it translates DeepSeek's reasoning_content dialect into unified reasoning-delta events — the reasoning stream that got silently dropped in our earlier incident takes three lines to catch in a provider we own.

The core: a loop that only sees the IR

// mini-ai-sdk/stream-text.ts (skeleton; full version in the repo)
export async function* streamText({ model, system, prompt, tools = {}, stopWhen = stepCountIs(1) }) {
  const messages: MiniMessage[] = [/* system + user */];
  const toolDefs = Object.values(tools).map(({ execute, ...def }) => def); // the interface goes to the model; execution logic stays local

  let steps = 0;
  while (true) {
    steps++;
    const calls = [];
    for await (const part of model.doStream({ prompt: messages, tools: toolDefs })) {
      yield part;                                        // pass stream events through to the consumer
      if (part.type === "tool-call") calls.push(part);   // while keeping our own ledger
    }
    messages.push(/* assistant: this step's text + call intents */);
    if (calls.length === 0) return;                      // no call intent = the model gave its final answer

    for (const call of calls) {
      const output = await tools[call.toolName].execute(call.input);  // execution is in our hands
      yield { type: "tool-result", ...call, output };  // ← a loop-produced event (MiniLoopPart), not from the model
    }
    messages.push(/* role:"tool": all results */);           // splice back into the conversation, enter the next round
    if (stopWhen({ steps })) return;
  }
}

Notice that no trace of any vendor appears in this file — no fetch, no SSE, no field names. Everything it knows about model is the contract's doStream. That's the power of an intermediate representation.


Acceptance: swap providers in one line, run the same agent over both protocols

Text streaming (npm run 06) — zero changes to business code; swapping providers means changing only the model you pass in:

npm run 06 — real output
=== Dialect A: OpenAI protocol (provider: openai-compatible) ===
A protocol adapter layer is an intermediate layer that translates communication protocols between different systems or components…
=== Dialect B: Anthropic protocol (provider: anthropic) ===
A protocol adapter layer is an intermediate layer in communication systems that bridges different technical standards or interfaces…
Zero changes to business code. The protocol differences were entirely absorbed by the provider layer.

Tool-calling agent loop (npm run 07) — the tool's JSON Schema was written exactly once, and both protocols complete the three steps "check inventory → create purchase order → report":

npm run 07 — real output (OpenAI protocol; Anthropic protocol yields the same result)
Sure, let me check the inventory for MML-001 first.
⚙ model calls tool get_inventory({"sku":"MML-001"})
── step 1 finished ──
✓ tool returned {"sku":"MML-001","stock":3}
Current stock is only 3 units, below 10… I'll create a purchase order right away.
⚙ model calls tool create_purchase_order({"sku":"MML-001","quantity":47})
✓ tool returned {"orderId":"PO-20260611-001","sku":"MML-001","quantity":47}
Report: created purchase order PO-20260611-001 for 47 units; stock after restock is 50. ── step 3 finished ──

The model even did the arithmetic itself: 50 − 3 = 47. The whole loop runs inside our 80-line core, and neither dialect missed a beat.


Wrapping up: what we cut — and why it matters

The mini version handles the core scenarios, but every "cut edge case" is debt the real SDK pays off for you in production:

What we cutIts counterpart in the real SDKThe day in production you'll miss it
ReadableStream + teethe entire core pipelinethe day one stream must feed the UI, the database, and the logs simultaneously
Error retries / backoffmaxRetries + the APICallError hierarchythe day the vendor returns 429/503
Truncated-JSON repairfixJson / parsePartialJson (see the companion piece)the day you progressively render with streamObject
Multimodal / files / imagesthe contract's FilePart systemthe day product says "add image upload"
UI message stream protocoltoUIMessageStreamResponse + useChatthe day the chat UI needs to distinguish text/tools/steps
Provider registry / middlewarecreateProviderRegistry and friendsthe day you need config-driven model switching or uniform caching

So the conclusion is not "go write your own" — quite the opposite: use the real SDK in production, but carry this 400-line skeleton in your head. With it, you can answer these questions: why swapping providers is a one-line change (the IR); why reasoning streams get dropped (generic adapters don't translate dialects); why tools "get called but nothing happens"; and when an incident hits, which layer to lift open (request translation? response translation? the core loop?).

When is skipping the SDK genuinely right? Only two cases remain: one-off scripts to study a vendor's protocol itself (this article's experiment 05 is exactly that); or you call one fixed endpoint of one fixed vendor, it has an official SDK, and you will never switch. Everywhere else, N+M beats N×M, forever.


Iron rules

⚡ Iron Rule #1

An adapter layer is an intermediate representation: N×M becomes N+M

Write core features once, against the unified format; one bidirectional translator per vendor. To judge whether an AI SDK is any good, first check whether its IR covers the semantics you need (reasoning, tools, multimodal) — if a semantic has no home in the IR, no number of translators can save you.

⚡ Iron Rule #2

Tool calling has no magic: the model only emits intent; execution and looping are yours

An "agent" = the model streaming out call intents + you executing + splicing results back into the conversation + calling the model again, until the model stops asking for tools or stopWhen triggers. Remember stopWhen defaults to stepCountIs(1): without explicitly allowing more steps, the loop never spins.

⚡ Iron Rule #3

Use a mature SDK in production, but keep the hand-written skeleton in your head

Every edge we cut (retries, backpressure, JSON repair, multimodal) is debt production will collect, so don't roll your own; but write the skeleton once by hand, or when an incident strikes beneath the abstraction, you won't even know which layer to lift open.


Reproduce it yourself

git clone https://github.com/stanleyyylau/ai-sdk-streaming-lab
cd ai-sdk-streaming-lab && npm install
cp .env.example .env   # fill in a DeepSeek API key (platform.deepseek.com)
npm run 05   # Acts One & Two: hand-write both vendor dialects, feel the Tower of Babel
npm run 06   # Act Six: the mini SDK, swap providers in one line
npm run 07   # Act Six: tool-calling agent loop, three steps under each protocol

The mini SDK itself lives in the repo's mini-ai-sdk/ directory (5 files; comments mark which real SDK package each file corresponds to).

Companion pieces: "The 50-Second AI Streaming Freeze" tells the origin story of this mental model (a production incident); "streamObject Deep Dive" covers another chunk of value in the core — truncated-JSON repair and structured output's cross-vendor compatibility.