Sample code for 30+ languages & platforms
Lianja

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 the id that can later be used to reference the file in an query. This currently works with ChatGPT, Gemini, Claude, and Grok.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

loAi = createobject("CkAi")

// The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
loAi.Provider = "openai"
// Use your provider's API key.
loAi.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.
lcContentType = "application/json"
lcLocalFilePath = "qa_data/hamlet.json"
lcFilenameOnServer = "hamlet.json"

// Upload directly from a file.
lcFile_id = loAi.UploadFile(lcLocalFilePath,lcContentType)
if (loAi.LastMethodSuccess = .F.) then
    ? loAi.LastErrorText
    ? "AI File Upload Failed."
else
    ? "File ID: " + lcFile_id
    ? "File uploaded."
endif

// Upload from the contents of a StringBuilder
loSb = createobject("CkStringBuilder")
llSuccess = loSb.LoadFile(lcLocalFilePath,"utf-8")
if (llSuccess = .F.) then
    ? loSb.LastErrorText
    release loAi
    release loSb
    return
endif

lcFile_id = loAi.UploadFileSb(loSb,lcFilenameOnServer,lcContentType)
if (loAi.LastMethodSuccess = .F.) then
    ? loAi.LastErrorText
    ? "AI File Upload Failed."
else
    ? "File ID: " + lcFile_id
    ? "File uploaded."
endif

// Upload from the contents of a BinData
loBd = createobject("CkBinData")
llSuccess = loBd.LoadFile(lcLocalFilePath)
if (llSuccess = .F.) then
    ? loBd.LastErrorText
    release loAi
    release loSb
    release loBd
    return
endif

lcFile_id = loAi.UploadFileBd(loBd,lcFilenameOnServer,lcContentType)
if (loAi.LastMethodSuccess = .F.) then
    ? loAi.LastErrorText
    ? "AI File Upload Failed."
else
    ? "File ID: " + lcFile_id
    ? "File uploaded."
endif



release loAi
release loSb
release loBd