Rust
Rust
OpenAI (ChatGPT) Upload File
See more OpenAI ChatGPT Examples
Demonstrate how to upload a file to a OpenAI user's organization.Chilkat Rust Downloads
// 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/files \
// -H "Authorization: Bearer $OPENAI_API_KEY" \
// -F purpose="fine-tune" \
// -F file="@mydata.jsonl"
// Use the following online tool to generate HTTP code from a CURL command
// Convert a cURL Command to HTTP Source Code
let req = chilkat::HttpRequest::new();
req.set_http_verb("POST");
req.set_path("/v1/files");
req.set_content_type("multipart/form-data");
req.add_param("purpose", "fine-tune");
// myData.json contains the following:
// { "prompt": "aa", "completion": "bb" }
// { "prompt": "cc", "completion": "dd" }
let _ = req.add_file_for_upload2("file", "qa_data/json/mydata.jsonl", "application/octet-stream").is_ok();
// This is NOT a real key. Change the "sk-vi...." to your own key.
req.add_header("Authorization", "Bearer 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");
req.add_header("Expect", "100-continue");
let resp = chilkat::HttpResponse::new();
if http.http_s_req("api.openai.com", 443, true, &req, &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": "file-XjGxS3KTG0uNmNOK362iJua3",
// "object": "file",
// "bytes": 140,
// "created_at": 1613779121,
// "filename": "mydata.jsonl",
// "purpose": "fine-tune"
// }
// 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 v_bytes = j_resp.int_of("bytes");
let created_at = j_resp.int_of("created_at");
let filename = j_resp.string_of("filename").unwrap_or_default();
let purpose = j_resp.string_of("purpose").unwrap_or_default();