parse method
Parses one raw generated turn into prose plus any tool calls.
Throws FormatException when the [TOOL_CALLS] body is not a valid JSON
array so the decoder can fall back to raw text.
Implementation
ParsedTurn parse(String generated) {
final at = generated.indexOf(toolCalls);
if (at < 0) {
return ParsedTurn(text: generated.trim(), calls: const []);
}
final text = generated.substring(0, at).trim();
final body = generated.substring(at + toolCalls.length).trim();
final decoded = jsonDecode(body);
if (decoded is! List) {
throw FormatException('Tool calls are not a JSON array', body);
}
final calls = <FunctionCallContent>[];
for (final entry in decoded) {
if (entry is! Map) {
throw FormatException('Tool call is not a JSON object', body);
}
final args = (entry['arguments'] ?? entry['parameters']) as Map?;
calls.add(
FunctionCallContent(
callId: 'call_${calls.length}',
name: entry['name'] as String? ?? '',
arguments: args?.cast<String, Object?>() ?? const <String, Object?>{},
),
);
}
return ParsedTurn(text: text, calls: calls);
}