agentMessage method

Future<ResponseMessage> agentMessage(
  1. String question,
  2. String sessionId,
  3. String agentId, {
  4. required bool isMarkdown,
  5. String? threadId,
})

Implementation

Future<ResponseMessage> agentMessage(String question, String sessionId, String agentId, {required bool isMarkdown, String? threadId,}) async {
  try {
    final response = await http.post(
      Uri.parse(_agentUrl),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'content': question,
        'session_id': sessionId,
        'agent_id': agentId,
        'thread_id': threadId ?? _threadId,
      }),
    );

    print('Response body: ${response.body}');

    if (response.statusCode == 200) {
      final responseJson = jsonDecode(response.body) as Map<String, dynamic>;
      print('Response JSON: $responseJson');

      if (responseJson.containsKey('response') && responseJson.containsKey('response_type') && responseJson.containsKey('thread_id')) {

        final newThreadId = responseJson['thread_id'] as String;
        final responseTypes = List<String>.from(responseJson['response_type']);
        final messageText = responseJson['response']['message'] as String? ?? '';
        final chartData = responseJson['response']['chartData'] as Map<String, dynamic>?;

        // Update the global _threadId with the new threadId
        _threadId = newThreadId;

        return ResponseMessage(
          MessageType.bot,
          DateTime.now(),
          text: responseTypes.contains('message') ? messageText : null,
          customComponent: responseTypes.contains('chart') ?  chartData : null,
          threadId: newThreadId,
          responseTypesAgent: responseTypes,
          wholeResponsePayload: responseJson,
        );
      }
      else {
        print('Error: Response JSON does not contain expected keys.');
        return ResponseMessage(
          MessageType.bot,
          DateTime.now(),
          text: 'Sorry, an error occurred. Please try again later.',
        );
      }
    }
    else {
      print('Error: ${response.statusCode} - ${response.body}');
      return ResponseMessage(
        MessageType.bot,
        DateTime.now(),
        text: 'Sorry, an error occurred. Please try again later.',
      );
    }
  } catch (e, stackTrace) {
    print('Exception: $e');
    print('StackTrace: $stackTrace');
    return ResponseMessage(
      MessageType.bot,
      DateTime.now(),
      text: 'Sorry, an error occurred. Please try again later.',
    );
  }
}