generateStructured<T> method
Future<T>
generateStructured<T>(
- ChatRequest request, {
- required String name,
- required JsonSchema schema,
- required T fromJson(
- JsonMap json
- AgenticContext? context,
Answers with a value conforming to schema.
Uses guaranteed structured output where the model supports it and falls
back to JSON mode where it does not, so the same call site works across
providers of different strengths. The answer is validated against schema
either way, so the fallback is weaker in cost — a possible retry — not in
correctness.
Implementation
Future<T> generateStructured<T>(
ChatRequest request, {
required String name,
required JsonSchema schema,
required T Function(JsonMap json) fromJson,
AgenticContext? context,
}) async {
final format = info.supports(ModelCapability.structuredOutput)
? ResponseFormat.jsonSchema(name: name, schema: schema)
: ResponseFormat.json;
final response = await generate(
request.copyWith(responseFormat: format),
context: context,
);
return response.decodeAs(fromJson, schema: schema);
}