Class AnthropicProvider
java.lang.Object
org.machanism.machai.process.provider.AbstractAIProvider
org.machanism.machai.genai.provider.AnthropicProvider
- All Implemented Interfaces:
ProcessProvider
- Direct Known Subclasses:
CodeMieProvider.ClaudeProviderExtension
Anthropic-backed implementation of Machai's
ProcessProvider
abstraction.
This provider adapts the Anthropic Java SDK to the Machai provider interface. It manages prompt collection, request construction for the Anthropic Beta Messages API, custom tool execution, optional web search integration, optional MCP server forwarding, and usage tracking.
- Since:
- 1.1.13
- Author:
- Viktor Tovstyi
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringConfiguration property name that contains the Anthropic API key or authorization token.static final StringConfiguration property that overrides the Anthropic API base URL.private final List<com.anthropic.models.beta.messages.BetaMessageParam> Accumulated Anthropic message inputs for the current conversation.private static final org.slf4j.LoggerLogger used for provider diagnostics and request lifecycle messages.private List<com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition> MCP server definitions forwarded to Anthropic with each request.private final Map<com.anthropic.models.beta.messages.BetaTool.Builder, ToolFunction> Mapping between Anthropic tool definitions and local functions.private ObjectAnthropic web search tool instance registered for outgoing requests, ornull.Fields inherited from class org.machanism.machai.process.provider.AbstractAIProvider
DEFAULT_WEBSEARCH_TYPE_NAME, ERROR_TOOL_RESULT_PREFIX, LINE_SEPARATOR, LOG_LINE_LENG, MAX_OUTPUT_TOKENS, MCP_PROP_NAME_PREFIX, PARAGRAPH_SEPARATOR, PASSWORD_PROP_NAME, PROJECT_DIR_PARAM_NAME, USERNAME_PROP_NAME -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddMcpServer(String name, String url, String authorization, String description) Registers an MCP server definition for future requests.protected voidaddTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc) Registers a local function tool.protected voidaddWebSearch(String type, String city, String country, String region) Registers a web search tool and optional location hints.private com.anthropic.models.beta.messages.BetaMessagecall(com.anthropic.models.beta.messages.MessageCreateParams params) Submits a request to the Anthropic Beta Messages API and records its token usage.private ObjectcallFunction(com.anthropic.models.beta.messages.BetaToolUseBlock toolUse) Locates and invokes the locally registered handler for an Anthropic tool invocation.private voidcaptureUsage(com.anthropic.models.beta.messages.BetaMessage response) Captures token usage and updates global usage statistics.voidclear()Clears accumulated conversation inputs.private com.anthropic.models.beta.messages.MessageCreateParamscreateResponseBuilder(List<com.anthropic.models.beta.messages.BetaMessageParam> inputs) Builds a Messages API request from the current conversation and provider configuration, including registered local tools, MCP servers, and web search when configured.protected com.anthropic.client.AnthropicClientCreates and configures an Anthropic client.Returns the names of locally registered Anthropic tools.private voidhandleFunctionCall(com.anthropic.models.beta.messages.BetaToolUseBlock toolUse) Adds a received tool-use block to the conversation, invokes its local handler, and appends the corresponding tool-result user message.private StringparseResponse(com.anthropic.models.beta.messages.BetaMessage response) Converts an Anthropic response into text, executing local tool calls and recursively submitting their results until no tool call remains.perform()Sends the accumulated conversation and returns the final text response.voidAdds a non-blank user prompt.Methods inherited from class org.machanism.machai.process.provider.AbstractAIProvider
addMcpServers, addPrompt, addPrompts, addResource, addResources, addTools, addWebSearch, getConfigurator, getInstructions, getMaxOutputTokens, getMaxToolCalls, getModel, getParamValue, getProjectDir, getTimeout, init, instructions, isErrorHandling, normalize, safelyInvokeTool, setErrorHandling, setInstructions, setMaxOutputTokens, setMaxToolCalls, setModel, setProjectDir, setTimeout, toSnakeCase
-
Field Details
-
logger
private static final org.slf4j.Logger loggerLogger used for provider diagnostics and request lifecycle messages. -
ANTHROPIC_API_KEY
Configuration property name that contains the Anthropic API key or authorization token.- See Also:
-
ANTHROPIC_BASE_URL
Configuration property that overrides the Anthropic API base URL.- See Also:
-
inputs
Accumulated Anthropic message inputs for the current conversation. -
toolMap
Mapping between Anthropic tool definitions and local functions. -
webSearchTool
Anthropic web search tool instance registered for outgoing requests, ornull. -
mcpServers
MCP server definitions forwarded to Anthropic with each request.
-
-
Constructor Details
-
AnthropicProvider
public AnthropicProvider()Creates an Anthropic provider instance.
-
-
Method Details
-
addMcpServer
Registers an MCP server definition for future requests.- Overrides:
addMcpServerin classAbstractAIProvider- Parameters:
name- server name exposed to the modelurl- server endpoint URLauthorization- optional authorization tokendescription- optional description, currently unused by the SDK model
-
addWebSearch
Registers a web search tool and optional location hints.- Overrides:
addWebSearchin classAbstractAIProvider- Parameters:
type- web search tool versioncity- optional city hintcountry- optional country hintregion- optional region hint- Throws:
IllegalArgumentException- iftypeis unsupported
-
prompt
Adds a non-blank user prompt. @param text prompt text- Specified by:
promptin interfaceProcessProvider- Overrides:
promptin classAbstractAIProvider- Parameters:
text- the prompt text
-
perform
Sends the accumulated conversation and returns the final text response. @return response text- Returns:
- the provider response as a string
-
call
private com.anthropic.models.beta.messages.BetaMessage call(com.anthropic.models.beta.messages.MessageCreateParams params) Submits a request to the Anthropic Beta Messages API and records its token usage.- Parameters:
params- immutable request parameters to submit- Returns:
- the message returned by Anthropic
-
parseResponse
Converts an Anthropic response into text, executing local tool calls and recursively submitting their results until no tool call remains.- Parameters:
response- response to process- Returns:
- final assistant text, or
nullwhen the response contains no text
-
captureUsage
private void captureUsage(com.anthropic.models.beta.messages.BetaMessage response) Captures token usage and updates global usage statistics. @param response response message -
handleFunctionCall
private void handleFunctionCall(com.anthropic.models.beta.messages.BetaToolUseBlock toolUse) Adds a received tool-use block to the conversation, invokes its local handler, and appends the corresponding tool-result user message.- Parameters:
toolUse- tool invocation returned by Anthropic
-
callFunction
Locates and invokes the locally registered handler for an Anthropic tool invocation.- Parameters:
toolUse- tool invocation to execute- Returns:
- handler result, or
nullwhen no matching handler is registered
-
createResponseBuilder
private com.anthropic.models.beta.messages.MessageCreateParams createResponseBuilder(List<com.anthropic.models.beta.messages.BetaMessageParam> inputs) Builds a Messages API request from the current conversation and provider configuration, including registered local tools, MCP servers, and web search when configured.- Parameters:
inputs- conversation messages to include in the request- Returns:
- configured immutable request parameters
-
clear
public void clear()Clears accumulated conversation inputs.- Specified by:
clearin interfaceProcessProvider- Overrides:
clearin classAbstractAIProvider
-
addTool
protected void addTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc) Registers a local function tool.- Specified by:
addToolin classAbstractAIProvider- Parameters:
name- tool namedescription- tool descriptionfunction- local callbackparamsDesc- tool input descriptors
-
getClient
protected com.anthropic.client.AnthropicClient getClient()Creates and configures an Anthropic client. @return configured client -
getToolNames
Returns the names of locally registered Anthropic tools.- Returns:
- a list of registered tool names in registration order
-