Class AbstractAIProvider
- All Implemented Interfaces:
ProcessProvider
ProcessProvider 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 inProcessProvider.perform().private ConfiguratorConfiguration source used to initialize clients and provider features.static final StringDefault web search type name.static final StringPrefix prepended to tool invocation error messages that are returned back to the LLM.private booleanFlag indicating if standard runtime exceptions should be wrapped or handled conversationally.protected StringOptional instructions applied to the request.static final StringLine separator used when composing prompts.static final intMaximum length for log lines.(package private) static org.slf4j.LoggerLogger instance for this provider.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.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.private voidConfigures and registers a single prompt method.voidaddPrompts(FunctionTools tools) Registers all annotated prompt methods from the givenFunctionToolsinstance.protected voidaddResource(URI uri, String description, String mimeType, ToolFunction function, ParamDescriptor... paramsDesc) Registers a resource callback for providers that support resource management tools.private voidaddResource(FunctionTools tools, Method method, String[] uris, String description, String mimeType) Resolves resource endpoints from declared arrays and binds them to the implementation context.voidaddResources(FunctionTools tools) Scans the providedFunctionToolsinstance for methods annotated withResource, and registers each resource for use during a run.protected abstract voidaddTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc) Adds a tool to the provider.private voidaddTool(FunctionTools tools, Method method, String name, String description) Configures and registers a single tool method.voidaddTools(FunctionTools tools, String[] enabledTools) Registers tool methods from the givenFunctionToolsinstance, filtering them based on an optional array of enabled tool patterns.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.private ParamDescriptor[]fillParamDesc(Method method) Analyzes method signature annotations to build an array of parameter descriptions.Returns the configurator context source.private <T> TgetParamByType(Class<T> type, Object[] paramsByType) Filters parameter arrays to find the first assignment-compatible instance of the specified type.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.voidinstructions(String instructions) Sets system-level instructions applied to subsequent requests.private StringinterpolateDescription(String description) Interpolates system metadata variables (e.g., OS Name) inside the annotation's tool description text before registering it with the LLM.private Objectinvoke(FunctionTools tools, Method method, com.fasterxml.jackson.databind.JsonNode props, Object... paramsByType) Dynamically invokes the specified method on the given tools instance, matching arguments dynamically.booleanReturns whether runtime tool errors are handled conversationally.protected StringNormalizes a string for case-insensitive comparisons.voidSets the prompt text for the provider.protected ObjectsafelyInvokeTool(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) Sets the timeout value used by provider client creation.static StringtoSnakeCase(String input) Converts a given string into snake_case format.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.machanism.machai.process.provider.ProcessProvider
getToolNames, perform
-
Field Details
-
logger
static org.slf4j.Logger loggerLogger instance for this provider. -
ERROR_TOOL_RESULT_PREFIX
Prefix prepended to tool invocation error messages that are returned back to the LLM.- 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:
-
LOG_LINE_LENG
public static final int LOG_LINE_LENGMaximum length for log lines. Configures the truncation threshold when logging tool parameters and result strings.- 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:
-
PROJECT_DIR_PARAM_NAME
Name of the project directory parameter.- See Also:
-
chatModel
Active model identifier used inProcessProvider.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. -
config
Configuration source used to initialize clients and provider features. -
errorHandling
private boolean errorHandlingFlag indicating if standard runtime exceptions should be wrapped or handled conversationally.
-
-
Constructor Details
-
AbstractAIProvider
protected 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.- Specified by:
initin interfaceProcessProvider- Parameters:
model- the model identifier to useconfig- provider configuration source
-
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.This is an optional lifecycle method intended to be overridden by subclasses that natively support the Model Context Protocol (MCP).
- 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.This is an optional capability hook intended to be overridden by subclasses whose underlying models natively support real-time web-search tools.
- 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 Object 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 string
- Throws:
SpecialException- if a non-recoverable error occurs or when error-handling is disabled
-
instructions
Sets system-level instructions applied to subsequent requests.- Specified by:
instructionsin interfaceProcessProvider- Parameters:
instructions- instruction text, ornullto clear
-
getTimeout
public long getTimeout()Returns the configured request timeout.- Returns:
- timeout in seconds;
0indicates the SDK default
-
setTimeout
public void setTimeout(long timeout) 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 defaults
-
addTool
protected abstract void addTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc) Adds a tool to the provider.Implemented by concrete subclasses to register the functional tool definition with the provider's specific API schemas (such as OpenAI's Tool schema or Claude's Tool definition).
- Parameters:
name- the tool namedescription- the tool descriptionfunction- the tool function implementation callbackparamsDesc- descriptors for the tool parameters
-
addTools
Registers tool methods from the givenFunctionToolsinstance, filtering them based on an optional array of enabled tool patterns.This method inspects all public methods of the provided
toolsobject using reflection, looking for methods annotated withTool. For each annotated method, it performs the following steps:- Extracts and interpolates the tool's description via
interpolateDescription(String). - Determines the tool's name — either from
Tool.name()if explicitly set, or falls back to the method's name ifTool.name()equalsTool.NOT_DEFINED. - Builds a fully qualified tool name in the format
<ClassName>:<toolName>. - Checks whether the tool should be registered based on the
enabledToolsfilter (see below for filtering logic). - If the tool passes the filter, it is registered via
addTool(FunctionTools, Method, String, String).
Filtering logic:
- If
enabledToolsisnull, all annotated tools are registered without restriction. - If
enabledToolsis provided, each entry is treated as a regular expression pattern. A tool is registered only if its fully qualified name matches at least one of the provided patterns (usingPattern.compile(String)andMatcher.find()). - When
enabledToolsis notnulland a tool matches, an informational log entry is written indicating which tool was enabled.
- Specified by:
addToolsin interfaceProcessProvider- Parameters:
tools- theFunctionToolsinstance whose annotated methods should be scanned and registered as tools; must not benullenabledTools- an optional array of regular expression patterns used to filter which tools should be enabled. Ifnull, all discovered tools are enabled by default. Each pattern is matched against the fully qualified tool name (format:<ClassName>:<toolName>).- See Also:
- Extracts and interpolates the tool's description via
-
toSnakeCase
Converts a given string into snake_case format.Examples:
"myMethodName"becomes"my_method_name""Already-Kebab"becomes"already_kebab""getHTTPResponse"becomes"get_http_response"nullor""returns""
- Parameters:
input- the original string to convert- Returns:
- the snake_case representation, or an empty string if input is null or empty
-
interpolateDescription
Interpolates system metadata variables (e.g., OS Name) inside the annotation's tool description text before registering it with the LLM.- Parameters:
description- the raw tool description from the annotation- Returns:
- the interpolated description string
-
addPrompts
Registers all annotated prompt methods from the givenFunctionToolsinstance.This method inspects the public methods of the provided
FunctionToolsclass. For any method annotated withPrompt, it extracts its configured metadata—such as the name, description, and targetRole. If no explicit name is defined in the annotation, it falls back to using the method's Java name, before registering it as an active prompt.- Specified by:
addPromptsin interfaceProcessProvider- Parameters:
tools- theFunctionToolsinstance containing the annotated prompt methods to register
-
addResources
Scans the providedFunctionToolsinstance for methods annotated withResource, and registers each resource for use during a run.- Specified by:
addResourcesin interfaceProcessProvider- Parameters:
tools- theFunctionToolsinstance whose methods will be scanned forResourceannotations
-
addResource
private void addResource(FunctionTools tools, Method method, String[] uris, String description, String mimeType) Resolves resource endpoints from declared arrays and binds them to the implementation context.- Parameters:
tools- target instance containermethod- reflective execution handleuris- URIs declared in the annotation configdescription- resource description textmimeType- the mime type associated with the resource- Throws:
IllegalArgumentException- if any URIs have incorrect syntax or execution fails
-
addResource
protected void addResource(URI uri, String description, String mimeType, ToolFunction function, ParamDescriptor... paramsDesc) Registers a resource callback for providers that support resource management tools.Intended to be implemented by concrete subclasses to natively expose local/remote resources to the LLM model context.
- Parameters:
uri- resource URIdescription- a description of the resource toolmimeType- the mime type format (e.g. application/json)function- the callback execution handlerparamsDesc- variable-arity array of parameter descriptors
-
addPrompt
private void addPrompt(FunctionTools tools, Method method, String name, String description, Role role) Configures and registers a single prompt method.- Parameters:
tools- instance containermethod- reflection handlename- the prompt namedescription- descriptive purposerole- role level instructions
-
addPrompt
protected void addPrompt(String name, String description, ToolFunction function, Role role, ParamDescriptor... paramsDesc) Registers a prompt callback for providers that support prompt tools.Intended to be implemented by concrete subclasses to natively expose dynamic prompt templates to the underlying model execution context.
- 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
-
addTool
Configures and registers a single tool method.- Parameters:
tools- instance containermethod- reflection handlename- the tool namedescription- tool capabilities description
-
fillParamDesc
Analyzes method signature annotations to build an array of parameter descriptions.- Parameters:
method- the method to inspect- Returns:
- an array of
ParamDescriptorinstances detailing parameters
-
invoke
private Object invoke(FunctionTools tools, Method method, com.fasterxml.jackson.databind.JsonNode props, Object... paramsByType) throws ReflectiveOperationException Dynamically invokes the specified method on the given tools instance, matching arguments dynamically.- Parameters:
tools- target instancemethod- method handleprops- the incoming JSON attributesparamsByType- variable array of parameter context constraints- Returns:
- execution output
- Throws:
ReflectiveOperationException- if the invoked target throws an exception
-
getParamByType
Filters parameter arrays to find the first assignment-compatible instance of the specified type.- Type Parameters:
T- the generic class type to filter for- Parameters:
type- the class definition type representing the constraintparamsByType- variable array containing contextual params- Returns:
- the mapped parameter matching the target class, or
nullif not found
-
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 active projectDir File context
-
setProjectDir
Sets the project directory.- Specified by:
setProjectDirin interfaceProcessProvider- Parameters:
projectDir- the projectDir to set
-
prompt
Sets the prompt text for the provider.- Specified by:
promptin interfaceProcessProvider- Parameters:
text- the prompt text
-
clear
public void clear()Clears the provider state.- Specified by:
clearin interfaceProcessProvider
-
isErrorHandling
public boolean isErrorHandling()Returns whether runtime tool errors are handled conversationally.- Returns:
trueif errors are returned as text payload to the model;falseif exceptions propagate and fail immediately.
-
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 interfaceProcessProvider- Parameters:
errorHandling-trueto enable conversational intercept and recovery;falseto disable intercept and trigger strict stack propagation.
-
getConfigurator
Returns the configurator context source.- Returns:
- the config configuration source
-