Examples
This section links to example projects and code snippets in the repository.
From a checkout with ProtoLink installed:
python examples/progressive_control.py
python examples/subagents.py
python examples/durable_execution.py
python examples/harness_controls.py
python examples/worker_execution.py
python examples/application_runtime.py
These scripts need no API keys or external services. The notebook and larger projects below include their own setup instructions for optional transports and model providers.
harness_controls.py demonstrates scoped context-artifact retrieval, a completion hook, transient model fallback and repeated local evaluations. durable_management.py creates a pending question and exports a reusable application factory for the CLI/dashboard; it writes a private managed-runs.sqlite file in the current working directory. Container execution is optional and uses separately installed Docker and a pre-pulled image, as described in the tool guide.
Start with the Basic Example notebook in examples/notebooks/basic_example. It starts a registry and two agents in one interactive walkthrough.
Jupyter Notebook (Recommended)
basic_example.ipynb is one detailed notebook built around short, direct ProtoLink calls. Run its cells in order to start the registry first, then WeatherAgent, then AlertAgent. Both are ordinary Agent instances with tools and an LLM; AlertAgent also enables conversation state. No handle_task override is needed.
The default configuration uses HTTP, a small weather tool and MockLLM. No API key, model server, or external weather service is required. Mock replies are configured text; the optional delegation example scripts a peer call but does not generate its final reply from the returned weather data.
What You'll Learn
- Core API: start the services, then use
call_tool(),invoke()andcall_agent(). - Discovery and state: use the agent's existing
clientto inspect peers and manage conversation state. - Tools and knowledge: add a calculator, attach a reusable
Tool, replace a weather implementation and attach knowledge. - HTTP APIs: open status and chat pages, send small JSON requests and consult the endpoint tables for health, tasks, chat and state controls.
- Replaceable components: follow short configuration recipes for LLMs, storage, run stores and HTTP, SSE JSON-RPC, WebSocket, runtime, or gRPC transports.
- Optional extensions: explore declarative mock delegation and reference snippets for streaming and cancellation.
- Lifecycle: stop the agents and registry before changing settings or rerunning the example.
Quick Start
From the repository root:
python -m pip install -e '.[http,notebook]'
python -m jupyter lab examples/notebooks/basic_example/basic_example.ipynb
Select the environment where ProtoLink is installed as the notebook kernel and run from top to bottom. Jupyter supports the notebook's top-level await.
The default registry listens on localhost:9010, WeatherAgent on localhost:8010 and AlertAgent on localhost:8020. Each has a /status page; the agents also expose /chat. The registry handles discovery and tasks go directly to the discovered agent.
Run All also runs cleanup at the end. Pause before the final cleanup cell to use the browser pages, then run cleanup when finished. To change the agents' transport, update TRANSPORT and their URLs together, rerun from the top after cleanup and skip the two HTTP-only request cells. The registry can stay on HTTP. See the example README for the endpoint reference and rerun guidance.
Progressive control walkthrough
progressive_control.py
shows bulk tools, task creation and output readers, controlled invocation, streaming/reporting,
transport aliases and explicit configuration, managed peer calls, local flows, callable/tool
steps, bounded acceptance and typed responses in one offline script.
Run python examples/progressive_control.py; add --mcp to include the bundled MCP server
with the optional protolink[mcp] extra. See the guide.
Example Scripts
The repository includes several standalone example scripts that demonstrate specific Protolink capabilities:
FastAPI application runtime
application_runtime.py
embeds two specialists and a coordinator with native registry discovery, local delegation, threaded tools,
private request context, per-request model factories, streamed events and tool evidence. It persists sessions
with SQLite and owns startup/readiness/shutdown through AgentGroup. Its offline ASGI demonstration uses no paid
provider or listening socket; the same factory can be served with Uvicorn. See the application guide.
Bounded worker execution
worker_execution.py
exposes a child's typed customer lookup, streams the child's activity, corrects a
PreparedTool preparation rejection and checkpoints unfinished work after two
model steps. The application inspects RunHandoff and explicitly resumes the
saved run without repeating the first write. It uses scripted responses and a
temporary SQLite file. See worker execution for budgets,
restart recovery, nested handoffs and event semantics.
Retrieval-augmented Agent
rag_agent.pybuilds a dependency-free in-memory knowledge base from twoDocumentvalues and attaches it to an Agent in automatic retrieval mode. ItsMockLLMselects the generatedsearch_handbooktool, reads the actual retrieved passage and returns a citation-bearing answer through the normal inference loop.
python examples/rag_agent.py
The example opens no port and needs no API key, model server, vector-database
service, or network access. Read the
Retrieval-Augmented Generation guide for persistent SQLite
knowledge, existing Chroma/Pinecone/Qdrant indexes, custom retrievers,
deterministic Agent.ask(), filters, index lifecycle and citation metadata.
Built-in web search
builtin_web_search.pyregistersweb_search()on a runtime Agent with an explicitnetwork.readpolicy. It defaults to English Wikipedia's documented keyless search API and accepts--engine,--freshnessand--max-resultsoptions. DuckDuckGo remains an explicit best-effort HTML option; select Brave after exportingBRAVE_SEARCH_API_KEY.
python examples/builtin_web_search.py "What is the capital of Greece?"
export BRAVE_SEARCH_API_KEY="your-key"
python examples/builtin_web_search.py "Python structured concurrency" --engine brave
python examples/builtin_web_search.py "Python structured concurrency" --engine duckduckgo
Run it without a query to inspect the CLI without making a network request.
A2A core and A2A 1.0 boundary
provider_free_mesh.pyruns a deterministic three-agent mesh with no provider, API key, registry, or network port. It demonstrates the A2A-derivedAgentCard,TaskandMessagemodel through the in-process runtime transport.a2a_tck_agent.pyis the provider-free HTTP fixture for the official A2A 1.0 TCK. It explicitly usesAgent(..., a2a=True); ordinary HTTP agents remain native-only by default. It is a compatibility test target, not a substitute for a published passing TCK result; follow the pinned instructions in A2A Core and 1.0 Compatibility.
Run regression diffing
run_regression_diff.pycreates provider-free baseline and candidate reports with different known runtime IDs, timestamps, sequence counters and bounded latency, proves that schema-aware normalization plus an explicit tolerance remove that noise and then detects a real final-output change withdiff_run_reports()andassert_run_matches(). Real candidate runs must be executed and recorded separately.
🧩 Runtime-control examples
These small, provider-free scripts demonstrate runtime controls for application integrators:
- Context budgets shows
ContextManifest,LLMModelProfileand enforcedRunBudgetbehavior before a model call. - History compaction shows local
recent,tokensand isolatedsummarycompaction plus remoteAgentClient.compact_history()over the request-spec endpoint. - State controls shows client/server state
describe,compactandresetrequests for one persistent conversation session. - Run reports shows
start_run,RunReport,RunReplay, golden-run assertions and redaction. - ProtoAgent policy mesh sketches the ProtoAgent Explorer/Coder/Architect structure abstractly. The prompts are intentionally tiny; the example focuses on tool capabilities,
CapabilityPolicy, diff-previewaction_builders and approval-gated workspace writes.
Production case study: ProtoAgent
ProtoAgent is a full local-first coding assistant built on ProtoLink. Read the case study to see how the runtime engine powers its Architect, Explorer and Coder agent deck, approval-gated diffs, completion validation, Context Loom evidence, cancellation, history control and run reports.
Flagship experiment: AI Courtroom
The AI Courtroom is a replayable multi-agent experiment built around a fictional autonomous-vehicle liability case. It compares one generalist, five independent specialists, a foreperson-star topology and a direct agent-selected mesh while keeping public evidence and observable decision contracts controlled. Read the example page to see how jurors author direct ProtoLink messages, how one communication topology produces a different deterministic verdict and how every run automatically generates standalone interactive HTML reports for replay and comparison.
For a model-versus-model experiment, see the
ai_courtroom_benchmark
example. It runs two advocates on opposite sides of a portable JSON case,
swaps their roles, keeps the judge and independent jury fixed and generates a
standalone replay report with opinion trajectories, citations, vote flips and
fairness checks.
🛠️ devtools_dashboard.py
Purpose: Local devtools, run replay, registry snapshot, dashboard and Studio
- Uses
create_llm("mock"), so it runs without provider credentials - Creates several agents and registers their cards in an in-process registry
- Runs a small task loop and records each streamed run with
RunRecorder - Saves durable task snapshots and
RunReportrecords toSQLiteRunStore - Renders static dashboard HTML using
DevtoolsHtmlRenderer, including the provider-free Studio starter blueprint and catalog - Prints follow-up commands for
protolink run list,protolink run replayandprotolink dashboard - Supports
--serve-liveto start provider-free HTTP agents, an HTTP registry and the dashboard so ping/chat and Studio Generate/Run/Stop actions are available - Static Studio supports visual editing plus JSON import/export; the served dashboard adds Python view/copy/download, runtime status and local process controls
- The dashboard also contains registry health, selected-agent detail, run replay, telemetry and chat panels
📝 basic_agent.py
Purpose: Minimal agent setup focused on core concepts
- Demonstrates simplified agent creation using dictionary-based
AgentCard - Shows how to add native tools using the
@agent.tooldecorator with automatic schema inference - Demonstrates direct agent invocation using convenience methods:
invoke()andsync.invoke() - Includes optional LLM integration for reasoning and inference
- Uses
runtimetransport for in-memory execution (no network dependencies)
🧠 agent_memory.py
Purpose: Conversation memory and persistence across tasks
- Demonstrates the difference between stateless agents (
state=None) and persistent agents (state=["conversation"]) - Shows how
sync.invoke()handles session history automatically using a defaultsession_id - Demonstrates history persistence across sequential calls to the same agent instance
- Useful for building conversational bots and multi-turn interaction assistants
🌐 http_agents.py
Purpose: HTTP transport and agent-to-agent communication
- Demonstrates two agents communicating over HTTP
- Tests client functions:
get_agent_card,send_message_to,call_agent - Shows how to set up multiple agents on different ports
- Includes comprehensive error handling and cleanup
🔒 authentication.py
Purpose: Authentication, credentials propagation and security verification
- Demonstrates API key, Basic and signed Bearer JWT authentication providers
- Covers server-side route authentication (returning
401 Unauthorizedfor failed requests) - Covers client-side lazy authentication (automatic signature/credential injection on outgoing requests)
- Verifies both HTTP (Starlette and FastAPI backends) and WebSocket handshake verification
- Demonstrates success and failure scenarios for both transports
🤖 LLM notebooks
Purpose: LLM backend integration, inference loops and delegation
- Demonstrates direct API LLM usage
- Shows
infer()with local tool calling - Shows
agent_calldelegation between agents - Complements the LLM Examples guide
📋 registry.py
Purpose: Registry discovery and autonomous agent behaviour
- Creates autonomous agents that discover peers and send tasks
- Demonstrates registry-based agent discovery
- Shows background task management and cleanup
- Multi-agent orchestration with automatic peer communication
⚡ runtime_agents.py
Purpose: In-memory agent communication interoperability
- Uses the
transport="runtime"alias andruntime://URLs without opening ports - Uses
AgentGroupfor readiness and cleanup without startup sleeps - Sends a task to a peer and reads its agent card through the public client API
- Preserves the serialized task boundary used by network transports
📡 streaming_agent.py
Purpose: Real-time streaming with progress updates
- Demonstrates streaming task handlers with progress events
- Shows artifact production and streaming
- Context management for multi-turn conversations
- Event-driven architecture with task status updates
🔌 websocket_basic_example.py
Purpose: WebSocket transport with streaming support
- Mirrors the basic notebook example but uses WebSocket transport
- Demonstrates both request/response and streaming task patterns
- Shows registry discovery over WebSockets
- Real-time progress updates via WebSocket events
grpc_agent.py
Purpose: gRPC transport request/response and streaming smoke test
- Starts a provider-free mock-LLM agent on a local
grpc://port - Fetches the agent card and sends a normal task through
AgentClient - Consumes task events through the gRPC streaming API
- Demonstrates the
transport="grpc"factory path without generated protobuf files
tls_agent.py
Purpose: Native TLS and mutual TLS through the high-level agent API
- Starts a provider-free mock agent on an
https://endpoint usingTLSConfig - Configures verified client trust without disabling hostname or certificate checks
- Supports
--require-client-certto demonstrate mutual TLS - Keeps certificate transport security separate from bearer/API-key authentication
🔄 structured_flows/
Purpose: Advanced flow orchestration patterns
- Demonstrates Graph flow for complex state machine topologies with cyclic loops
- Shows conditional branching and multi-step review workflows
- Examples include sequential processing, parallel execution and dynamic routing
- Illustrates integration of multiple agents in structured flow patterns
Built-in assistants and tools
Run python examples/generic_tools.py to exercise filesystem reads/edits/recovery, storage CRUD,
configured HTTP requests, document extraction and database queries on one ordinary Agent.
The example uses temporary files, in-memory storage, a mocked HTTP transport, CSV and real SQLite.
See Built-in Tools for the APIs and optional document formats.
Run python examples/builtin_assistants.py to verify shell, Git, user questions, calendar and email
through Assistant and CodeAssistant. The example uses a temporary repository, a mock model and
in-memory service adapters, so it needs no accounts or API keys and sends no real messages.
See Built-in Agents for the preset APIs.
Run python examples/builtin_agents.py for ResearchAgent, KnowledgeAgent, DatabaseAgent,
ExplorerAgent and EchoAgent. It uses fixture web providers, local knowledge, scoped files and a
temporary SQLite database; its scripted models build answers from the actual tool results.
Run python examples/service_backends.py to exercise every concrete backend: GoogleCalendar,
Gmail, OutlookCalendar, OutlookEmail and IMAPEmail. Install protolink[integrations] first.
The example replaces HTTP/IMAP/SMTP transports with offline fixtures while using real Assistant
tools, approvals, serialization and MIME handling. See the service backend reference.
Subagents and durable execution examples
- Local specialists: an owned child using the existing
agent_callaction, with shared limits and streamed evidence. - Durable execution: approval and user input across three separate application invocations, with an offline model and a persisted tool result.
Both examples run without API keys or external services. Read the subagent and durable execution guides for application controls and recovery scope.