Class Ai
- All Implemented Interfaces:
AutoCloseable
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.
Also see Markdown to HTML Overview. For an extended overview, see Ai Class Overview.
</section>
Event-capable: long-running methods report progress through a ProgressListener installed
with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier),
onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidSends the current potentially multimodal input within the context of the selected conversation and receives the model's output.voiddeleteConvo(String name)Deletes the conversation by itsname.voidexportConvo(String name, JsonObject json)Exports the conversation specified bynametojson, replacingjson's contents with the exported transcript.This is the API key used for authentication.For custom's, use this field name for the API key in the HTTP header, but only if the API key is to be placed in agetProvider()customheader field.Specifies the API specification to be used.Specifies the provider's base URL.booleanIftruea secret specifier of the format "!!part1|part2|.." can be provided instead of the actual value for the ApiKey property.booleanFor multimodal inputs like image data, image URLs, file data, and file URLs, the full data or URL is sent initially.booleangetFunctionCalls(JsonObject json)This method returns the function calls injsonif the output contains any.booleantrueif the response output has function calls.intThe interval in milliseconds between eachevent callback, which enables an application to abort certain method calls before they complete.AbortCheckbooleanThis applies to providers like OpenAI that can maintain conversation state on the server.intThe maximum amount of time to wait for additional incoming data when receiving a response.intThe maximum time in seconds allowed for an automatic JavaScript tool function.voidgetLastJsonData(JsonObject json)Provides details about the last method called on this object instance.booleanRead-only.getModel()The model to be used for AI conversations.voidgetModels(StringTable st)Returns a list of models available to your account, such asGPT-4oandGPT-5.voidgetOutputBd(BinData bd)Returns inbdthe binary output from the last call to, such as for an AI generated image.ask(String)booleangetOutputJson(JsonObject json)Returns the model's structured JSON output from the most recent, parsed intoask(String)json.Returns the text output from the last call to.ask(String)voidReturns the text output, appended tosb, from the last call to.ask(String)Returns the installed listener, ornull.This is the AI provider.Read-only.intThe HTTP response status code for the lastis as follows:ask(String)0indicates an error occurred before receiving an HTTP response.booleangetSearchResults(JsonObject json)Returns the web search sources the model used in the most recent, if web search was enabled via theask(String)web_searchparam of.setAskParams(JsonObject)The currently selected conversation can be set to your desired conversation name.booleanWhen set totrue, themethod operates in streaming mode, returning immediately after the request is sent.ask(String)This is a catch-all property to be used for uncommon needs.voidimportConvo(String name, JsonObject json)Imports the conversation fromjsonand assigns it the name inname.voidinputAddFileData(String filename, BinData bd, String summary)Adds file data, such as a PDF, to the potentially multimodal input that will be sent in the next call to.ask(String)voidinputAddFileId(String file_id, String mime_type)Adds a reference to a previously uploaded file.voidinputAddFileUrl(String url, String summary)Adds a file located at aurlto the potentially multimodal input that will be sent in the next call to.ask(String)voidinputAddFnResult(String call_id, String fnResult)Provide a function call result to the model.voidinputAddImageData(BinData bd, String summary)Adds an image to the potentially multimodal input that will be sent in the next call to.ask(String)voidinputAddImageFileId(String file_id, String mime_type)Adds a reference to a previously uploaded image file.voidinputAddImageUrl(String url, String summary)Adds an image located at aurlto the potentially multimodal input that will be sent in the next call to.ask(String)voidinputAddText(String text)Adds text to the potentially multimodal input that will be sent in the next call to.ask(String)voidAdds text to the potentially multimodal input that will be sent in the next call to.ask(String)voidClears the inputs to be sent in the next call to.ask(String)voidlistConvos(StringTable st)Returns the full list of conversation names inst.voidCreates and initializes a transcript for a new conversation.voidnextAiEvent(int maxWaitMs, StringBuilder sbName, StringBuilder sbDelta)Retrieves the next available AI streaming mode response update.voidonAbortCheck(BooleanSupplier callback)Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it.voidonPercentDone(IntPredicate callback)Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it.voidonProgressInfo(BiConsumer<String,String> callback)Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds.intpollAi(boolean abort)Returns immediately with one of the following values:voidregisterJsTools(StringBuilder sb, boolean evalOnly, boolean allowAllKeyword)Adds JavaScript tool functions to the AI.voidregisterManualTools(JsonObject json)Sets the tools JSON for AI requests.voidSets theApiKeyproperty; seegetApiKey().voidsetApiKeyHeader(String value)Sets theApiKeyHeaderproperty; seegetApiKeyHeader().voidsetApiSpec(String value)Sets theApiSpecproperty; seegetApiSpec().voidsetAskParams(JsonObject json)Sets additionalparams such as:ask(String)effort(see below)max_output_tokens(see below)max_tool_iterations-v11.4.0Applies only to automatic JavaScript tool function calls.voidsetBaseUrl(String value)Sets theBaseUrlproperty; seegetBaseUrl().voidsetConnectionSettings(Socket sock)This method copies connection settings, including HTTP proxy, SOCKS proxy, network interface IP address, and other related settings fromsock.voidsetEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().voidsetFullTranscript(boolean value)Sets theFullTranscriptproperty; seegetFullTranscript().voidsetHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().voidsetHostedConvo(boolean value)Sets theHostedConvoproperty; seegetHostedConvo().voidsetIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().voidsetJsToolTimeout(int value)Sets theJsToolTimeoutproperty; seegetJsToolTimeout().voidSets theModelproperty; seegetModel().voidsetOutputSchema(String name, JsonObject schema, boolean strict)Requests schema-constrained JSON output (structured output) for subsequent calls to.ask(String)voidsetProgressListener(ProgressListener listener)Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.voidsetProvider(String value)Sets theProviderproperty; seegetProvider().voidsetProviderParams(JsonObject json)Sets additional provider params needed for some pre-defined providers.voidsetSelectedConvo(String value)Sets theSelectedConvoproperty; seegetSelectedConvo().voidsetStreaming(boolean value)Sets theStreamingproperty; seegetStreaming().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidsleepMs(int millisec)This method is provided for convenience.voidHandles ajs_function_callevent within a streamingresponse loop by automatically executing the requested tool and adding its result to the conversation.ask(String)uploadFile(String path, String mimeType)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.uploadFileBd(BinData bd, String filename, String mimeType)Uploads the contents ofbdand returns the file_id (or uri) that can be used to reference the pre-uploaded file using InputAddFileId before an Ask.uploadFileSb(StringBuilder sb, String filename, String mimeType)Uploads the contents ofsband returns the file_id (or uri) that can be used to reference the pre-uploaded file using InputAddFileId before an Ask.voidRegisters the tools provided by the connected MCP (Model Context Protocol) servercMcpso the AI model can call them during a conversation.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Ai
public Ai()Creates a newAiobject.
-
-
Method Details
-
getApiKey
This is the API key used for authentication. Use your API key that matches your.getProvider()Suggestion: Use Chilkat's
Secretsclass 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
- Returns:
- the value of the
ApiKeyproperty
-
setApiKey
Sets theApiKeyproperty; seegetApiKey().- Parameters:
value- the new value (notnull)
-
getApiKeyHeader
For custom's, use this field name for the API key in the HTTP header, but only if the API key is to be placed in agetProvider()customheader 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.
- Returns:
- the value of the
ApiKeyHeaderproperty
-
setApiKeyHeader
Sets theApiKeyHeaderproperty; seegetApiKeyHeader().- Parameters:
value- the new value (notnull)
-
getApiSpec
Specifies the API specification to be used. Possible choices areChatCompletions,Responses,Gemini,Anthropic. The default value isResponsesbecause the default value of theproperty isgetProvider()openai. Setting theproperty to a value other thangetProvider()customwill also automatically set this property to the correct and needed value.- Returns:
- the value of the
ApiSpecproperty
-
setApiSpec
Sets theApiSpecproperty; seegetApiSpec().- Parameters:
value- the new value (notnull)
-
getBaseUrl
Specifies the provider's base URL. For example,http://localhost:11434/v1orhttps://api.together.xyz/v1. The default value ishttps://api.openai.com/v1because the default value of theproperty isgetProvider()openai. Setting theproperty to a value other thangetProvider()customwill also automatically set this property to the correct and needed value.- Returns:
- the value of the
BaseUrlproperty
-
setBaseUrl
Sets theBaseUrlproperty; seegetBaseUrl().- Parameters:
value- the new value (notnull)
-
getEnableSecrets
public boolean getEnableSecrets()Iftruea secret specifier of the format "!!part1|part2|.." can be provided instead of the actual value for the ApiKey property.The default value is
false.- Returns:
- the value of the
EnableSecretsproperty
-
setEnableSecrets
public void setEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().- Parameters:
value- the new value
-
getFullTranscript
public boolean getFullTranscript()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 totrue, the full data/URL is re-sent in subsequent interactions. If set tofalse, 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.- Returns:
- the value of the
FullTranscriptproperty
-
setFullTranscript
public void setFullTranscript(boolean value)Sets theFullTranscriptproperty; seegetFullTranscript().- Parameters:
value- the new value
-
getHasFunctionCalls
public boolean getHasFunctionCalls()trueif the response output has function calls. Otherwisefalse. This only applies to manual function tool calling, not automatic JS tool calls.- Returns:
- the value of the
HasFunctionCallsproperty (read-only)
-
getHeartbeatMs
public int getHeartbeatMs()The interval in milliseconds between eachevent callback, which enables an application to abort certain method calls before they complete. By default, HeartbeatMs is set toAbortCheck0, meaning no AbortCheck event callbacks will trigger.- Returns:
- the value of the
HeartbeatMsproperty
-
setHeartbeatMs
public void setHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().- Parameters:
value- the new value
-
getHostedConvo
public boolean getHostedConvo()This applies to providers like OpenAI that can maintain conversation state on the server. If set totrue, only the conversation ID is sent with each query. If set tofalse, 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.- Returns:
- the value of the
HostedConvoproperty
-
setHostedConvo
public void setHostedConvo(boolean value)Sets theHostedConvoproperty; seegetHostedConvo().- Parameters:
value- the new value
-
getIdleTimeoutMs
public int getIdleTimeoutMs()The maximum amount of time to wait for additional incoming data when receiving a response. The default value is90000(90 seconds) inv11.3.0and earlier. Starting inv11.4.0, the default value is180000(180 seconds).This is not a total timeout, but the maximum time allowed when data transmission has paused.
- Returns:
- the value of the
IdleTimeoutMsproperty
-
setIdleTimeoutMs
public void setIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().- Parameters:
value- the new value
-
getJsToolTimeout
public int getJsToolTimeout()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.- Returns:
- the value of the
JsToolTimeoutproperty
-
setJsToolTimeout
public void setJsToolTimeout(int value)Sets theJsToolTimeoutproperty; seegetJsToolTimeout().- Parameters:
value- the new value
-
getLastResponseRefused
public boolean getLastResponseRefused()Read-only.trueif the model refused to produce the requested structured output during the most recent. When a refusal occurs,ask(String)returnsgetOutputJson(JsonObject)falseand the provider's explanation is available in. This property is reset at the start of eachgetRefusalText().ask(String)- Returns:
- the value of the
LastResponseRefusedproperty (read-only)
-
getModel
The model to be used for AI conversations. For example,GPT-4oorGPT-5. The list of available models can be obtained by calling.getModels(StringTable)The default value is the empty string. A model must always be specified. Chilkat won't try to guess or default to a model.
- Returns:
- the value of the
Modelproperty
-
setModel
Sets theModelproperty; seegetModel().- Parameters:
value- the new value (notnull)
-
getProvider
This is the AI provider. Possible values are:openai,google,claude,deepseek,perplexity,mistral, andxai.Starting in Chilkat
v11.3.0, this property can be set tocustom, and theandgetBaseUrl()properties can also be set to fully specify the provider.getApiSpec()Starting in
v11.6.0, this property can also be set toopenai-compatible, a convenience alias for acustomprovider that speaks the OpenAI Chat Completions API. It presetstogetApiSpec()ChatCompletions, so you only need to set(plusgetBaseUrl()andgetApiKey()). This is the simplest way to use OpenAI-compatible endpoints such as Ollama, LM Studio, OpenWebUI, and many hosting providers.getModel()Note:
mistralis recognized as a pre-configured known provider starting inv11.4.0.The default value is
openai.- Returns:
- the value of the
Providerproperty
-
setProvider
Sets theProviderproperty; seegetProvider().- Parameters:
value- the new value (notnull)
-
getRefusalText
Read-only. WhenisgetLastResponseRefused()true, this is the model's message explaining why it declined to produce the requested structured output. Otherwise it is the empty string.- Returns:
- the value of the
RefusalTextproperty (read-only)
-
getResponseStatusCode
public int getResponseStatusCode()The HTTP response status code for the lastis as follows:ask(String)0indicates an error occurred before receiving an HTTP response.200indicates a successful response.- A failed response has a status code of
400or higher.
- Returns:
- the value of the
ResponseStatusCodeproperty (read-only)
-
getSelectedConvo
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.- Returns:
- the value of the
SelectedConvoproperty
-
setSelectedConvo
Sets theSelectedConvoproperty; seegetSelectedConvo().- Parameters:
value- the new value (notnull)
-
getStreaming
public boolean getStreaming()When set totrue, themethod 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 isask(String)false.- Returns:
- the value of the
Streamingproperty
-
setStreaming
public void setStreaming(boolean value)Sets theStreamingproperty; seegetStreaming().- Parameters:
value- the new value
-
getUncommonOptions
This is a catch-all property to be used for uncommon needs. This property defaults to the empty string, and should typically remain empty.- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
ask
Sends the current potentially multimodal input within the context of the selected conversation and receives the model's output. Prior tov11.4.0theoutputTypeis limited totext. Starting inv11.4.0, theoutputTypecan be set toimagefor 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
falseand nothing will occur.- Parameters:
outputType- theoutputTypeargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
deleteConvo
Deletes the conversation by itsname. Ifnameequals*then all conversations are deleted.- Parameters:
name- thenameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
exportConvo
Exports the conversation specified bynametojson, replacingjson's contents with the exported transcript. You can later import a conversation using. The currently selected conversation can be exported by passingimportConvo(String, JsonObject)*for thename.- Parameters:
name- thenameargument (notnull)json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getFunctionCalls
This method returns the function calls injsonif the output contains any. Returnstrueif one or more function calls were returned, otherwise returnsfalse. This only applies to manual function tool calling, not automatic JS tool calls.- Parameters:
json- thejsonargument (notnull)- Returns:
- the result; this method never throws
ChilkatException
-
getLastJsonData
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(StringTable)- Parameters:
json- thejsonargument (notnull)
-
getModels
Returns a list of models available to your account, such asGPT-4oandGPT-5. The models are listed inst, sorted in ascending, case-insensitive order. To access the raw JSON response after calling this method, use.getLastJsonData(JsonObject)- Parameters:
st- thestargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getOutputBd
Returns inbdthe binary output from the last call to, such as for an AI generated image.ask(String)- Parameters:
bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getOutputJson
Returns the model's structured JSON output from the most recent, parsed intoask(String)json. Use this after setting a schema with. ReturnssetOutputSchema(String, JsonObject, boolean)trueand populatesjsonwhen the output is valid JSON. Returnsfalseif the model refused to produce the output (in which caseisgetLastResponseRefused()trueandcontains the explanation), if there is no output, or if the output is not valid JSON. The raw JSON text is also available fromgetRefusalText().getOutputText()- Parameters:
json- thejsonargument (notnull)- Returns:
- the result; this method never throws
ChilkatException
-
getOutputText
Returns the text output from the last call to.ask(String)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getOutputTextSb
Returns the text output, appended tosb, from the last call to.ask(String)- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getSearchResults
Returns the web search sources the model used in the most recent, if web search was enabled via theask(String)web_searchparam of. ReturnssetAskParams(JsonObject)trueif the lastperformed one or more web searches, in which case the normalized results are placed inask(String)json. Returnsfalseif no web search occurred.Chilkat normalizes the differing citation formats of each AI provider into a single flat structure.
jsonis 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
snippetandpage_agemembers are populated only when the provider supplies them, and may be absent otherwise. Each provider returns a different citation shape (for example, OpenAI returnsurl_citationannotations with character offsets, Anthropic returnsweb_search_tool_resultcontent blocks, Google returnsgroundingMetadata, and Perplexity returns asearch_resultsarray). The full, unmodified provider response — including any character-offset annotations not represented in the normalized form — remains available via.getLastJsonData(JsonObject)Streaming: In streaming mode, a standardized
web_search_callevent is delivered throughwhen the provider begins a search, and the normalized results are available from this method after thenextAiEvent(int, StringBuilder, StringBuilder)null_terminatorevent completes the response.- Parameters:
json- thejsonargument (notnull)- Returns:
- the result; this method never throws
ChilkatException
-
importConvo
Imports the conversation fromjsonand assigns it the name inname.- Parameters:
name- thenameargument (notnull)json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddFileData
Adds file data, such as a PDF, to the potentially multimodal input that will be sent in the next call to. Theask(String)bdcontains the file data.If
is _CKFALSE_,getFullTranscript()summaryis sent in subsequent interactions instead of the file data. IfisgetFullTranscript()true,summaryis not sent, and the file data is re-sent in each interaction.This method cannot be used with
DeepSeek.- Parameters:
filename- thefilenameargument (notnull)bd- thebdargument (notnull)summary- thesummaryargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddFileId
Adds a reference to a previously uploaded file. Thefile_idis the id returned from the provider when originally uploading the file. Themime_type, such as "application/pdf", "application/json", "text/xml", etc. is needed for some AI providers such as Google.- Parameters:
file_id- thefile_idargument (notnull)mime_type- themime_typeargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddFileUrl
Adds a file located at aurlto the potentially multimodal input that will be sent in the next call to.ask(String)If
is _CKFALSE_,getFullTranscript()summaryis sent in subsequent interactions instead of the file URL. IfisgetFullTranscript()true,summaryis not sent, and the file URL is re-sent in each interaction.This method cannot be used with
DeepSeek.- Parameters:
url- theurlargument (notnull)summary- thesummaryargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddFnResult
Provide a function call result to the model. This only applies tomanual function tool calling, not automatic JS tool calls.- Parameters:
call_id- thecall_idargument (notnull)fnResult- thefnResultargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddImageData
Adds an image to the potentially multimodal input that will be sent in the next call to. Theask(String)bdcontains the images data. The image data must be jpeg, png, or webp format.If
is _CKFALSE_,getFullTranscript()summaryis sent in subsequent interactions instead of the image data. IfisgetFullTranscript()true,summaryis 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.- Parameters:
bd- thebdargument (notnull)summary- thesummaryargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddImageFileId
Adds a reference to a previously uploaded image file. Thefile_idis the id returned from the provider when originally uploading the file. Themime_type, such as "image/jpeg" is needed for some AI providers such as Google.Note: At this time, only
OpenAIandGooglesupport the ability to upload once → get file_id → reuse in later requests' workflow for images.- Parameters:
file_id- thefile_idargument (notnull)mime_type- themime_typeargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddImageUrl
Adds an image located at aurlto the potentially multimodal input that will be sent in the next call to.ask(String)If
is _CKFALSE_,getFullTranscript()summaryis sent in subsequent interactions instead of the image URL. IfisgetFullTranscript()true,summaryis 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.- Parameters:
url- theurlargument (notnull)summary- thesummaryargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddText
Adds text to the potentially multimodal input that will be sent in the next call to.ask(String)- Parameters:
text- thetextargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputAddTextSb
Adds text to the potentially multimodal input that will be sent in the next call to.ask(String)- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
inputClear
public void inputClear()Clears the inputs to be sent in the next call to.ask(String) -
listConvos
Returns the full list of conversation names inst.- Parameters:
st- thestargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
newConvo
Creates and initializes a transcript for a new conversation. Thenameis a unique name for the conversation. You can reference the conversation by this name, such as for themethod.exportConvo(String, JsonObject)The
sysMsgsets 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
devMsgprovides 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
. You can use any unique name for a conversation exceptgetSelectedConvo()*.- Parameters:
name- thenameargument (notnull)sysMsg- thesysMsgargument (notnull)devMsg- thedevMsgargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
nextAiEvent
Retrieves the next available AI streaming mode response update. Use themethod to check if a response update is immediately accessible. The event name is returned inpollAi(boolean)sbName. If the event name isdelta, the text is returned insbDelta.For the complete raw event JSON, use the
function. Note that the raw JSON format varies by AI provider.getLastJsonData(JsonObject)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. Callto run it. This covers both JavaScript tools (streamingJsToolCall(StringBuilder)) and MCP tools (registerJsTools(StringBuilder, boolean, boolean)).useMcp(Mcp, String)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 fromafter the response completes.getSearchResults(JsonObject)
maxWaitMsdefines the maximum wait time to receive the complete event. For instance, ifsignals 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.pollAi(boolean)- Parameters:
maxWaitMs- themaxWaitMsargumentsbName- thesbNameargument (notnull)sbDelta- thesbDeltaargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
pollAi
public int pollAi(boolean abort)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 vianextAiEvent(int, StringBuilder, StringBuilder)
2- The streaming AI response has already completed, or no streaming response is ongoing.If
abortistrue, then the streaming response is aborted and this method returns the value2. Applications should pass infalseforabortto continue streaming.- Parameters:
abort- theabortargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
registerJsTools
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 insb. IfevalOnlyistrue, then thesbcontains JavaScript to be run for the purpose of adding supporting functions and does not contain atoolRegistry.The
allowAllKeywordindicates whether theallkeyword is allowed in thetoolPermissions. 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 tofalse.- Parameters:
sb- thesbargument (notnull)evalOnly- theevalOnlyargumentallowAllKeyword- theallowAllKeywordargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
registerManualTools
Sets the tools JSON for AI requests.- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAskParams
Sets additionalparams such as:ask(String)effort(see below)max_output_tokens(see below)max_tool_iterations-v11.4.0Applies only to automatic JavaScript tool function calls. Sets a maximum number of AI model tool responses that can be received. The default is5. 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.0A 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.0Adds even more detailed logging to the, more than what is added when theChilkatObject.getLastErrorText()property is enabled.ChilkatObject.getVerboseLogging()
effortThe
effortcan be set tonone,minimal,low,medium, orhigh.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|highAnthropic Claude
output_config.effort→low|medium|highGoogle Gemini
generationConfig.thinkingConfig.thinkingLevel→LOW|HIGHOpenAI Chat Completions
reasoning_effort→none|minimal|low|medium|highmax_output_tokensMax 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_tokensAnthropic Claude
max_tokensGoogle Gemini
generationConfig.maxOutputTokensOpenAI Chat Completions
max_completion_tokensTypical 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
temperatureMost modern AI APIs (including OpenAI’s) allow a
temperaturerange from 0.0 to 2.0. Chilkat will ignore and not send atemperaturehaving 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 inv11.6.0)The
web_searchparam 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, the retrieved sources can be obtained by callingask(String).getSearchResults(JsonObject)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
and silently ignores fields the provider does not support. OnlygetProvider()enabledis required; every other field is optional.enabled— Iftrue, web search is offered to the model for this. Forask(String)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 bothallowed_domainsandblocked_domainsin the same request unless the provider permits it.recency— Limits results by age. Possible values areday,week,month, oryear.user_location— An optional object withcountry,city,region, andtimezonemembers used to localize results.
Provider support matrix
Field openai claude google xai perplexity
enabledweb_search tool web_search tool google_search web_search tool always onmax_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, onlyallowed_domainsandblocked_domains(each limited to 5 domains, and mutually exclusive) are supported. xAI's older chat-completions "Live Search" is deprecated.Not supported:
deepseekandmistral(chat) do not expose a web search tool. Ifweb_searchis set for these providers, theproceeds without search and a note is written to theask(String). This keeps provider-switching code working when only theChilkatObject.getLastErrorText()property changes.getProvider()Billing note: Most providers bill web searches separately from tokens (typically per 1,000 searches). Use
max_useswhere supported to bound per-request cost.Streaming: When
is enabled, agetStreaming()web_search_callevent is delivered throughwhile the provider performs a search.nextAiEvent(int, StringBuilder, StringBuilder)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setConnectionSettings
This method copies connection settings, including HTTP proxy, SOCKS proxy, network interface IP address, and other related settings fromsock. It's optional; if not used, default settings apply. Call this method before sending REST API requests to an AI provider.- Parameters:
sock- thesockargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setOutputSchema
Requests schema-constrained JSON output (structured output) for subsequent calls to.ask(String)nameis a short schema name (letters, digits, underscores, and hyphens) used as an identifier by some providers.schemais the desired output shape as a JSON Schema.strict(strict) requests strict conformance where the provider supports it.Pass an empty string for
nameto clear a previously-set schema, which disables structured output.When
strict(strict) istrue, Chilkat automatically augments the schema for the providers that require it — adding"additionalProperties": falseand marking every propertyrequiredon each object — so an ordinary JSON Schema can be supplied. For example,schemamight be:{ "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "required": ["name", "age"] }After
, the model's JSON is available as text fromask(String)or parsed fromgetOutputText().getOutputJson(JsonObject)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).
- Parameters:
name- thenameargument (notnull)schema- theschemaargument (notnull)strict- thestrictargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setProviderParams
Sets additional provider params needed for some pre-defined providers. As of this current version, the possible params are:azure.clientId, a GUID/UUID such as 17280f2d-f709-4a7b-af1d-9928190e13cfazure.clientSecret, such as UZc8Q~YBrRIgfe_zbAOwWV.8ikuHa3JJF7LvCdt.azure.tenantId, a GUID/UUID such as aa4b5625-a31f-44dd-94ec-e2f6c0c64d2cazure.location, such aseastusazure.subscription, a GUID/UUID such as 4abd4bf6-5260-4795-90f6-1e91ce4f582c
- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sleepMs
public void sleepMs(int millisec)This method is provided for convenience. It causes the calling thread to sleep for a number of milliseconds.- Parameters:
millisec- themillisecargument
-
streamingJsToolCall
Handles ajs_function_callevent within a streamingresponse loop by automatically executing the requested tool and adding its result to the conversation. The tool may be a JavaScript tool (registered withask(String)) or an MCP tool (registered withregisterJsTools(StringBuilder, boolean, boolean)).useMcp(Mcp, String)- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
uploadFile
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. ThemimeTypespecifies the MIME type, such as "application/pdf" or "text/plain". IfmimeTypeis the emptys string, Chilkat will automatically choose the MIME type based on the filename extension.- Parameters:
path- thepathargument (notnull)mimeType- themimeTypeargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
uploadFileBd
Uploads the contents ofbdand 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. Thefilenameis mostly informational. ThemimeTypespecifies the MIME type, such as "application/pdf" or "text/plain". IfmimeTypeis the emptys string, Chilkat will automatically choose the MIME type based on the extension of the filename passed infilename.- Parameters:
bd- thebdargument (notnull)filename- thefilenameargument (notnull)mimeType- themimeTypeargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
uploadFileSb
Uploads the contents ofsband 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. Thefilenameis mostly informational. ThemimeTypespecifies the MIME type, such as "application/pdf" or "text/plain". IfmimeTypeis the emptys string, Chilkat will automatically choose the MIME type based on the extension of the filename passed infilename. It is the utf-8 byte representation of the string that is uploaded.- Parameters:
sb- thesbargument (notnull)filename- thefilenameargument (notnull)mimeType- themimeTypeargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
useMcp
Registers the tools provided by the connected MCP (Model Context Protocol) servercMcpso 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 innamePrefix(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. An informationalask(String)ProgressInfoevent namedMcpToolCall(value = the qualified tool name) is emitted for each automatic call. MCP tools may be mixed with JavaScript tools () in the same conversation.registerJsTools(StringBuilder, boolean, boolean)The
cMcpMcpobject must already be connected (seeMcp.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.- Parameters:
cMcp- thecMcpargument (notnull)namePrefix- thenamePrefixargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setProgressListener
Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.- Parameters:
listener- the listener, ornull- Throws:
IllegalStateException- if called from inside one of this object's own callbacks
-
getProgressListener
Returns the installed listener, ornull.- Returns:
- the listener installed with
setProgressListener(ProgressListener)or one of theon...methods
-
onAbortCheck
Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onPercentDone
Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onProgressInfo
Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-