parse method

Lfm2Turn parse(
  1. String generated
)

Parses one raw generated model turn into prose plus any tool calls.

generated is the text emitted for a single model turn with the <|im_end|> stop sequence already stripped, so any <|tool_call_start|>…<|tool_call_end|> block is complete. Synthetic sequential FunctionCallContent.callIds are assigned so results can be correlated downstream.

Implementation

Lfm2Turn parse(String generated) {
  final calls = <FunctionCallContent>[];
  final text = StringBuffer();
  var cursor = 0;
  while (cursor < generated.length) {
    final open = generated.indexOf(toolCallStart, cursor);
    if (open < 0) {
      text.write(generated.substring(cursor));
      break;
    }
    text.write(generated.substring(cursor, open));
    final close = generated.indexOf(toolCallEnd, open);
    final bodyEnd = close < 0 ? generated.length : close;
    final block = generated.substring(open + toolCallStart.length, bodyEnd);
    _parseCalls(block, calls);
    cursor = close < 0 ? generated.length : close + toolCallEnd.length;
  }
  return Lfm2Turn(text: text.toString().trim(), calls: calls);
}