streamText method
Stream<String>
streamText({
- required String instructions,
- required List<
AiMessage> messages, - String locale = 'en',
- int maxTokens = 512,
override
Streams a free-text answer to messages, chunk by chunk. Cancelling the
subscription, or calling cancel, stops the generation.
Implementation
@override
Stream<String> streamText({
required String instructions,
required List<AiMessage> messages,
String locale = 'en',
int maxTokens = 512,
}) {
_checkMessages(messages);
final events = _transport
.postSse(config.endpoint('/chat/completions'), _headers, {
..._body(
instructions: instructions,
messages: messages,
maxTokens: maxTokens,
),
'stream': true,
});
return _textStream(events, (event) {
if (event.data.trim() == '[DONE]') return _end;
final json = _eventJson(event);
if (json is Map && json['error'] != null) {
throw const SystemLlmException(SystemLlmException.generationFailed);
}
final content = _at(json, ['choices', 0, 'delta', 'content']);
final finished = _at(json, ['choices', 0, 'finish_reason']) != null;
return (
text: content is String ? content : null,
complete: finished,
done: false,
);
});
}