What you'll get out of this post
- A mechanism explained: JSON is flat-out invalid until it's fully streamed, so how do
streamObject/useObjectpull off progressive parsing? (fixJson's repair-then-parse trick) - Two engineering rules: which parts of a streamed "partial object" you can use, and which you absolutely cannot
- A copy-paste fix: the root cause and complete solution for the
This response_format type is unavailable nowerror (downgrade + schema injection)
This is the second half of the same production incident as The 50-Second AI Streaming Freeze, but it stands on its own. Every claim here is reproducible in ai-sdk-streaming-lab — and the partial-JSON experiment needs no API key; clone it and it runs.
Background: the code that broke, and two natural enemies
The feature is an AI summary for sales follow-up notes in a CRM: a rep pastes in a meeting transcript, and the AI streams back structured JSON (a 150-character summary plus a todo list). Here's the full server-side code:
// app/api/notes/analyze/route.ts — Next.js + Vercel AI SDK
import { streamObject } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
import { z } from "zod";
// At launch, baseURL pointed at the AiHubMix gateway (a multi-model
// aggregator that speaks the OpenAI protocol). The fuse for the incident
// in this post is buried in this one line of config.
const deepseek = createOpenAI({
baseURL: "https://aihubmix.com/v1",
apiKey: process.env.AIHUBMIX_API_KEY!,
});
const noteSchema = z.object({
summary: z.string().describe("Summary, 150 characters max"),
todos: z.array(
z.object({
action: z.string(),
dueDate: z.string().nullable().describe("YYYY-MM-DD or null"),
}),
),
});
export async function POST(req: Request) {
const { content } = await req.json();
const result = streamObject({
model: deepseek.chat("deepseek-v4-pro"),
schema: noteSchema, // ← hand it a zod schema; the model streams back JSON that matches it
system: "You are a CRM assistant. Extract a summary and todos from sales follow-up notes.",
prompt: content,
});
return result.toTextStreamResponse();
}
For the timeline (same one as the companion post): the feature launched on the AiHubMix gateway → after closing out the first half's "streaming freeze" incident, we switched baseURL to DeepSeek's official endpoint — driven by time-to-first-token, cost, and unease about the gateway being a black box. One line of config changed. That line is the fuse for everything that blows up in this post.
With the code on the table, let's start with the conceptual problem from the first half: streaming and JSON are natural enemies.
Key Concept
Structured Output
Instead of free-form text, the model emits JSON conforming to a given schema. In the AI SDK this is streamObject({ schema }) — exactly the usage in the code above.
Here's the tension: streaming means text arrives a little at a time, but JSON is a format that's either valid as a whole or not valid at all. A half-finished fragment like {"summary":"Met with the cli makes JSON.parse throw immediately. Intuitively this shouldn't be possible — and yet the matching useObject hook on the frontend really does render the object progressively. How?
First, let's clear up a common point of confusion. Under the hood, streamObject sends an HTTP request to the provider's API, and the request body contains two fields that both look output-related but have nothing to do with each other:
| Parameter | What it controls | Relationship to streaming |
|---|---|---|
stream: true | How the response is delivered: all at once vs. token by token | This is the actual streaming switch |
response_format | What shape the model generates: constrains output to JSON | Zero relationship to streaming |
response_format comes in two tiers: json_object (loose — "just give me valid JSON") and json_schema (strict — "it must conform to this schema"). Keep these two tiers in mind; they're what explodes in the second half.
First half: how do you parse half-finished JSON?
Symptom: the object "grows" into shape
You can consume streamObject's return value right on the server instead of (or in addition to) forwarding it to the browser — and every partial frame is a directly usable JS object:
const result = streamObject({ model: deepseek.chat("deepseek-v4-pro"), schema: noteSchema, system, prompt });
for await (const partial of result.partialObjectStream) {
console.log(partial); // {} → {summary:"Met"} → {summary:"Met with…", todos:[{}]} → …
}
The object that useObject hands you on the frontend is the same progressive sequence:
import { experimental_useObject as useObject } from "@ai-sdk/react";
const { object, submit, isLoading } = useObject({
api: "/api/notes/analyze",
schema: noteSchema,
});
// object?.summary grows from "Met" into the full summary — bind it straight to the UI
Mechanism: never parse directly — repair first, then parse, every frame
The answer is parsePartialJson, exported from the ai package. Every time useObject receives a delta, it runs this loop:
// Inside @ai-sdk/react's useObject (actual source logic, not pseudocode)
accumulatedText += chunk; // ① accumulate all text received so far
const { value } = await parsePartialJson(accumulatedText); // ② repair + parse
setObject(value); // ③ update React state → re-render
// Inside parsePartialJson:
result = safeParseJSON({ text }); // try strict parsing first
if (!result.success)
result = safeParseJSON({ text: fixJson(text) }); // failed → repair, then retry
fixJson is a roughly 300-line state machine: it scans character by character, using a stack to track "what's still open right now" (string quotes, object braces, array brackets...), and when it hits the end, it closes everything that's still owed in one go. Run lab experiment 03 (no key needed) to watch it work:
That "typewriter effect rendering an object" you see in the UI is just dozens of repair → parse → diff → re-render cycles per second.
Two non-negotiable engineering rules follow from this
Look at the red line in that output: "dueDate":"20" — a value that looks valid but is actually half-finished. Which leads to:
| Rule | Why |
|---|---|
| Mid-stream objects are for display only — never persist or act on them | Any field can be truncated at any moment: a date cut in half, an array missing its tail, a sentence that isn't done |
| After the stream ends, you must run strict schema validation | Repair-parsing only guarantees "this is valid JSON" — not "this matches your schema" |
useObject builds the second rule in: when the stream ends, it validates against your schema with safeValidateTypes, and if validation fails, it gives you onFinish({ object: undefined }). So the correct way to persist looks like this:
useObject({
api, schema,
onFinish: ({ object }) => {
if (!object) return saveRawFallback(); // validation failed → fall back to storing the raw text
saveToDatabase(object); // only a validated object earns a database write
},
});
Second half: json_schema blows up on the official endpoint
Symptom: switch to the direct endpoint, structured output dies on the spot
The first half's mechanics ran fine on the AiHubMix gateway. As mentioned in the background, we later switched baseURL from the gateway to DeepSeek's official endpoint to cut costs — one config change, same code, and it immediately threw:
Diagnosis: the gateway had been quietly absorbing the difference all along
By default, streamObject compiles your zod schema into the strict tier and ships it: response_format: { type: "json_schema", json_schema: {...} }. The two endpoints treat it completely differently:
Same request, two fates
The gateway's well-meaning compatibility made 'tests pass' and 'works direct' two different things
Full disclosure: we never captured the request the gateway forwarded upstream, so we can't prove exactly what it did (translate json_schema into something the upstream understands? Strip the field entirely?). What we can prove is the behavioral difference: same request, no error through the gateway, 400 on the direct connection. And that's enough to make the point — your "tests pass" may be the result of a middle layer quietly covering for you.
There's a sneaky follow-on trap too: AI SDK v6 does not inject the schema into the prompt — the schema travels only via response_format. (We grepped streamObject's prompt construction in the ai package's dist source to confirm there's no injection logic; older versions' JSON mode behaved differently.) So if you naively change json_schema to json_object, the model no longer knows the exact field names. The downgrade must come paired with schema injection.
Fix: downgrade + inject inside a custom fetch
The complete fix (case B in lab experiment 04 — safe to copy straight into production):
const fixingFetch: typeof fetch = async (input, init) => {
const body = typeof init?.body === "string" ? init.body : null;
if (!body) return fetch(input, init);
const payload = JSON.parse(body) as Record<string, unknown>;
// thinking: disabled is the fix for the first half's freeze incident — see the companion post.
// This post's protagonist is response_format below.
const next: Record<string, unknown> = { ...payload, thinking: { type: "disabled" } };
const rf = payload.response_format as
| { type?: string; json_schema?: { schema?: unknown } }
| undefined;
if (rf?.type === "json_schema") {
next.response_format = { type: "json_object" }; // ① downgrade to the loose tier the official API supports
const schema = rf.json_schema?.schema;
if (schema && Array.isArray(payload.messages)) { // ② inject the schema into the system message
const messages = [...(payload.messages as Array<{ role?: string; content?: unknown }>)];
const instruction = `\n\nYour output must be a single JSON object conforming to this JSON Schema:\n${JSON.stringify(schema)}`;
const i = messages.findIndex((m) => m?.role === "system" && typeof m.content === "string");
if (i >= 0) messages[i] = { ...messages[i], content: `${messages[i].content}${instruction}` };
else messages.unshift({ role: "system", content: instruction.trim() });
next.messages = messages;
}
}
return fetch(input, { ...init, body: JSON.stringify(next) });
};
const deepseek = createOpenAI({
baseURL: "https://api.deepseek.com",
apiKey,
fetch: fixingFetch, // ← once this is attached, streamObject works as-is
});
The same code's output after the fix (real run log):
When consuming streamObject, handle errors via fullStream
On an upstream 4xx, for await (… of result.partialObjectStream) yields zero frames and never surfaces the error reason — your script just hangs on an unsettled await. Use result.fullStream instead: the error arrives as a { type: "error" } event in the stream, and the stream ends cleanly. We hit this trap while writing this very post; experiment 04's code is the fixed version.
Easter egg: the lab deliberately leaves a hallucination in
Experiment 04's prompt never tells the model today's date, so you'll see it resolve "next Monday" to some day in 2023. Production code must inject the current date (with timezone and day of week) into the system prompt — that's the only way relative-date math comes out right.
Iron rules
⚡ Iron Rule #1
Mid-stream objects: display yes, trust no
fixJson makes every frame of half-finished JSON parseable — at the cost that any field may briefly exist as dirty data ("dueDate":"20"). Render it freely; but persisting, triggering side effects, or making decisions must wait until the stream ends and strict schema validation passes.
⚡ Iron Rule #2
response_format has nothing to do with streaming — and everything to do with the vendor
stream controls transport; response_format controls output shape. json_schema is OpenAI's strict tier, and not every "OpenAI-compatible" endpoint supports it — your gateway may be translating on your behalf. Before switching to a direct connection, check every request parameter against the target vendor's official docs.
⚡ Iron Rule #3
Downgrading to json_object means injecting the schema yourself
AI SDK v6 no longer writes the schema into the prompt. Change only the response_format type and the model has no idea what your field names are — the downgrade and the injection are a paired move; skip either one and you've got a silent quality incident.
Reproduce it yourself
git clone https://github.com/stanleyyylau/ai-sdk-streaming-lab
cd ai-sdk-streaming-lab && npm install
npm run 03 # partial-JSON repair, frame by frame (no API key needed — runs right after clone)
cp .env.example .env # add your DeepSeek API key; 04 needs it
npm run 04 # json_schema blowing up + the fixed version, side by side
For the first half of this incident (the two-hop architecture, the thinking-induced freeze, the TTFB diagnostic method), see The 50-Second AI Streaming Freeze: A Full Production Postmortem. To understand the SDK's entire layered architecture underneath streamObject, see Build Your Own Mini Vercel AI SDK.