Skip to content

Latest commit

 

History

History
348 lines (269 loc) · 15.6 KB

File metadata and controls

348 lines (269 loc) · 15.6 KB

Examples

Runnable examples demonstrating every feature of the Agentspan SDK.


Examples vs. Production

Every example uses runtime.run() for convenience. In production, you should not.

Examples call runtime.run() so you can try them in a single command — no setup, no separate processes. But run() blocks the caller until the agent finishes, which is fine for demos but not how you deploy real agents.

Production: Deploy → Serve → Run

In production, the three concerns are separated:

┌──────────────────────────────────────────────────────────────┐
│  1. DEPLOY (once, during CI/CD)                              │
│     Registers the agent definition with the Agentspan server │
│                                                              │
│     runtime.deploy(agent)                                    │
│     # or CLI: agentspan deploy --package my_agents           │
├──────────────────────────────────────────────────────────────┤
│  2. SERVE (long-running worker process)                      │
│     Listens for tool-call tasks and executes them            │
│                                                              │
│     runtime.serve(agent)                                     │
│     # typically run as a daemon, container, or systemd unit  │
├──────────────────────────────────────────────────────────────┤
│  3. RUN (on-demand, from anywhere)                           │
│     Triggers an agent execution                              │
│                                                              │
│     agentspan run <agent-name> "prompt"                      │
│     # or SDK: runtime.run("agent_name", "prompt")            │
│     # or REST API                                            │
└──────────────────────────────────────────────────────────────┘

Every example includes the deploy/serve pattern as commented code at the bottom of its __main__ block — look for the # Production pattern: comment.

See 63_deploy.py, 63b_serve.py, and 63c_run_by_name.py for a complete working example of this pattern.


Getting Started

1. Install dependencies

The core examples (numbered files in this directory) only need the conductor-agent-sdk package:

uv pip install conductor-agent-sdk

Framework-specific examples require additional packages. Install only what you need:

LangChain examples (langchain/)

uv pip install langchain langchain-core langchain-openai
Package Required Notes
langchain Yes Core framework, includes create_agent
langchain-core Yes Tools, prompts, output parsers, messages
langchain-openai Yes ChatOpenAI LLM provider
pydantic Some examples Used for structured output (03, 04, 24, 25)

LangGraph examples (langgraph/)

uv pip install langgraph langchain-core langchain-openai
Package Required Notes
langgraph Yes StateGraph, create_react_agent, prebuilt nodes
langchain-core Yes Messages, tools, documents
langchain-openai Yes ChatOpenAI LLM provider
langchain-anthropic Optional Only for 43_react_agent_multi_model.py (requires ANTHROPIC_API_KEY)
pydantic Some examples Used for structured output (08)

OpenAI Agents SDK examples (openai/)

uv pip install openai-agents
Package Required Notes
openai-agents Yes Agent, function_tool, ModelSettings, guardrails
pydantic Some examples Used for structured output (03)

Requires OPENAI_API_KEY environment variable.

Google ADK examples (adk/)

uv pip install google-adk
Package Required Notes
google-adk Yes Agent, SequentialAgent, ParallelAgent, LoopAgent, planners
pydantic Some examples Used for structured output (03)

Requires GOOGLE_GEMINI_API_KEY environment variable.

Install everything

To install all framework dependencies at once:

uv pip install langchain langchain-core langchain-openai langgraph openai-agents google-adk

2. Configure your environment

Export environment variables:

export AGENTSPAN_LLM_MODEL=openai/gpt-4o-mini
export AGENTSPAN_SERVER_URL=http://localhost:8080/api
# export AGENTSPAN_AUTH_KEY=<key>     # if authentication is enabled
# export AGENTSPAN_AUTH_SECRET=<secret>

2.1. Choose a model

The AGENTSPAN_LLM_MODEL variable uses the provider/model-name format. Examples:

Provider Model string API key env var
OpenAI anthropic/claude-sonnet-4-6 (default) OPENAI_API_KEY
Anthropic anthropic/claude-sonnet-4-20250514 ANTHROPIC_API_KEY
Google Gemini google_gemini/gemini-2.0-flash GOOGLE_GEMINI_API_KEY
AWS Bedrock aws_bedrock/... AWS credentials
Azure OpenAI azure_openai/... Azure credentials

All supported providers: openai, anthropic, google_gemini, google_vertex_ai, azure_openai, aws_bedrock, cohere, mistral, groq, perplexity, hugging_face, deepseek.

3. Run an example

# Core SDK examples
python examples/01_basic_agent.py
python examples/15_agent_discussion.py

# Framework-specific examples
python examples/langchain/01_hello_world.py
python examples/langgraph/01_hello_world.py
python examples/openai/01_basic_agent.py
python examples/adk/01_basic_agent.py

Basic Examples

# Example What it demonstrates
01 Basic Agent Simplest possible agent — single LLM, no tools, 5 lines of code
02 Tools Multiple @tool functions, approval-required tools

Tool Calling

# Example What it demonstrates
02a Simple Tools Two tools (weather, stocks) — LLM picks the right one
02b Multi-Step Tools Chained tool calls: lookup → fetch → calculate → answer
03 Structured Output Pydantic output_type for typed, validated responses
04 HTTP & MCP Tools Server-side tools via http_tool() and mcp_tool() — no workers needed
04b MCP Weather Real-time weather via an MCP server
14 Existing Workers Use existing @worker_task functions directly as agent tools
33 Single Turn Tool Single-turn tool invocation with immediate response
33 External Workers Reference workers in other services via @tool(external=True) — no local code needed

