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
Usemode: "json_object" when you need valid JSON but don’t care about the exact shape:
JSON schema mode
Usemode: "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:
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 bychatJson(). Use stream() instead and accumulate the deltas, then parse the full result: