sendMessage method

Future<String> sendMessage(
  1. String text
)

Implementation

Future<String> sendMessage(String text) async {
  final response = await http.Client()
      .post(url, headers: _getHeaders(), body: _getBody(text, false));

  dynamic decodedResponse;
  if (response.contentLength != null) {
    decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
  }

  final statusCode = response.statusCode;
  if (!(statusCode >= 200 && statusCode < 300)) {
    if (decodedResponse != null) {
      final errorMessage = decodedResponse["error"]["message"] as String;
      throw Exception("($statusCode) $errorMessage");
    }
    throw Exception(
        "($statusCode) Bad response ${response.reasonPhrase ?? ""}");
  }

  final choices = decodedResponse["choices"] as List;
  final choice = choices[0] as Map;
  final content = choice["message"]["content"] as String;
  _appendToHistoryList(text, content);
  return content;
}