LiteLLM Client
Optional Dependency
LiteLLM is an optional dependency. Install with:
max_tokens limits provider output. context_window_tokens (required) separately
tells the agent when conversation history should be summarized.
stirrup.clients.litellm_client
LiteLLM-based LLM client for multi-provider support.
This client uses LiteLLM to provide a unified interface to multiple LLM providers (OpenAI, Anthropic, Google, etc.) with automatic retries for transient failures.
Requires the litellm extra: pip install stirrup[litellm]
AssistantBlock
AssistantBlock = Annotated[
TextBlock
| ReasoningBlock
| SignedReasoningBlock
| RedactedReasoningBlock
| ReasoningRefBlock
| EncryptedReasoningBlock
| OpaqueBlock
| ToolCall
| ImageContentBlock
| VideoContentBlock
| AudioContentBlock,
Field(discriminator=kind),
]
One block of an assistant turn, discriminated on kind.
ChatMessage
ChatMessage = Annotated[
SystemMessage
| UserRoleMessage
| AssistantMessage
| ToolMessage,
Field(discriminator=role),
]
Discriminated union of all message types, automatically parsed based on role field.
ReasoningEffort
ReasoningEffort = Literal[
"none",
"minimal",
"low",
"medium",
"high",
"xhigh",
"default",
]
ContextOverflowError
Bases: Exception
Raised when request input exceeds the model's context capacity.
OutputTokenLimitError
Bases: Exception
Raised when a provider exhausts the configured response-token budget.
Source code in src/stirrup/core/exceptions.py
AssistantMessage
Bases: BaseModel
LLM response message: an ordered sequence of assistant blocks.
blocks is the only stored content. The channel-era content and
tool_calls attributes remain deprecated views; reasoning raises because
an ordered reasoning block sequence has no faithful channel-shaped projection.
Serialized v0.1 payloads upgrade to blocks during validation. Channel-shaped
construction is not part of the v0.2 API; new code constructs blocks directly.
Mixing blocks with non-empty legacy channel keys raises.
provider_response_id
class-attribute
instance-attribute
provider_response_id: str | None = None
Provider-attached continuation state, e.g. an OpenAI Responses resp_... id.
This is turn metadata rather than emitted assistant content, so it lives beside
blocks instead of inside their emission order. It is distinct from id
(Stirrup's message identity) and ReasoningRefBlock.id (an emitted reasoning
item handle).
content
property
content: list[AssistantBlock] | str
Bare text for one text block, empty text for no blocks, or the block list.
reasoning
property
reasoning: Reasoning | None
Deprecated channel accessor retained only to fail with migration guidance.
LLMClient
Bases: Protocol
Protocol defining the interface for LLM client implementations.
Any LLM client must implement this protocol to work with the Agent class. Provides text generation with tool support and model capability inspection.
ReasoningBlock
Bases: BaseModel
In-band reasoning text with no passback token.
E.g. reasoning_content on Chat Completions-compatible hosts, or
RedactedReasoningBlock
Bases: BaseModel
Reasoning the provider withheld, replaced by an opaque payload.
E.g. Anthropic redacted_thinking: data must be re-emitted verbatim as a
redacted_thinking block on passback. Carries no readable content.
SignedReasoningBlock
Bases: BaseModel
Reasoning bound to an opaque provider signature re-emitted verbatim on passback.
E.g. Anthropic signed thinking blocks.
TextBlock
Bases: BaseModel
One contiguous run of answer text in an assistant turn.
signature carries opaque passback state attached to this exact block,
e.g. a Google thought signature emitted on a visible text part. A client
that cannot re-emit the signature must reject passback rather than silently
stripping it.
TokenUsage
Bases: BaseModel
Token counts for LLM usage.
Token terminology: output = reasoning + answer.
__add__
__add__(other: TokenUsage) -> TokenUsage
Add two TokenUsage objects together, summing each field independently.
Source code in src/stirrup/core/models.py
Tool
Bases: BaseModel
Tool definition with name, description, parameter schema, and executor function.
Generic over
P: Parameter model type (Pydantic BaseModel subclass, or EmptyParams for parameterless tools) M: Metadata type (should implement Addable for aggregation; use None for tools without metadata)
Tools are simple, stateless callables. For tools requiring lifecycle management (setup/teardown, resource pooling), use a ToolProvider instead.
Example with parameters
Example without parameters (uses EmptyParams by default):
time_tool = Tool[EmptyParams, None](
name="time",
description="Get current time",
executor=lambda _: ToolResult(content=datetime.now().isoformat()),
)
ToolCall
Bases: BaseModel
Represents a tool invocation request from the LLM.
Also a member of the AssistantBlock union: the kind discriminator is
defaulted, so legacy payloads without the key still validate anywhere ToolCall
is used as a plain input, and new dumps always carry it.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the tool to invoke |
arguments |
str
|
JSON string containing tool parameters |
tool_call_id |
str
|
Unique identifier for tracking this tool call and its result |
signature
class-attribute
instance-attribute
signature: str | None = None
Opaque passback state attached to this exact block, e.g. a Google thought signature.
has_provider_tool_call_id
class-attribute
instance-attribute
has_provider_tool_call_id: bool = True
Whether tool_call_id was present on the provider's original block.
A client may synthesize tool_call_id for internal call/result matching
while retaining that it must be omitted from provider-attached passback.
from_provider
classmethod
from_provider(
*,
provider_id: str | None,
name: str,
arguments: str,
signature: str | None = None,
) -> Self
Capture one provider call with a stable internal correlation ID.
Source code in src/stirrup/core/models.py
LiteLLMClient
LiteLLMClient(
model: str | None = None,
max_tokens: int = 64000,
*,
context_window_tokens: int,
model_slug: str | None = None,
api_key: str | None = None,
reasoning_effort: ReasoningEffort | None = None,
kwargs: dict[str, Any] | None = None,
)
Bases: LLMClient
LiteLLM-based client supporting multiple LLM providers with unified interface.
Includes automatic retries for transient failures and token usage tracking.
Initialize LiteLLM client with model configuration and capabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
Model identifier for LiteLLM (e.g., 'anthropic/claude-opus-5') |
None
|
max_tokens
|
int
|
Maximum number of tokens the provider may generate |
64000
|
context_window_tokens
|
int
|
Context capacity used to decide when Agent history should be summarized. |
required |
model_slug
|
str | None
|
Deprecated. Use model instead. |
None
|
reasoning_effort
|
ReasoningEffort | None
|
Reasoning effort level for extended thinking models (e.g., 'medium', 'high') |
None
|
kwargs
|
dict[str, Any] | None
|
Additional arguments to pass to LiteLLM completion calls.
Keys that collide with the arguments this client sets (including
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no model is provided, |
Source code in src/stirrup/clients/litellm_client.py
context_window_tokens
property
context_window_tokens: int
Context capacity used by agents for history summarization.
generate
async
generate(
messages: list[ChatMessage], tools: dict[str, Tool]
) -> AssistantMessage
Generate assistant response with optional tool calls. Retries up to 3 times on timeout/connection errors.
Source code in src/stirrup/clients/litellm_client.py
to_openai_messages
to_openai_messages(
msgs: list[ChatMessage],
*,
allow_tool_call_signatures: bool = False,
) -> list[dict[str, Any]]
Convert ChatMessage list to OpenAI-compatible message dictionaries.
Handles all message types: SystemMessage, UserMessage, AssistantMessage, and ToolMessage. Preserves reasoning content and tool calls for assistant messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msgs
|
list[ChatMessage]
|
List of ChatMessage objects (System, User, Assistant, or Tool messages). |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of message dictionaries ready for the OpenAI API. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If an unsupported message type is encountered. |
Source code in src/stirrup/clients/utils.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
to_openai_tools
Convert Tool objects to OpenAI function calling format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
dict[str, Tool]
|
Dictionary mapping tool names to Tool objects. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of tool definitions in OpenAI's function calling format. |
Example
tools = {"calculator": calculator_tool} openai_tools = to_openai_tools(tools)
Returns: [{"type": "function", "function": {"name": "calculator", ...}}]
Source code in src/stirrup/clients/utils.py
validate_token_budgets
Reject an invalid budget pair at client construction.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stirrup/clients/utils.py
_parse_thinking_blocks
_parse_thinking_blocks(
thinking_blocks: list[dict[str, Any]] | None,
) -> list[
SignedReasoningBlock
| RedactedReasoningBlock
| ReasoningBlock
]
Parse LiteLLM thinking_blocks into reasoning blocks, one per entry, in order.