Ai Lua Reference Documentation

chilkat.Ai

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Ai

Use one consistent API for multiple AI providers.

Chilkat.Ai provides a unified interface for sending prompts, multimodal input, conversations, streaming requests, tool calls, and file references to many AI providers. Instead of writing separate REST integrations for each vendor, applications can use one Chilkat API while Chilkat handles provider-specific differences in authentication, request formatting, response parsing, streaming events, and tool-calling workflows.

OpenAI Google Gemini Anthropic Claude xAI Grok Mistral DeepSeek Perplexity Custom Providers

Portable provider access

Write code once and switch providers by changing settings such as Provider, Model, ApiKey, BaseUrl, and ApiSpec.

Conversations

Create, select, export, import, list, and delete named conversations. Chilkat can maintain local transcripts or use provider-hosted conversation state where supported.

Multimodal input

Add text, image data, image URLs, file data, file URLs, and uploaded file references to the next request.

Streaming responses

Use Streaming, PollAi, and NextAiEvent to receive incremental output and standardized streaming events.

Tool calling

Supports manual function tool calling and automatic JavaScript tool calling, including safeguards such as tool timeouts and iteration limits.

File upload and reuse

Upload files once, receive a file ID or URI, and reference that file in later requests when supported by the provider.

Starting in v11.4.0: Chilkat.Ai adds manual tool function calling, automatic JavaScript tool calling, file uploads for later reference by file ID, and conversational image output for providers that support it.

AI responses are often returned as Markdown. Chilkat also provides Markdown to HTML support in the StringBuilder class, including streaming Markdown-to-HTML conversion for applications that display AI output as it is generated.

Object Creation

local chilkat = require("chilkat")

local ai = chilkat.Ai.new()
local ai = chilkat.Ai.new()

Creates the object (chilkat.Ai() does the same). Lua's garbage collector frees it when it is no longer referenced; ai:dispose() frees it at once, and in Lua 5.4 and later local ai <close> = chilkat.Ai.new() frees it when the block ends. Calling a method of a disposed object raises an error.

Errors

A method that fails returns nil followed by the error text, as io.open does: local body, err = ai:method(...), where err is the object's last_error_text. Wrap the call in assert() to raise an error with that text instead. Methods that answer a question return true or false, numbers are returned as they are (check last_method_success where the description says a value means failure), and property reads and writes never fail for Chilkat reasons.

