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=lambda params: ToolResult(
content=reason, metadata=ToolUseCountMetadata()
),
)
_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.
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 (must be a Pydantic BaseModel, or None for parameterless tools) M: Metadata type (should implement Addable for aggregation; use None for tools without metadata)
Tools are simple, stateless callables. For tools requiring lifecycle management (setup/teardown, resource pooling), use a ToolProvider instead.
Example with parameters
class CalcParams(BaseModel): expression: str
calc_tool = ToolCalcParams, None)
Example without parameters
time_tool = ToolNone, None)
ToolCall
ToolMessage
Bases: BaseModel
Tool execution result returned to the LLM.
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.
UserMessage
Bases: BaseModel
User input message to the LLM.
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
__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
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
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 | |
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
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
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
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
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 371 372 373 374 375 376 | |
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
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 462 463 | |
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
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
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(),
)
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,
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,
) -> 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
|
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
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 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 | |
__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
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 | |
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], ToolCall | 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, list[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, list[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
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 | |
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
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 | |
_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]],
) -> TokenUsage
Aggregate token usage across all assistant messages in grouped conversation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[list[ChatMessage]]
|
List of message groups, where each group represents a segment of conversation. |
required |