### Quick Start Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/browser-use.md A basic example demonstrating the usage of the BrowserUseToolProvider. ```python --8<-- "examples/browser_use_example.py:main" ``` -------------------------------- ### Simple Agent Quick Start Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/index.md A basic example to get started with the Stirrup agent. Requires OPENROUTER_API_KEY environment variable. Web search functionality needs BRAVE_API_KEY. ```python --8<-- "examples/getting_started.py:simple" ``` -------------------------------- ### Run MCP Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/mcp.md This snippet demonstrates the main function for MCP integration. Ensure `pip install stirrup[mcp]` or `uv add stirrup[mcp]` is run first. ```python from stirrup.mcp import MCPToolProvider def main(): # Load configuration from .mcp/mcp.json provider = MCPToolProvider.from_config() # Get a tool from the 'deepwiki' server tool = provider.get_tool("deepwiki__search") # Use the tool result = tool.run(query="example search") print(result) if __name__ == "__main__": main() ``` -------------------------------- ### Install Local Browser for Browser-Use Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/browser-use.md Install the Chromium browser locally to be used by the browser-use library. ```bash uvx browser-use install ``` -------------------------------- ### LiteLLM Client Installation Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/clients/litellm.md Instructions on how to install LiteLLM as an optional dependency for Stirrup. ```APIDOC ## LiteLLM Client Installation LiteLLM is an optional dependency. Install with: ```bash pip install stirrup[litellm] # or: uv add stirrup[litellm] ``` ``` -------------------------------- ### SKILL.md Frontmatter and Quick Start Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/skills.md Defines the metadata for a skill in YAML frontmatter and provides a Python code snippet for a quick start example using the Polars library. ```markdown --- name: data_analysis description: High-performance data analysis using Polars - load, transform, aggregate, and export tabular data. --- # Data Analysis Skill Comprehensive data analysis toolkit using **Polars**. ## Quick Start ```python import polars as pl df = pl.read_csv("data.csv") df.describe() ``` ## When to Use This Skill - Loading datasets (CSV, JSON, Parquet) - Data cleaning and transformation - Statistical analysis ... ``` -------------------------------- ### Install Stirrup Framework Source: https://github.com/artificialanalysis/stirrup/blob/main/README.md Install the core Stirrup framework or with optional components for extended functionality. Use 'uv add' for faster installation. ```bash pip install stirrup # or: uv add stirrup ``` ```bash # With all optional components pip install 'stirrup[all]' # or: uv add 'stirrup[all]' ``` ```bash # Individual extras pip install 'stirrup[litellm]' # or: uv add 'stirrup[litellm]' ``` ```bash pip install 'stirrup[docker]' # or: uv add 'stirrup[docker]' ``` ```bash pip install 'stirrup[e2b]' # or: uv add 'stirrup[e2b]' ``` ```bash pip install 'stirrup[mcp]' # or: uv add 'stirrup[mcp]' ``` ```bash pip install 'stirrup[browser]' # or: uv add 'stirrup[browser]' ``` -------------------------------- ### Install Stirrup Core Framework Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/getting-started.md Install the core Stirrup framework using pip or uv. Use the `[all]` extra for optional components. ```bash pip install stirrup # or: uv add stirrup ``` ```bash pip install 'stirrup[all]' # or: uv add 'stirrup[all]' ``` -------------------------------- ### Install Stirrup Framework Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/index.md Install the core Stirrup framework or with optional components using pip or uv. ```bash # Core framework pip install stirrup # or: uv add stirrup # With all optional components pip install 'stirrup[all]' # or: uv add 'stirrup[all]' # Individual extras pip install 'stirrup[litellm]' # or: uv add 'stirrup[litellm]' pip install 'stirrup[docker]' # or: uv add 'stirrup[docker]' pip install 'stirrup[e2b]' # or: uv add 'stirrup[e2b]' pip install 'stirrup[mcp]' # or: uv add 'stirrup[mcp]' pip install 'stirrup[browser]' # or: uv add 'stirrup[browser]' ``` -------------------------------- ### Skill Script Example with Bash Command Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/skills.md Shows how to reference a Python script within a SKILL.md file and provides an example bash command for executing it. ```markdown ### Ready-to-Use Scripts - `scripts/explore_data.py` - Quick dataset exploration ```bash python scripts/explore_data.py data.csv --output report.txt ``` ``` -------------------------------- ### MCP Integration Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md Connects to MCP servers to access additional tools. Requires `pip install stirrup[mcp]`. ```python --8<-- "examples/mcp_example.py" ``` ```json { "mcpServers": { "deepwiki": { "url": "https://mcp.deepwiki.com/sse" } } } ``` -------------------------------- ### LiteLLM Multi-Provider Support Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md Uses LiteLLM to connect to various non-OpenAI providers. Requires `pip install stirrup[litellm]` and the appropriate API key. ```python --8<-- "examples/litellm_example.py" ``` -------------------------------- ### Install Stirrup with Browser Support Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/browser-use.md Install the Stirrup library with the necessary dependencies for browser automation. ```bash pip install 'stirrup[browser]' ``` ```bash uv add 'stirrup[browser]' ``` -------------------------------- ### Extending Stirrup with Pre-Built Tools Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/index.md Example demonstrating how to extend Stirrup's capabilities by setting up pre-built tools, such as web search and calculator. ```python --8<-- "examples/web_calculator.py:setup" ``` -------------------------------- ### OpenAI-Compatible APIs Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md Connects to any OpenAI-compatible API by specifying a custom `base_url`. Requires the relevant API key environment variable. ```python --8<-- "examples/deepseek_example.py" ``` -------------------------------- ### Initialize DockerCodeExecToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/code_backends.md Instantiate DockerCodeExecToolProvider using a specified Docker image. Requires `pip install stirrup[docker]`. ```python from stirrup.tools.code_backends.docker import DockerCodeExecToolProvider provider = DockerCodeExecToolProvider.from_image("python:3.12-slim") ``` -------------------------------- ### Run Stirrup Slack Bot (Quick Start) Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/slack.md Set environment variables for Slack tokens and an API key, then run the Stirrup Slack bot. This uses a default model via OpenRouter. ```bash export SLACK_BOT_TOKEN=xoxb-... export SLACK_APP_TOKEN=xapp-... export OPENROUTER_API_KEY=sk-or-... python -m stirrup.integrations.slack ``` -------------------------------- ### Code Execution Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md Demonstrates executing code in isolated environments. Supports local, Docker, and E2B backends. ```python --8<-- "examples/code_executor/code_executor.py" ``` -------------------------------- ### Agent Finish Parameters Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/concepts.md Illustrates the structure of `finish_params`, which includes a reason for task completion and a list of paths for created or modified files. ```python finish_params = { "reason": "Successfully found Australia's population for 2022-2024 and created a chart.", "paths": ["australia_population_chart.png"] } ``` -------------------------------- ### Configure Stdio MCP Server Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/mcp.md Configuration for a local MCP server running as a command-line process. This example sets up the 'filesystem' server using 'npx' to run '@anthropics/mcp-server-filesystem'. ```json { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@anthropics/mcp-server-filesystem", "/path/to/files"] } } } ``` -------------------------------- ### Example Usage of OpenResponsesClient Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/clients/open_responses.md Demonstrates how to use the OpenResponsesClient, including configuring reasoning effort for models that support extended thinking. ```python from stirrup.clients.open_responses_client import OpenResponsesClient def example(): client = OpenResponsesClient(model="gpt-4o", reasoning_effort="high") response = client.create( messages=[ { "role": "user", "content": [ { "type": "input_text", "text": "Hello world!" } ] } ] ) print(response.choices[0].message.content) if __name__ == "__main__": example() ``` -------------------------------- ### Web Calculator Agent Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md An agent configured with a calculator tool in addition to default tools. ```python --8<-- "examples/web_calculator.py" ``` -------------------------------- ### Quick Start: Load, Explore, Transform, Analyze, Export Source: https://github.com/artificialanalysis/stirrup/blob/main/skills/data_analysis/SKILL.md A basic workflow demonstrating loading CSV data, exploring its structure, performing a simple aggregation, and exporting the result. ```python import polars as pl from polars import col # Load data df = pl.read_csv("data.csv") # Explore print(df.shape, df.schema) df.describe() # Transform and analyze result = ( df.filter(col("value") > 0) .group_by("category") .agg(col("value").sum().alias("total")) .sort("total", descending=True) ) # Export result.write_csv("output.csv") ``` -------------------------------- ### Custom Finish Tool Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md Defines structured output using a custom finish tool with Pydantic models for analysis results. Connects to OpenRouter. ```python import asyncio from pydantic import BaseModel, Field from stirrup import Agent, Tool, ToolResult, ToolUseCountMetadata from stirrup.clients.chat_completions_client import ChatCompletionsClient class AnalysisResult(BaseModel): """Structured analysis output.""" summary: str = Field(description="Brief summary of findings") confidence: float = Field(description="Confidence score 0-1") sources: list[str] = Field(description="URLs of sources used") async def main(): # Create client for OpenRouter client = ChatCompletionsClient( base_url="https://openrouter.ai/api/v1", model="anthropic/claude-sonnet-4.5", ) # Create custom finish tool finish_tool = Tool( name="finish", description="Complete the analysis with structured results", parameters=AnalysisResult, executor=lambda p: ToolResult( content="Analysis complete", metadata=ToolUseCountMetadata() ), ) agent = Agent( client=client, name="analyst", finish_tool=finish_tool, ) async with agent.session() as session: finish_params, _, _ = await session.run( "Analyze the current state of renewable energy adoption globally." ) # finish_params is now typed as AnalysisResult print(f"Summary: {finish_params.summary}") print(f"Confidence: {finish_params.confidence}") print(f"Sources: {finish_params.sources}") asyncio.run(main()) ``` -------------------------------- ### Skill Reference Documentation Structure Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/skills.md Illustrates how to organize reference documentation within a skill's directory structure, with examples for data loading and transformations. ```markdown ### Reference Documentation - `reference/loading.md` - Loading data from all supported formats - `reference/transformations.md` - Column operations, filtering, sorting ``` -------------------------------- ### Configure DockerCodeExecToolProvider Environment Variables Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/code-execution.md Example of configuring `DockerCodeExecToolProvider` to forward specific environment variables into the Docker container. ```python from stirrup.tools.code_backends.docker import DockerCodeExecToolProvider provider = DockerCodeExecToolProvider.from_image( "python:3.12-slim", env_vars=["API_KEY", "SECRET"], # Environment variables to forward ) ``` -------------------------------- ### Minimal CodeExecToolProvider Implementation Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/extending/code_backends.md A basic implementation of a custom code execution backend. This example executes commands in the current directory and handles file I/O. ```python from stirrup.tools.code_backends import ( CodeExecToolProvider, CommandResult, format_result, ) from stirrup import Tool, ToolResult class SimpleExecProvider(CodeExecToolProvider): """Simple execution in current directory.""" async def __aenter__(self) -> Tool: return self.get_code_exec_tool() async def __aexit__(self, *args): pass # No cleanup needed async def run_command(self, cmd: str, *, timeout: int = 300) -> CommandResult: import asyncio try: proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await asyncio.wait_for( proc.communicate(), timeout=timeout, ) return CommandResult( exit_code=proc.returncode or 0, stdout=stdout.decode(), stderr=stderr.decode(), ) except asyncio.TimeoutError: return CommandResult( exit_code=1, stdout="", stderr="", error_kind="timeout", advice=f"Command timed out after {timeout} seconds", ) async def read_file_bytes(self, path: str) -> bytes: with open(path, "rb") as f: return f.read() async def write_file_bytes(self, path: str, content: bytes) -> None: with open(path, "wb") as f: f.write(content) ``` -------------------------------- ### Sub-Agent Pattern Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md Illustrates a supervisor agent coordinating specialized sub-agents. The parent agent needs a `CodeExecToolProvider` if sub-agents produce files. ```python --8<-- "examples/sub_agent_example.py" ``` -------------------------------- ### BrowserUseToolProvider Configuration Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/browser-use.md Configuration options for the BrowserUseToolProvider, including local and cloud browser setups. ```APIDOC ## BrowserUseToolProvider Configuration Options | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `headless` | `bool` | `True` | Run browser without visible window | | `disable_security` | `bool` | `False` | Disable browser security features | | `executable_path` | `str | None` | `None` | Path to Chrome/Chromium | | `cdp_url` | `str | None` | `None` | CDP URL for remote browser | | `tool_prefix` | `str` | `"browser"` | Prefix for tool names | | `extra_args` | `list[str] | None` | `None` | Extra Chromium args | ## Cloud Browser Configuration To use a cloud-hosted browser, set the `BROWSER_USE_API_KEY` environment variable and initialize the provider with `use_cloud=True`. ```python import os browser_provider = BrowserUseToolProvider( use_cloud=True, # Requires BROWSER_USE_API_KEY env var ) ``` ``` -------------------------------- ### Initialize E2BCodeExecToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/code_backends.md Instantiate E2BCodeExecToolProvider for executing code in E2B cloud sandboxes. Requires `pip install stirrup[e2b]` and the `E2B_API_KEY` environment variable. ```python from stirrup.tools.code_backends.e2b import E2BCodeExecToolProvider provider = E2BCodeExecToolProvider() ``` -------------------------------- ### Extend Agent with Custom Tools Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/getting-started.md Extend your agent with additional tools by importing and setting up the desired tool modules. This example shows setting up a web calculator. ```python from stirrup.tools.web_calculator import setup setup() ``` -------------------------------- ### Run Web Search and Charting Agent Source: https://github.com/artificialanalysis/stirrup/blob/main/README.md Example of creating and running an agent that searches the web for population data and generates a matplotlib chart. Requires OPENROUTER_API_KEY and optionally BRAVE_API_KEY for web search. ```python import asyncio from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient async def main() -> None: """Run an agent that searches the web and creates a chart.""" # Create client using ChatCompletionsClient # Automatically uses OPENROUTER_API_KEY environment variable client = ChatCompletionsClient( base_url="https://openrouter.ai/api/v1", model="anthropic/claude-sonnet-4.5", ) # As no tools are provided, the agent will use the default tools, which consist of: # - Web tools (web search and web fetching, note web search requires BRAVE_API_KEY) # - Local code execution tool (to execute shell commands) agent = Agent(client=client, name="agent", max_turns=15) # Run with session context - handles tool lifecycle, logging and file outputs async with agent.session(output_dir="./output/getting_started_example") as session: finish_params, history, metadata = await session.run( """ What is the population of Australia over the last 3 years? Search the web to find out and create a simple chart using matplotlib showing the current population per year.""" ) print("Finish params: ", finish_params) print("History: ", history) print("Metadata: ", metadata) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Web Search Agent Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md A basic agent that uses default tools for web searching. Requires the BRAVE_API_KEY environment variable. ```python --8<-- "examples/getting_started.py" ``` -------------------------------- ### Agent Session with ToolProviders Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/tool-providers.md Demonstrates how an agent's `session()` automatically manages the lifecycle of `ToolProvider` instances. Providers are set up when the session starts and cleaned up when it ends. Use this pattern to integrate tools with lifecycle management into your agent. ```python from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient # Provider is set up when session starts, cleaned up when it ends client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="my_agent", tools=[ HTTPToolProvider(timeout=60), DatabaseToolProvider("postgresql://..."), ], ) async with agent.session() as session: # Tools are available here await session.run("Fetch data from the API and store in database") # Providers are cleaned up automatically ``` -------------------------------- ### Data Analysis Skill Directory Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/skills.md Provides a detailed view of the file structure for a 'data_analysis' skill, including its SKILL.md, reference documentation, and scripts. ```text skills/data_analysis/ ├── SKILL.md # Main instructions ├── reference/ │ ├── aggregations.md # Group by, window functions │ ├── loading.md # File format support │ ├── statistics.md # Statistical analysis │ ├── time_series.md # Date/time operations │ ├── transformations.md # Data transformations │ └── visualization.md # Chart creation └── scripts/ ├── explore_data.py # Dataset profiling script └── summary_stats.py # Statistics report script ``` -------------------------------- ### Initialize Agent with E2BCodeExecToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/code-execution.md Sets up an agent to execute code in E2B cloud sandboxes for maximum isolation. Requires `stirrup[e2b]` installation and `E2B_API_KEY`. Files can be uploaded and output saved. ```python from stirrup import Agent from stirrup.tools.code_backends.e2b import E2BCodeExecToolProvider provider = E2BCodeExecToolProvider() client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="e2b_coder", tools=[provider], max_turns=20, ) async with agent.session( input_files="data/*.csv", output_dir="./results", ) as session: await session.run("Analyze the CSV files and create a report") ``` -------------------------------- ### Initialize Agent with DockerCodeExecToolProvider from Image Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/code-execution.md Sets up an agent to execute code within a Docker container using a specified image. Requires Docker daemon and `stirrup[docker]` installation. Environment variables can be forwarded. ```python from stirrup import Agent from stirrup.tools.code_backends.docker import DockerCodeExecToolProvider provider = DockerCodeExecToolProvider.from_image( "python:3.12-slim", env_vars=["OPENAI_API_KEY"], # Forward these env vars ) client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="docker_coder", tools=[provider], ) ``` -------------------------------- ### Create Tool with State Management Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/extending/tools.md Develop a tool that maintains state across calls, such as conversation memory. This example shows tools for remembering and recalling facts. ```python class ConversationMemoryProvider: """Tool that remembers context across calls.""" has_lifecycle = True def __init__(self): self._memories: list[str] = [] async def __aenter__(self) -> list[Tool]: return [self._create_remember_tool(), self._create_recall_tool()] def _create_remember_tool(self) -> Tool: async def remember(params: RememberParams) -> ToolResult[ToolUseCountMetadata]: self._memories.append(params.fact) return ToolResult( content=f"Remembered: {params.fact}", metadata=ToolUseCountMetadata(), ) return Tool( name="remember", description="Store a fact for later recall", parameters=RememberParams, executor=remember, ) def _create_recall_tool(self) -> Tool: async def recall(params: RecallParams) -> ToolResult[ToolUseCountMetadata]: relevant = [m for m in self._memories if params.query.lower() in m.lower()] if relevant: return ToolResult(content="\n".join(relevant), metadata=ToolUseCountMetadata()) return ToolResult(content="No relevant memories found", metadata=ToolUseCountMetadata()) return Tool( name="recall", description="Recall previously stored facts", parameters=RecallParams, executor=recall, ) async def __aexit__(self, *args): self._memories.clear() ``` -------------------------------- ### Implement Custom Metadata with Addable Protocol Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/tools.md Implement the `Addable` protocol to create custom metadata for tools. This example shows tracking API calls and costs. ```python from stirrup import Addable from pydantic import BaseModel class APICallMetadata(BaseModel, Addable): """Track API calls and costs.""" calls: int = 1 tokens_used: int = 0 cost_usd: float = 0.0 def __add__(self, other: "APICallMetadata") -> "APICallMetadata": return APICallMetadata( calls=self.calls + other.calls, tokens_used=self.tokens_used + other.tokens_used, cost_usd=self.cost_usd + other.cost_usd, ) ``` ```python async def api_tool(params: APIParams) -> ToolResult[APICallMetadata]: response = await call_api(params) return ToolResult( content=response.text, metadata=APICallMetadata( tokens_used=response.tokens, cost_usd=response.cost, ), ) ``` -------------------------------- ### View Image Tool with Agent Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/code-execution.md Use `ViewImageToolProvider` to enable an agent to view images from the execution environment. This setup includes `LocalCodeExecToolProvider` for general code execution. ```python from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import LocalCodeExecToolProvider, ViewImageToolProvider client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="image_viewer", tools=[ LocalCodeExecToolProvider(), ViewImageToolProvider(), # Auto-detects exec env ], ) async with agent.session() as session: await session.run("Create a matplotlib chart and view it") ``` -------------------------------- ### Initialize LiteLLMClient for Multiple Providers Source: https://context7.com/artificialanalysis/stirrup/llms.txt Access over 100 LLM providers via LiteLLM's unified interface. Requires `pip install stirrup[litellm]`. ```python from stirrup import Agent from stirrup.clients.litellm_client import LiteLLMClient from stirrup.tools import LocalCodeExecToolProvider # Anthropic Claude via LiteLLM (reads ANTHROPIC_API_KEY) client = LiteLLMClient(model="claude-3-5-sonnet-20241022", max_tokens=64_000) # Google Gemini client = LiteLLMClient(model="gemini/gemini-2.0-flash", max_tokens=32_000) agent = Agent(client=client, name="gemini-agent", tools=[LocalCodeExecToolProvider()]) async with agent.session(output_dir="./out") as session: await session.run("Write and run a Python script that prints Fibonacci numbers.") ``` -------------------------------- ### Run Stirrup Slack Bot (Custom Agents) Source: https://github.com/artificialanalysis/stirrup/blob/main/src/stirrup/integrations/slack/README.md Configure and run the Stirrup Slack bot with custom agents and clients. This example sets up a default assistant and a 'data' agent with a specific system prompt and skills directory. ```python import asyncio import os from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.integrations.slack import SlackBot, SlackBotConfig, SlackAgentConfig client = ChatCompletionsClient( model="google/gemini-3-flash-preview", base_url="https://openrouter.ai/api/v1", ) config = SlackBotConfig( slack_bot_token=os.environ["SLACK_BOT_TOKEN"], slack_app_token=os.environ["SLACK_APP_TOKEN"], default_agent=SlackAgentConfig(name="assistant", client=client), named_agents={ "data": SlackAgentConfig( name="data-analyst", client=client, system_prompt="You are a data analysis expert.", skills_dir="./skills", # optional: load SKILL.md files ), }, ) asyncio.run(SlackBot(config).start()) ``` -------------------------------- ### Initialize and Run Agent with Tools Source: https://context7.com/artificialanalysis/stirrup/llms.txt Sets up an agent with a specific client and tool providers, then runs a task within a session context. Ensure the client and tools are correctly configured for your needs. ```python import asyncio from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import LocalCodeExecToolProvider, WebToolProvider async def main(): client = ChatCompletionsClient( base_url="https://openrouter.ai/api/v1", model="anthropic/claude-sonnet-4-5", max_tokens=64_000, ) agent = Agent( client=client, name="assistant", tools=[WebToolProvider(), LocalCodeExecToolProvider()], max_turns=20, system_prompt="You are a research assistant. Save all findings to files.", ) async with agent.session(output_dir="./output", input_files="data/*.csv") as session: finish_params, message_history, run_metadata = await session.run( "Summarise the CSV files and produce a markdown report." ) if finish_params: print("Done:", finish_params.reason) else: print("Max turns reached without finishing.") asyncio.run(main()) ``` -------------------------------- ### Configure and Run Custom Slack Bot Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/slack.md Configure a custom Slack bot with specific clients and agents. This example sets up a default agent and a named 'data' agent with a custom system prompt and skills directory. ```python import asyncio import os from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.integrations.slack import SlackBot, SlackBotConfig, SlackAgentConfig client = ChatCompletionsClient( model="google/gemini-3-flash-preview", base_url="https://openrouter.ai/api/v1", ) config = SlackBotConfig( slack_bot_token=os.environ["SLACK_BOT_TOKEN"], slack_app_token=os.environ["SLACK_APP_TOKEN"], default_agent=SlackAgentConfig(name="assistant", client=client), named_agents={ "data": SlackAgentConfig( name="data-analyst", client=client, system_prompt="You are a data analysis expert.", skills_dir="./skills", ), }, ) asyncio.run(SlackBot(config).start()) ``` -------------------------------- ### Build and Serve Project Locally Source: https://github.com/artificialanalysis/stirrup/blob/main/README.md Use this command to build and serve the project documentation locally for development and testing. ```bash uv run mkdocs serve ``` -------------------------------- ### Implement HttpToolProvider for Async HTTP Requests Source: https://context7.com/artificialanalysis/stirrup/llms.txt Provides a ToolProvider that reuses an httpx.AsyncClient for multiple HTTP GET requests within an Agent session. The fetch tool limits content to 2000 characters. ```python import asyncio import httpx from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.core.models import Tool, ToolProvider, ToolResult, ToolUseCountMetadata from pydantic import BaseModel class FetchParams(BaseModel): url: str class HttpToolProvider(ToolProvider): """Reuses a single httpx.AsyncClient for all fetch calls in a session.""" async def __aenter__(self) -> Tool: self._client = httpx.AsyncClient(timeout=10) async def fetch(params: FetchParams) -> ToolResult[ToolUseCountMetadata]: r = await self._client.get(params.url) return ToolResult(content=r.text[:2000], metadata=ToolUseCountMetadata()) return Tool(name="fetch_url", description="Fetch a URL.", parameters=FetchParams, executor=fetch) async def __aexit__(self, *_): await self._client.aclose() async def main(): client = ChatCompletionsClient(model="gpt-4o-mini") agent = Agent(client=client, name="fetcher", tools=[HttpToolProvider()]) async with agent.session() as session: finish, _, _ = await session.run("Fetch https://example.com and summarise it.") asyncio.run(main()) ``` -------------------------------- ### Minimal Logger Implementation Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/extending/loggers.md Implement a basic logger that prints agent session start, step summaries, and completion status to the console. Requires extending AgentLoggerBase and implementing __enter__, __exit__, and on_step. ```python from stirrup.utils.logging import AgentLoggerBase class MinimalLogger(AgentLoggerBase): """Minimal logger that prints step summaries.""" def __enter__(self): print(f"Starting agent: {self.name}") return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: print(f"Agent failed: {exc_val}") else: print(f"Agent completed: {self.finish_params}") def on_step(self, turn, total_tools, input_tokens, output_tokens): print(f"Turn {turn}: {total_tools} tools, {input_tokens + output_tokens} tokens") ``` -------------------------------- ### Mixing Tools and Providers in an Agent Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/tool-providers.md Demonstrates how to initialize an Agent with a mix of regular tools and tool providers, including built-in and custom providers. Ensure necessary imports are present. ```python from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import CALCULATOR_TOOL, WebToolProvider client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="mixed_agent", tools=[ CALCULATOR_TOOL, # Regular tool (no lifecycle) HTTPToolProvider(), # Provider (has lifecycle) WebToolProvider(), # Built-in provider ], ) ``` -------------------------------- ### File Logger Implementation Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/extending/loggers.md Create a logger that writes agent session details and step-by-step progress to a JSON file. This logger logs start and end events, along with detailed step information, to a specified directory. ```python import json from pathlib import Path from datetime import datetime class FileLogger(AgentLoggerBase): """Logger that writes to a JSON file.""" def __init__(self, log_dir: str = "./logs"): self.log_dir = Path(log_dir) self.log_file: Path | None = None self.steps: list[dict] = [] def __enter__(self): self.log_dir.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") self.log_file = self.log_dir / f"{self.name}_{timestamp}.json" self.steps = [] # Write initial entry self._write({ "event": "start", "agent": self.name, "model": self.model, "max_turns": self.max_turns, "timestamp": datetime.now().isoformat(), }) return self def __exit__(self, exc_type, exc_val, exc_tb): # Write final entry self._write({ "event": "end", "success": exc_type is None, "error": str(exc_val) if exc_val else None, "finish_params": self.finish_params.model_dump() if self.finish_params else None, "steps": self.steps, "timestamp": datetime.now().isoformat(), }) def on_step(self, turn, total_tools, input_tokens, output_tokens): step = { "turn": turn, "total_tools": total_tools, "input_tokens": input_tokens, "output_tokens": output_tokens, "timestamp": datetime.now().isoformat(), } self.steps.append(step) def _write(self, data: dict): if self.log_file: with open(self.log_file, "w") as f: json.dump(data, f, indent=2) ``` -------------------------------- ### Initialize Agent with ViewImageToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/view-image.md Demonstrates how to initialize an Agent with both LocalCodeExecToolProvider and ViewImageToolProvider. The ViewImageToolProvider automatically detects the execution environment when not explicitly provided. ```python from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import LocalCodeExecToolProvider, ViewImageToolProvider client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="image_viewer", tools=[ LocalCodeExecToolProvider(), ViewImageToolProvider(), # Auto-detects exec environment ], ) async with agent.session() as session: await session.run("Create a chart with matplotlib and view it") ``` -------------------------------- ### Run Commands in E2B Cloud Sandbox Source: https://context7.com/artificialanalysis/stirrup/llms.txt Use E2BCodeExecToolProvider to execute commands in a secure E2B cloud sandbox. Requires `pip install stirrup[e2b]` and an `E2B_API_KEY`. Supports custom templates, command allowlists, and rate limiting for sandbox creation. ```python import asyncio from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools.code_backends.e2b import E2BCodeExecToolProvider, make_create_gate async def main(): client = ChatCompletionsClient(model="gpt-4o") # Basic usage provider = E2BCodeExecToolProvider( timeout=600, # sandbox lifetime (seconds) template="my-template", # optional custom E2B template allowed_commands=[r"^python", r"^pip"], shell_timeout=60, ) # With rate limiting (requires stirrup[e2b-throttle]) gate = make_create_gate(max_rate=3) # max 3 sandbox creates/sec provider = E2BCodeExecToolProvider(timeout=300, create_gate=gate) agent = Agent(client=client, name="cloud-coder", tools=[provider]) async with agent.session(output_dir="./output") as session: finish, _, _ = await session.run( "Write a Python script that downloads stock data using yfinance, plots it, and saves the chart." ) if finish: print("Saved files:", finish.paths) asyncio.run(main()) ``` -------------------------------- ### Install LiteLLM Dependency Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/clients/litellm.md Install LiteLLM as an optional dependency for Stirrup. This is required to use LiteLLM-specific features. ```bash pip install stirrup[litellm] ``` ```bash uv add stirrup[litellm] ``` -------------------------------- ### Install Stirrup in Editable Mode Source: https://github.com/artificialanalysis/stirrup/blob/main/README.md Install the Stirrup library in editable mode for development. This allows changes to the source code to be reflected immediately without reinstallation. ```bash git clone https://github.com/ArtificialAnalysis/Stirrup.git cd stirrup pip install -e . # or: uv venv && uv pip install -e . ``` ```bash pip install -e '.[all]' # or: uv venv && uv pip install -e '.[all]' ``` -------------------------------- ### Initialize Agent with Default Logger Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/concepts.md Demonstrates initializing the Agent with the default AgentLogger, which provides detailed console output including progress spinners and visual hierarchy. ```python from stirrup.utils.logging import AgentLogger import logging # Custom log level logger = AgentLogger(level=logging.DEBUG) agent = Agent(client=client, name="assistant", logger=logger) ``` -------------------------------- ### Install Stirrup with Slack and Docker Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/slack.md Install the Stirrup package with the necessary extras for Slack integration and Docker support. The Docker extra is required for the default code execution backend. ```bash pip install stirrup[slack,docker] ``` -------------------------------- ### Install Browser Extra for Slack Integration Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/slack.md Install the 'browser' extra for Stirrup to enable browser automation capabilities within the Slack integration. This is required for agents that need to interact with web pages. ```bash pip install stirrup[slack,docker,browser] ``` -------------------------------- ### Install Stirrup in Editable Mode Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/extending/full-customization.md Install Stirrup using pip in editable mode. This allows changes in the source code to be reflected immediately without reinstallation. Use `.[all]` to include optional dependencies. ```bash pip install -e . # or: uv venv && uv pip install -e . ``` ```bash pip install -e '.[all]' # or: uv venv && uv pip install -e '.[all]' ``` -------------------------------- ### Skills with Docker Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/skills.md Demonstrates how to create a Dockerfile for skills with specific dependencies and pass it to `DockerCodeExecToolProvider.from_dockerfile()`. ```APIDOC ## Skills with Docker When using skills that require specific dependencies, create a Dockerfile: ```dockerfile --8<-- "examples/skills/Dockerfile" ``` Then pass it to `DockerCodeExecToolProvider.from_dockerfile()` as shown in the example above. ``` -------------------------------- ### Image Processing Agent Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/examples.md An agent capable of downloading and viewing images. ```python --8<-- "examples/view_image_example.py" ``` -------------------------------- ### DockerCodeExecToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/code_backends.md Executes code in a Docker container. Requires `pip install stirrup[docker]`. ```APIDOC ## DockerCodeExecToolProvider Executes code in a Docker container. ### Usage ```python from stirrup.tools.code_backends.docker import DockerCodeExecToolProvider provider = DockerCodeExecToolProvider.from_image("python:3.12-slim") ``` ``` -------------------------------- ### Initialize Agent with LocalCodeExecToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/code-execution.md Sets up an agent to execute code using the `LocalCodeExecToolProvider` in a temporary directory. Use for development or with trusted code. ```python from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import LocalCodeExecToolProvider client = ChatCompletionsClient(model="gpt-5") agent = Agent( client=client, name="local_coder", tools=[LocalCodeExecToolProvider()], ) async with agent.session(output_dir="./output") as session: await session.run("Write and run a Python hello world script") ``` -------------------------------- ### Synchronous Tool Executor Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/tools.md A standard synchronous function that takes parameters and returns a ToolResult. ```python def my_tool(params: MyParams) -> ToolResult[ToolUseCountMetadata]: result = do_something(params) return ToolResult(content=result, metadata=ToolUseCountMetadata()) ``` -------------------------------- ### Setting Up Multiple Specialized Sub-Agents Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/sub-agents.md Shows how to initialize multiple distinct specialist agents (researcher, coder, reviewer) with their respective tools, preparing them to be used as sub-agents by a parent. ```python from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import LocalCodeExecToolProvider, WebToolProvider client = ChatCompletionsClient( base_url="https://api.openai.com/v1", model="gpt-5", ) # Specialist agents researcher = Agent( client=client, name="researcher", tools=[WebToolProvider()], ) coder = Agent( client=client, name="coder", tools=[LocalCodeExecToolProvider()], ) reviewer = Agent( client=client, name="reviewer", tools=[LocalCodeExecToolProvider()], ) ``` -------------------------------- ### Agent Session with ViewImageToolProvider Source: https://context7.com/artificialanalysis/stirrup/llms.txt Sets up an agent with a multimodal client and the ViewImageToolProvider to generate an image, save it, and then describe its content. Requires a multimodal model. ```python import asyncio from stirrup import Agent from stirrup.clients.chat_completions_client import ChatCompletionsClient from stirrup.tools import LocalCodeExecToolProvider from stirrup.tools.view_image import ViewImageToolProvider async def main(): client = ChatCompletionsClient(model="gpt-4o") # multimodal model required exec_env = LocalCodeExecToolProvider() agent = Agent( client=client, name="vision-coder", tools=[ exec_env, ViewImageToolProvider(), # auto-detects exec_env from session ], max_turns=10, ) async with agent.session(output_dir="./output") as session: finish, _, _ = await session.run( "Write Python code that generates a matplotlib bar chart of [10, 25, 7, 42], " "saves it as chart.png, then view the image and describe what you see." ) asyncio.run(main()) ``` -------------------------------- ### E2BCodeExecToolProvider Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/code_backends.md Executes code in an E2B cloud sandbox. Requires `pip install stirrup[e2b]` and `E2B_API_KEY` environment variable. ```APIDOC ## E2BCodeExecToolProvider Executes code in an E2B cloud sandbox. ### Usage ```python from stirrup.tools.code_backends.e2b import E2BCodeExecToolProvider provider = E2BCodeExecToolProvider() ``` ``` -------------------------------- ### Create a Simple Agent Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/getting-started.md Create a basic agent capable of web searching and code execution. Ensure environment variables like OPENROUTER_API_KEY and BRAVE_API_KEY are set. ```python from stirrup import Agent agent = Agent() async with agent.session() as session: await session.run("What is the capital of France?") ``` -------------------------------- ### Initialize BrowserUseToolProvider with Cloud Option Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/api/tools/browser-use.md Initialize the BrowserUseToolProvider to use cloud-hosted browsers. Ensure the BROWSER_USE_API_KEY environment variable is set. ```python import os browser_provider = BrowserUseToolProvider( use_cloud=True, # Requires BROWSER_USE_API_KEY env var ) ``` -------------------------------- ### Asynchronous Tool Executor Example Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/tools.md An asynchronous function that takes parameters and returns a ToolResult. Use 'await' for async operations. ```python async def my_async_tool(params: MyParams) -> ToolResult[ToolUseCountMetadata]: result = await do_something_async(params) return ToolResult(content=result, metadata=ToolUseCountMetadata()) ``` -------------------------------- ### Exporting DataFrames Source: https://github.com/artificialanalysis/stirrup/blob/main/skills/data_analysis/SKILL.md Provides examples for exporting Polars DataFrames to common file formats like CSV, Parquet, and JSON. ```python df.write_csv("output.csv") ``` ```python df.write_parquet("output.parquet") ``` ```python df.write_json("output.json", row_oriented=True) ``` -------------------------------- ### Configure OpenAI-Compatible Client Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/getting-started.md Use `ChatCompletionsClient` to connect to OpenAI models or any OpenAI-compatible API. This example uses the Deepseek API. ```python from stirrup import ChatCompletionsClient client = ChatCompletionsClient( api_key="YOUR_DEEPSEEK_API_KEY", base_url="https://api.deepseek.com", model="deepseek-coder" ) ``` -------------------------------- ### Create Skills Directory Structure Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/skills.md This illustrates the basic directory structure for a skill, including the main instruction file and optional subdirectories for reference documentation and scripts. ```bash skills/ └── data_analysis/ ├── SKILL.md ├── reference/ │ ├── loading.md │ └── transformations.md └── scripts/ ├── explore_data.py └── summary_stats.py ``` -------------------------------- ### Filtering and Selecting DataFrames Source: https://github.com/artificialanalysis/stirrup/blob/main/skills/data_analysis/SKILL.md Examples of how to select specific columns and filter rows based on various conditions, including string matching. ```python # Select columns df.select("col1", "col2") df.select(col("name"), col("value") * 2) ``` ```python # Filter rows df.filter(col("age") > 25) ``` ```python df.filter((col("status") == "active") & (col("value") > 100)) ``` ```python df.filter(col("name").str.contains("Smith")) ``` -------------------------------- ### Run Tests Source: https://github.com/artificialanalysis/stirrup/blob/main/README.md Use this command to execute the project's test suite. ```bash uv run pytest tests ``` -------------------------------- ### OpenAI-Compatible API Client Configuration Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/index.md Configure a client to use OpenAI-compatible APIs with Stirrup. This example demonstrates setting the base URL for the ChatCompletionsClient. ```python --8<-- "examples/deepseek_example.py:client" ``` -------------------------------- ### Import Stirrup Components Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/extending/full-customization.md Import core classes and default tools from the Stirrup library after installation. These are commonly used components for building agent-based applications. ```python from stirrup import Agent, DEFAULT_TOOLS from stirrup.core.models import SystemMessage, UserMessage from stirrup.clients import ChatCompletionsClient ``` -------------------------------- ### Upload Files to Execution Environment Source: https://github.com/artificialanalysis/stirrup/blob/main/docs/guides/code-execution.md Demonstrates how to upload single files, multiple files, or entire directories/patterns to the agent's execution environment using the `input_files` parameter in `agent.session`. ```python async with agent.session( input_files="data.csv", # Single file # input_files=["a.csv", "b.csv"], # Multiple files # input_files="data/*.csv", # Glob pattern # input_files="./data/", # Directory (recursive) ) as session: await session.run("Process the uploaded files") ```