chatRawMessage method
Stream<String>
chatRawMessage(
- String messageJson, {
- bool enableThinking = false,
- SendOptions options = SendOptions.none,
override
Streams raw SDK JSON for a prebuilt message. This is how tool results go
back: chatRaw always sends role user, and a tool result has to be role
tool for the model to read it as the answer to its call.
Implementation
@override
Stream<String> chatRawMessage(
String messageJson, {
bool enableThinking = false,
SendOptions options = SendOptions.none,
}) {
if (_closed) {
return Stream.error(StateError('Conversation handle is closed'));
}
final refusal = _refusal(messageJson, enableThinking, options);
if (refusal != null) return Stream.error(refusal);
final message = _jsMessage(messageJson);
final turn = _Turn(jsonDecode(messageJson) as Map<String, Object?>);
_liveTurns.add(turn);
final controller = StreamController<String>();
// The listener let go of the reply: the pump reads the JS stream to its
// end, emitting nothing, and only then lets the next lock holder in.
var listenerGone = false;
void finish({Object? error, StackTrace? stack}) {
if (turn.finished) return;
turn.finished = true;
_liveTurns.remove(turn);
if (identical(_streaming, turn)) _streaming = null;
turn.release();
if (controller.isClosed) return;
if (error != null && !listenerGone) controller.addError(error, stack);
controller.close();
}
turn.abort = (error) => finish(error: error, stack: StackTrace.current);
// How a turn that was asked to end, or that failed here, ended: with the
// local fault, normally after a stop, with [LiteRtLmTurnClosedException]
// after a close that came first.
void finishAsked(StackTrace stack) {
if (turn.fault case (final error, final faultStack)) {
finish(error: error, stack: faultStack);
} else {
finish(
error: turn.stopAsked ? null : LiteRtLmTurnClosedException(),
stack: stack,
);
}
}
void start() {
final stream = _conversation.sendMessageStreaming(message);
turn.sent = true;
_images += _imagesIn([turn.message]);
final JsAsyncIterator iterator;
try {
_onGeneration();
final asyncIterator = globalContext
.getProperty<JSObject>('Symbol'.toJS)
.getProperty<JSAny>('asyncIterator'.toJS);
iterator =
(stream.getProperty<JSFunction?>(asyncIterator) != null
? stream.callMethod<JSObject>(asyncIterator)
: stream) // Already an iterator.
as JsAsyncIterator;
} catch (e, st) {
// Sent, but its stream cannot be read: stop the generation, and let
// the page go only once it has left the module.
turn.fault = (
LiteRtLmNativeException(
'litertlm_dart could not read the reply stream of '
'$liteRtLmWebRuntime: $e',
),
st,
);
_mustRebuild = true;
_rebuildCause = 'a reply stream litertlm_dart could not read';
_stopJs(turn, 'its reply stream could not be read');
_fence().then((_) => finishAsked(StackTrace.current));
return;
}
void pump() {
// Every path ends in [finish] or another [pump]: a callback that
// threw would otherwise keep the page lock, and with it every LLM and
// EmbeddingGemma 2 call on the page, for good.
void onStep(JSObject step) {
// Given up on (the page was poisoned): nothing more is read.
if (turn.finished) return;
final done = step.getProperty<JSAny?>('done'.toJS);
if (!done.isA<JSBoolean>()) {
// The iterator broke its contract: where the generation is, and
// whether it ever ends, cannot be known. The module may still be
// in it, so nothing else may enter.
final error = LiteRtLmNativeException(
'$liteRtLmWebRuntime streamed a step without a boolean `done`: '
'${_stringifySafe(step)}',
);
_mustRebuild = true;
_pageLock.poisonFor(
turn.lease!,
'$liteRtLmWebRuntime streamed a step without a boolean `done`.',
);
finish(error: error, stack: StackTrace.current);
return;
}
if ((done as JSBoolean).toDart) {
// Ended on its own: the runtime conversation keeps working (also
// after a stop that came after the last chunk).
if (turn.asked || turn.fault != null) {
finishAsked(StackTrace.current);
} else {
finish();
}
return;
}
try {
final value = step.getProperty<JSAny?>('value'.toJS);
if (value != null && turn.fault == null) {
final json = _stringify(value);
// Bookkeeping for a stop only: a chunk it cannot read keeps
// nothing, and the chunk still goes to the listener.
turn.raw.write(json);
try {
// As natively: any chunk with text, a thought or a tool call
// counts, and the kept reply is the text without thoughts.
if (extractResponseText(json).isNotEmpty) turn.streamed = true;
turn.reply.write(messageFromChunk(json).text);
} catch (e) {
runtimeLog('[WebConversationHandle] unreadable chunk: $e');
}
if (!listenerGone && !controller.isClosed) controller.add(json);
}
} catch (e, st) {
// A fault here, not the runtime's: stop the generation and read
// its stream to the end before the turn fails, so the page is
// left only once the module has.
if (turn.fault == null) {
turn.fault = (
LiteRtLmNativeException(
'litertlm_dart could not read a chunk of the reply from '
'$liteRtLmWebRuntime: $e',
),
st,
);
_rebuildCause = 'a reply litertlm_dart could not read';
_stopJs(turn, 'its turn failed in litertlm_dart ($e)');
}
}
pump();
}
void onError(Object error, StackTrace stack) {
if (turn.finished) return;
// A rejected stream: the runtime conversation refuses every later
// send ("Task cancelled" after a stop, measured on 0.18.0 and
// 0.19.0).
_mustRebuild = true;
if (turn.stopAsked) _rebuildCause = 'a stopped reply';
if (turn.stopAsked && turn.streamed) {
_stopped = (
message: turn.message,
reply: assistantTurnMessage(
toolCallsOf,
turn.reply.toString(),
turn.raw.toString(),
),
);
} else if (!turn.asked && turn.fault == null) {
// The runtime keeps a refused message at the end of its history
// (M1, N5): the rebuild leaves it out.
_failed = turn.message;
if (_isContextFull(error)) {
_rebuildCause = 'a message too long for the context window';
_lastTurnEnd = NativeLastTurnEnd.contextFull;
} else {
_rebuildCause = 'a failed turn';
}
}
// 0.19.0 rejects from inside the generation's chunk callback:
// wait until it has left the module before the page is let go.
_armDrain(turn, 'its stream failed');
_fence().then((count) {
if (_lastTurnEnd == NativeLastTurnEnd.contextFull &&
_historyLeavesNoRoom(count, turn.message, error)) {
_contextFull = _contextFullMessage(error);
}
if (turn.asked || turn.fault != null) {
// How the runtime ends a stopped generation is its business:
// the turn was asked to end, and it did.
runtimeLog(
'[WebConversationHandle] the stopped generation ended with '
'$error',
);
finishAsked(stack);
} else {
finish(
error: _lastTurnEnd == NativeLastTurnEnd.contextFull
? ContextFullException(
_contextFull ?? _tooLongMessage(error),
)
: _typed(error),
stack: stack,
);
}
});
}
try {
iterator.next().toDart.then(onStep, onError: onError);
} catch (e, st) {
onError(e, st);
}
}
pump();
}
controller.onListen = () async {
try {
turn.lease = await _pageLock.acquire();
} catch (e, st) {
// A poisoned page: nothing more runs on it.
finish(error: e, stack: st);
return;
}
if (turn.asked || listenerGone) {
// Stopped, closed or let go while it waited: never sent.
if (turn.asked) {
finishAsked(StackTrace.current);
} else {
finish();
}
return;
}
if (_contextFull == null) _lastTurnEnd = null;
// A conversation at a dead end (also one reached while this turn was
// queued) sends nothing more.
if (_deadEnd() case final error?) {
finish(error: error, stack: StackTrace.current);
return;
}
// From here the turn holds the page until its stream ends; close()
// waits for that (a turn still queued above has nothing to wait for).
_streaming = turn;
try {
if (_mustRebuild) await _rebuildConversation();
} catch (e, st) {
if (turn.asked) {
// Stopped meanwhile: the turn ends as stopped, and the rebuild's
// failure is only said here; the next message tries again.
runtimeLog('[WebConversationHandle] $e');
finishAsked(st);
} else {
finish(error: e, stack: st);
}
return;
}
if (turn.asked) {
finishAsked(StackTrace.current);
return;
}
// Counted here, once a rebuild has settled what the conversation
// holds, and after every turn queued before this one was sent.
if (_imageRefusal(_imagesIn([turn.message])) case final refusal?) {
finish(error: refusal, stack: StackTrace.current);
return;
}
try {
start();
} catch (e, st) {
// Nothing reached the stream's end if the send threw: no drain.
finish(error: _typed(e), stack: st);
}
};
controller.onCancel = () {
listenerGone = true;
};
return controller.stream;
}