Lua Requires Chilkat v11.4.0+
Lua
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 Lua Downloads
local chilkat = require("chilkat")
local ai = chilkat.Ai.new()
-- 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.api_key = "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.
local contentType = "application/json"
local localFilePath = "qa_data/hamlet.json"
local filenameOnServer = "hamlet.json"
-- Upload directly from a file.
local file_id = ai:upload_file(localFilePath, contentType)
if not ai.last_method_success then
print(ai.last_error_text)
print("AI File Upload Failed.")
else
print("File ID: " .. file_id)
print("File uploaded.")
end
-- Upload from the contents of a StringBuilder
local sb = chilkat.StringBuilder.new()
local success = sb:load_file(localFilePath, "utf-8")
if not success then
print(sb.last_error_text)
return
end
file_id = ai:upload_file_sb(sb, filenameOnServer, contentType)
if not ai.last_method_success then
print(ai.last_error_text)
print("AI File Upload Failed.")
else
print("File ID: " .. file_id)
print("File uploaded.")
end
-- Upload from the contents of a BinData
local bd = chilkat.BinData.new()
success = bd:load_file(localFilePath)
if not success then
print(bd.last_error_text)
return
end
file_id = ai:upload_file_bd(bd, filenameOnServer, contentType)
if not ai.last_method_success then
print(ai.last_error_text)
print("AI File Upload Failed.")
else
print("File ID: " .. file_id)
print("File uploaded.")
end