Misuse raises a Lua error: a wrong argument type or a missing argument (bad argument #1 to ...), an unknown property name, a write to a read-only property, an out-of-range integer, or an object of the wrong class.

Names are Chilkat's in snake_case: QuickGetStr is quick_get_str, LastErrorText is last_error_text. Properties are fields (ai.verbose_logging = true) and methods use the colon (ai:method(...)). Strings are UTF-8; binary data is a Lua string of bytes. Indexes are 0-based, as in every Chilkat API. Unlocking: call chilkat.unlock_bundle("...") once at startup.

Properties

ApiKey
-- strVal is a string
local strVal = ai.api_key
ai.api_key = strVal
Introduced in version 11.2.0

This is the API key used for authentication. Use your API key that matches your Provider .

Suggestion: Use Chilkat's Secrets class to store and retrieve API keys in any of the following locations.

  • Windows Credentials Manager
  • Apple Keychain
  • AWS Secrets Manager
  • Azure Key Vault
  • IBM Cloud Secrets Manager
  • Oracle Cloud Secrets
  • Doppler Secrets
  • top
ApiKeyHeader
-- strVal is a string
local strVal = ai.api_key_header
ai.api_key_header = strVal
Introduced in version 11.3.0

For custom Provider's, use this field name for the API key in the HTTP header, but only if the API key is to be placed in a custom header field. If the API key is to be provided in an "Authorization: Bearer" header, then leave this property empty.

The default value of this property is the empty string.

top
ApiSpec
-- strVal is a string
local strVal = ai.api_spec
ai.api_spec = strVal
Introduced in version 11.3.0

Specifies the API specification to be used. Possible choices are ChatCompletions, Responses, Gemini, Anthropic. The default value is Responses because the default value of the Provider property is openai. Setting the Provider property to a value other than custom will also automatically set this property to the correct and needed value.

top
BaseUrl
-- strVal is a string
local strVal = ai.base_url
ai.base_url = strVal
Introduced in version 11.3.0

Specifies the provider's base URL. For example, http://localhost:11434/v1 or https://api.together.xyz/v1. The default value is https://api.openai.com/v1 because the default value of the Provider property is openai. Setting the Provider property to a value other than custom will also automatically set this property to the correct and needed value.

More Information and Examples
top
DebugLogFilePath
-- strVal is a string
local strVal = ai.debug_log_file_path
ai.debug_log_file_path = strVal

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
EnableSecrets
-- boolVal is a boolean
local boolVal = ai.enable_secrets
ai.enable_secrets = boolVal
Introduced in version 11.5.0

If true a secret specifier of the format "!!part1|part2|.." can be provided instead of the actual value for the ApiKey property.

The default value is false.

top
FullTranscript
-- boolVal is a boolean
local boolVal = ai.full_transcript
ai.full_transcript = boolVal
Introduced in version 11.2.0

For multimodal inputs like image data, image URLs, file data, and file URLs, the full data or URL is sent initially. If the property is set to true, the full data/URL is re-sent in subsequent interactions. If set to false, only the image or file summary is sent thereafter.

By default, this property is false.

Full transcript style: always send the entire conversation (including files/images). This guarantees the model has all context, but can get expensive.

Summarized transcript style: for previously sent multimodal items, sends the summary message (e.g. “Earlier, I uploaded a PDF with account statements”) instead of the raw file or url itself.

top
HasFunctionCalls
-- boolVal is a boolean (read-only)
local boolVal = ai.has_function_calls
Introduced in version 11.4.0

true if the response output has function calls. Otherwise false. This only applies to manual function tool calling, not automatic JS tool calls.

More Information and Examples
top
HeartbeatMs
-- intVal is an integer
local intVal = ai.heartbeat_ms
ai.heartbeat_ms = intVal
Introduced in version 11.2.0

The interval in milliseconds between each AbortCheck event callback, which enables an application to abort certain method calls before they complete. By default, HeartbeatMs is set to 0, meaning no AbortCheck event callbacks will trigger.

top
HostedConvo
-- boolVal is a boolean
local boolVal = ai.hosted_convo
ai.hosted_convo = boolVal
Introduced in version 11.2.0

This applies to providers like OpenAI that can maintain conversation state on the server. If set to true, only the conversation ID is sent with each query. If set to false, the entire conversation transcript is sent with each query, making each query stateless.

This only applies if a conversation is selected.

The default value of this property is false.

top
IdleTimeoutMs
-- intVal is an integer
local intVal = ai.idle_timeout_ms
ai.idle_timeout_ms = intVal
Introduced in version 11.2.0

The maximum amount of time to wait for additional incoming data when receiving a response. The default value is 90000 (90 seconds) in v11.3.0 and earlier. Starting in v11.4.0, the default value is 180000 (180 seconds).

This is not a total timeout, but the maximum time allowed when data transmission has paused.

top
JsToolTimeout
-- intVal is an integer
local intVal = ai.js_tool_timeout
ai.js_tool_timeout = intVal
Introduced in version 11.4.0

The maximum time in seconds allowed for an automatic JavaScript tool function. The default value is 60 seconds to allow for most use cases, but to prevent an tool call that never returns.

top
LastErrorHtml
-- strVal is a string (read-only)
local strVal = ai.last_error_html

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
-- strVal is a string (read-only)
local strVal = ai.last_error_text

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
-- strVal is a string (read-only)
local strVal = ai.last_error_xml

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
-- boolVal is a boolean
local boolVal = ai.last_method_success
ai.last_method_success = boolVal

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
LastResponseRefused
-- boolVal is a boolean (read-only)
local boolVal = ai.last_response_refused
Introduced in version 11.6.0

Read-only. true if the model refused to produce the requested structured output during the most recent Ask. When a refusal occurs, GetOutputJson returns false and the provider's explanation is available in RefusalText . This property is reset at the start of each Ask.

top
Model
-- strVal is a string
local strVal = ai.model
ai.model = strVal
Introduced in version 11.2.0

The model to be used for AI conversations. For example, GPT-4o or GPT-5. The list of available models can be obtained by calling GetModels.

The default value is the empty string. A model must always be specified. Chilkat won't try to guess or default to a model.

top
Provider
-- strVal is a string
local strVal = ai.provider
ai.provider = strVal
Introduced in version 11.2.0

This is the AI provider. Possible values are: openai, google, claude, deepseek, perplexity, mistral, and xai.

Starting in Chilkat v11.3.0, this property can be set to custom, and the BaseUrl and ApiSpec properties can also be set to fully specify the provider.

Starting in v11.6.0, this property can also be set to openai-compatible, a convenience alias for a custom provider that speaks the OpenAI Chat Completions API. It presets ApiSpec to ChatCompletions, so you only need to set BaseUrl (plus ApiKey and Model). This is the simplest way to use OpenAI-compatible endpoints such as Ollama, LM Studio, OpenWebUI, and many hosting providers.

Note: mistral is recognized as a pre-configured known provider starting in v11.4.0.

The default value is openai.

top
RefusalText
-- strVal is a string (read-only)
local strVal = ai.refusal_text
Introduced in version 11.6.0

Read-only. When LastResponseRefused is true, this is the model's message explaining why it declined to produce the requested structured output. Otherwise it is the empty string.

top
ResponseStatusCode
-- intVal is an integer (read-only)
local intVal = ai.response_status_code
Introduced in version 11.2.0

The HTTP response status code for the last Ask is as follows:

  • 0 indicates an error occurred before receiving an HTTP response.
  • 200 indicates a successful response.
  • A failed response has a status code of 400 or higher.

top
SelectedConvo
-- strVal is a string
local strVal = ai.selected_convo
ai.selected_convo = strVal
Introduced in version 11.2.0

The currently selected conversation can be set to your desired conversation name. Once set, all future queries will be part of that conversation, updating its state with each input and output. By default, no conversation is selected, indicated by an empty string, leading to stateless queries. The first conversation created or imported will be automatically selected. If you attempt to select a non-existent conversation, the selection will not change. You can reset this property to an empty string to revert to stateless querying.

top
Streaming
-- boolVal is a boolean
local boolVal = ai.streaming
ai.streaming = boolVal
Introduced in version 11.2.0

When set to true, the Ask method operates in streaming mode, returning immediately after the request is sent. You can then use the PollAi and NextAiEvent methods to receive streaming events. By default, this property is false.

top
UncommonOptions
-- strVal is a string
local strVal = ai.uncommon_options
ai.uncommon_options = strVal
Introduced in version 11.2.0

This is a catch-all property to be used for uncommon needs. This property defaults to the empty string, and should typically remain empty.

top
VerboseLogging
-- boolVal is a boolean
local boolVal = ai.verbose_logging
ai.verbose_logging = boolVal

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
-- strVal is a string (read-only)
local strVal = ai.version

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

Ask
-- output_type is a string
-- ok is true, or nil and err on failure
local ok, err = ai:ask(output_type)
Introduced in version 11.2.0

Sends the current potentially multimodal input within the context of the selected conversation and receives the model's output. Prior to v11.4.0 the output_type is limited to text. Starting in v11.4.0, the output_type can be set to image for AI providers that support conversational image output.

Accumulated outputs are cleared on entry to this method. Accumulated inputs are cleared on the successful return of this method.

This method cannot be called while a streaming Ask is in progress. In such a case the return value is false and nothing will occur.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
DeleteConvo
-- name is a string
-- ok is true, or nil and err on failure
local ok, err = ai:delete_convo(name)
Introduced in version 11.2.0

Deletes the conversation by its name. If name equals * then all conversations are deleted.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
ExportConvo
-- name is a string
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = ai:export_convo(name, json)
Introduced in version 11.2.0

Exports the conversation specified by name to json, replacing json's contents with the exported transcript. You can later import a conversation using ImportConvo . The currently selected conversation can be exported by passing * for the name.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetFunctionCalls
-- json is a chilkat.JsonObject
-- flag is true or false
local flag = ai:get_function_calls(json)
Introduced in version 11.4.0

This method returns the function calls in json if the output contains any. Returns true if one or more function calls were returned, otherwise returns false. This only applies to manual function tool calling, not automatic JS tool calls.

Returns true or false: an answer, not a success flag.

More Information and Examples
top
GetLastJsonData
-- json is a chilkat.JsonObject
ai:get_last_json_data(json)
Introduced in version 11.2.0

Provides details about the last method called on this object instance. While many methods do not generate information, some allow you to retrieve details by accessing the last JSON data immediately after the method call returns.

Methods that produce last JSON information include: GetModels .

More Information and Examples
top
GetModels
-- st is a chilkat.StringTable
-- ok is true, or nil and err on failure
local ok, err = ai:get_models(st)
Introduced in version 11.2.0

Returns a list of models available to your account, such as GPT-4o and GPT-5. The models are listed in st, sorted in ascending, case-insensitive order. To access the raw JSON response after calling this method, use GetLastJsonData .

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetOutputBd
-- bd is a chilkat.BinData
-- ok is true, or nil and err on failure
local ok, err = ai:get_output_bd(bd)
Introduced in version 11.4.0

Returns in bd the binary output from the last call to Ask, such as for an AI generated image.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetOutputJson
-- json is a chilkat.JsonObject
-- flag is true or false
local flag = ai:get_output_json(json)
Introduced in version 11.6.0

Returns the model's structured JSON output from the most recent Ask, parsed into json. Use this after setting a schema with SetOutputSchema . Returns true and populates json when the output is valid JSON. Returns false if the model refused to produce the output (in which case LastResponseRefused is true and RefusalText contains the explanation), if there is no output, or if the output is not valid JSON. The raw JSON text is also available from GetOutputText .

Returns true or false: an answer, not a success flag.

top
GetOutputText
-- str is a string, or nil and err on failure
local str, err = ai:get_output_text()
Introduced in version 11.2.0

Returns the text output from the last call to Ask.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetOutputTextSb
-- sb is a chilkat.StringBuilder
-- ok is true, or nil and err on failure
local ok, err = ai:get_output_text_sb(sb)
Introduced in version 11.2.0

Returns the text output, appended to sb, from the last call to Ask.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetSearchResults
-- json is a chilkat.JsonObject
-- flag is true or false
local flag = ai:get_search_results(json)
Introduced in version 11.6.0

Returns the web search sources the model used in the most recent Ask, if web search was enabled via the web_search param of SetAskParams . Returns true if the last Ask performed one or more web searches, in which case the normalized results are placed in json. Returns false if no web search occurred.

Chilkat normalizes the differing citation formats of each AI provider into a single flat structure. json is populated as follows:

{
  "search_results": [
    {
      "url": "https://example.com/article",
      "title": "Example Article Title",
      "snippet": "The relevant excerpt the model drew from...",
      "page_age": "2025-08-01"
    }
  ]
}

The snippet and page_age members are populated only when the provider supplies them, and may be absent otherwise. Each provider returns a different citation shape (for example, OpenAI returns url_citation annotations with character offsets, Anthropic returns web_search_tool_result content blocks, Google returns groundingMetadata, and Perplexity returns a search_results array). The full, unmodified provider response — including any character-offset annotations not represented in the normalized form — remains available via GetLastJsonData .

Streaming: In streaming mode, a standardized web_search_call event is delivered through NextAiEvent when the provider begins a search, and the normalized results are available from this method after the null_terminator event completes the response.

Returns true or false: an answer, not a success flag.

top
ImportConvo
-- name is a string
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = ai:import_convo(name, json)
Introduced in version 11.2.0

Imports the conversation from json and assigns it the name in name.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
InputAddFileData
-- filename is a string
-- bd is a chilkat.BinData
-- summary is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_file_data(filename, bd, summary)
Introduced in version 11.2.0

Adds file data, such as a PDF, to the potentially multimodal input that will be sent in the next call to Ask. The bd contains the file data.

If FullTranscript is _CKFALSE_, summary is sent in subsequent interactions instead of the file data. If FullTranscript is true, summary is not sent, and the file data is re-sent in each interaction.

This method cannot be used with DeepSeek.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InputAddFileId
-- file_id is a string
-- mime_type is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_file_id(file_id, mime_type)
Introduced in version 11.4.0

Adds a reference to a previously uploaded file. The file_id is the id returned from the provider when originally uploading the file. The mime_type, such as "application/pdf", "application/json", "text/xml", etc. is needed for some AI providers such as Google.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
InputAddFileUrl
-- url is a string
-- summary is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_file_url(url, summary)
Introduced in version 11.2.0

Adds a file located at a url to the potentially multimodal input that will be sent in the next call to Ask.

If FullTranscript is _CKFALSE_, summary is sent in subsequent interactions instead of the file URL. If FullTranscript is true, summary is not sent, and the file URL is re-sent in each interaction.

This method cannot be used with DeepSeek.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InputAddFnResult
-- call_id is a string
-- fn_result is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_fn_result(call_id, fn_result)
Introduced in version 11.4.0

Provide a function call result to the model. This only applies to manual function tool calling, not automatic JS tool calls.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InputAddImageData
-- bd is a chilkat.BinData
-- summary is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_image_data(bd, summary)
Introduced in version 11.2.0

Adds an image to the potentially multimodal input that will be sent in the next call to Ask. The bd contains the images data. The image data must be jpeg, png, or webp format.

If FullTranscript is _CKFALSE_, summary is sent in subsequent interactions instead of the image data. If FullTranscript is true, summary is not sent, and the image data is re-sent in each interaction.

This method cannot be used with DeepSeek. DeepSeek does not appear to expose an OpenAI-compatible vision model (yet). You cannot send image URLs or image data to DeepSeek.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
InputAddImageFileId
-- file_id is a string
-- mime_type is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_image_file_id(file_id, mime_type)
Introduced in version 11.4.0

Adds a reference to a previously uploaded image file. The file_id is the id returned from the provider when originally uploading the file. The mime_type, such as "image/jpeg" is needed for some AI providers such as Google.

Note: At this time, only OpenAI and Google support the ability to upload once → get file_id → reuse in later requests' workflow for images.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
InputAddImageUrl
-- url is a string
-- summary is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_image_url(url, summary)
Introduced in version 11.2.0

Adds an image located at a url to the potentially multimodal input that will be sent in the next call to Ask.

If FullTranscript is _CKFALSE_, summary is sent in subsequent interactions instead of the image URL. If FullTranscript is true, summary is not sent, and the image URL is re-sent in each interaction.

This method cannot be used with DeepSeek. DeepSeek does not appear to expose an OpenAI-compatible vision model (yet). You cannot send image URLs or image data to DeepSeek.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InputAddText
-- text is a string
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_text(text)
Introduced in version 11.2.0

Adds text to the potentially multimodal input that will be sent in the next call to Ask.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
InputAddTextSb
-- sb is a chilkat.StringBuilder
-- ok is true, or nil and err on failure
local ok, err = ai:input_add_text_sb(sb)
Introduced in version 11.2.0

Adds text to the potentially multimodal input that will be sent in the next call to Ask.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
InputClear
ai:input_clear()
Introduced in version 11.2.0

Clears the inputs to be sent in the next call to Ask.

top
ListConvos
-- st is a chilkat.StringTable
-- ok is true, or nil and err on failure
local ok, err = ai:list_convos(st)
Introduced in version 11.2.0

Returns the full list of conversation names in st.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
NewConvo
-- name is a string
-- sys_msg is a string
-- dev_msg is a string
-- ok is true, or nil and err on failure
local ok, err = ai:new_convo(name, sys_msg, dev_msg)
Introduced in version 11.2.0

Creates and initializes a transcript for a new conversation. The name is a unique name for the conversation. You can reference the conversation by this name, such as for the ExportConvo method.

The sys_msg sets the broad behavior, tone, and role of the assistant. Example: "You are a polite tutor who explains concepts clearly and simply." Think of it as the high-level persona or instructions the model follows throughout the conversation. The dev_msg provides more technical or policy-level guidance. Example: "Always respond in Markdown. Do not reveal internal reasoning. Keep answers under 200 words." It’s like hidden scaffolding to enforce app rules, formatting, or safety constraints.

Note: The first conversation created is automatically set as the SelectedConvo . You can use any unique name for a conversation except *.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
NextAiEvent
-- max_wait_ms is an integer
-- sb_name is a chilkat.StringBuilder
-- sb_delta is a chilkat.StringBuilder
-- ok is true, or nil and err on failure
local ok, err = ai:next_ai_event(max_wait_ms, sb_name, sb_delta)
Introduced in version 11.2.0

Retrieves the next available AI streaming mode response update. Use the PollAi method to check if a response update is immediately accessible. The event name is returned in sb_name. If the event name is delta, the text is returned in sb_delta.

For the complete raw event JSON, use the GetLastJsonData function. Note that the raw JSON format varies by AI provider.

Each AI provider (e.g., OpenAI, Claude, xAI) sends a unique set of events. Some of these events mark the start and end of sections and content parts, while others do not. Chilkat standardizes these events and returns the following event types.

  • response_created — The server acknowledges the request and has created a response object. Nothing has been streamed yet — it’s just the signal that the response pipeline is open.
  • empty — Some AI providers send empty heartbeat / keep-alive updates to ensure the stream stays open and proxies don't time out.
  • output_item_added — A new output item has been added to the response. An “output item” is a top-level container — could be text, tool call, or other structured content.
  • content_part_added — Within the output item, the model starts a new content part. A content part is typically a segment of a specific type (e.g., text, JSON snippet, or image reference).
  • delta — These are the incremental text tokens being streamed. Each delta contains the next piece of text (like characters or words). You’ll see many of these in sequence while the model is generating.
  • output_text_done — Marks the end of the text streaming for that content part. No more deltas will arrive for this part.
  • content_part_done — Closes the current content part. Tells you the model is finished with that segment (e.g., done streaming a paragraph).
  • output_item_done — Closes the current output item entirely. Means that item is fully complete (all its parts are done).
  • response_completed — The entire response object is finished. No more items will be added, and the stream will soon close.
  • null_terminator — The stream is closed. All streaming responses end with a single null_terminator.
  • function_call — (starting in v11.4.0) The AI model is requesting a function call. This is for manual tool calling.
  • js_function_call — (starting in v11.4.0) The AI model is requesting a function call that Chilkat can execute automatically. Call StreamingJsToolCall to run it. This covers both JavaScript tools (RegisterJsTools) and MCP tools (UseMcp).
  • web_search_call — (starting in v11.6.0) The AI provider is performing a server-side web search while generating the response. This is an informational progress event (useful for showing a "Searching the web…" indicator); the application takes no action. The retrieved sources are available from GetSearchResults after the response completes.

max_wait_ms defines the maximum wait time to receive the complete event. For instance, if PollAi signals an available streaming update but only part of the event JSON has been received, the rest is probably on its way. In such cases, this method must wait to receive the entire JSON.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
PollAi
-- abort is a boolean
-- n is an integer
local n = ai:poll_ai(abort)
Introduced in version 11.2.0

Returns immediately with one of the following values:

-1 - Error
0 - No streaming event updates are available.
1 - A streaming event updates is ready for retrieval via NextAiEvent
2 - The streaming AI response has already completed, or no streaming response is ongoing.

If abort is true, then the streaming response is aborted and this method returns the value 2. Applications should pass in false for abort to continue streaming.

top
RegisterJsTools
-- sb is a chilkat.StringBuilder
-- eval_only is a boolean
-- allow_all_keyword is a boolean
-- ok is true, or nil and err on failure
local ok, err = ai:register_js_tools(sb, eval_only, allow_all_keyword)
Introduced in version 11.4.0

Adds JavaScript tool functions to the AI. This function can be called multiple times to add tool functions from multiple JavaScript sources. The JavaScript is passed in sb. If eval_only is true, then the sb contains JavaScript to be run for the purpose of adding supporting functions and does not contain a toolRegistry.

The allow_all_keyword indicates whether the all keyword is allowed in the toolPermissions. If multiple JavaScript tool sources are loaded with several calls to RegisterJsTools, we may not want one to clobber the permissions needed by another. The application can ensure this doesn't happen by setting this property to false.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
RegisterManualTools
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = ai:register_manual_tools(json)
Introduced in version 11.4.0

Sets the tools JSON for AI requests.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetAskParams
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = ai:set_ask_params(json)
Introduced in version 11.3.0

Sets additional Ask params such as:

  • effort (see below)
  • max_output_tokens (see below)
  • max_tool_iterations - v11.4.0 Applies only to automatic JavaScript tool function calls. Sets a maximum number of AI model tool responses that can be received. The default is 5. This is to prevent an unlikely and unexpected infinite cycle of AI model tool responses and automatic tool calling.
  • temperature (see below)
  • web_search - v11.6.0 A JSON object that enables provider-hosted web search (also called "grounding") so the model can retrieve live results and answer with citations. See below.
  • verbose_ai_logging- v11.4.0 Adds even more detailed logging to the LastErrorText , more than what is added when the VerboseLogging property is enabled.

effort

The effort can be set to none, minimal, low, medium, or high.

Chilkat will automatically convert "effort" to the correct JSON member name and value based on the AI provider.

API / Provider JSON Member for Effort
OpenAI Responses API reasoning.effort → none|minimal|low|medium|high
Anthropic Claude output_config.effort → low|medium|high
Google Gemini generationConfig.thinkingConfig.thinkingLevel → LOW|HIGH
OpenAI Chat Completions reasoning_effort → none|minimal|low|medium|high

max_output_tokens

Max output tokens simply limit how long the model’s response is allowed to be. It’s just a cap — the model may use fewer, but cannot exceed it.

Chilkat will automatically convert "max_output_tokens" to the correct JSON member name based on the AI provider.

API / Provider JSON Member for Max Tokens
OpenAI Responses API max_output_tokens
Anthropic Claude max_tokens
Google Gemini generationConfig.maxOutputTokens
OpenAI Chat Completions max_completion_tokens

Typical limits (approximate)

Different AI providers enforce different maximum output sizes:

Provider / Model Typical Max Output Tokens
OpenAI GPT-4, GPT-4 Turbo ~4,096–8,192 tokens
OpenAI GPT-5 / GPT-5.1 Often ~8,192–16,384 tokens (varies by deployment)
OpenAI o-series (o1, o1-mini, o3) ~4,096–8,192 tokens
Anthropic Claude 3 / 3.5 ~4,096 tokens (fixed; cannot request more)
Google Gemini 1.5 ~8,192–16,384 tokens
xAI Grok 1.5 ~2,048–4,096 tokens
Ollama / local models Usually 1,024–4,096 depending on model size

temperature

Most modern AI APIs (including OpenAI’s) allow a temperature range from 0.0 to 2.0. Chilkat will ignore and not send a temperature having a value outside this range.

Here’s the breakdown:

  • 0.0 → 1.0: Traditional range used by older models and most examples.
  • >1.0 up to 2.0: Expands randomness even further. Outputs can become highly creative, unusual, or less controlled.

Practical guidance:

Temperature Behavior
0.0 Fully deterministic. Same prompt → same answer.
0.1–0.5 Focused, safe, factual, ideal for coding and instructions.
0.6–1.0 Creative but still coherent. Great for writing or brainstorming.
1.1–2.0 Very creative, exploratory, sometimes chaotic; useful for idea generation or stylistic experimentation.

The valid range is technically 0.0 to 2.0, but the commonly useful range is usually 0.0 to ~1.2 for most applications.


web_search (starting in v11.6.0)

The web_search param is a JSON object that turns on the AI provider's server-side web search tool. The provider performs the search while generating the response, and the model answers using the retrieved results. After the Ask, the retrieved sources can be obtained by calling GetSearchResults .

Example:

{
  "web_search": {
    "enabled": true,
    "max_uses": 3,
    "allowed_domains": [ "wikipedia.org", "nasa.gov" ],
    "blocked_domains": [ ],
    "recency": "week",
    "user_location": {
      "country": "US",
      "city": "Chicago",
      "region": "Illinois",
      "timezone": "America/Chicago"
    }
  }
}

Chilkat maps each field to the equivalent option for the selected Provider and silently ignores fields the provider does not support. Only enabled is required; every other field is optional.

  • enabled — If true, web search is offered to the model for this Ask. For perplexity, search is always on, so this is a no-op.
  • max_uses — The maximum number of searches the model may perform while answering. This is the primary cost-control knob (see the billing note below).
  • allowed_domains — An array of domains. When present, search results are restricted to these domains.
  • blocked_domains — An array of domains to exclude from results. Do not specify both allowed_domains and blocked_domains in the same request unless the provider permits it.
  • recency — Limits results by age. Possible values are day, week, month, or year.
  • user_location — An optional object with country, city, region, and timezone members used to localize results.

Provider support matrix

Field openai claude google xai perplexity
enabled web_search tool web_search tool google_search web_search tool always on
max_uses — ✓ — — —
allowed_domains ✓ ✓ — ✓ ✓
blocked_domains — ✓ — ✓ ✓
recency — — — — ✓
user_location ✓ ✓ — — —

xAI (Grok): Web search uses xAI's Agent Tools API on the Responses endpoint. Chilkat automatically routes a Grok web search request to that endpoint, so a web-search-capable Grok model (for example grok-4.5) is required. For Grok, only allowed_domains and blocked_domains (each limited to 5 domains, and mutually exclusive) are supported. xAI's older chat-completions "Live Search" is deprecated.

Not supported: deepseek and mistral (chat) do not expose a web search tool. If web_search is set for these providers, the Ask proceeds without search and a note is written to the LastErrorText . This keeps provider-switching code working when only the Provider property changes.

Billing note: Most providers bill web searches separately from tokens (typically per 1,000 searches). Use max_uses where supported to bound per-request cost.

Streaming: When Streaming is enabled, a web_search_call event is delivered through NextAiEvent while the provider performs a search.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetConnectionSettings
-- sock is a chilkat.Socket
-- ok is true, or nil and err on failure
local ok, err = ai:set_connection_settings(sock)
Introduced in version 11.2.0

This method copies connection settings, including HTTP proxy, SOCKS proxy, network interface IP address, and other related settings from sock. It's optional; if not used, default settings apply. Call this method before sending REST API requests to an AI provider.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetOutputSchema
-- name is a string
-- schema is a chilkat.JsonObject
-- strict is a boolean
-- ok is true, or nil and err on failure
local ok, err = ai:set_output_schema(name, schema, strict)
Introduced in version 11.6.0

Requests schema-constrained JSON output (structured output) for subsequent calls to Ask. name is a short schema name (letters, digits, underscores, and hyphens) used as an identifier by some providers. schema is the desired output shape as a JSON Schema. strict (strict) requests strict conformance where the provider supports it.

Pass an empty string for name to clear a previously-set schema, which disables structured output.

When strict (strict) is true, Chilkat automatically augments the schema for the providers that require it — adding "additionalProperties": false and marking every property required on each object — so an ordinary JSON Schema can be supplied. For example, schema might be:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "required": ["name", "age"]
}

