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: ABC

Abstract 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.

Parameters:

llm_config (dict[str, Any])

Return type:

None

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.

Parameters:
Return type:

dict[str, Any] | None

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:

tuple[Any, str]

async get_external_tool_names()[source]

Return discovered external MCP tool names.

Return type:

set[str]

async get_external_tools()[source]

Return external MCP tools in OpenAI-compatible tool schema.

Return type:

list[dict[str, Any]]

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:
  • response (Any) – The raw response object from generate_response()

  • context (list[Any]) – Current conversation context/history (will be updated)

  • execute_tool_callback (Any) – Async function to execute tools. Signature: async def(tool_name: str, args: dict) -> dict

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:

tuple[int, list[Any], list[str]]

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.

Parameters:
  • agent_name (str) – Name of the current agent making the request

  • phase (str) – Current simulation phase (e.g., “planning”, “execution”)

  • iteration (int | None) – Current iteration number in the simulation

  • round_num (int | None) – Current round number within the iteration

Return type:

None

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: AbstractClient

Client 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:
  • api_key (Any | None)

  • api_key_env_var (str)

  • base_url (str | None)

  • default_query (Dict[str, Any] | None)

  • timeout (float)

  • provider_name (str)

  • capability_model (str | None)

generate_response(input, params)[source]

Outputs the response object, updated context, and response string.

Parameters:
Return type:

tuple[Any, str]

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:
  • response (Any) – OpenAI response object with .output attribute

  • context (list[Any]) – List of Message/FunctionCallOutput objects

  • execute_tool_callback (Any) – Async function(tool_name: str, args: dict) -> dict

Returns:

Tuple of (tools_executed_count, updated_context, tool_names_list)

Return type:

tuple[int, list[Any], list[str]]

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: OpenAIClient

Microsoft Foundry Models client via project endpoint + OpenAI SDK.

Supports: - API key auth - Microsoft Entra token auth (azure-identity)

Parameters:
  • project_endpoint (Optional[str])

  • api_key (Optional[str])

  • auth_mode (Optional[str])

  • entra_scope (Optional[str])

  • timeout (float)

  • base_model (Optional[str])

  • api_style (Optional[str])

generate_response(input, params)[source]

Outputs the response object, updated context, and response string.

Parameters:
Return type:

Tuple[Any, str]

init_context(system_prompt, user_prompt)[source]

Initialize context/prompt/input for OpenAI responses.

Parameters:
  • system_prompt (str)

  • user_prompt (str)

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:
  • response (Any) – OpenAI response object with .output attribute

  • context (list[Any]) – List of Message/FunctionCallOutput objects

  • execute_tool_callback (Any) – Async function(tool_name: str, args: dict) -> dict

Returns:

Tuple of (tools_executed_count, updated_context, tool_names_list)

Return type:

Tuple[int, list[Any], list[str]]

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: OpenAIClient

First-party xAI Grok client using xAI’s OpenAI-compatible Responses API.

Parameters:
  • api_key (Optional[Any])

  • api_key_env_var (str)

  • base_url (Optional[str])

  • timeout (float)

  • base_model (Optional[str])

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: AbstractClient

Client 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:
  • input (List[Any]) – List of message dictionaries in Anthropic format.

  • params (dict[str, Any]) – Generation parameters. Supported keys include model, max_tokens, max_output_tokens, temperature, tools, system, and thinking.

Returns:

Tuple of (response_object, response_text)

Return type:

tuple[Any, str]

static get_usage(response, current_usage)[source]

Accumulate usage statistics from response.

Parameters:
Return type:

Dict[str, int]

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.

Parameters:
  • system_prompt (str) – System instructions (stored in first message metadata)

  • user_prompt (str) – Initial user message

Returns:

List of message dictionaries in Anthropic format

Return type:

List[Dict]

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:
  • response (Any) – Anthropic response object with .content attribute

  • context (list[Any]) – List of message dictionaries in Anthropic format

  • execute_tool_callback (Any) – Async function(tool_name: str, args: dict) -> dict

Returns:

Tuple of (tools_executed_count, updated_context, tool_names_list)

Return type:

tuple[int, list[Any], list[str]]

set_meta_context(agent_name, phase, iteration=None, round_num=None)[source]

Set metadata context for logging purposes.

Parameters:
  • agent_name (str) – Name of the current agent

  • phase (str) – Current simulation phase

  • iteration (int | None) – Current iteration number

  • round_num (int | None) – Current round number

Return type:

None

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: AbstractClient

Client 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:

tuple[Any, str]

static get_usage(response, current_usage)[source]

Accumulate usage statistics from response.

Parameters:
Return type:

Dict[str, int]

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.

Parameters:
  • system_prompt (str) – System instructions (will be included in first message for reference)

  • user_prompt (str) – Initial user message

