Models
stirrup.core.models
__all__
module-attribute
__all__ = [
"Addable",
"AssistantMessage",
"AudioContentBlock",
"BinaryContentBlock",
"ChatMessage",
"Content",
"ContentBlock",
"ImageContentBlock",
"LLMClient",
"SubAgentMetadata",
"SystemMessage",
"TokenUsage",
"Tool",
"ToolCall",
"ToolMessage",
"ToolProvider",
"ToolResult",
"ToolUseCountMetadata",
"UserMessage",
"VideoContentBlock",
"aggregate_metadata",
]
ContentBlock
ContentBlock = (
ImageContentBlock
| VideoContentBlock
| AudioContentBlock
| str
)
Union of all content block types (image, video, audio, or text).
Content
Content = list[ContentBlock] | str
Message content: either a plain string or list of mixed content blocks.
ChatMessage
ChatMessage = Annotated[
SystemMessage
| UserMessage
| AssistantMessage
| ToolMessage,
Field(discriminator=role),
]
Discriminated union of all message types, automatically parsed based on role field.
BinaryContentBlock
ImageContentBlock
Bases: BinaryContentBlock
Image content supporting PNG, JPEG, WebP, PSD formats with automatic downscaling.
to_base64_url
to_base64_url(
max_pixels: int | None = RESOLUTION_1MP,
) -> str
Convert image to base64 data URL, optionally resizing to max pixel count.
Source code in src/stirrup/core/models.py
VideoContentBlock
Bases: BinaryContentBlock
MP4 video content with automatic transcoding and resolution downscaling.
to_base64_url
to_base64_url(
max_pixels: int | None = RESOLUTION_480P,
fps: int | None = None,
) -> str
Transcode to MP4 and return base64 data URL.
Source code in src/stirrup/core/models.py
AudioContentBlock
Bases: BinaryContentBlock
Audio content supporting MPEG, WAV, AAC, and other common audio formats.
to_base64_url
Transcode to MP3 and return base64 data URL.
Source code in src/stirrup/core/models.py
Addable
TokenUsage
Bases: BaseModel
Token counts for LLM usage (input, output, reasoning tokens).
__add__
__add__(other: TokenUsage) -> TokenUsage
Add two TokenUsage objects together, summing each field independently.
Source code in src/stirrup/core/models.py
ToolUseCountMetadata
Bases: BaseModel
Generic metadata tracking tool usage count.
Implements Addable protocol for aggregation. Use this for tools that only need to track how many times they were called.
ToolResult
Bases: BaseModel
Result from a tool executor with optional metadata.
Generic over metadata type M. M should implement Addable protocol for aggregation support, but this is not enforced at the class level due to Pydantic schema generation limitations.
Tool
Bases: BaseModel
Tool definition with name, description, parameter schema, and executor function.
Generic over
P: Parameter model type (must be a Pydantic BaseModel, or None 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
class CalcParams(BaseModel): expression: str
calc_tool = ToolCalcParams, None)
Example without parameters
time_tool = ToolNone, None)
ToolProvider
Bases: ABC
Abstract base class for tool providers with lifecycle management.
ToolProviders manage resources (HTTP clients, sandboxes, server connections) and return Tool instances when entering their async context. They implement the async context manager protocol.
Use ToolProvider for: - Tools requiring setup/teardown (connections, temp directories) - Tools that return multiple Tool instances (e.g., MCP servers) - Tools with shared state across calls (e.g., HTTP client pooling)
Example
class MyToolProvider(ToolProvider): async def aenter(self) -> Tool | list[Tool]: # Setup resources and return tool(s) return self._create_tool()
# __aexit__ is optional - default is no-op
Agent automatically manages ToolProvider lifecycle via its session() context.
__aenter__
abstractmethod
async
__aexit__
async
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit async context: cleanup resources. Default: no-op.
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.
ToolCall
SystemMessage
Bases: BaseModel
System-level instructions and context for the LLM.
UserMessage
Bases: BaseModel
User input message to the LLM.
Reasoning
Bases: BaseModel
Extended thinking/reasoning content from models that support chain-of-thought reasoning.
AssistantMessage
Bases: BaseModel
LLM response message with optional tool calls and token usage tracking.
ToolMessage
Bases: BaseModel
Tool execution result returned to the LLM.
SubAgentMetadata
Bases: BaseModel
Metadata from sub-agent execution including token usage, message history, and child run metadata.
Implements Addable protocol to support aggregation across multiple subagent calls.
__add__
__add__(other: SubAgentMetadata) -> SubAgentMetadata
Combine metadata from multiple subagent calls.
Source code in src/stirrup/core/models.py
downscale_image
Downscale image dimensions to fit within max pixel count while maintaining aspect ratio.
Returns even dimensions with minimum 2x2 size.
Source code in src/stirrup/core/models.py
_aggregate_list
_aggregate_list(metadata_list: list[T]) -> T | None
Aggregate a list of metadata using add.
Source code in src/stirrup/core/models.py
to_json_serializable
Source code in src/stirrup/core/models.py
_collect_all_token_usage
_collect_all_token_usage(result: dict) -> TokenUsage
Recursively collect all token_usage from a flattened aggregate_metadata result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict
|
The flattened dict from aggregate_metadata (before JSON serialization) |
required |
Returns:
| Type | Description |
|---|---|
TokenUsage
|
Combined TokenUsage from all entries (direct and nested sub-agents) |
Source code in src/stirrup/core/models.py
aggregate_metadata
aggregate_metadata(
metadata_dict: dict[str, list[Any]],
prefix: str = "",
return_json_serializable: bool = True,
) -> dict | object
Aggregate metadata lists and flatten sub-agents into a single-level dict with hierarchical keys.
For entries with nested run_metadata (e.g., SubAgentMetadata), flattens sub-agents using dot notation. Each sub-agent's value is a dict mapping its direct tool names to their aggregated metadata (excluding nested sub-agent data, which gets its own top-level key).
At the root level, token_usage is rolled up to include all sub-agent token usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata_dict
|
dict[str, list[Any]]
|
Dict mapping names (tools or agents) to lists of metadata instances |
required |
prefix
|
str
|
Key prefix for nested calls (used internally for recursion) |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
dict | object
|
Flat dict with dot-notation keys for sub-agents. |
|
Example |
dict | object
|
{
"token_usage": |
dict | object
|
} |