sendMessage method

Future<void> sendMessage(
  1. String message, {
  2. dynamic onResponseContent(
    1. String accumulatedText
    )?,
  3. dynamic onCitationsReceived(
    1. List<Map<String, dynamic>> citations
    )?,
  4. dynamic onThreadIdReceived(
    1. String threadId
    )?,
  5. dynamic onError(
    1. dynamic error
    )?,
})

Implementation

Future<void> sendMessage(
  String message, {
  Function(String accumulatedText)? onResponseContent,
  Function(List<Map<String, dynamic>> citations)? onCitationsReceived,
  Function(String threadId)? onThreadIdReceived,
  Function(dynamic error)? onError,
}) async {
  final trimmedMessage = message.trim();
  if (trimmedMessage.isEmpty) return;
  if (_isLoading) {
    if (onError != null) onError("Please wait...");
    return;
  }
  _setLoading(true);
  try {
    final userMessage = ChatMessage(
        message: trimmedMessage,
        isUser: true,
        timestamp: DateTime.now(),
        type: 'content');
    _addMessage(userMessage);

    final placeholderIndex = _messages.length;
    final placeholderMessage = ChatMessage(
        message: '',
        isUser: false,
        isWaiting: true,
        timestamp: DateTime.now(),
        type: 'content');
    _addMessage(placeholderMessage);

    await _sseSubscription?.cancel();
    _sseSubscription = null;

    _streamResponse(
        message: trimmedMessage,
        threadId: _currentThreadId,
        placeholderIndex: placeholderIndex,
        onResponseContent: onResponseContent,
        onCitationsReceived: onCitationsReceived,
        onThreadIdReceived: onThreadIdReceived,
        onError: onError);
  } catch (e) {
    _handleError('Failed to send message: $e', _messages.length - 1);
    if (onError != null) onError(e);
    _setLoading(false);
  }
}