Class AbstractAIProvider
- All Implemented Interfaces:
Genai
- Direct Known Subclasses:
AnthropicProvider,OpenAIProvider,ToolsProvider
Genai contract shared by concrete provider
integrations.
This class centralizes common configuration handling, request input logging, tool invocation safety, MCP/web-search bootstrap logic, and usage accounting state used by subclasses such as OpenAI- and Claude-based providers.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected StringActive model identifier used inGenai.perform().static final StringDefault web search type name.protected StringOptional instructions applied to the request.static final StringLine separator used when composing prompts.static final StringConfiguration property name indicating whether provider inputs should be logged.static final intMaximum length for log lines.static final StringSeparator for log sections.static final longDefault maximum number of tokens the model may generate.protected LongMaximum number of output tokens for responses.protected LongMaximum number of tool calls permitted per response.protected static final StringPrefix for MCP property names.static final StringParagraph separator used when composing prompts.static final StringEnvironment variable name for authenticating with the GenAI provider.static final StringName of the project directory parameter.protected FileWorking directory passed to tool handlers as contextual information.static final StringConfiguration property name for the target GenAI server identifier.protected LongRequest timeout in seconds;0means SDK defaults are used.static final StringEnvironment variable name for authenticating with the GenAI provider. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddMcpServer(String label, String url, String authorization, String description) Registers one MCP server/tool with the underlying provider SDK.protected voidReads sequential MCP server configuration groups and registers them with the concrete provider implementation.protected voidaddPrompt(String name, String description, ToolFunction function, Role role, ParamDescriptor... paramsDesc) Registers a prompt callback for providers that support prompt tools.voidaddPrompts(FunctionTools tools) Scans the providedFunctionToolsinstance for methods annotated withPrompt, and registers each prompt using its name, description, and role.protected abstract voidaddTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc) Adds a tool to the provider.voidaddTools(FunctionTools tools) Registers all annotated tool methods from the givenFunctionToolsinstance.protected voidRegisters a web-search capability when enabled in configuration.protected voidaddWebSearch(String type, String city, String country, String region) Registers a provider-specific web-search tool.voidclear()Clears the provider state.protected StringgetParamValue(com.fasterxml.jackson.databind.JsonNode props, String paramName, String defaultValue) Retrieves the value for a parameter from the given JSON node, or returns the default value if not present.Returns the current project directory.longReturns the configured request timeout.voidinit(String model, Configurator config) Initializes the provider from the given configuration.voidEnables request input logging to the given file.voidinstructions(String instructions) Sets system-level instructions applied to subsequent requests.booleanReturns whether runtime tool errors are handled conversationally.protected voidWrites the current request inputs toinputsLogwhen logging is enabled.protected voidlogInputsSpec(Writer streamWriter) Writes provider-specific input items to the supplied log writer.protected StringNormalizes a string for case-insensitive comparisons.voidSets the prompt text for the provider.protected StringsafelyInvokeTool(String name, ToolFunction tool, com.fasterxml.jackson.databind.JsonNode params, File projectDir) Safely invokes a tool function and convertsIOExceptions into a textual error payload suitable for the model conversation.voidsetErrorHandling(boolean errorHandling) Configures how runtime tool errors are handled by the invocation logic.voidsetProjectDir(File projectDir) Sets the project directory.voidsetTimeout(long timeout, OpenAIProvider openAIProvider) Sets the timeout value used by provider client creation.
-
Field Details
-
LOG_LINE_LENG
public static final int LOG_LINE_LENGMaximum length for log lines.- See Also:
-
LOG_INPUTS_PROP_NAME
Configuration property name indicating whether provider inputs should be logged.- See Also:
-
SERVERID_PROP_NAME
Configuration property name for the target GenAI server identifier.- See Also:
-
USERNAME_PROP_NAME
Environment variable name for authenticating with the GenAI provider.- See Also:
-
PASSWORD_PROP_NAME
Environment variable name for authenticating with the GenAI provider.- See Also:
-
LINE_SEPARATOR
Line separator used when composing prompts.- See Also:
-
PARAGRAPH_SEPARATOR
Paragraph separator used when composing prompts.- See Also:
-
MCP_PROP_NAME_PREFIX
Prefix for MCP property names.- See Also:
-
MAX_OUTPUT_TOKENS
public static final long MAX_OUTPUT_TOKENSDefault maximum number of tokens the model may generate.- See Also:
-
DEFAULT_WEBSEARCH_TYPE_NAME
Default web search type name.- See Also:
-
LOG_SECTION_SEPARATOR
Separator for log sections.- See Also:
-
PROJECT_DIR_PARAM_NAME
Name of the project directory parameter.- See Also:
-
chatModel
Active model identifier used inGenai.perform(). -
projectDir
Working directory passed to tool handlers as contextual information. -
timeoutSec
Request timeout in seconds;0means SDK defaults are used. -
instructions
Optional instructions applied to the request. -
maxOutputTokens
Maximum number of output tokens for responses. -
maxToolCalls
Maximum number of tool calls permitted per response.
-
-
Constructor Details
-
AbstractAIProvider
public AbstractAIProvider()Creates a provider base instance.Subclasses are expected to complete initialization in
init(String, Configurator).
-
-
Method Details
-
init
Initializes the provider from the given configuration. -
addMcpServers
protected void addMcpServers()Reads sequential MCP server configuration groups and registers them with the concrete provider implementation.The method looks for configuration keys named
MCP.*, thenMCP_1.*,MCP_2.*, and so on until no further URL is found. -
addMcpServer
Registers one MCP server/tool with the underlying provider SDK.- Parameters:
label- provider-visible MCP server labelurl- server endpoint URLauthorization- optional authorization token/valuedescription- optional human-readable description
-
addWebSearch
protected void addWebSearch()Registers a web-search capability when enabled in configuration.The default implementation reads configuration values and delegates the actual SDK-specific registration to
addWebSearch(String, String, String, String). -
addWebSearch
Registers a provider-specific web-search tool.- Parameters:
type- provider-specific web-search tool type/versioncity- optional user citycountry- optional user countryregion- optional user region
-
normalize
Normalizes a string for case-insensitive comparisons.- Parameters:
value- source value- Returns:
- lower-cased value, or an empty string when the input is
null
-
safelyInvokeTool
protected String safelyInvokeTool(String name, ToolFunction tool, com.fasterxml.jackson.databind.JsonNode params, File projectDir) Safely invokes a tool function and convertsIOExceptions into a textual error payload suitable for the model conversation.- Parameters:
name- tool nametool- tool handlerparams- parsed tool parametersprojectDir- working directory passed to the tool- Returns:
- tool output or a formatted error message
-
logInputs
protected void logInputs()Writes the current request inputs toinputsLogwhen logging is enabled. -
logInputsSpec
Writes provider-specific input items to the supplied log writer.- Parameters:
streamWriter- destination writer- Throws:
IOException- when writing fails
-
instructions
Sets system-level instructions applied to subsequent requests.- Specified by:
instructionsin interfaceGenai- Parameters:
instructions- instruction text, ornullto clear
-
inputsLog
Enables request input logging to the given file. -
getTimeout
public long getTimeout()Returns the configured request timeout.- Returns:
- timeout in seconds;
0indicates the SDK default
-
setTimeout
Sets the timeout value used by provider client creation.The second parameter is unused and retained only for API compatibility.
- Parameters:
timeout- timeout in seconds; use0to use SDK defaultsopenAIProvider- ignored compatibility parameter
-
addTool
protected abstract void addTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc) Adds a tool to the provider.- Parameters:
name- the tool namedescription- the tool descriptionfunction- the tool function implementationparamsDesc- descriptors for the tool parameters
-
addTools
Registers all annotated tool methods from the givenFunctionToolsinstance. -
addPrompts
Scans the providedFunctionToolsinstance for methods annotated withPrompt, and registers each prompt using its name, description, and role.For each method in the tools class, if a
Promptannotation is present, the method extracts the prompt's description, name (using the method name if not defined in the annotation), and role, then callsaddPrompt(FunctionTools, Method, String, String, Role)to register the prompt.- Specified by:
addPromptsin interfaceGenai- Parameters:
tools- TheFunctionToolsinstance whose methods will be scanned forPromptannotations.
-
addPrompt
protected void addPrompt(String name, String description, ToolFunction function, Role role, ParamDescriptor... paramsDesc) Registers a prompt callback for providers that support prompt tools.- Parameters:
name- prompt name exposed to the providerdescription- prompt description used by the providerfunction- callback used to resolve the prompt contentrole- role associated with the generated promptparamsDesc- descriptors for prompt input parameters
-
getParamValue
protected String getParamValue(com.fasterxml.jackson.databind.JsonNode props, String paramName, String defaultValue) Retrieves the value for a parameter from the given JSON node, or returns the default value if not present.- Parameters:
props- the JSON node containing parametersparamName- the parameter namedefaultValue- the default value to use if not present- Returns:
- the parameter value as a string
-
getProjectDir
Returns the current project directory.- Returns:
- the projectDir
-
setProjectDir
Sets the project directory.- Specified by:
setProjectDirin interfaceGenai- Parameters:
projectDir- the projectDir to set
-
prompt
Sets the prompt text for the provider. -
clear
public void clear()Clears the provider state. -
isErrorHandling
public boolean isErrorHandling()Returns whether runtime tool errors are handled conversationally.- Returns:
- the errorHandling
-
setErrorHandling
public void setErrorHandling(boolean errorHandling) Configures how runtime tool errors are handled by the invocation logic.Use this setter to toggle between conversational error recovery and strict, fail-fast exception reporting.
Behavior Summary:
setErrorHandling(true)(Default): Captures all standard runtime tool exceptions and returns them in a text payload (e.g."Error: The functional tool call failed..."). This permits conversational LLM agents to review the failure description and attempt self-correction.setErrorHandling(false): Re-throws all invocation exceptions as a wrappedSpecialExceptionup the current thread execution. Use this setting to debug and fail execution immediately upon the first unhandled exception.
- Specified by:
setErrorHandlingin interfaceGenai- Parameters:
errorHandling-trueto enable conversational intercept and recovery;falseto disable intercept and trigger strict stack propagation.
-
getConfigurator
- Returns:
- the config
-