Agentspan: Durable AI Agent Workflow Orchestration
Expert AI Agent for Agentspan Workflows
Create, run, schedule, monitor, and debug durable AI agent workflows using the Agentspan Python SDK and CLI.
What I Do
I am an expert Agentspan workflow architect and developer. I help you build reliable, scalable, and fault-tolerant AI agent systems using Agentspan's durable execution runtime.
Agentspan guarantees your agent workflows complete successfully, even through:
- Worker process crashes and restarts
- Server failures and deployments
- Long-running operations (hours/days/weeks)
- Human-in-the-loop approval delays
- Network partitions and timeouts
Core Capabilities
| Capability | Description | |
|---|
| Create | Design and implement agents, tools, multi-agent strategies, guardrails, and memory systems | |
| Run | Execute agent workflows locally or against a remote server | |
| Schedule | Set up recurring agent runs and batch processing | |
| Monitor | Stream events, query status, inspect execution history | |
| Debug | Troubleshoot failed executions, replay events, analyze errors | |
| Test | Mock agent behavior, record/replay, pytest integration | |
When to Use Agentspan
| Use Case | Use Agentspan | Use Dagu | Use Temporal | |
|---|
| AI agent orchestration | ✅ Perfect fit | ❌ Not designed for agents | ⚠️ Overkill, no agent primitives | |
| Multi-agent pipelines (research→write→edit) | ✅ Built-in strategies | ⚠️ Possible but manual | ⚠️ No agent primitives | |
| Human-in-the-loop approval flows | ✅ Built-in HITL | ⚠️ Manual approval gates | ✅ Signals/queries | |
| LLM tool-calling workflows | ✅ First-class @tool support | ❌ No LLM integration | ❌ No LLM integration | |
| Cron-style task scheduling | ✅ Agent + CLI | ✅ Perfect fit | ✅ Built-in | |
| Simple shell script orchestration | ❌ Overkill | ✅ Perfect fit | ❌ Overkill | |
| Durable business process (multi-day) | ⚠️ Can work | ❌ Not designed for it | ✅ Designed for it | |
| Batch document processing | ✅ Parallel agents | ✅ Sequential steps | ⚠️ Overkill | |
Quick Start
bash
# Install
pip install agentspan
# Verify setup
agentspan doctor
# Set API key
export OPENAI_API_KEY=sk-...
# Start the server (downloads JAR on first run)
agentspan server start
# UI at http://localhost:6767
# Run your first agent
python hello.py
python
# hello.py
from agentspan.agents import Agent, AgentRuntime, tool
@tool
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"72°F and sunny in {city}"
agent = Agent(name="weatherbot", model="openai/gpt-4o", tools=[get_weather])
with AgentRuntime() as runtime:
result = runtime.run(agent, "What's the weather in NYC?")
result.print_result()
Architecture Overview
┌─────────────────────────────────────────────────────┐
│ Agentspan Server │
│ (port 6767, SQLite or PostgreSQL) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ Workflow │ │ Task │ │ Execution History │ │
│ │ Engine │ │ Queue │ │ & State Store │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │
│ │ │ │ │
└─────────┼─────────────┼────────────────┼───────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────┐
│ Python Worker Process │
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ @tool │ │ http_ │ │ mcp_ │ │
│ │ Python │ │ tool() │ │ tool() │ │
│ │ funcs │ │ (server)│ │ (server)│ │
│ └─────────┘ └─────────┘ └─────────┘ │
│ │
│ AgentRuntime manages the worker lifecycle │
└──────────────────────────────────────────────────────┘
Key principle: @tool functions run in your Python worker process (full access to code, libraries, local state). http_tool(), api_tool(), mcp_tool() run server-side (no code to write).
CLI Reference
See references/cli-quick-reference.md for the full CLI command reference.
bash
# Server management
agentspan server start # Start server (downloads JAR on first run)
agentspan server stop # Stop server
agentspan server logs # View server logs
# Credentials
agentspan credentials set KEY value # Store encrypted credential
agentspan credentials list # List credential keys
agentspan credentials delete KEY # Delete a credential
# Agent operations
agentspan agent status <exec-id> # Check execution status
agentspan agent list # List registered agents
agentspan agent run --name my_agent "prompt" # Run and stream
agentspan agent execution --since 1h # View execution history
# Diagnostics
agentspan doctor # Check system dependencies
# Configuration
agentspan configure --url https://server.example.com
Agent Definition
python
from agentspan.agents import Agent, AgentRuntime
agent = Agent(
name="my_agent", # Unique name (becomes workflow name)
model="openai/gpt-4o", # Provider/model format
instructions="You are helpful.", # System prompt (str or callable)
tools=[...], # @tool functions or ToolDefs
agents=[...], # Sub-agents for multi-agent
strategy="handoff", # Multi-agent strategy
router=None, # Router agent or function
output_type=None, # Pydantic BaseModel for structured output
guardrails=[...], # Input/output validation
memory=None, # ConversationMemory or SemanticMemory
dependencies={...}, # Injected into ToolContext
max_turns=25, # Max agent loop iterations
max_tokens=None, # LLM max tokens
temperature=None, # LLM temperature
stop_when=None, # Early termination condition
metadata=None, # Arbitrary metadata
)
Tools
@tool — Custom Python Functions
python
from agentspan.agents import Agent, AgentRuntime, tool
@tool
def get_weather(city: str) -> dict:
"""Get current weather for a city."""
return {"city": city, "temp": 72, "condition": "Sunny"}
@tool(name="custom_name", approval_required=True, timeout_seconds=60)
def dangerous_action(target: str) -> dict:
"""Do something that requires human approval."""
return {"done": True}
agent = Agent(name="bot", model="openai/gpt-4o", tools=[get_weather])
ToolContext — Shared State and Dependencies
python
from agentspan.agents import tool, ToolContext
@tool
def query_database(query: str, context: ToolContext) -> dict:
"""Run a database query."""
db = context.dependencies["db"]
user_id = context.dependencies["user_id"]
return db.execute(query, user=user_id)
agent = Agent(
name="bot", model="openai/gpt-4o",
tools=[query_database],
dependencies={"db": my_database, "user_id": "u-123"},
)
http_tool — HTTP Endpoints (Server-Side)
python
from agentspan.agents import http_tool
weather = http_tool(
name="get_weather",
description="Get weather for a city",
url="https://api.weather.com/v1/current",
method="GET",
headers={"Authorization": "Bearer ${WEATHER_KEY}"},
input_schema={
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
credentials=["WEATHER_KEY"],
)
api_tool — OpenAPI Auto-Discovery (Server-Side)
python
from agentspan.agents import api_tool
stripe = api_tool(
url="https://api.stripe.com/openapi.json",
headers={"Authorization": "Bearer ${STRIPE_KEY}"},
credentials=["STRIPE_KEY"],
max_tools=20, # LLM auto-filters to most relevant
)
mcp_tool — MCP Servers (Server-Side)
python
from agentspan.agents import mcp_tool
github = mcp_tool(
server_url="http://localhost:3001/mcp",
name="github",
description="GitHub operations",
)
Credential Management
bash
# Store credentials (encrypted at rest with AES-256-GCM)
agentspan credentials set GITHUB_TOKEN ghp_xxxxxxxxxxxx
agentspan credentials set STRIPE_API_KEY sk_live_xxxxxxxx
python
# Option A: Isolated subprocess (credentials as env vars)
@tool(credentials=["GITHUB_TOKEN"])
def list_repos(username: str) -> dict:
import os
token = os.environ["GITHUB_TOKEN"] # Auto-injected
# Option B: In-process (use get_credential)
@tool(isolated=False, credentials=["SEARCH_API_KEY"])
def search(query: str) -> dict:
from agentspan.agents import get_credential
key = get_credential("SEARCH_API_KEY")
Multi-Agent Strategies
Sequential Pipeline (a >> b >> c)
python
researcher = Agent(name="researcher", model="openai/gpt-4o",
instructions="Research the topic thoroughly.")
writer = Agent(name="writer", model="openai/gpt-4o",
instructions="Write an article from the research.")
editor = Agent(name="editor", model="openai/gpt-4o",
instructions="Polish the article for publication.")
pipeline = researcher >> writer >> editor
with AgentRuntime() as runtime:
result = runtime.run(pipeline, "AI agents in 2025")
Parallel
python
market = Agent(name="market", model="openai/gpt-4o",
instructions="Analyze market size and growth.")
risk = Agent(name="risk", model="openai/gpt-4o",
instructions="Analyze risks.")
financial = Agent(name="financial", model="openai/gpt-4o",
instructions="Analyze financial projections.")
analysis = Agent(
name="analysis",
model="openai/gpt-4o",
agents=[market, risk, financial],
strategy="parallel",
)
with AgentRuntime() as runtime:
result = runtime.run(analysis, "Launching an AI healthcare tool")
print(result.sub_results["market"])
print(result.sub_results["risk"])
print(result.sub_results["financial"])
Handoff (Default)
python
billing = Agent(name="billing", model="openai/gpt-4o",
instructions="Handle billing inquiries.", tools=[check_balance])
technical = Agent(name="technical", model="openai/gpt-4o",
instructions="Handle technical issues.")
support = Agent(
name="support",
model="openai/gpt-4o",
instructions="Route customer requests to the right team.",
agents=[billing, technical],
strategy="handoff",
)
Router
python
# Router agent classifies and dispatches
classifier = Agent(
name="classifier",
model="openai/gpt-4o-mini",
instructions="Classify: billing, technical, or general. Reply with just the category.",
)
support = Agent(
name="support",
model="openai/gpt-4o",
agents=[billing, technical, general],
strategy="router",
router=classifier,
)
# Or use a Python function as router
def route(prompt: str) -> str:
if "bill" in prompt.lower():
return "billing"
elif "error" in prompt.lower():
return "technical"
return "general"
support = Agent(name="support", agents=[billing, technical, general],
strategy="router", router=route)
Swarm (Condition-Based Handoffs)
python
from agentspan.agents import Agent, AgentRuntime, Strategy
from agentspan.agents import TextMentionTermination