After Ask, the model's JSON is available as text from GetOutputText or parsed from GetOutputJson .

Provider support: OpenAI, Anthropic Claude, Google Gemini, xAI Grok, Mistral, and Perplexity return schema-conforming JSON. DeepSeek supports JSON-object mode only (a valid JSON object is returned, but the schema is not enforced).

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetProviderParams
-- json is a chilkat.JsonObject
-- ok is true, or nil and err on failure
local ok, err = ai:set_provider_params(json)
Introduced in version 11.3.0

Sets additional provider params needed for some pre-defined providers. As of this current version, the possible params are:

  1. azure.clientId, a GUID/UUID such as 17280f2d-f709-4a7b-af1d-9928190e13cf
  2. azure.clientSecret, such as UZc8Q~YBrRIgfe_zbAOwWV.8ikuHa3JJF7LvCdt.
  3. azure.tenantId, a GUID/UUID such as aa4b5625-a31f-44dd-94ec-e2f6c0c64d2c
  4. azure.location, such as eastus
  5. azure.subscription, a GUID/UUID such as 4abd4bf6-5260-4795-90f6-1e91ce4f582c

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SleepMs
-- millisec is an integer
ai:sleep_ms(millisec)
Introduced in version 11.2.0

This method is provided for convenience. It causes the calling thread to sleep for a number of milliseconds.

