generateObject (now deprecated) requests JSON mode from the provider (e.g. response_format: { type: "json_object" }), constraining the model to output valid JSON. Its documented replacement generateText + Output.object() does not — it parses free-form text client-side instead.
This causes two issues:
- Models that wrap JSON in markdown fences (
```json ... ```) fail to parse. extractJsonMiddleware() fixes this.
- Even with the middleware, models aren't constrained to produce schema-valid JSON, so validation failures are higher than with
generateObject.
Benchmark (20 runs, same prompt, same model):
| Approach |
Success |
generateObject |
20/20 |
generateText + Output.object() |
17/20 |
generateText + Output.object() + extractJsonMiddleware() |
17/20 |
import { generateText, Output, extractJsonMiddleware, wrapLanguageModel } from "ai";
import { z } from "zod";
const schema = z.object({
items: z.array(z.object({ name: z.string(), price: z.number() })).length(6),
});
// Fails ~15% — model wraps JSON in ```json fences or produces invalid output
const result = await generateText({
model: someOpenAICompatibleModel,
output: Output.object({ schema }),
prompt: "Generate 6 products for a store",
});
Expected: Output.object() should request JSON mode from the provider when available, matching generateObject reliability.
AI SDK Version: ai@6.0.81
generateObject(now deprecated) requests JSON mode from the provider (e.g.response_format: { type: "json_object" }), constraining the model to output valid JSON. Its documented replacementgenerateText+Output.object()does not — it parses free-form text client-side instead.This causes two issues:
```json ... ```) fail to parse.extractJsonMiddleware()fixes this.generateObject.Benchmark (20 runs, same prompt, same model):
generateObjectgenerateText+Output.object()generateText+Output.object()+extractJsonMiddleware()Expected:
Output.object()should request JSON mode from the provider when available, matchinggenerateObjectreliability.AI SDK Version:
ai@6.0.81