LLM Clients¶
Client Interface¶
Abstract base class for LLM client implementations.
This module defines the interface that all LLM clients must implement, along with optional helper methods that can be shared across implementations.
- class terrarium.llm.clients.abstract_client.AbstractClient[source]¶
Bases:
ABCAbstract base class for LLM client implementations.
All client implementations (OpenAI, vLLM, GPT-OSS, etc.) should inherit from this class and implement the generate_response method. This ensures a consistent interface across different LLM backends.
- configure_external_mcp(llm_config)[source]¶
Configure optional external MCP servers for this client instance.
The default implementation is a no-op when no external server config is provided and lazily initializes a shared registry otherwise.
- async execute_external_tool(tool_name, arguments)[source]¶
Execute a discovered external MCP tool.
Returns None when the tool name is not managed by the external registry.
- abstractmethod generate_response(input, params)[source]¶
Generate a response from the LLM.
This is the core method that all client implementations must provide. The method signature is standardized to use flexible input and params to accommodate different API styles.
- Parameters:
input (list[Any]) – List of message/context items representing the conversation history. Format depends on the specific client implementation (e.g., OpenAI Message objects).
params (dict[str, Any]) – Dictionary of generation parameters including: - model: str - Model identifier to use - max_completion_tokens: int - Maximum tokens to generate - max_output_tokens: int - Alternative token limit parameter - temperature: float - Sampling temperature (0.0 = deterministic) - tools: list - Available tools/functions for the model - reasoning_effort: str - Effort level for reasoning models - verbosity: str - Verbosity setting for model output Additional client-specific parameters can be included.
- Returns:
Tuple containing –
response_object: The raw response object from the LLM API
response_string: Extracted text content from the response
- Raises:
Exception – If the LLM request fails or encounters an error
- Return type:
- abstractmethod async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from the LLM response.
This method handles provider-specific tool call parsing and execution. Each client implementation must parse its own response format, detect tool calls, execute them via the callback, and update the context appropriately for the next conversation turn.
- Parameters:
- Returns:
Tuple containing –
tool_calls_executed: Number of tool calls that were executed
updated_context: Context list with tool calls and results appended
- tool_names_list: List of executed tool names with args (for logging)
Format: [“tool_name – {args_json}”, …]
- Raises:
Exception – If tool call parsing or execution fails
- Return type:
- set_meta_context(agent_name, phase, iteration=None, round_num=None)[source]¶
Set metadata context for logging and tracking purposes.
This is an optional method used primarily for debugging and logging. Subclasses that support detailed logging (like OpenAI client with tool call logging) can override this method to track agent context across turns.
API Providers¶
- class terrarium.llm.clients.openai_client.OpenAIClient(*, api_key=None, api_key_env_var='OPENAI_API_KEY', base_url=None, default_query=None, timeout=30.0, provider_name='OpenAI', capability_model=None)[source]¶
Bases:
AbstractClientClient for using OpenAI API for LLM agents.
This module provides a client for using OpenAI models via their Responses API. Supports tool use, multi-turn conversations, and various OpenAI models.
Retries use exponential backoff for transient errors such as timeouts, connection errors, 408/409/429 responses, and 5xx responses.
Environment variables:
OPENAI_MAX_RETRIES(default: 6)OPENAI_RETRY_INITIAL_S(default: 0.5)OPENAI_RETRY_MAX_S(default: 20)OPENAI_RETRY_MULTIPLIER(default: 2)OPENAI_RETRY_JITTER(default: 0.1)
- Parameters:
- generate_response(input, params)[source]¶
Outputs the response object, updated context, and response string.
- static init_context(system_prompt, user_prompt)[source]¶
Initialize context/prompt/input for OpenAI responses.
- Return type:
List[openai.types.responses.response_input_item_param.Message]
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from OpenAI response.
Parses response.output for function_call items, executes them via callback, and adds both the function call and result to the context.
- Parameters:
- Returns:
Tuple of (tools_executed_count, updated_context, tool_names_list)
- Return type:
- class terrarium.llm.clients.foundry_client.FoundryClient(*, project_endpoint=None, api_key=None, auth_mode=None, entra_scope=None, timeout=30.0, base_model=None, api_style=None)[source]¶
Bases:
OpenAIClientMicrosoft Foundry Models client via project endpoint + OpenAI SDK.
Supports: - API key auth - Microsoft Entra token auth (azure-identity)
- Parameters:
- generate_response(input, params)[source]¶
Outputs the response object, updated context, and response string.
- init_context(system_prompt, user_prompt)[source]¶
Initialize context/prompt/input for OpenAI responses.
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from OpenAI response.
Parses response.output for function_call items, executes them via callback, and adds both the function call and result to the context.
- Parameters:
- Returns:
Tuple of (tools_executed_count, updated_context, tool_names_list)
- Return type:
- class terrarium.llm.clients.grok_client.GrokClient(*, api_key=None, api_key_env_var='GROK_API_KEY', base_url=None, timeout=3600.0, base_model=None)[source]¶
Bases:
OpenAIClientFirst-party xAI Grok client using xAI’s OpenAI-compatible Responses API.
Anthropic Claude client implementation.
This module provides a client for using Anthropic’s Claude models via their Messages API. Supports tool use, extended thinking, and multi-turn conversations.
- class terrarium.llm.clients.anthropic_client.AnthropicClient[source]¶
Bases:
AbstractClientClient for using Anthropic Claude API for LLM agents.
Provides the same interface as other clients but uses Anthropic’s Messages API. Supports Claude models including claude-3-5-sonnet, claude-opus-4, etc.
Initialize the Anthropic client.
- generate_response(input, params)[source]¶
Generate a response using Anthropic’s Messages API.
- Parameters:
- Returns:
Tuple of (response_object, response_text)
- Return type:
- static init_context(system_prompt, user_prompt)[source]¶
Initialize context for Anthropic Messages API.
Note: Anthropic handles system instructions separately via the API parameter, not as part of the message history. The system prompt should be passed in params[“system”] when calling generate_response.
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from Anthropic response.
Parses response.content for tool_use blocks, executes them via callback, and adds both the function call and result to the context.
- Parameters:
- Returns:
Tuple of (tools_executed_count, updated_context, tool_names_list)
- Return type:
Google Gemini client implementation.
This module provides a client for using Google’s Gemini models via the google-genai SDK. Supports tool use, multi-turn conversations, and various Gemini models.
- class terrarium.llm.clients.gemini_client.GeminiClient[source]¶
Bases:
AbstractClientClient for using Google Gemini API for LLM agents.
Provides the same interface as other clients but uses Google’s Generative AI API. Supports Gemini models including gemini-2.0-flash-exp, gemini-1.5-pro, etc.
Initialize the Gemini client.
- generate_response(input, params)[source]¶
Generate a response using Google’s Gemini API.
- Parameters:
input (List[Any]) – List of message dictionaries in Gemini format
params (dict[str, Any]) – Generation parameters including: - model: Model name (e.g., “gemini-2.0-flash-exp”) - max_tokens: Maximum tokens to generate (max_output_tokens in Gemini) - temperature: Sampling temperature - tools: List of tool definitions - system: System instruction (optional)
- Returns:
Tuple of (response_object, response_text)
- Return type:
- static init_context(system_prompt, user_prompt)[source]¶
Initialize context for Gemini API.
Note: Gemini handles system instructions separately via model initialization, not as part of the message history. The system prompt should be passed in params[“system”] when calling generate_response.
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from Gemini response.
Parses response.candidates[0].content.parts for function_call items, executes them via callback, and adds both the function call and result to context.
- Parameters:
- Returns:
Tuple of (tools_executed_count, updated_context, tool_names_list)
- Return type:
- class terrarium.llm.clients.together_client.TogetherClient(*, base_url='https://api.together.xyz/v1', api_key=None, request_timeout=60)[source]¶
Bases:
AbstractClientClient that talks to Together.ai’s OpenAI-compatible chat endpoint.
- generate_response(input, params)[source]¶
Generate a response from the LLM.
This is the core method that all client implementations must provide. The method signature is standardized to use flexible input and params to accommodate different API styles.
- Parameters:
input (List[Dict[str, Any]]) – List of message/context items representing the conversation history. Format depends on the specific client implementation (e.g., OpenAI Message objects).
params (Dict[str, Any]) – Dictionary of generation parameters including: - model: str - Model identifier to use - max_completion_tokens: int - Maximum tokens to generate - max_output_tokens: int - Alternative token limit parameter - temperature: float - Sampling temperature (0.0 = deterministic) - tools: list - Available tools/functions for the model - reasoning_effort: str - Effort level for reasoning models - verbosity: str - Verbosity setting for model output Additional client-specific parameters can be included.
- Returns:
Tuple containing –
response_object: The raw response object from the LLM API
response_string: Extracted text content from the response
- Raises:
Exception – If the LLM request fails or encounters an error
- Return type:
- static init_context(system_prompt, user_prompt)[source]¶
Initialize chat-style context for Together.
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from the LLM response.
This method handles provider-specific tool call parsing and execution. Each client implementation must parse its own response format, detect tool calls, execute them via the callback, and update the context appropriately for the next conversation turn.
- Parameters:
- Returns:
Tuple containing –
tool_calls_executed: Number of tool calls that were executed
updated_context: Context list with tool calls and results appended
- tool_names_list: List of executed tool names with args (for logging)
Format: [“tool_name – {args_json}”, …]
- Raises:
Exception – If tool call parsing or execution fails
- Return type:
- class terrarium.llm.clients.fireworks_client.FireworksClient(*, base_url='https://api.fireworks.ai/inference/v1', api_key=None, request_timeout=60)[source]¶
Bases:
AbstractClientClient that talks to Fireworks.ai’s OpenAI-compatible chat endpoint.
- generate_response(input, params)[source]¶
Generate a response from the LLM.
This is the core method that all client implementations must provide. The method signature is standardized to use flexible input and params to accommodate different API styles.
- Parameters:
input (List[Dict[str, Any]]) – List of message/context items representing the conversation history. Format depends on the specific client implementation (e.g., OpenAI Message objects).
params (Dict[str, Any]) – Dictionary of generation parameters including: - model: str - Model identifier to use - max_completion_tokens: int - Maximum tokens to generate - max_output_tokens: int - Alternative token limit parameter - temperature: float - Sampling temperature (0.0 = deterministic) - tools: list - Available tools/functions for the model - reasoning_effort: str - Effort level for reasoning models - verbosity: str - Verbosity setting for model output Additional client-specific parameters can be included.
- Returns:
Tuple containing –
response_object: The raw response object from the LLM API
response_string: Extracted text content from the response
- Raises:
Exception – If the LLM request fails or encounters an error
- Return type:
- static init_context(system_prompt, user_prompt)[source]¶
Initialize chat-style context for Fireworks.
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from the LLM response.
This method handles provider-specific tool call parsing and execution. Each client implementation must parse its own response format, detect tool calls, execute them via the callback, and update the context appropriately for the next conversation turn.
- Parameters:
- Returns:
Tuple containing –
tool_calls_executed: Number of tool calls that were executed
updated_context: Context list with tool calls and results appended
- tool_names_list: List of executed tool names with args (for logging)
Format: [“tool_name – {args_json}”, …]
- Raises:
Exception – If tool call parsing or execution fails
- Return type:
Local vLLM¶
- class terrarium.llm.clients.vllm_client.VLLMClient(base_url, model_name, api_key='EMPTY', request_timeout=60)[source]¶
Bases:
AbstractClientClient that talks to a vLLM OpenAI-compatible server.
- generate_response(input, params)[source]¶
Generate a response from the LLM.
This is the core method that all client implementations must provide. The method signature is standardized to use flexible input and params to accommodate different API styles.
- Parameters:
input (List[Dict[str, Any]]) – List of message/context items representing the conversation history. Format depends on the specific client implementation (e.g., OpenAI Message objects).
params (Dict[str, Any]) – Dictionary of generation parameters including: - model: str - Model identifier to use - max_completion_tokens: int - Maximum tokens to generate - max_output_tokens: int - Alternative token limit parameter - temperature: float - Sampling temperature (0.0 = deterministic) - tools: list - Available tools/functions for the model - reasoning_effort: str - Effort level for reasoning models - verbosity: str - Verbosity setting for model output Additional client-specific parameters can be included.
- Returns:
Tuple containing –
response_object: The raw response object from the LLM API
response_string: Extracted text content from the response
- Raises:
Exception – If the LLM request fails or encounters an error
- Return type:
- async process_tool_calls(response, context, execute_tool_callback)[source]¶
Process tool calls from the LLM response.
This method handles provider-specific tool call parsing and execution. Each client implementation must parse its own response format, detect tool calls, execute them via the callback, and update the context appropriately for the next conversation turn.
- Parameters:
- Returns:
Tuple containing –
tool_calls_executed: Number of tool calls that were executed
updated_context: Context list with tool calls and results appended
- tool_names_list: List of executed tool names with args (for logging)
Format: [“tool_name – {args_json}”, …]
- Raises:
Exception – If tool call parsing or execution fails
- Return type:
- class terrarium.llm.vllm.runtime.ToolCallingRule(name, substrings, parser=None, chat_template=None, reasoning_parser=None, enable_reasoning=False, supports_tool_calling=True)[source]¶
Bases:
objectKnown vLLM tool/Reasoning presets keyed by substrings in the model id.
- class terrarium.llm.vllm.runtime.VLLMGlobalConfig(models, primary_model_id, auto_start_server=False, persistent_server=False, auto_configure_tool_choice=True, startup_timeout=180, health_check_path='/v1/models', health_poll_interval=2.0, api_key=None, env=<factory>)[source]¶
Bases:
objectGlobal configuration shared across all vLLM model specs.
- class terrarium.llm.vllm.runtime.VLLMModelSpec(id, checkpoint=None, served_model_name=None, base_url=None, host='127.0.0.1', port=8000, tensor_parallel_size=None, trust_remote_code=False, max_model_len=None, dtype=None, download_dir=None, gpu_memory_utilization=None, additional_args=<factory>, env=<factory>, request_timeout=60, api_key=None, launch_command=None, auto_configure_tool_choice=None, enable_auto_tool_choice=None, tool_call_parser=None, chat_template=None, tool_parser_plugin=None, reasoning_parser=None, enable_reasoning=None)[source]¶
Bases:
objectPer-model serving configuration.
- Parameters:
id (str)
checkpoint (str | None)
served_model_name (str | None)
base_url (str | None)
host (str)
port (int)
tensor_parallel_size (int | None)
trust_remote_code (bool)
max_model_len (int | None)
dtype (str | None)
download_dir (str | None)
gpu_memory_utilization (float | None)
request_timeout (int)
api_key (str | None)
launch_command (Any | None)
auto_configure_tool_choice (bool | None)
enable_auto_tool_choice (bool | None)
tool_call_parser (str | None)
chat_template (str | None)
tool_parser_plugin (str | None)
reasoning_parser (str | None)
enable_reasoning (bool | None)
- class terrarium.llm.vllm.runtime.VLLMProviderRuntime(raw_config)[source]¶
Bases:
objectHigh level helper that ties configuration, server manager, and clients together.
- Parameters:
raw_config (Dict[str, Any])
- class terrarium.llm.vllm.runtime.VLLMServerManager(config)[source]¶
Bases:
objectBootstraps and monitors vLLM server processes.
- Parameters:
config (VLLMGlobalConfig)
- ensure_server(spec)[source]¶
Ensure a server for the given model is reachable, launching if needed.
- Parameters:
spec (VLLMModelSpec)
- Return type:
None
Provider Utilities¶
- terrarium.llm.clients.azure_common.build_entra_token_provider(scope)[source]¶
Create a token provider callable for OpenAI SDK api_key parameter.
- Parameters:
scope (str)
- terrarium.llm.clients.azure_common.normalize_openai_v1_base_url(endpoint, *, setting_name)[source]¶
Normalize a Microsoft-hosted OpenAI-compatible endpoint into an OpenAI v1 base URL.
Accepts either: - project endpoint (e.g. https://…services.ai.azure.com/api/projects/<project>) - full OpenAI v1 endpoint (e.g. https://…/openai/v1/)
External MCP tool discovery and routing are documented under Tools.