repairStreamToolCalls function

Stream<Map<String, dynamic>> repairStreamToolCalls(
  1. Stream<Map<String, dynamic>> parts,
  2. Object prompt,
  3. GenerateTextOptions? options
)

Replace every invalid ToolCall part of parts with its repaired version.

Returns parts unchanged when options.repairToolCall is null. Every other part — tool-input deltas included — passes through untouched and in order (the AI SDK never holds argument deltas back), which asyncMap guarantees by awaiting one element before pulling the next.

Implementation

Stream<Map<String, dynamic>> repairStreamToolCalls(
  Stream<Map<String, dynamic>> parts,
  Object prompt,
  GenerateTextOptions? options,
) {
  final repair = options?.repairToolCall;
  if (repair == null) return parts;

  final promptJson = promptToJson(prompt);
  final optsJson = encodeJson(options!.toJson(), 'options');

  return parts.asyncMap((part) async {
    // Externally tagged: {"ToolCall": {...}}.
    final call = part['ToolCall'];
    if (call is! Map<String, dynamic> || call['invalid'] != true) return part;

    final context = _contextFor(call, promptJson, optsJson);
    if (context == null) return part;

    Map<String, dynamic> reply;
    try {
      reply = _replyFor(await repair(context));
    } catch (e) {
      reply = _failedReply(e);
    }

    final patched = _call3(_applyRepair, jsonEncode(call), optsJson,
        encodeJson(reply, 'repairToolCall reply'), 'apply_tool_call_repair');
    return {'ToolCall': jsonDecode(patched)};
  });
}