PureBasic
PureBasic
Upload a File to an AI Provider (OpenAI, Google, Antropic, X)
See more AI Examples
Uploads a file to an AI provider using the provider's File API and returns theid that can later be used to reference the file in an query. This currently works with ChatGPT, Gemini, Claude, and Grok.
Chilkat PureBasic Downloads
IncludeFile "CkBinData.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkAi.pb"
Procedure ChilkatExample()
success.i = 0
ai.i = CkAi::ckCreate()
If ai.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
CkAi::setCkProvider(ai, "openai")
; Use your provider's API key.
CkAi::setCkApiKey(ai, "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.
contentType.s = "application/json"
localFilePath.s = "qa_data/hamlet.json"
filenameOnServer.s = "hamlet.json"
; Upload directly from a file.
file_id.s = CkAi::ckUploadFile(ai,localFilePath,contentType)
If CkAi::ckLastMethodSuccess(ai) = 0
Debug CkAi::ckLastErrorText(ai)
Debug "AI File Upload Failed."
Else
Debug "File ID: " + file_id
Debug "File uploaded."
EndIf
; Upload from the contents of a StringBuilder
sb.i = CkStringBuilder::ckCreate()
If sb.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkStringBuilder::ckLoadFile(sb,localFilePath,"utf-8")
If success = 0
Debug CkStringBuilder::ckLastErrorText(sb)
CkAi::ckDispose(ai)
CkStringBuilder::ckDispose(sb)
ProcedureReturn
EndIf
file_id = CkAi::ckUploadFileSb(ai,sb,filenameOnServer,contentType)
If CkAi::ckLastMethodSuccess(ai) = 0
Debug CkAi::ckLastErrorText(ai)
Debug "AI File Upload Failed."
Else
Debug "File ID: " + file_id
Debug "File uploaded."
EndIf
; Upload from the contents of a BinData
bd.i = CkBinData::ckCreate()
If bd.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkBinData::ckLoadFile(bd,localFilePath)
If success = 0
Debug CkBinData::ckLastErrorText(bd)
CkAi::ckDispose(ai)
CkStringBuilder::ckDispose(sb)
CkBinData::ckDispose(bd)
ProcedureReturn
EndIf
file_id = CkAi::ckUploadFileBd(ai,bd,filenameOnServer,contentType)
If CkAi::ckLastMethodSuccess(ai) = 0
Debug CkAi::ckLastErrorText(ai)
Debug "AI File Upload Failed."
Else
Debug "File ID: " + file_id
Debug "File uploaded."
EndIf
CkAi::ckDispose(ai)
CkStringBuilder::ckDispose(sb)
CkBinData::ckDispose(bd)
ProcedureReturn
EndProcedure