Agent
stirrup.core.agent
MESSAGE_SUMMARIZER_BRIDGE_TEMPLATE
module-attribute
DEFAULT_TOOLS
module-attribute
DEFAULT_TOOLS: list[Tool[Any, Any] | ToolProvider] = [
LocalCodeExecToolProvider(),
WebToolProvider(),
]
SIMPLE_FINISH_TOOL
module-attribute
SIMPLE_FINISH_TOOL: Tool[
FinishParams, ToolUseCountMetadata
] = Tool[FinishParams, ToolUseCountMetadata](
name=DEFAULT_FINISH_TOOL_NAME,
description="Signal task completion with a reason. Use when the task is finished or cannot proceed further. Note that you will need a separate turn to finish.",
parameters=FinishParams,
executor=_validating_finish_executor,
)
_PARENT_DEPTH
module-attribute
_PARENT_DEPTH: ContextVar[int] = ContextVar(
"parent_depth", default=0
)
_SESSION_STATE
module-attribute
_SESSION_STATE: ContextVar[SessionState] = ContextVar(
"session_state"
)
DEFAULT_SUB_AGENT_DESCRIPTION
module-attribute
DEFAULT_SUB_AGENT_DESCRIPTION = "A sub agent that can be used to handle a contained, specific task."
ChatMessage
ChatMessage = Annotated[
SystemMessage
| UserMessage
| AssistantMessage
| ToolMessage,
Field(discriminator=role),
]
Discriminated union of all message types, automatically parsed based on role field.
CacheManager
Manages cache operations for agent sessions.
Handles saving/loading cache state and execution environment files.
Initialize CacheManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_base_dir
|
Path | None
|
Base directory for cache storage. Defaults to ~/.cache/stirrup/ |
None
|
clear_on_success
|
bool
|
If True (default), automatically clear the cache when the agent completes successfully. Set to False to preserve caches for inspection or manual management. |
True
|
Source code in src/stirrup/core/cache.py
save_state
save_state(
task_hash: str,
state: CacheState,
exec_env_dir: Path | None = None,
) -> None
Save cache state and optionally archive execution environment files.
Uses atomic writes to prevent corrupted cache files if interrupted mid-write.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_hash
|
str
|
Unique identifier for this task/cache. |
required |
state
|
CacheState
|
CacheState to persist. |
required |
exec_env_dir
|
Path | None
|
Optional path to execution environment temp directory. If provided, all files will be copied to cache. |
None
|
Source code in src/stirrup/core/cache.py
load_state
load_state(task_hash: str) -> CacheState | None
Load cached state for a task hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_hash
|
str
|
Unique identifier for the task/cache. |
required |
Returns:
| Type | Description |
|---|---|
CacheState | None
|
CacheState if cache exists, None otherwise. |
Source code in src/stirrup/core/cache.py
restore_files
Restore cached files to the destination directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_hash
|
str
|
Unique identifier for the task/cache. |
required |
dest_dir
|
Path
|
Destination directory (typically the new exec env temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if files were restored, False if no files cache exists. |
Source code in src/stirrup/core/cache.py
clear_cache
clear_cache(task_hash: str) -> None
Remove cache for a specific task.
Called after successful completion to clean up.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_hash
|
str
|
Unique identifier for the task/cache. |
required |
Source code in src/stirrup/core/cache.py
list_caches
get_cache_info
Get metadata about a cache without fully loading it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_hash
|
str
|
Unique identifier for the task/cache. |
required |
Returns:
| Type | Description |
|---|---|
dict | None
|
Dictionary with cache info (turn, timestamp, agent_name) or None. |
Source code in src/stirrup/core/cache.py
CacheState
dataclass
CacheState(
msgs: list[ChatMessage],
full_msg_history: list[list[ChatMessage]],
task_hash: str,
timestamp: str = (lambda: isoformat())(),
agent_name: str = "",
run_metadata_by_turn: dict[
str, dict[str, list[Any]]
] = dict(),
)
Serializable state for resuming an agent run.
Captures all necessary state to resume execution from a specific turn.
msgs
instance-attribute
msgs: list[ChatMessage]
Current conversation messages in the active run loop.
full_msg_history
instance-attribute
full_msg_history: list[list[ChatMessage]]
Groups of messages (separated when context summarization occurs).
task_hash
instance-attribute
task_hash: str
Hash of the original init_msgs for verification on resume.
timestamp
class-attribute
instance-attribute
ISO timestamp when cache was created.
agent_name
class-attribute
instance-attribute
agent_name: str = ''
Name of the agent that created this cache.
run_metadata_by_turn
class-attribute
instance-attribute
Accumulated tool metadata keyed by assistant message id.
to_dict
to_dict() -> dict
Convert to JSON-serializable dictionary.
Source code in src/stirrup/core/cache.py
from_dict
classmethod
from_dict(data: dict) -> CacheState
Create CacheState from JSON dictionary.
Source code in src/stirrup/core/cache.py
ContextOverflowError
Bases: Exception
Raised when LLM context window is exceeded (max_tokens or length finish_reason).
AssistantMessage
Bases: BaseModel
LLM response message with optional tool calls and token usage tracking.
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
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.
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
SummaryMessage
SystemMessage
Bases: BaseModel
System-level instructions and context for the LLM.
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
ToolMessage
Bases: BaseModel
Tool execution result returned to the LLM.
Attributes:
| Name | Type | Description |
|---|---|---|
role |
Literal['tool']
|
Always "tool" |
content |
Content
|
The tool result content |
tool_call_id |
str | None
|
ID linking this result to the corresponding tool call |
name |
str | None
|
Name of the tool that was called |
args_was_valid |
bool
|
Whether the tool arguments were valid |
success |
bool
|
Whether the tool executed successfully (used by finish tool to control termination) |
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.
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.
Attributes:
| Name | Type | Description |
|---|---|---|
content |
Content
|
The result content (string, list of content blocks, or images) |
success |
bool
|
Whether the tool call was successful. For finish tools, controls if agent terminates. |
metadata |
M | None
|
Optional metadata (e.g., usage stats) that implements Addable for aggregation |
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.
Subclasses can override add with their own type thanks to Self typing.
TurnWarningMessage
UserMessage
Bases: BaseModel
User input message to the LLM.
SkillMetadata
dataclass
Metadata extracted from a skill's SKILL.md frontmatter.
CodeExecToolProvider
CodeExecToolProvider(
*,
allowed_commands: list[str] | None = None,
shell_timeout: int = SHELL_TIMEOUT,
)
Bases: ToolProvider, ABC
Abstract base class for code execution tool providers.
CodeExecToolProvider is a ToolProvider that manages code execution environments (sandboxes, containers, local temp directories) and returns a code_exec Tool.
Subclasses must implement: - aenter(): Initialize environment and return the code_exec tool - aexit(): Cleanup the execution environment - run_command(): Execute a command and return raw result - read_file_bytes(): Read file content as bytes from the environment - write_file_bytes(): Write bytes to a file in the environment
Default implementations are provided for: - save_output_files(): Save files to local dir or another exec env (uses primitives) - upload_files(): Upload files from local or another exec env (uses primitives)
All code execution providers support an optional allowlist of command patterns. If provided, only commands matching at least one pattern are allowed. If None, all commands are allowed.
Usage with Agent
from stirrup.clients.chat_completions_client import ChatCompletionsClient
client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="assistant", tools=[LocalCodeExecToolProvider(), CALCULATOR_TOOL], )
Initialize execution environment with optional command allowlist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_commands
|
list[str] | None
|
Optional list of regex patterns. If provided, only commands matching at least one pattern are allowed. If None, all commands are allowed. |
None
|
shell_timeout
|
int
|
Per-command wall-clock timeout (seconds) applied to
every |
SHELL_TIMEOUT
|
Source code in src/stirrup/tools/code_backends/base.py
temp_dir
property
temp_dir: Path | None
Return the temporary directory for this execution environment, if any.
__aenter__
abstractmethod
async
__aenter__() -> Tool[
CodeExecutionParams, ToolUseCountMetadata
]
Enter async context: set up environment and return code_exec tool.
__aexit__
abstractmethod
async
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Exit async context: cleanup the execution environment.
run_command
abstractmethod
async
run_command(
cmd: str, *, timeout: int | None = None
) -> CommandResult
Execute a shell command and return raw CommandResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
Shell command to execute (bash syntax). |
required |
timeout
|
int | None
|
Per-call wall-clock timeout (seconds). If None, falls back
to |
None
|
Source code in src/stirrup/tools/code_backends/base.py
read_file_bytes
abstractmethod
async
Read file content as bytes from this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path within this execution environment (relative or absolute within the env's working directory). |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
File contents as bytes. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file does not exist. |
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
write_file_bytes
abstractmethod
async
Write bytes to a file in this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination path within this execution environment. |
required |
content
|
bytes
|
File contents to write. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
file_exists
abstractmethod
async
Check if a file exists in this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path within this execution environment (relative or absolute within the env's working directory). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the file exists, False otherwise. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
is_directory
abstractmethod
async
Check if a path is a directory in this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path within this execution environment. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the path exists and is a directory, False otherwise. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
list_files
abstractmethod
async
List all files recursively in a directory within this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Directory path within this execution environment. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of file paths (relative to the given path) for all files in the directory. |
list[str]
|
Returns an empty list if the path is a file or doesn't exist. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
save_output_files
async
save_output_files(
paths: list[str],
output_dir: Path | str,
dest_env: CodeExecToolProvider | None = None,
) -> SaveOutputFilesResult
Save files from this execution environment to a destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths in this execution environment to save. |
required |
output_dir
|
Path | str
|
Directory path to save files to. |
required |
dest_env
|
CodeExecToolProvider | None
|
If provided, output_dir is interpreted as a path within dest_env (cross-environment transfer). If None, output_dir is a local filesystem path. |
None
|
Returns:
| Type | Description |
|---|---|
SaveOutputFilesResult
|
SaveOutputFilesResult containing lists of saved files and any failures. |
Source code in src/stirrup/tools/code_backends/base.py
upload_files
async
upload_files(
*paths: Path | str,
source_env: CodeExecToolProvider | None = None,
dest_dir: str | None = None,
) -> UploadFilesResult
Upload files to this execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
Path | str
|
File or directory paths to upload. If source_env is None, these are local filesystem paths. If source_env is provided, these are paths within source_env (cross-environment transfer). |
()
|
source_env
|
CodeExecToolProvider | None
|
If provided, paths are within source_env. If None, paths are local filesystem paths. |
None
|
dest_dir
|
str | None
|
Destination directory in this environment. If None, uses the environment's working directory. |
None
|
Returns:
| Type | Description |
|---|---|
UploadFilesResult
|
UploadFilesResult containing lists of uploaded files and any failures. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
Source code in src/stirrup/tools/code_backends/base.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
get_code_exec_tool
get_code_exec_tool(
*,
name: str = "code_exec",
description: str | None = None,
) -> Tool[CodeExecutionParams, ToolUseCountMetadata]
Create a code execution tool for this environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Tool name |
'code_exec'
|
description
|
str | None
|
Tool description |
None
|
Returns:
| Type | Description |
|---|---|
Tool[CodeExecutionParams, ToolUseCountMetadata]
|
Tool[CodeExecutionParams] that executes commands in this environment |
Source code in src/stirrup/tools/code_backends/base.py
get_view_image_tool
get_view_image_tool(
*,
name: str = "view_image",
description: str | None = None,
) -> Tool[ViewImageParams, ToolUseCountMetadata]
Create a view_image tool for this environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Tool name |
'view_image'
|
description
|
str | None
|
Tool description |
None
|
Returns:
| Type | Description |
|---|---|
Tool[ViewImageParams, ToolUseCountMetadata]
|
Tool[ViewImageParams, ToolUseCountMetadata] that views images in this environment |
Source code in src/stirrup/tools/code_backends/base.py
view_image
abstractmethod
async
view_image(path: str) -> ImageContentBlock
Read and return an image file from the execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to image file in the execution environment (relative or absolute). |
required |
Returns:
| Type | Description |
|---|---|
ImageContentBlock
|
ImageContentBlock containing the image data. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
FileNotFoundError
|
If file does not exist. |
ValueError
|
If path is outside the execution environment, is a directory, or the file is not a valid image. |
Source code in src/stirrup/tools/code_backends/base.py
LocalCodeExecToolProvider
LocalCodeExecToolProvider(
*,
allowed_commands: list[str] | None = None,
temp_base_dir: Path | str | None = None,
description: str | None = None,
shell_timeout: int = SHELL_TIMEOUT,
)
Bases: CodeExecToolProvider
Local code execution tool provider using an isolated temp directory.
Commands are executed with the temp directory as the working directory. An optional allowlist can restrict which commands are permitted.
Usage with Agent
from stirrup.clients.chat_completions_client import ChatCompletionsClient
client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="assistant", tools=[LocalCodeExecToolProvider(), CALCULATOR_TOOL], )
async with agent.session(output_dir="./output") as session: await session.run("Run some Python code")
Standalone usage
provider = LocalCodeExecToolProvider()
async with provider as tool: # tool is a Tool instance for code execution result = await provider.run_command("python script.py") await provider.save_output_files(["output.txt"], "/path/to/output")
Initialize LocalCodeExecToolProvider configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_commands
|
list[str] | None
|
Optional list of regex patterns. If provided, only commands matching at least one pattern are allowed. If None, all commands are allowed. |
None
|
temp_base_dir
|
Path | str | None
|
Optional base directory for creating the execution environment temp directory. If None, uses the system default temp directory. |
None
|
description
|
str | None
|
Optional description of the tool. If None, uses the default description. |
None
|
shell_timeout
|
int
|
Per-command wall-clock timeout (seconds) for every
|
SHELL_TIMEOUT
|
Source code in src/stirrup/tools/code_backends/local.py
__aenter__
async
__aenter__() -> Tool[
CodeExecutionParams, ToolUseCountMetadata
]
Create temp directory and return the code_exec tool.
Source code in src/stirrup/tools/code_backends/local.py
__aexit__
async
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Cleanup the local execution environment.
Source code in src/stirrup/tools/code_backends/local.py
read_file_bytes
async
Read file content as bytes from the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
File contents as bytes. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
FileNotFoundError
|
If file does not exist. |
Source code in src/stirrup/tools/code_backends/local.py
write_file_bytes
async
Write bytes to a file in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination path (relative or absolute within the temp dir). |
required |
content
|
bytes
|
File contents to write. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
file_exists
async
Check if a file exists in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the file exists, False otherwise. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
is_directory
async
Check if a path is a directory in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the path exists and is a directory, False otherwise. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
list_files
async
List all files recursively in a directory within the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Directory path (relative or absolute within the temp dir). |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of file paths (relative to the given path) for all files in the directory. |
list[str]
|
Returns an empty list if the path is a file or doesn't exist. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If environment not started. |
ValueError
|
If path is outside temp directory. |
Source code in src/stirrup/tools/code_backends/local.py
run_command
async
run_command(
cmd: str, *, timeout: int | None = None
) -> CommandResult
Execute command in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
Shell command to execute (bash syntax). |
required |
timeout
|
int | None
|
Maximum time in seconds to wait for command completion.
If None, falls back to |
None
|
Returns:
| Type | Description |
|---|---|
CommandResult
|
CommandResult with exit_code, stdout, stderr, and optional error info. |
Source code in src/stirrup/tools/code_backends/local.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
save_output_files
async
save_output_files(
paths: list[str],
output_dir: Path | str,
dest_env: CodeExecToolProvider | None = None,
) -> SaveOutputFilesResult
Move files from the temp directory to a destination.
When dest_env is None (local filesystem), files are MOVED (not copied) - originals are deleted from the execution environment. Existing files in output_dir are silently overwritten.
When dest_env is provided (cross-environment transfer), files are copied using the base class implementation via read/write primitives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths in the execution environment (relative or absolute). Relative paths are resolved against the execution environment temp directory. |
required |
output_dir
|
Path | str
|
Directory path to save files to. |
required |
dest_env
|
CodeExecToolProvider | None
|
If provided, output_dir is interpreted as a path within dest_env (cross-environment transfer). If None, output_dir is a local filesystem path. |
None
|
Returns:
| Type | Description |
|---|---|
SaveOutputFilesResult
|
SaveOutputFilesResult containing lists of saved files and any failures. |
Source code in src/stirrup/tools/code_backends/local.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
upload_files
async
upload_files(
*paths: Path | str,
source_env: CodeExecToolProvider | None = None,
dest_dir: str | None = None,
) -> UploadFilesResult
Upload files to the execution environment.
When source_env is None (local filesystem), files are COPIED (not moved) - originals remain on the local filesystem. Directories are uploaded recursively, preserving their structure.
When source_env is provided (cross-environment transfer), files are copied using the base class implementation via read/write primitives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
Path | str
|
File or directory paths to upload. If source_env is None, these are local filesystem paths. If source_env is provided, these are paths within source_env. |
()
|
source_env
|
CodeExecToolProvider | None
|
If provided, paths are within source_env. If None, paths are local filesystem paths. |
None
|
dest_dir
|
str | None
|
Destination subdirectory within the temp directory. If None, files are placed directly in the temp directory. |
None
|
Returns:
| Type | Description |
|---|---|
UploadFilesResult
|
UploadFilesResult containing lists of uploaded files and any failures. |
Source code in src/stirrup/tools/code_backends/local.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |
view_image
async
view_image(path: str) -> ImageContentBlock
Read and return an image file from the local execution environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to image file (relative to temp directory, or absolute within it). |
required |
Returns:
| Type | Description |
|---|---|
ImageContentBlock
|
ImageContentBlock containing the image data. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If execution environment not started. |
FileNotFoundError
|
If file does not exist. |
ValueError
|
If path is outside temp directory, is a directory, or not a valid image. |
Source code in src/stirrup/tools/code_backends/local.py
SimpleFinishParams
Bases: BaseModel
Explanation for why the task is complete or cannot proceed.
AgentLogger
Bases: AgentLoggerBase
Rich console logger for agent workflows.
Implements AgentLoggerBase with rich formatting, spinners, and visual hierarchy. Each agent (including sub-agents) should have its own logger instance.
Usage
from stirrup.clients.chat_completions_client import ChatCompletionsClient
Agent creates logger internally by default
client = ChatCompletionsClient(model="gpt-4") agent = Agent(client=client, name="assistant")
Or pass a pre-configured logger
logger = AgentLogger(show_spinner=False) agent = Agent(client=client, name="assistant", logger=logger)
Agent sets these properties before calling enter:
logger.name, logger.model, logger.max_turns, logger.depth
Agent sets these before calling exit:
logger.finish_params, logger.run_metadata, logger.output_dir
Initialize the agent logger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_spinner
|
bool
|
Whether to show a spinner while agent runs (only for depth=0) |
True
|
level
|
int
|
Logging level (default: INFO) |
INFO
|
Source code in src/stirrup/utils/logging.py
__enter__
__enter__() -> Self
Enter logging context. Logs agent start and starts spinner if depth=0.
Source code in src/stirrup/utils/logging.py
__exit__
__exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Exit logging context. Stops spinner and logs completion stats.
Source code in src/stirrup/utils/logging.py
on_step
Report step progress and stats during agent execution.
Source code in src/stirrup/utils/logging.py
pause_live
Pause the live spinner display.
Call this before prompting for user input to prevent the spinner from interfering with the input prompt.
resume_live
Resume the live spinner display.
Call this after user input is complete to restart the spinner.
set_level
set_level(level: int) -> None
is_enabled_for
debug
Log a debug message (dim style).
info
warning
Log a warning message (yellow style).
error
Log an error message (red style).
critical
Log a critical message (bold red style).
Source code in src/stirrup/utils/logging.py
exception
Log an error message with exception traceback (red style with traceback).
Source code in src/stirrup/utils/logging.py
assistant_message
assistant_message(
turn: int,
max_turns: int,
assistant_message: AssistantMessage,
) -> None
Log an assistant message with content and tool calls in a panel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
turn
|
int
|
Current turn number (1-indexed) |
required |
max_turns
|
int
|
Maximum number of turns |
required |
assistant_message
|
AssistantMessage
|
The assistant's response message |
required |
Source code in src/stirrup/utils/logging.py
user_message
user_message(user_message: UserMessage) -> None
Log a user message in a panel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_message
|
UserMessage
|
The user's message |
required |
Source code in src/stirrup/utils/logging.py
task_message
Log the initial task/prompt at the start of a run.
Source code in src/stirrup/utils/logging.py
warnings_message
Display warnings at run start as simple text.
Source code in src/stirrup/utils/logging.py
tool_result
tool_result(tool_message: ToolMessage) -> None
Log a single tool execution result in a panel with XML syntax highlighting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_message
|
ToolMessage
|
The tool execution result |
required |
Source code in src/stirrup/utils/logging.py
context_summarization_start
Log context window summarization starting in an orange panel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct_used
|
float
|
Percentage of context window currently used (0.0-1.0) |
required |
cutoff
|
float
|
The threshold that triggered summarization (0.0-1.0) |
required |
Source code in src/stirrup/utils/logging.py
context_summarization_complete
Log the completed context summarization with summary content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
summary
|
str
|
The generated summary of the conversation |
required |
bridge
|
str
|
The bridge message that will be used to continue the conversation |
required |
Source code in src/stirrup/utils/logging.py
AgentLoggerBase
Bases: ABC
Abstract base class for agent loggers.
Defines the interface that Agent uses for logging. Implement this to create custom loggers (e.g., for testing, file output, or monitoring services).
Properties are set by Agent after construction: - name, model, max_turns, depth: Agent configuration - finish_params, run_metadata, output_dir: Set before exit for final stats
__enter__
abstractmethod
__enter__() -> Self
__exit__
abstractmethod
__exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Exit logging context. Called when agent session ends.
on_step
abstractmethod
Report step progress and stats during agent execution.
assistant_message
abstractmethod
assistant_message(
turn: int,
max_turns: int,
assistant_message: AssistantMessage,
) -> None
user_message
abstractmethod
user_message(user_message: UserMessage) -> None
task_message
abstractmethod
tool_result
abstractmethod
tool_result(tool_message: ToolMessage) -> None
context_summarization_start
abstractmethod
context_summarization_complete
abstractmethod
debug
abstractmethod
info
abstractmethod
warning
abstractmethod
error
abstractmethod
pause_live
SessionState
dataclass
SessionState(
exit_stack: AsyncExitStack,
exec_env: CodeExecToolProvider | None = None,
output_dir: str | None = None,
parent_exec_env: CodeExecToolProvider | None = None,
depth: int = 0,
exec_env_owned: bool = True,
uploaded_file_paths: list[str] = list(),
skills_metadata: list[SkillMetadata] = list(),
logger: AgentLoggerBase | None = None,
)
Per-session state for resource lifecycle management.
Kept minimal - only contains resources that need async lifecycle management (exit_stack, exec_env) and session-specific configuration (output_dir).
Tool availability is managed via Agent._active_tools (instance-scoped), and run results are stored on the agent instance temporarily.
For subagent file transfer: - parent_exec_env: Reference to the parent's exec env (for cross-env transfers) - depth: Agent depth (0 = root, >0 = subagent) - output_dir: For root agent, this is a local filesystem path. For subagents, this is a path within the parent's exec env. - exec_env_owned: Whether this session owns the exec_env and should clean it up. When share_parent_exec_env=True, the subagent borrows the parent's exec_env and exec_env_owned=False to prevent cleanup on subagent exit.
SubAgentParams
Bases: BaseModel
Parameters for sub-agent tool invocation.
Agent
Agent(
client: LLMClient,
name: str,
*,
max_turns: int = ...,
system_prompt: str | None = ...,
tools: list[Tool | ToolProvider] | None = ...,
finish_tool: None = None,
context_summarization_cutoff: float = ...,
turns_remaining_warning_threshold: int = ...,
run_sync_in_thread: bool = ...,
text_only_tool_responses: bool = ...,
block_successive_assistant_messages: bool = ...,
recover_from_context_overflow: bool = ...,
share_parent_exec_env: bool = ...,
logger: AgentLoggerBase | None = ...,
)
Agent(
client: LLMClient,
name: str,
*,
max_turns: int = ...,
system_prompt: str | None = ...,
tools: list[Tool | ToolProvider] | None = ...,
finish_tool: Tool[FinishParams, FinishMeta],
context_summarization_cutoff: float = ...,
turns_remaining_warning_threshold: int = ...,
run_sync_in_thread: bool = ...,
text_only_tool_responses: bool = ...,
block_successive_assistant_messages: bool = ...,
recover_from_context_overflow: bool = ...,
share_parent_exec_env: bool = ...,
logger: AgentLoggerBase | None = ...,
)
Agent(
client: LLMClient,
name: str,
*,
max_turns: int = ...,
system_prompt: str | None = ...,
tools: list[Tool | ToolProvider] | None = ...,
finish_tool: list[Tool],
context_summarization_cutoff: float = ...,
turns_remaining_warning_threshold: int = ...,
run_sync_in_thread: bool = ...,
text_only_tool_responses: bool = ...,
block_successive_assistant_messages: bool = ...,
recover_from_context_overflow: bool = ...,
share_parent_exec_env: bool = ...,
logger: AgentLoggerBase | None = ...,
)
Agent(
client: LLMClient,
name: str,
*,
max_turns: int = AGENT_MAX_TURNS,
system_prompt: str | None = None,
tools: list[Tool | ToolProvider] | None = None,
finish_tool: Tool[FinishParams, FinishMeta]
| list[Tool]
| None = None,
context_summarization_cutoff: float = CONTEXT_SUMMARIZATION_CUTOFF,
turns_remaining_warning_threshold: int = TURNS_REMAINING_WARNING_THRESHOLD,
run_sync_in_thread: bool = True,
text_only_tool_responses: bool = True,
block_successive_assistant_messages: bool = True,
recover_from_context_overflow: bool = True,
share_parent_exec_env: bool = False,
logger: AgentLoggerBase | None = None,
)
Agent that executes tool-using loops with automatic context management.
Runs up to max_turns iterations of: LLM generation → tool execution → message accumulation. When conversation history exceeds context window limits, older messages are automatically condensed into a summary to preserve working memory.
The Agent can be used as an async context manager via .session() for automatic tool lifecycle management, logging, and file saving:
from stirrup.clients.chat_completions_client import ChatCompletionsClient
# Create client and agent
client = ChatCompletionsClient(model="gpt-5")
agent = Agent(client=client, name="assistant")
async with agent.session(output_dir="./output") as session:
finish_params, history, metadata = await session.run("Your task here")
Initialize the agent with an LLM client and configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
LLMClient
|
LLM client for generating responses. Use ChatCompletionsClient for OpenAI/OpenAI-compatible APIs, or LiteLLMClient for other providers. |
required |
name
|
str
|
Name of the agent (used for logging purposes) |
required |
max_turns
|
int
|
Maximum number of turns before stopping |
AGENT_MAX_TURNS
|
system_prompt
|
str | None
|
System prompt to prepend to all runs (when using string prompts) |
None
|
tools
|
list[Tool | ToolProvider] | None
|
List of Tools and/or ToolProviders available to the agent. If None, uses DEFAULT_TOOLS. ToolProviders are automatically set up and torn down by Agent.session(). Use [*DEFAULT_TOOLS, extra_tool] to extend defaults. |
None
|
finish_tool
|
Tool[FinishParams, FinishMeta] | list[Tool] | None
|
Tool or list of Tools used to signal task completion. Defaults to SIMPLE_FINISH_TOOL. If a list is provided, a successful call to any listed tool ends the run. |
None
|
context_summarization_cutoff
|
float
|
Fraction of context window (0-1) at which to trigger summarization |
CONTEXT_SUMMARIZATION_CUTOFF
|
run_sync_in_thread
|
bool
|
Execute synchronous tool executors in a separate thread |
True
|
text_only_tool_responses
|
bool
|
Extract images from tool responses as separate user messages |
True
|
block_successive_assistant_messages
|
bool
|
If True (default), automatically inject a continue message when assistant responds without tool calls to prevent successive assistant messages. |
True
|
recover_from_context_overflow
|
bool
|
If True (default), drop one completed turn and retry when the model reports a context overflow. If the original prompt still overflows, the context error is raised. |
True
|
share_parent_exec_env
|
bool
|
When True and used as a subagent, share the parent's code execution environment instead of creating a new one. This provides better performance (no file copying) and allows the subagent to see all files in the parent's environment. Only effective when the agent is used as a subagent via to_tool(). |
False
|
logger
|
AgentLoggerBase | None
|
Optional logger instance. If None, creates AgentLogger() internally. |
None
|
Source code in src/stirrup/core/agent.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | |
tools
property
Currently active tools (available after entering session context).
finish_tool
property
finish_tool: Tool[FinishParams, FinishMeta]
The single finish tool used to signal task completion.
Raises ValueError if multiple finish tools are configured; use finish_tools instead.
session
session(
output_dir: Path | str | None = None,
input_files: str
| Path
| list[str | Path]
| None = None,
skills_dir: Path | str | None = None,
resume: bool = False,
clear_cache_on_success: bool = True,
cache_on_interrupt: bool = True,
) -> Self
Configure a session and return self for use as async context manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
Path | str | None
|
Directory to save output files from finish_params.paths |
None
|
input_files
|
str | Path | list[str | Path] | None
|
Files to upload to the execution environment at session start. Accepts a single path or list of paths. Supports: - File paths (str or Path) - Directory paths (uploaded recursively) - Glob patterns (e.g., "data/.csv", "/.py") Raises ValueError if no CodeExecToolProvider is configured or if a glob pattern matches no files. |
None
|
skills_dir
|
Path | str | None
|
Directory containing skill definitions to load and make available to the agent. Skills are uploaded to the execution environment and their metadata is included in the system prompt. |
None
|
resume
|
bool
|
If True, attempt to resume from cached state if available. The cache is identified by hashing the init_msgs passed to run(). Cached state includes message history, current turn, and execution environment files from a previous interrupted run. |
False
|
clear_cache_on_success
|
bool
|
If True (default), automatically clear the cache when the agent completes successfully. Set to False to preserve caches for inspection or debugging. |
True
|
cache_on_interrupt
|
bool
|
If True (default), set up a SIGINT handler to cache state on Ctrl+C. Set to False when running agents in threads or subprocesses where signal handlers cannot be registered from non-main threads. |
True
|
Returns:
| Type | Description |
|---|---|
Self
|
Self, for use with |
Example
async with agent.session(output_dir="./output", input_files="data/*.csv") as session: result = await session.run("Analyze the CSV files")
Note
Multiple concurrent sessions from the same Agent instance are supported. Each session maintains isolated state via ContextVar.
Source code in src/stirrup/core/agent.py
__aenter__
async
__aenter__() -> SessionAgent[FinishParams, FinishMeta]
Enter session context: set up tools, logging, and resources.
Returns a SessionAgent wrapping this agent's state, providing access to both static tools and ToolProvider-created tools. The SessionAgent shares this agent's dict, so state changes are visible to aexit.
Source code in src/stirrup/core/agent.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 | |
__aexit__
async
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit session context: save files, cleanup resources.
File handling is depth-aware: - Root agent (depth=0): Saves files to local filesystem output_dir - Subagent (depth>0): Transfers files to parent's exec env at output_dir path
Source code in src/stirrup/core/agent.py
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 | |
run_tool
async
Execute a single tool call with error handling for invalid JSON/arguments.
Returns a ToolMessage containing either the tool output or an error description. Metadata from the tool result is stored in the provided run_metadata dict.
Source code in src/stirrup/core/agent.py
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 | |
step
async
step(
messages: list[ChatMessage],
run_metadata: dict[str, list[Any]],
turn: int = 0,
max_turns: int = 0,
) -> tuple[
AssistantMessage, list[ToolMessage], FinishParams | None
]
Execute one agent step: generate assistant message and run any requested tool calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ChatMessage]
|
Current conversation messages |
required |
run_metadata
|
dict[str, list[Any]]
|
Metadata storage for tool results |
required |
turn
|
int
|
Current turn number (1-indexed) for logging |
0
|
max_turns
|
int
|
Maximum turns for logging |
0
|
Returns the assistant message, tool execution results, and finish tool call (if present).
Source code in src/stirrup/core/agent.py
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 | |
summarize_messages
async
summarize_messages(
messages: list[ChatMessage],
run_metadata_by_turn: dict[str, dict[str, list[Any]]],
) -> tuple[list[ChatMessage], list[ChatMessage]]
Summarize messages, unwinding completed turns if summarization overflows.
Source code in src/stirrup/core/agent.py
run
async
run(
init_msgs: str | list[ChatMessage],
*,
depth: int | None = None,
) -> tuple[
FinishParams | None,
list[list[ChatMessage]],
dict[str, Any],
]
Execute the agent loop until finish tool is called or max_turns reached.
A base system prompt is automatically prepended to all runs, including: - Agent purpose and max_turns info - List of input files (if provided via session()) - User's custom system_prompt (if configured in init)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_msgs
|
str | list[ChatMessage]
|
Either a string prompt (converted to UserMessage) or a list of ChatMessage to extend the conversation after the system prompt. |
required |
depth
|
int | None
|
Logging depth for sub-agent runs. If provided, updates logger.depth for this run. |
None
|
Returns:
| Type | Description |
|---|---|
FinishParams | None
|
Tuple of (finish params, message history, run metadata). |
list[list[ChatMessage]]
|
finish params is None if max_turns reached. |
dict[str, Any]
|
run metadata maps tool/agent names to lists of metadata returned by each call. |
Example
Simple string prompt
await agent.run("Analyze this data and create a report")
Multiple messages
await agent.run([ UserMessage(content="First, read the data"), AssistantMessage(content="I've read the data file..."), UserMessage(content="Now analyze it"), ])
Source code in src/stirrup/core/agent.py
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 | |
to_tool
to_tool(
*,
description: str = DEFAULT_SUB_AGENT_DESCRIPTION,
system_prompt: str | None = None,
) -> Tool[SubAgentParams, SubAgentMetadata]
Convert this Agent to a Tool for use as a sub-agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
str
|
Tool description shown to the parent agent |
DEFAULT_SUB_AGENT_DESCRIPTION
|
system_prompt
|
str | None
|
Optional system prompt to prepend when running |
None
|
Returns:
| Type | Description |
|---|---|
Tool[SubAgentParams, SubAgentMetadata]
|
Tool that executes this agent when called, returning SubAgentMetadata |
Tool[SubAgentParams, SubAgentMetadata]
|
containing token usage, message history, and any metadata from tools |
Tool[SubAgentParams, SubAgentMetadata]
|
the sub-agent used. |
Source code in src/stirrup/core/agent.py
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 | |
SessionAgent
SessionAgent(
client: LLMClient,
name: str,
*,
max_turns: int = ...,
system_prompt: str | None = ...,
tools: list[Tool | ToolProvider] | None = ...,
finish_tool: None = None,
context_summarization_cutoff: float = ...,
turns_remaining_warning_threshold: int = ...,
run_sync_in_thread: bool = ...,
text_only_tool_responses: bool = ...,
block_successive_assistant_messages: bool = ...,
recover_from_context_overflow: bool = ...,
share_parent_exec_env: bool = ...,
logger: AgentLoggerBase | None = ...,
)
SessionAgent(
client: LLMClient,
name: str,
*,
max_turns: int = ...,
system_prompt: str | None = ...,
tools: list[Tool | ToolProvider] | None = ...,
finish_tool: Tool[FinishParams, FinishMeta],
context_summarization_cutoff: float = ...,
turns_remaining_warning_threshold: int = ...,
run_sync_in_thread: bool = ...,
text_only_tool_responses: bool = ...,
block_successive_assistant_messages: bool = ...,
recover_from_context_overflow: bool = ...,
share_parent_exec_env: bool = ...,
logger: AgentLoggerBase | None = ...,
)
SessionAgent(
client: LLMClient,
name: str,
*,
max_turns: int = ...,
system_prompt: str | None = ...,
tools: list[Tool | ToolProvider] | None = ...,
finish_tool: list[Tool],
context_summarization_cutoff: float = ...,
turns_remaining_warning_threshold: int = ...,
run_sync_in_thread: bool = ...,
text_only_tool_responses: bool = ...,
block_successive_assistant_messages: bool = ...,
recover_from_context_overflow: bool = ...,
share_parent_exec_env: bool = ...,
logger: AgentLoggerBase | None = ...,
)
SessionAgent(
client: LLMClient,
name: str,
*,
max_turns: int = AGENT_MAX_TURNS,
system_prompt: str | None = None,
tools: list[Tool | ToolProvider] | None = None,
finish_tool: Tool[FinishParams, FinishMeta]
| list[Tool]
| None = None,
context_summarization_cutoff: float = CONTEXT_SUMMARIZATION_CUTOFF,
turns_remaining_warning_threshold: int = TURNS_REMAINING_WARNING_THRESHOLD,
run_sync_in_thread: bool = True,
text_only_tool_responses: bool = True,
block_successive_assistant_messages: bool = True,
recover_from_context_overflow: bool = True,
share_parent_exec_env: bool = False,
logger: AgentLoggerBase | None = None,
)
Bases: Agent[FinishParams, FinishMeta]
Agent running inside an active session with full tool access.
Returned by async with agent.session(...) as session. A SessionAgent
shares its __dict__ with the parent Agent, so it has the same
configuration and state. The key difference is that ToolProvider-created
tools have been initialized and are available in _active_tools.
Agent.run() raises RuntimeError when ToolProviders are present
but the caller is not a SessionAgent. This makes the invalid state
(calling run() with uninitialized ToolProviders) a type-level
distinction rather than just a runtime flag.
Source code in src/stirrup/core/agent.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | |
from_agent
classmethod
from_agent(
agent: Agent[FinishParams, FinishMeta],
) -> SessionAgent[FinishParams, FinishMeta]
Create a SessionAgent sharing the given Agent's __dict__.
Source code in src/stirrup/core/agent.py
compute_task_hash
compute_task_hash(
init_msgs: str | list[ChatMessage],
) -> str
Compute deterministic hash from initial messages for cache identification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_msgs
|
str | list[ChatMessage]
|
Either a string prompt or list of ChatMessage objects. |
required |
Returns:
| Type | Description |
|---|---|
str
|
First 12 characters of SHA256 hash (hex) for readability. |
Source code in src/stirrup/core/cache.py
format_skills_section
format_skills_section(skills: list[SkillMetadata]) -> str
Format skills metadata as a system prompt section.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skills
|
list[SkillMetadata]
|
List of skill metadata to include |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted string for inclusion in system prompt. |
str
|
Returns empty string if no skills provided. |
Source code in src/stirrup/skills/skills.py
load_skills_metadata
load_skills_metadata(
skills_dir: Path,
) -> list[SkillMetadata]
Scan skills directory for SKILL.md files and extract metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skills_dir
|
Path
|
Path to the skills directory |
required |
Returns:
| Type | Description |
|---|---|
list[SkillMetadata]
|
List of SkillMetadata for each valid skill found. |
list[SkillMetadata]
|
Returns empty list if skills_dir doesn't exist or has no skills. |
Source code in src/stirrup/skills/skills.py
_num_turns_remaining_msg
_num_turns_remaining_msg(
number_of_turns_remaining: int,
) -> TurnWarningMessage
Create a user message warning the agent about remaining turns before max_turns is reached.
Source code in src/stirrup/core/agent.py
_handle_text_only_tool_responses
_handle_text_only_tool_responses(
tool_messages: list[ToolMessage],
) -> tuple[list[ToolMessage], list[UserMessage]]
Extract image blocks from tool messages and convert them to user messages for text-only models.
Source code in src/stirrup/core/agent.py
_normalize_finish_tools
_normalize_finish_tools(
finish_tool: Tool[FinishParams, FinishMeta]
| list[Tool]
| None,
) -> dict[str, Tool[Any, Any]]
Normalize a single finish tool or list of finish tools into a name-keyed mapping.
Source code in src/stirrup/core/agent.py
_get_total_token_usage
_get_total_token_usage(
messages: list[list[ChatMessage]],
) -> list[TokenUsage]
Returns a list of TokenUsage objects aggregated from all AssistantMessage instances across the provided grouped message history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[list[ChatMessage]]
|
A list where each item is a list of ChatMessage objects representing a segment or turn group of the conversation history. |
required |
Returns:
| Type | Description |
|---|---|
list[TokenUsage]
|
List of TokenUsage corresponding to each AssistantMessage in the flattened conversation history. |
Source code in src/stirrup/core/agent.py
_get_tool_durations
Collect tool execution durations grouped by tool name from message history.
Source code in src/stirrup/core/agent.py
_get_turn_count
_get_turn_count(
full_msg_history: list[list[ChatMessage]],
messages: list[ChatMessage],
) -> int
Count accepted assistant turns still present in history.
Source code in src/stirrup/core/agent.py
_merge_run_metadata
_merge_run_metadata(
run_metadata_by_turn: dict[str, dict[str, list[Any]]],
) -> dict[str, list[Any]]
Merge per-turn metadata into the public run_metadata shape.
Source code in src/stirrup/core/agent.py
_get_model_speed_stats
_get_model_speed_stats(
messages: list[list[ChatMessage]], model_slug: str
) -> dict[str, float | int | str]
Compute speed stats for this agent's model from AssistantMessages.
Returns a flat dict with model_slug, num_calls, output_tokens, duration, e2e_otps. Returns empty dict if no timed messages found.