createCompletion method

Future<GptCompletion> createCompletion({
  1. required String apiKey,
  2. required String organizationId,
  3. required GptCompletionRequest request,
})

Creates a completion for the provided prompt and parameters.

Implementation

Future<GptCompletion> createCompletion({
  required String apiKey,
  required String organizationId,
  required GptCompletionRequest request,
}) async {

  Map<String, String> headers = {
    "Authorization": "Bearer $apiKey",
    "OpenAI-Organization": organizationId,
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  };


  Uri endpoint;
  if(secure) {
    endpoint = Uri.https(
        baseUrl, "/v1/completions");
  }
  else {
    endpoint = Uri.http(
        baseUrl, "/v1/completions");
  }

  var response = await
  http.post(endpoint, headers: headers, body:jsonEncode(request.toJson()));

  if (response.statusCode == 200 || response.statusCode == 201) {
    //return GptCompletion.fromJson(jsonDecode(response.body));
    return GptCompletion.fromJson(jsonDecode(const Utf8Decoder().convert(response.bodyBytes)));
  }
  else {
    var error = ServerError.fromJson(jsonDecode(response.body));
    throw CompletionsException(statusCode: response.statusCode, message: error.message);
  }
}