Skip to content

anthropic_api

microbots.llm.anthropic_api

Anthropic Messages API client implementing the LLMInterface with native tool calling.

MAX_TOKENS = 16000 module-attribute

api_key = os.getenv('ANTHROPIC_API_KEY') module-attribute

deployment_name = os.getenv('ANTHROPIC_DEPLOYMENT_NAME') module-attribute

endpoint = os.getenv('ANTHROPIC_END_POINT') module-attribute

logger = getLogger(__name__) module-attribute

AnthropicApi(system_prompt, tools: list[ToolAbstract], deployment_name=deployment_name, token_provider: Callable[[], str] | None = None)

Bases: LLMInterface

LLM client backed by the Anthropic Messages API.

The model acts through native tool calls. The API keeps no conversation state, so the full history is sent with every request, and automatic prompt caching avoids reprocessing the part that was already sent.

Parameters:

Name Type Description Default
system_prompt str

System prompt sent with every request.

required
tools list[ToolAbstract]

Tools the model can call. Each tool's parameters is a JSON schema.

required
deployment_name str

Anthropic model name (e.g. 'claude-sonnet-4-5').

deployment_name
token_provider Callable[[], str] | None

Optional callable returning an Azure AD bearer token, used with Azure AI Foundry instead of ANTHROPIC_API_KEY when provided.

None

Create the client.

Parameters:

Name Type Description Default
system_prompt str

System prompt sent with every request.

required
tools list[ToolAbstract]

Tools the model can call. Each tool's parameters is a JSON schema.

required
deployment_name str

Anthropic model name (e.g. 'claude-sonnet-4-5').

deployment_name
token_provider Callable[[], str] | None

Optional callable returning an Azure AD bearer token, used with Azure AI Foundry instead of ANTHROPIC_API_KEY when provided.

None

Raises:

Type Description
ValueError

If no authentication is configured or the token provider is invalid.

Source code in src/microbots/llm/anthropic_api.py
def __init__(self, system_prompt, tools: list[ToolAbstract], deployment_name=deployment_name,
             token_provider: Callable[[], str] | None = None):
    """
    Create the client.

    Parameters
    ----------
    system_prompt : str
        System prompt sent with every request.
    tools : list[ToolAbstract]
        Tools the model can call. Each tool's ``parameters`` is a JSON schema.
    deployment_name : str
        Anthropic model name (e.g. 'claude-sonnet-4-5').
    token_provider : Callable[[], str] | None
        Optional callable returning an Azure AD bearer token, used with
        Azure AI Foundry instead of ANTHROPIC_API_KEY when provided.

    Raises
    ------
    ValueError
        If no authentication is configured or the token provider is invalid.
    """
    self.token_provider = token_provider

    if not token_provider and not api_key:
        raise ValueError(
            "No authentication configured for Anthropic. Either set the ANTHROPIC_API_KEY "
            "environment variable or provide a token_provider (e.g. AzureTokenProvider)."
        )

    if token_provider:
        if not callable(token_provider):
            raise ValueError("token_provider must be a callable that returns a string token.")
        try:
            token = token_provider()
        except Exception as e:
            raise ValueError(f"token_provider failed during validation: {e}") from e
        if not isinstance(token, str) or not token:
            raise ValueError("token_provider must return a non-empty string token.")
        # Azure AD auth — use AnthropicFoundry with ANTHROPIC_END_POINT as base_url
        self.ai_client = AnthropicFoundry(
            azure_ad_token_provider=token_provider,
            base_url=endpoint,
        )
    else:
        self.ai_client = Anthropic(
            api_key=api_key,
            base_url=endpoint
        )
    self.deployment_name = deployment_name
    self.system_prompt = system_prompt
    self.tools = [self._to_anthropic_tool(tool) for tool in tools]
    self.messages = []
    self.unanswered_call_ids = []

ai_client = AnthropicFoundry(azure_ad_token_provider=token_provider, base_url=endpoint) instance-attribute

deployment_name = deployment_name instance-attribute

messages = [] instance-attribute

system_prompt = system_prompt instance-attribute

token_provider = token_provider instance-attribute

tools = [self._to_anthropic_tool(tool) for tool in tools] instance-attribute

unanswered_call_ids = [] instance-attribute

ask(message) -> LLMAskResponse

Send a message to the LLM and return its parsed response.

Returns:

Type Description
LLMAskResponse

The parsed LLM response.

Source code in src/microbots/llm/anthropic_api.py
def ask(self, message) -> LLMAskResponse:
    """
    Send a message to the LLM and return its parsed response.

    Parameters
    ----------
        message : str
            The message/prompt to send to the LLM.

    Returns
    -------
        LLMAskResponse
            The parsed LLM response.
    """
    # A run that stopped early can leave tool calls unanswered, and the API
    # rejects a new message until every call has a result.
    content = [
        self._tool_result(call_id, "Not run: the previous run stopped.", is_error=True)
        for call_id in self.unanswered_call_ids
    ]
    content.append({"type": "text", "text": message})
    return self._send(content)

clear_history()

Clear the LLM's conversation history.

Returns:

Type Description
bool

True if the history was cleared successfully.

Source code in src/microbots/llm/anthropic_api.py
def clear_history(self):
    """
    Clear the LLM's conversation history.

    Returns
    -------
        bool
            True if the history was cleared successfully.
    """
    self.messages = []
    self.unanswered_call_ids = []
    return True

send_tool_outputs(outputs: dict[str, str]) -> LLMAskResponse

Send the outputs of the requested tool calls and return the LLM's next response.

Returns:

Type Description
LLMAskResponse

The parsed LLM response.

Source code in src/microbots/llm/anthropic_api.py
def send_tool_outputs(self, outputs: dict[str, str]) -> LLMAskResponse:
    """
    Send the outputs of the requested tool calls and return the LLM's next response.

    Parameters
    ----------
        outputs : dict[str, str]
            The output of each tool call, keyed by its call id.

    Returns
    -------
        LLMAskResponse
            The parsed LLM response.
    """
    return self._send([self._tool_result(call_id, output) for call_id, output in outputs.items()])