parseAssistantReply function

AssistantReply parseAssistantReply(
  1. String text
)

Parses generated text. The prompt usually ends in <think> or <think></think>, so the reply may start with the reasoning body itself and contain only the closing tag.

Implementation

AssistantReply parseAssistantReply(String text) {
  var rest = text;
  final end = rest.indexOf('<|im_end|>');
  if (end >= 0) rest = rest.substring(0, end);

  String? reasoning;
  final close = rest.indexOf('</think>');
  if (close >= 0) {
    var body = rest.substring(0, close);
    if (body.startsWith('<think>')) body = body.substring('<think>'.length);
    reasoning = body.replaceFirst(RegExp(r'^\n'), '');
    rest = rest.substring(close + '</think>'.length).trimLeft();
  }

  final calls = <ToolCall>[];
  final content = rest.replaceAllMapped(_toolCall, (m) {
    final body = m[2]!.trim();
    calls.add(
      ToolCall(m[1]!, {
        for (final p in _parameter.allMatches(body)) p[1]!: p[2]!,
      }),
    );
    return '';
  });
  return AssistantReply(reasoning, content.trim(), calls);
}