Sample code for 30+ languages & platforms
Rust

OpenAI (ChatGPT) Create Chat Completion

See more OpenAI ChatGPT Examples

Shows how to create a model response for a given chat conversation.

Chilkat Rust Downloads

Rust

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let http = chilkat::Http::new();

// Implements the following CURL command:

// curl https://api.openai.com/v1/chat/completions \
//   -H "Content-Type: application/json" \
//   -H "Authorization: Bearer $OPENAI_API_KEY" \
//   -d '{
//     "model": "gpt-3.5-turbo",
//     "messages": [{"role": "user", "content": "Hello!"}]
//   }'

// Use the following online tool to generate HTTP code from a CURL command
// Convert a cURL Command to HTTP Source Code

// Use this online tool to generate code from sample JSON:
// Generate Code to Create JSON

// The following JSON is sent in the request body.

// {
//   "model": "gpt-3.5-turbo",
//   "messages": [
//     {
//       "role": "user",
//       "content": "Hello!"
//     }
//   ]
// }

let json = chilkat::JsonObject::new();
let _ = json.update_string("model", "gpt-3.5-turbo");
let _ = json.update_string("messages[0].role", "user");
let _ = json.update_string("messages[0].content", "Hello!");

// Adds the "Authorization: Bearer $OPENAI_API_KEY" header.
// This is NOT a real key.  Change the "sk-vi...." to your own key.
http.set_auth_token("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");
http.set_request_header("Content-Type", "application/json");

let resp = chilkat::HttpResponse::new();
if http.http_json("POST", "https://api.openai.com/v1/chat/completions", &json, "application/json", &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

let sb_response_body = chilkat::StringBuilder::new();
let _ = resp.get_body_sb(&sb_response_body);

let j_resp = chilkat::JsonObject::new();
let _ = j_resp.load_sb(&sb_response_body);
j_resp.set_emit_compact(false);

println!("Response Body:");
println!("{}", j_resp.emit().unwrap_or_default());

let resp_status_code = resp.status_code();
println!("Response Status Code = {}", resp_status_code);
if resp_status_code >= 400 {
    println!("Response Header:");
    println!("{}", resp.header());
    println!("Failed.");
    return;
}

// Sample JSON response:
// (Sample code for parsing the JSON response is shown below)

// {
//   "id": "chatcmpl-123",
//   "object": "chat.completion",
//   "created": 1677652288,
//   "choices": [
//     {
//       "index": 0,
//       "message": {
//         "role": "assistant",
//         "content": "\n\nHello there, how may I assist you today?"
//       },
//       "finish_reason": "stop"
//     }
//   ],
//   "usage": {
//     "prompt_tokens": 9,
//     "completion_tokens": 12,
//     "total_tokens": 21
//   }
// }

// Sample code for parsing the JSON response...
// Use the following online tool to generate parsing code from sample JSON:
// Generate Parsing Code from JSON

let id = j_resp.string_of("id").unwrap_or_default();
let v_object = j_resp.string_of("object").unwrap_or_default();
let created = j_resp.int_of("created");
let prompt_tokens = j_resp.int_of("usage.prompt_tokens");
let completion_tokens = j_resp.int_of("usage.completion_tokens");
let total_tokens = j_resp.int_of("usage.total_tokens");
let mut i = 0;
let count_i = j_resp.size_of_array("choices");
while i < count_i {
    j_resp.set_i(i);
    let _ = j_resp.int_of("choices[i].index");
    let _ = j_resp.string_of("choices[i].message.role").unwrap_or_default();
    let _ = j_resp.string_of("choices[i].message.content").unwrap_or_default();
    let _ = j_resp.string_of("choices[i].finish_reason").unwrap_or_default();
    i = i + 1;
}