Returns:

List of message dictionaries in Gemini format

Return type:

List[Dict]

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:
  • response (Any) – Gemini response object with .candidates attribute

  • context (list[Any]) – List of message dictionaries in Gemini format

  • execute_tool_callback (Any) – Async function(tool_name: str, args: dict) -> dict

Returns:

Tuple of (tools_executed_count, updated_context, tool_names_list)

Return type:

tuple[int, list[Any], list[str]]

set_meta_context(agent_name, phase, iteration=None, round_num=None)[source]

Set metadata context for logging purposes.

Parameters:
  • agent_name (str) – Name of the current agent

  • phase (str) – Current simulation phase

  • iteration (int | None) – Current iteration number

  • round_num (int | None) – Current round number

Return type:

None

class terrarium.llm.clients.together_client.TogetherClient(*, base_url='https://api.together.xyz/v1', api_key=None, request_timeout=60)[source]

Bases: AbstractClient

Client that talks to Together.ai’s OpenAI-compatible chat endpoint.

Parameters:
  • base_url (str)

  • api_key (Optional[str])

  • request_timeout (int)

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:

Tuple[Dict[str, Any], str]

static init_context(system_prompt, user_prompt)[source]

Initialize chat-style context for Together.

Parameters:
  • system_prompt (str)

  • user_prompt (str)

Return type:

List[Dict[str, Any]]

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:
  • response (Dict[str, Any]) – The raw response object from generate_response()

  • context (List[Dict[str, Any]]) – Current conversation context/history (will be updated)

  • execute_tool_callback (Any) – Async function to execute tools. Signature: async def(tool_name: str, args: dict) -> dict

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:

Tuple[int, List[Dict[str, Any]], List[str]]

class terrarium.llm.clients.fireworks_client.FireworksClient(*, base_url='https://api.fireworks.ai/inference/v1', api_key=None, request_timeout=60)[source]

Bases: AbstractClient

Client that talks to Fireworks.ai’s OpenAI-compatible chat endpoint.

Parameters:
  • base_url (str)

  • api_key (Optional[str])

  • request_timeout (int)

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:

Tuple[Dict[str, Any], str]

static init_context(system_prompt, user_prompt)[source]

Initialize chat-style context for Fireworks.

Parameters:
  • system_prompt (str)

  • user_prompt (str)

Return type:

List[Dict[str, Any]]

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:
  • response (Dict[str, Any]) – The raw response object from generate_response()

  • context (List[Dict[str, Any]]) – Current conversation context/history (will be updated)

  • execute_tool_callback (Any) – Async function to execute tools. Signature: async def(tool_name: str, args: dict) -> dict

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:

Tuple[int, List[Dict[str, Any]], List[str]]

Local vLLM

class terrarium.llm.clients.vllm_client.VLLMClient(base_url, model_name, api_key='EMPTY', request_timeout=60)[source]

Bases: AbstractClient

Client that talks to a vLLM OpenAI-compatible server.

Parameters:
  • base_url (str)

  • model_name (str)

  • api_key (str)

  • request_timeout (int)

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:

Tuple[Dict[str, Any], str]

static init_context(system_prompt, user_prompt)[source]

Initialize chat-style context for vLLM.

Parameters:
  • system_prompt (str)

  • user_prompt (str)

Return type:

List[Dict[str, Any]]

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:
  • response (Dict[str, Any]) – The raw response object from generate_response()

  • context (List[Dict[str, Any]]) – Current conversation context/history (will be updated)

  • execute_tool_callback (Any) – Async function to execute tools. Signature: async def(tool_name: str, args: dict) -> dict

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:

Tuple[int, List[Dict[str, Any]], List[str]]

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: object

Known vLLM tool/Reasoning presets keyed by substrings in the model id.

Parameters:
  • name (str)

  • substrings (Tuple[str, ...])

  • parser (str | None)

  • chat_template (str | None)

  • reasoning_parser (str | None)

  • enable_reasoning (bool)

  • supports_tool_calling (bool)

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: object

Global configuration shared across all vLLM model specs.

Parameters:
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: object

Per-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)

  • additional_args (List[str])

  • env (Dict[str, str])

  • 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: object

High level helper that ties configuration, server manager, and clients together.

Parameters:

raw_config (Dict[str, Any])

create_client(agent_name)[source]

Return (client, served_model_name) for a specific agent.

Parameters:

agent_name (str)

describe_log_path()[source]

Return the expected log file path for the active vLLM model.

Return type:

str

class terrarium.llm.vllm.runtime.VLLMServerManager(config)[source]

Bases: object

Bootstraps 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

shutdown()[source]

Terminate any managed vLLM processes.

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/)

Parameters:
  • endpoint (Any)

  • setting_name (str)

Return type:

str

External MCP tool discovery and routing are documented under Tools.