Skip to main content
chatJson<T>() combines a chat request with automatic JSON parsing and TypeScript typing. It wraps chat() and calls JSON.parse() on the response — if the model returns anything other than valid JSON, it throws a GatelitError.

JSON object mode

Use mode: "json_object" when you need valid JSON but don’t care about the exact shape:

JSON schema mode

Use mode: "json_schema" to enforce an exact shape. The gateway translates your schema to the provider’s native format — OpenAI structured outputs, Anthropic tool use, Google response schema, Mistral JSON mode:
The same code works across OpenAI, Anthropic, Google, and Mistral — no provider-specific format wrangling.

Handling non-JSON responses

If the model returns text that isn’t valid JSON, chatJson() throws a GatelitError with code "invalid_json":
For production use, prefer json_schema over json_object. Schema mode gives the provider more explicit guidance and produces more consistent results across models.

Streaming JSON

Streaming with structured output isn’t directly supported by chatJson(). Use stream() instead and accumulate the deltas, then parse the full result:
The gateway still enforces the schema on the provider-side, so the accumulated response should be valid JSON matching your schema.