top
StreamingJsToolCall
-- sb is a chilkat.StringBuilder
-- ok is true, or nil and err on failure
local ok, err = ai:streaming_js_tool_call(sb)
Introduced in version 11.4.0

Handles a js_function_call event within a streaming Ask response loop by automatically executing the requested tool and adding its result to the conversation. The tool may be a JavaScript tool (registered with RegisterJsTools) or an MCP tool (registered with UseMcp).

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
UploadFile
-- path is a string
-- mime_type is a string
-- str is a string, or nil and err on failure
local str, err = ai:upload_file(path, mime_type)
Introduced in version 11.4.0

Uploads a file and returns the file_id (or uri) that can be used to reference the pre-uploaded file using InputAddFileId before an Ask. Files can be uploaded to the following providers: openai, gemini, claude, and grok. The mime_type specifies the MIME type, such as "application/pdf" or "text/plain". If mime_type is the emptys string, Chilkat will automatically choose the MIME type based on the filename extension.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
UploadFileBd
-- bd is a chilkat.BinData
-- filename is a string
-- mime_type is a string
-- str is a string, or nil and err on failure
local str, err = ai:upload_file_bd(bd, filename, mime_type)
Introduced in version 11.4.0

Uploads the contents of bd and returns the file_id (or uri) that can be used to reference the pre-uploaded file using InputAddFileId before an Ask. Files can be uploaded to the following providers: openai, gemini, claude, and grok. The filename is mostly informational. The mime_type specifies the MIME type, such as "application/pdf" or "text/plain". If mime_type is the emptys string, Chilkat will automatically choose the MIME type based on the extension of the filename passed in filename.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
UploadFileSb
-- sb is a chilkat.StringBuilder
-- filename is a string
-- mime_type is a string
-- str is a string, or nil and err on failure
local str, err = ai:upload_file_sb(sb, filename, mime_type)
Introduced in version 11.4.0

