|
|
(JavaScript) Upload a File to an AI Provider (OpenAI, Google, Antropic, X)
Uploads a file to an AI provider using the provider's File API and returns the id that can later be used to reference the file in an query. This currently works with ChatGPT, Gemini, Claude, and Grok.Note: This example requires Chilkat v11.4.0 or greater.
var success = false;
var ai = new CkAi();
// The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
ai.Provider = "openai";
// Use your provider's API key.
ai.ApiKey = "MY_API_KEY";
// We can upload directly from a file in the filesystem, or from a Chilkat StringBuilder, or from a Chilkat BinData.
// Some AI providers require a content-type.
// Also, some AI providers are picky about what content-type's are accepted.
// Check the AI provider's documentation.
// "application/json" is generally always acceptable.
// "text/plain" can be used as a fallback for any text file.
var contentType = "application/json";
var localFilePath = "qa_data/hamlet.json";
var filenameOnServer = "hamlet.json";
// Upload directly from a file.
var file_id = ai.UploadFile(localFilePath,contentType);
if (ai.LastMethodSuccess == false) {
console.log(ai.LastErrorText);
console.log("AI File Upload Failed.");
}
else {
console.log("File ID: " + file_id);
console.log("File uploaded.");
}
// Upload from the contents of a StringBuilder
var sb = new CkStringBuilder();
success = sb.LoadFile(localFilePath,"utf-8");
if (success == false) {
console.log(sb.LastErrorText);
return;
}
file_id = ai.UploadFileSb(sb,filenameOnServer,contentType);
if (ai.LastMethodSuccess == false) {
console.log(ai.LastErrorText);
console.log("AI File Upload Failed.");
}
else {
console.log("File ID: " + file_id);
console.log("File uploaded.");
}
// Upload from the contents of a BinData
var bd = new CkBinData();
success = bd.LoadFile(localFilePath);
if (success == false) {
console.log(bd.LastErrorText);
return;
}
file_id = ai.UploadFileBd(bd,filenameOnServer,contentType);
if (ai.LastMethodSuccess == false) {
console.log(ai.LastErrorText);
console.log("AI File Upload Failed.");
}
else {
console.log("File ID: " + file_id);
console.log("File uploaded.");
}
|