Typed Output

Because sometimes you need more than a string back from your AI.

Basic JSON

final result = await agent.send(
  'The windy city in the US of A',
  outputSchema: JsonSchema.create({
    'type': 'object',
    'properties': {
      'city': {'type': 'string'},
    },
    'required': ['city'],
  }),
);

print(result.output); // {"city":"Chicago"}

Parsed Map

final result = await agent.sendFor<Map<String, dynamic>>(
  'Name 3 colors that make you happy',
  outputSchema: JsonSchema.create({
    'type': 'object',
    'properties': {
      'colors': {
        'type': 'array',
        'items': {'type': 'string'},
      },
    },
    'required': ['colors'],
  }),
);

print(result.output['colors']); // ['sunshine yellow', 'ocean blue', 'grass green']

Custom Types

Here we're using a custom type to parse the JSON output via the outputFromJson parameter:

class Weather {
  final String city;
  final int temp;
  
  Weather.fromJson(Map<String, dynamic> json)
    : city = json['city'],
      temp = json['temp'];
}

final result = await agent.sendFor<Weather>(
  'How hot is it in the Big Apple right now?',
  outputSchema: JsonSchema.create({
    'type': 'object',
    'properties': {
      'city': {'type': 'string'},
      'temp': {'type': 'integer'},
    },
    'required': ['city', 'temp'],
  }),
  outputFromJson: Weather.fromJson,
);

print('${result.output.city}: ${result.output.temp}°F');

Schema Generation

Hand-writing schemas and JSON serialization is a lot of boilerplate. Consider using json_serializable and soti_schema to automate this:

// let's use the `soti_schema` package to generate the schema and JSON serialization
@SotiSchema()
@JsonSerializable()
class TownAndCountry {
  final String town;
  final String country;
  
  TownAndCountry({required this.town, required this.country});
  
  factory TownAndCountry.fromJson(Map<String, dynamic> json) =>
      _$TownAndCountryFromJson(json);
  
  @jsonSchema
  static Map<String, dynamic> get schemaMap => 
      _$TownAndCountrySchemaMap;
}

// now we pass the schema and JSON serialization to the agent and magic happens
final result = await agent.sendFor<TownAndCountry>(
  'What is the capital of France?',
  outputSchema: TownAndCountry.schema,
  outputFromJson: TownAndCountry.fromJson,
);

print('${result.output.town}, ${result.output.country}');

With Tools

// Typed output + tool calls in one request
final result = await agent.sendFor<Recipe>(
  'Get grandma\'s recipe for cookies',
  outputSchema: recipeSchema,
  outputFromJson: Recipe.fromJson,
  tools: [recipeLookupTool],
);

print('${result.output.name}: ${result.output.ingredients}');

Streaming

// Stream structured JSON
await for (final chunk in agent.sendStream(
  'List 3 facts',
  outputSchema: factsSchema,
)) {
  stdout.write(chunk.output); // Streams JSON chunks
}

Next Steps