Uploads the contents of sb and returns the file_id (or uri) that can be used to reference the pre-uploaded file using InputAddFileId before an Ask. Files can be uploaded to the following providers: openai, gemini, claude, and grok. The filename is mostly informational. The mime_type specifies the MIME type, such as "application/pdf" or "text/plain". If mime_type is the emptys string, Chilkat will automatically choose the MIME type based on the extension of the filename passed in filename. It is the utf-8 byte representation of the string that is uploaded.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
UseMcp
-- c_mcp is a chilkat.Mcp
-- name_prefix is a string
-- ok is true, or nil and err on failure
local ok, err = ai:use_mcp(c_mcp, name_prefix)
Introduced in version 11.6.0

Registers the tools provided by the connected MCP (Model Context Protocol) server c_mcp so the AI model can call them during a conversation. This lists the server's tools (a network operation) and namespaces each tool name using the prefix in name_prefix (to avoid collisions between servers and with JavaScript tools).

When the model requests one of these tools, Chilkat automatically routes the call to the MCP server via Mcp.CallTool, adds the result to the conversation, and continues the Ask. An informational ProgressInfo event named McpToolCall (value = the qualified tool name) is emitted for each automatic call. MCP tools may be mixed with JavaScript tools (RegisterJsTools) in the same conversation.

