getResponseAsync method

  1. @override
Stream<String> getResponseAsync()
override

Implementation

@override
Stream<String> getResponseAsync() {
  if (kDebugMode) {
    print('🌊 getResponseAsync: Starting async response generation');
  }

  _controller = StreamController<String>();

  try {
    final promptArray = _createPromptArray();

    if (kDebugMode) {
      print('🎯 getResponseAsync: Prompt array type: ${promptArray.runtimeType}');
      print('🎯 getResponseAsync: Is JSString? ${promptArray is JSString}');
    }

    // Use appropriate method based on prompt type
    if (promptArray is JSString) {
      if (kDebugMode) {
        print('πŸ“ getResponseAsync: Using generateResponse for text-only prompt');
      }
      llmInference.generateResponse(
        promptArray,
        ((JSString partialJs, JSAny completeRaw) {
          try {
            final complete = completeRaw.parseBool();
            final partial = partialJs.toDart;
            if (kDebugMode) {
              print('πŸ“ getResponseAsync: Received partial (complete: $complete): ${partial.substring(0, math.min(50, partial.length))}...');
            }
            _controller!.add(partial);
            if (complete) {
              if (kDebugMode) {
                print('βœ… getResponseAsync: Text response completed');
              }
              _controller!.close();
            }
          } catch (e) {
            if (kDebugMode) {
              print('❌ getResponseAsync: Error in text callback: $e');
            }
            _controller!.addError(e);
          }
        }).toJS,
      );
    } else {
      if (kDebugMode) {
        print('πŸ–ΌοΈ getResponseAsync: Using generateResponseMultimodal for multimodal prompt');
      }
      llmInference.generateResponseMultimodal(
        promptArray,
        ((JSString partialJs, JSAny completeRaw) {
          try {
            final complete = completeRaw.parseBool();
            final partial = partialJs.toDart;
            if (kDebugMode) {
              print('πŸ–ΌοΈ getResponseAsync: Received multimodal partial (complete: $complete): ${partial.substring(0, math.min(50, partial.length))}...');
            }
            _controller!.add(partial);
            if (complete) {
              if (kDebugMode) {
                print('βœ… getResponseAsync: Multimodal response completed');
              }
              _controller!.close();
            }
          } catch (e) {
            if (kDebugMode) {
              print('❌ getResponseAsync: Error in multimodal callback: $e');
            }
            _controller!.addError(e);
          }
        }).toJS,
      );
    }
  } catch (e, stackTrace) {
    if (kDebugMode) {
      print('❌ getResponseAsync: Exception during setup: $e');
      print('❌ getResponseAsync: Stack trace: $stackTrace');
    }
    _controller!.addError(e);
  }

  return _controller!.stream;
}