React Native
React Native
OpenAI (ChatGPT) Upload JSON String
See more OpenAI ChatGPT Examples
Demonstrate how to upload a file (from a JSON string) to a OpenAI user's organization.Chilkat React Native Downloads
import { Http, HttpRequest, HttpResponse, JsonObject, StringBuilder } from '@chilkat/react-native'
async function chilkatExample() {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const http = new Http();
// 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
const req = new HttpRequest();
req.httpVerb = 'POST';
req.path = '/v1/files';
req.contentType = 'multipart/form-data';
req.addParam('purpose', 'fine-tune');
// { "prompt": "aa", "completion": "bb" }
// { "prompt": "cc", "completion": "dd" }
const sbJsonData = new StringBuilder();
sbJsonData.appendLine('{ "prompt": "aa", "completion": "bb" }', true);
sbJsonData.appendLine('{ "prompt": "cc", "completion": "dd" }', true);
req.addStringForUpload2('file', 'mydata2.jsonl', sbJsonData.getAsString(), 'utf-8', 'application/octet-stream');
// This is NOT a real key. Change the "sk-vi...." to your own key.
req.addHeader('Authorization', 'Bearer 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');
req.addHeader('Expect', '100-continue');
const resp = new HttpResponse();
try {
await http.httpSReqAsync('api.openai.com', 443, true, req, resp);
} catch {
console.log(http.lastErrorText);
return;
}
const sbResponseBody = new StringBuilder();
resp.getBodySb(sbResponseBody);
const jResp = new JsonObject();
jResp.loadSb(sbResponseBody);
jResp.emitCompact = false;
console.log('Response Body:');
console.log(jResp.emit());
const respStatusCode = resp.statusCode;
console.log(`Response Status Code = ${respStatusCode}`);
if (respStatusCode >= 400) {
console.log('Response Header:');
console.log(resp.header);
console.log('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": "mydata2.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
const id = jResp.stringOf('id');
const vObject = jResp.stringOf('object');
const vBytes = jResp.intOf('bytes');
const createdAt = jResp.intOf('created_at');
const filename = jResp.stringOf('filename');
const purpose = jResp.stringOf('purpose');
}