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=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]],
turn: int,
run_metadata: dict[str, list[Any]],
task_hash: str,
timestamp: str = (lambda: isoformat())(),
agent_name: str = "",
)
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).
turn
instance-attribute
turn: int
Current turn number (0-indexed) - resume will start from this turn.
run_metadata
instance-attribute
Accumulated tool metadata from the run.
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.
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
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
SystemMessage
Bases: BaseModel
System-level instructions and context for the LLM.
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
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 |
UserMessage
Bases: BaseModel
User input message to the LLM.
SkillMetadata
dataclass
Metadata extracted from a skill's SKILL.md frontmatter.
CodeExecToolProvider
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
|
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 = SHELL_TIMEOUT
) -> CommandResult
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
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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 | |
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,
)
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
|
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 = SHELL_TIMEOUT
) -> CommandResult
Execute command in the temp directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
Shell command to execute (bash syntax). |
required |
timeout
|
int
|
Maximum time in seconds to wait for command completion. |
SHELL_TIMEOUT
|
Returns:
| Type | Description |
|---|---|
CommandResult
|
CommandResult with exit_code, stdout, stderr, and optional error info. |
Source code in src/stirrup/tools/code_backends/local.py
268 269 270 271 272 273 274 275 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 | |
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
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 430 431 432 433 434 435 436 | |
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
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 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 | |
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
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,
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.
SubAgentParams
Bases: BaseModel
Parameters for sub-agent tool invocation.
Agent
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]
| 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,
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] | None
|
Tool used to signal task completion. Defaults to SIMPLE_FINISH_TOOL. |
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
|
logger
|
AgentLoggerBase | None
|
Optional logger instance. If None, creates AgentLogger() internally. |
None
|
Source code in src/stirrup/core/agent.py
tools
property
Currently active tools (available after entering session context).
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__() -> Self
Enter session context: set up tools, logging, and resources.
Creates a new SessionState and stores it in the _SESSION_STATE ContextVar, allowing concurrent sessions from the same Agent instance.
Source code in src/stirrup/core/agent.py
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | |
__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
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 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 | |
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
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
summarize_messages
async
summarize_messages(
messages: list[ChatMessage],
) -> list[ChatMessage]
Condense message history using LLM to stay within context window.
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
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 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 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 | |
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
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 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 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 | |
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,
) -> UserMessage
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
_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. |