parseStructuredOutput<T> method

T parseStructuredOutput<T>(
  1. String text,
  2. T fromJson(
    1. Map<String, dynamic>
    )
)

Parse and validate structured output from generated text

Implementation

T parseStructuredOutput<T>(
    String text, T Function(Map<String, dynamic>) fromJson) {
  // Extract JSON from the response
  final jsonString = extractJSON(text);

  // Parse JSON
  try {
    final jsonData = jsonDecode(jsonString);

    if (jsonData is! Map<String, dynamic>) {
      throw StructuredOutputError.validationFailed(
        'Expected JSON object, got ${jsonData.runtimeType}',
      );
    }

    return fromJson(jsonData);
  } on FormatException catch (e) {
    throw StructuredOutputError.invalidJSON(
        'Invalid JSON format: ${e.message}');
  } catch (e) {
    throw StructuredOutputError.invalidJSON(e.toString());
  }
}