The c_mcp Mcp object must already be connected (see Mcp.Connect) and must remain valid for as long as its tools are in use. Tool use requires a conversation; it cannot be used with a stateless query.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top

Events

All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, chilkat.Ai reports progress to the functions given to set_event_handler, in a table keyed by event name (plain functions, not methods: closures carry whatever state they need):

ai:set_event_handler({
    percent_done  = function(pct) print(pct .. "%") end,              -- return true to abort
    progress_info = function(name, value) print(name, value) end,
})
ai.heartbeat_ms = 250   -- abort_check is called 4 times per second
ai:set_event_handler({ event_name = function(...) ... end, ... })

Installs the handlers, replacing any installed before; ai:set_event_handler(nil) removes them. The event names are checked when the table is installed: a misspelled one raises an error.

The abort_check handler is called at the interval set by the heartbeat_ms property (0, the default, disables it); percent_done is called when an operation's completion percentage is known; progress_info delivers named progress values. A true return from abort_check or percent_done aborts the running method, which then fails in the usual way (nil, err). An error raised in a handler aborts the method and is raised again from the method call; the object remains usable.

AbortCheck
-- handler: function() ... return abort end -- a true return aborts the method in progress
ai:set_event_handler({ abort_check = function() ... end })

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

More Information and Examples

Example

local deadline = os.time() + 30                  -- give up after 30 seconds
ai.heartbeat_ms = 250                      -- call the handler 4 times per second
ai:set_event_handler({ abort_check = function() return os.time() > deadline end })
top
PercentDone
-- handler: function(pct_done) ... return abort end -- a true return aborts
ai:set_event_handler({ percent_done = function(pct_done) ... end })

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples

Example

ai:set_event_handler({
    percent_done = function(pct_done)     -- 0 to 100
        print("Percent done: " .. pct_done)
        return false                       -- return true to abort the method in progress
    end,
})
top
ProgressInfo
-- handler: function(name, value) ... end
ai:set_event_handler({ progress_info = function(name, value) ... end })

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples

Example

ai:set_event_handler({
    progress_info = function(name, value) print(name .. ": " .. value) end,
})
top