streamText function

Stream<String> streamText(
  1. Stream<ServerSentEvent> events,
  2. StreamProtocol protocol
)

Implementation

Stream<String> streamText(
  Stream<ServerSentEvent> events,
  StreamProtocol protocol,
) async* {
  await for (final event in events) {
    if (event.data == '[DONE]') break;
    final text = switch (protocol) {
      StreamProtocol.openAI => _textFromOpenAI(event.json),
      StreamProtocol.anthropic => _textFromAnthropic(event),
      StreamProtocol.gemini => _textFromGemini(event.json),
    };
    if (text != null && text.isNotEmpty) {
      yield text;
    }
  }
}