Multi-Agent Orchestration

# Example Pattern Key API
05 Handoffs LLM-driven delegation to sub-agents strategy="handoff"
06 Sequential Pipeline Agents run in order, output chains forward strategy="sequential", >> operator
07 Parallel Agents All agents run concurrently, results aggregated strategy="parallel"
08 Router Agent Router (Agent or callable) selects which sub-agent runs strategy="router"
13 Hierarchical Agents 3-level nested hierarchy: CEO → leads → specialists Nested strategy="handoff"
15 Agent Discussion Round-robin debate between agents, piped to a summarizer strategy="round_robin", >>
16 Random Strategy Random agent selected each turn (brainstorming) strategy="random"
17 Swarm Orchestration Automatic transitions via handoff conditions strategy="swarm", OnTextMention
18 Manual Selection Human picks which agent speaks each turn strategy="manual"
20 Constrained Transitions Restrict which agents can follow which allowed_transitions
29 Agent Introductions Agents introduce themselves before a group discussion introduction parameter
38 Tech Trends Multi-agent research pipeline with live HTTP API tools >> operator, from __future__ import annotations

Human-in-the-Loop

# Example What it demonstrates
09 Human-in-the-Loop Tool approval gate — approve or reject before execution
09b HITL with Feedback Custom feedback via respond() — editorial review with revision notes
09c HITL with Streaming Real-time event stream with approval pauses

Guardrails & Safety

# Example What it demonstrates
10 Guardrails Output validation with @guardrail decorator, OnFail/Position enums
21 Regex Guardrails Pattern-based blocking (emails, SSNs) and allow-listing (JSON)
22 LLM Guardrails AI-powered content safety evaluation via a judge LLM
31 Tool Guardrails Pre-execution validation on tool inputs (SQL injection blocking)
32 Human Guardrail Pause agent for human review when output fails validation
35 Standalone Guardrails Use @guardrail as plain callables — no agent, no server needed
36 Simple Agent Guardrails Guardrails on agents without tools — mixed regex (InlineTask) + custom (worker)
37 Fix Guardrail Auto-correct output instead of retrying — deterministic fixes

Termination Conditions

# Example What it demonstrates
19 Composable Termination Text mention, stop message, max messages, token budget, AND/OR composition

Code Execution

# Example What it demonstrates
24 Code Execution Local, Docker, Jupyter, and serverless code execution sandboxes

Memory

# Example What it demonstrates
25 Semantic Memory Long-term memory with similarity-based retrieval across sessions

Observability

# Example What it demonstrates
23 Token Tracking Per-run token usage and cost estimation
26 OpenTelemetry Tracing Industry-standard OTel spans for runs, tools, and handoffs

Execution Modes

# Example What it demonstrates
11 Streaming Default runtime.run() flow with a commented runtime.stream() alternative for real-time events
12 Long-Running Default runtime.run() flow with a commented runtime.start() alternative for async polling
72 Client Reconnect Default runtime.run() flow plus an advanced reconnect demo that resumes the same execution after client death
73 Worker Restart Recovery Default runtime.run() flow plus an advanced deploy/serve/start recovery demo

Multimodal

# Example What it demonstrates
30 Multimodal Agent Image/video analysis with vision models via the media parameter

Integrations

# Example What it demonstrates
28 GPT Assistant Agent Wrap OpenAI Assistants API (with code interpreter) as a Conductor agent

Troubleshooting

SSL Certificate Errors on macOS

Examples that make outbound HTTPS calls (e.g., 38_tech_trends.py) may fail with:

[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate

This happens because macOS Python framework installs do not link to system certificates. Fix by running (once per Python installation):

# Replace 3.12 with your Python version
/Applications/Python\ 3.12/Install\ Certificates.command

PEP 563 Compatibility

Tool functions defined in modules that use from __future__ import annotations work correctly. The SDK resolves string annotations to real types at registration time.

Feature Index

Quick lookup — find the right example for any SDK feature:

Feature Example(s)
Agent 01
@tool decorator 02, 02a, 02b
http_tool() 04
mcp_tool() 04, 04b
output_type (Pydantic) 03
strategy="handoff" 05, 13
strategy="sequential", >> 06, 15
strategy="parallel" 07
strategy="router" 08
strategy="round_robin" 15, 20, 29
strategy="random" 16
strategy="swarm" 17
strategy="manual" 18
allowed_transitions 20
introduction 29
approval_required=True 02, 09
handle.approve() / reject() 09
handle.respond() / send() 09b, 27
runtime.run() 01, 02, 11, 12, 72, 73
runtime.stream() 09c, 11
runtime.start() 12, 18, 27, 72, 73
@guardrail decorator 10, 35
Guardrail 10, 32
OnFail / Position enums 10
RegexGuardrail 21
LLMGuardrail 22
on_fail="fix" 37
on_fail="human" 32
fixed_output 37
@tool(guardrails=[...]) 31
TextMentionTermination 19
StopMessageTermination 19
MaxMessageTermination 19
TokenUsageTermination 19
& / | (composable) 19
LocalCodeExecutor 24
DockerCodeExecutor 24
JupyterCodeExecutor 24
ServerlessCodeExecutor 24
SemanticMemory 25
TokenUsage 23
OpenTelemetry tracing 26
GPTAssistantAgent 28
@worker_task as tools 14
@tool(external=True) 33
OnTextMention / OnToolResult 17
media (multimodal input) 30
PromptTemplate kitchen_sink
from __future__ import annotations 38