queryStream method

Stream<RagEvent> queryStream(
  1. String question, {
  2. RagQueryOptions? options,
})

Answer question, emitting retrieved chunks then answer tokens.

The CHUNK_RETRIEVED/CONTEXT_READY/RETRIEVAL_STARTED stream-event kinds were deleted outright (idl/rag.proto): RAGStreamEventKind now has only TOKEN/COMPLETED/ERROR — retrieval no longer streams partial progress, so RagRetrieved is synthesized once, from the terminal RAGResult.retrievedChunks, immediately before the first RagToken (or before RagCompleted when the answer arrived with no token events).

Throws SDKException into the consumer when the query fails.

Implementation

Stream<RagEvent> queryStream(
  String question, {
  RagQueryOptions? options,
}) async* {
  _requireLive();
  _requireGeneration();
  var retrievedEmitted = false;
  await for (final event in DartBridgeRAG.shared.queryStream(
    _queryOptions(question, options),
  )) {
    switch (event.kind) {
      case RAGStreamEventKind.RAG_STREAM_EVENT_KIND_TOKEN:
        if (event.token.isNotEmpty) {
          if (!retrievedEmitted) {
            retrievedEmitted = true;
            // Chunks are not available before the terminal result on this
            // wire shape; emit an empty set so consumers that key their UI
            // off "retrieval happened" still see the transition.
            yield const RagRetrieved(<Match>[]);
          }
          yield RagToken(event.token);
        }
      case RAGStreamEventKind.RAG_STREAM_EVENT_KIND_COMPLETED:
        if (event.hasResult()) {
          final result = RagResult.fromProto(event.result);
          if (!retrievedEmitted) {
            retrievedEmitted = true;
            yield RagRetrieved(result.sources);
          }
          yield RagCompleted(result);
        }
      case RAGStreamEventKind.RAG_STREAM_EVENT_KIND_ERROR:
        throw SDKException.generationFailed(
          event.hasError() && event.error.message.isNotEmpty
              ? event.error.message
              : 'RAG query failed',
        );
      case RAGStreamEventKind.RAG_STREAM_EVENT_KIND_UNSPECIFIED:
        break;
    }
  }
}