CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
examples: port all recipe docs into runnable example scripts
xf gongbda19948a9e2
diff --git a/examples/README.md b/examples/README.mdindex a40ee02..57e1b74 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,7 +1,6 @@# Examples-Runnable scripts demonstrating CubePi features. They use `FauxProvider`, so-they need no API key — only the relevant service where noted.+Runnable scripts demonstrating CubePi features.Run any example with `uv`:@@ -9,15 +8,120 @@ Run any example with `uv`:uv run python examples/<name>.py```-## Checkpointing+## Provider setup++Recipe examples use a real LLM. Set one of the following before running:++```bash+# Anthropic (or Anthropic-compatible endpoint):+export ANTHROPIC_API_KEY=sk-ant-...+export ANTHROPIC_BASE_URL=https://... # optional, for compatible endpoints+export MODEL=claude-sonnet-4-6 # optional, this is the default++# OpenAI (or OpenAI-compatible endpoint):+export OPENAI_API_KEY=sk-...+export OPENAI_BASE_URL=https://... # optional, for compatible endpoints+export MODEL=gpt-4o # optional, this is the default+```++The shared `_provider.py` module reads these env vars and exposes `provider`+and `MODEL_ID` for each example to import. `ANTHROPIC_API_KEY` takes priority+when both are set.++## Recipes++| Example | What it shows | Extra deps |+|---|---|---|+| [`weather_agent.py`](weather_agent.py) | Tool calling, streaming output, Ctrl-C cancellation | `httpx` |+| [`persistent_chat.py`](persistent_chat.py) | SQLite-backed chat that survives restarts | `cubepi[sqlite]` |+| [`multi_provider_failover.py`](multi_provider_failover.py) | Automatic failover between providers on error | — |+| [`ask_user_form.py`](ask_user_form.py) | HITL multi-question form via `ask_user_tool` | — |+| [`sandbox_confirm.py`](sandbox_confirm.py) | `ApprovalPolicyMiddleware` — auto-allow, deny, or confirm tool calls | — |+| [`resumable_tasks.py`](resumable_tasks.py) | Crash-resilient tasks with idempotent tools and checkpointing | `cubepi[sqlite]` |+| [`postgres_fastapi.py`](postgres_fastapi.py) | Production HTTP service: FastAPI + SSE streaming + Postgres | `cubepi[postgres]` `fastapi` `uvicorn[standard]` `sse-starlette` |++### weather_agent.py++```bash+pip install httpx+uv run python examples/weather_agent.py+```++### persistent_chat.py++```bash+uv run python examples/persistent_chat.py alice+# Chat, then Ctrl-D. Re-run same command — history is restored.++uv run python examples/persistent_chat.py bob+# Different thread, clean slate.+```++Requires: `cubepi[sqlite]`++### multi_provider_failover.py++```bash+uv run python examples/multi_provider_failover.py+```++Runs with a bad primary key to demonstrate failover, then succeeds via the+real secondary key.++### ask_user_form.py++```bash+uv run python examples/ask_user_form.py+```++The host loop answers the form programmatically (simulating a UI). In a real+app you'd render the questions to a frontend.++### sandbox_confirm.py++```bash+uv run python examples/sandbox_confirm.py+```++Shows auto-allow (`echo`, `ls`, `cat`), hard-deny (`rm -rf /`), and+human-confirm (any other command, auto-approved in the simulated host).++### resumable_tasks.py++```bash+# Start a job:+uv run python examples/resumable_tasks.py job-1 start++# Kill mid-flight, then resume:+uv run python examples/resumable_tasks.py job-1+```++Items already processed are skipped on resume (idempotent tool backed by+a file-based job store in `/tmp/cubepi-jobs/`).++Requires: `cubepi[sqlite]`++### postgres_fastapi.py++```bash+pip install "cubepi[postgres]" fastapi "uvicorn[standard]" sse-starlette+export DATABASE_URL=postgresql://user:pass@localhost/cubepi+uvicorn examples.postgres_fastapi:app --reload --port 8000++curl -N -X POST http://localhost:8000/chat/conv1/messages \+ -H "content-type: application/json" \+ -d '{"text":"hi"}'+```++## Checkpointing (service integration)| Example | What it shows | Requires ||---|---|---|| [`checkpointing_postgres.py`](checkpointing_postgres.py) | Persist an agent conversation in Postgres and resume it after a simulated restart | A reachable Postgres || [`checkpointing_mysql.py`](checkpointing_mysql.py) | Same, on MySQL 8.0.13+ | A reachable MySQL |-Both create a **throwaway database** and drop it on exit, so they are safe to-re-run against a dev server. Point them at your server with an env var:+Both use `FauxProvider` (no API key needed) and create a **throwaway database**+that is dropped on exit — safe to re-run against a dev server.```bashCUBEPI_PG_DSN=postgresql://user:pass@host:5432/dbname \@@ -29,9 +133,7 @@ CUBEPI_MYSQL_DSN=mysql://user:pass@host:3306/dbname \Each script bootstraps the CubePi schema inline so it runs standalone, but inproduction the schema is owned by your host application's Alembic migration.-The inline DDL mirrors exactly what that migration produces and uses the same-`alembic_helpers`. See the host-integration runbooks for the migration recipe-and version-upgrade flow:+See the host-integration runbooks for the migration recipe and version-upgrade flow:- [`cubepi/checkpointer/postgres/README.md`](../cubepi/checkpointer/postgres/README.md)- [`cubepi/checkpointer/mysql/README.md`](../cubepi/checkpointer/mysql/README.md)diff --git a/examples/_provider.py b/examples/_provider.pynew file mode 100644index 0000000..97e843d--- /dev/null+++ b/examples/_provider.py@@ -0,0 +1,41 @@+"""Shared provider setup for cubepi examples.++Set one of the following before running any example:++ # Anthropic (or Anthropic-compatible endpoint):+ export ANTHROPIC_API_KEY=sk-ant-...+ export ANTHROPIC_BASE_URL=https://... # optional, for compatible endpoints+ export MODEL=claude-sonnet-4-6 # optional, this is the default++ # OpenAI (or OpenAI-compatible endpoint):+ export OPENAI_API_KEY=sk-...+ export OPENAI_BASE_URL=https://... # optional, for compatible endpoints+ export MODEL=gpt-4o # optional, this is the default++ANTHROPIC_API_KEY takes priority when both are set.+"""++import os+import sys++_anthropic_key = os.environ.get("ANTHROPIC_API_KEY")+_openai_key = os.environ.get("OPENAI_API_KEY")++if _anthropic_key:+ from cubepi.providers.anthropic import AnthropicProvider++ _base_url = os.environ.get("ANTHROPIC_BASE_URL") or None+ provider = AnthropicProvider(api_key=_anthropic_key, base_url=_base_url)+ MODEL_ID = os.environ.get("MODEL", "claude-sonnet-4-6")+elif _openai_key:+ from cubepi.providers.openai import OpenAIProvider++ _base_url = os.environ.get("OPENAI_BASE_URL") or None+ provider = OpenAIProvider(api_key=_openai_key, base_url=_base_url)+ MODEL_ID = os.environ.get("MODEL", "gpt-4o")+else:+ print(+ "Error: set ANTHROPIC_API_KEY or OPENAI_API_KEY before running examples.",+ file=sys.stderr,+ )+ sys.exit(1)diff --git a/examples/ask_user_form.py b/examples/ask_user_form.pynew file mode 100644index 0000000..fb21af2--- /dev/null+++ b/examples/ask_user_form.py@@ -0,0 +1,85 @@+"""Ask-user form — recipe example.++Demonstrates the ask_user HITL tool: the agent pauses and asks the user a+structured multi-question form before proceeding.++ uv run python examples/ask_user_form.py++The host loop answers the form programmatically (simulating a UI). In a real+app you'd render each question to a frontend and collect the response.++Uses the Ark coding endpoint by default — override via CUBEPI_* env vars (see _provider.py).+"""++import asyncio++from cubepi import Agent+from cubepi.hitl import InMemoryChannel, ask_user_tool++from _provider import MODEL_ID, provider+++async def host(channel: InMemoryChannel) -> None:+ """Simulate a UI that answers the agent's form questions."""+ async for req in channel.subscribe():+ if req.payload.kind == "ask":+ print("\n[Form received from agent]")+ answers: dict[str, object] = {}+ for q in req.payload.questions:+ if q.options is None:+ # Free-text: just echo the key as a placeholder answer.+ answers[q.key] = f"demo-{q.key}"+ print(f" {q.prompt!r} → {answers[q.key]!r}")+ elif q.multi_select:+ # Multi-select: pick first two options.+ picks = [o.value for o in q.options[:2]]+ answers[q.key] = picks+ print(f" {q.prompt!r} → {picks}")+ else:+ # Single-select: pick first option.+ answers[q.key] = q.options[0].value+ print(f" {q.prompt!r} → {q.options[0].label!r}")+ print()+ await channel.answer(req.question_id, answers)+++async def main() -> None:+ channel = InMemoryChannel()++ agent = Agent(+ model=provider.model(MODEL_ID),+ system_prompt=(+ "When you need structured input from the user, use the ask_user tool. "+ "Ask for project type, framework, desired features, and project name "+ "before scaffolding anything."+ ),+ tools=[ask_user_tool(channel)],+ channel=channel,+ )++ collected: list[str] = []++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ collected.append(event.stream_event.delta)+ elif event.type == "tool_execution_start":+ print(f"[tool: {event.tool_name}]")+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ host_task = asyncio.create_task(host(channel))+ try:+ await agent.prompt("Scaffold a new web project for me.")+ print("Agent response:", "".join(collected))+ finally:+ host_task.cancel()+ try:+ await host_task+ except asyncio.CancelledError:+ pass+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/multi_provider_failover.py b/examples/multi_provider_failover.pynew file mode 100644index 0000000..7b65b59--- /dev/null+++ b/examples/multi_provider_failover.py@@ -0,0 +1,165 @@+"""Multi-provider failover — recipe example.++Demonstrates a FailoverProvider wrapper that peeks at the first stream event+from each inner provider and falls over to the next on error.++ uv run python examples/multi_provider_failover.py++The example constructs a primary provider with a bad key to force a failover to+the real provider, proving the mechanism works end-to-end.++Set ANTHROPIC_API_KEY or OPENAI_API_KEY (and optionally MODEL) before running.+See _provider.py for details.+"""++import asyncio+import logging+import os+import time++from cubepi import Agent+from cubepi.providers.openai import OpenAIProvider+from cubepi.providers.anthropic import AnthropicProvider+from cubepi.providers.base import (+ AssistantMessage,+ BaseProvider,+ BoundModel,+ Message,+ MessageStream,+ Model,+ StreamEvent,+ StreamOptions,+ ToolDefinition,+ Usage,+)++from _provider import MODEL_ID, provider++log = logging.getLogger(__name__)+++class FailoverProvider(BaseProvider):+ """Try providers in order; fall over on construction or first-event errors.++ Built-in providers swallow API/network errors and surface them as+ StreamEvent(type="error") on the returned stream. We peek at the first+ event from each inner stream and only commit once we see a non-error event.++ Limitation: errors that arrive *after* the first event are forwarded as-is.+ """++ def __init__(self, primary: BoundModel, *fallbacks: BoundModel) -> None:+ super().__init__(provider_id=primary.spec.provider_id)+ self._chain: list[BoundModel] = [primary, *fallbacks]++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream:+ last_error: str | None = None++ for bound_model in self._chain:+ inner_provider = bound_model.provider+ mapped_model = bound_model.spec+ try:+ inner = await inner_provider.stream(+ mapped_model,+ messages,+ system_prompt=system_prompt,+ tools=tools,+ options=options,+ )+ except Exception as e:+ log.warning("provider %s failed at construction: %s", mapped_model.provider_id, e)+ last_error = repr(e)+ continue++ iterator = inner.__aiter__()+ try:+ first = await iterator.__anext__()+ except StopAsyncIteration:+ last_error = "stream ended before producing any events"+ continue++ if first.type == "error":+ log.warning(+ "provider %s errored on first event: %s",+ mapped_model.provider_id,+ first.error_message,+ )+ last_error = first.error_message or "stream error"+ continue++ outer = MessageStream()++ async def _forward(first_event=first, src=iterator, src_stream=inner):+ try:+ outer.push(first_event)+ async for ev in src:+ outer.push(ev)+ final = await src_stream.result()+ outer.set_result(final)+ except Exception as exc:+ fallback_msg = AssistantMessage(+ content=[],+ stop_reason="error",+ error_message=str(exc),+ usage=Usage(),+ timestamp=time.time(),+ )+ outer.push(StreamEvent(type="error", error_message=str(exc)))+ outer.set_result(fallback_msg)++ outer.attach_task(asyncio.create_task(_forward()))+ return outer++ raise RuntimeError(f"all providers exhausted; last error: {last_error!r}")+++def _bad_key_provider() -> tuple[BaseProvider, str]:+ """Build a provider identical to the real one but with an invalid key."""+ if os.environ.get("ANTHROPIC_API_KEY"):+ base_url = os.environ.get("ANTHROPIC_BASE_URL") or None+ return AnthropicProvider(api_key="bad-key", base_url=base_url), MODEL_ID+ else:+ base_url = os.environ.get("OPENAI_BASE_URL") or None+ return OpenAIProvider(api_key="bad-key", base_url=base_url), MODEL_ID+++async def main() -> None:+ logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")++ bad_provider, model_id = _bad_key_provider()++ # Primary: bad key → errors on first event → triggers failover.+ # Fallback: real provider from _provider.py.+ failover = FailoverProvider(+ bad_provider.model(model_id),+ provider.model(MODEL_ID),+ )++ agent = Agent(+ model=failover.model(MODEL_ID),+ system_prompt="You answer concisely.",+ )++ collected: list[str] = []++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ collected.append(event.stream_event.delta)++ agent.subscribe(on_event)++ print("Sending request (primary has bad key — expecting failover to secondary)...")+ await agent.prompt("Capital of Mongolia?")+ print("Answer:", "".join(collected))+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/persistent_chat.py b/examples/persistent_chat.pynew file mode 100644index 0000000..b3fed6c--- /dev/null+++ b/examples/persistent_chat.py@@ -0,0 +1,61 @@+"""Persistent chat — recipe example.++A REPL chat that survives restarts. Conversation history is kept in a SQLite+file; pass a thread_id as the first argument to identify the user/session.++ uv run python examples/persistent_chat.py alice+ # Have a chat, then Ctrl-D.++ uv run python examples/persistent_chat.py alice+ # History is restored. Ask "what did I just tell you?" — the model remembers.++ uv run python examples/persistent_chat.py bob+ # Different thread, clean slate.++Requires: cubepi[sqlite]+Uses the Ark coding endpoint by default — override via CUBEPI_* env vars (see _provider.py).+"""++import asyncio+import sys++from cubepi import Agent+from cubepi.checkpointer import SQLiteCheckpointer++from _provider import MODEL_ID, provider+++async def main(thread_id: str) -> None:+ async with SQLiteCheckpointer("chat.db") as cp:+ agent = Agent(+ model=provider.model(MODEL_ID),+ system_prompt="You are a concise, friendly assistant.",+ checkpointer=cp,+ thread_id=thread_id,+ )++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ print(f"Chatting on thread {thread_id!r}. Ctrl-D to quit.\n")+ loop = asyncio.get_event_loop()+ while True:+ try:+ user_input = await loop.run_in_executor(None, input, "you> ")+ except EOFError:+ print()+ return+ if not user_input.strip():+ continue+ print("ai > ", end="", flush=True)+ await agent.prompt(user_input)+++if __name__ == "__main__":+ thread_id = sys.argv[1] if len(sys.argv) > 1 else "default"+ asyncio.run(main(thread_id))diff --git a/examples/postgres_fastapi.py b/examples/postgres_fastapi.pynew file mode 100644index 0000000..b44eb2c--- /dev/null+++ b/examples/postgres_fastapi.py@@ -0,0 +1,112 @@+"""Postgres + FastAPI service — recipe example.++A production-shaped HTTP service: FastAPI for routing, server-sent events for+streaming, a shared PostgresCheckpointer for persistence.++ pip install "cubepi[postgres]" fastapi "uvicorn[standard]" sse-starlette+ export DATABASE_URL=postgresql://user:pass@localhost/cubepi+ uvicorn examples.postgres_fastapi:app --reload --port 8000++ # Then test:+ curl -N -X POST http://localhost:8000/chat/conv1/messages \\+ -H "content-type: application/json" \\+ -d '{"text":"hi"}'++Requires: cubepi[postgres], fastapi, uvicorn[standard], sse-starlette+Uses the Ark coding endpoint by default — override via CUBEPI_* env vars (see _provider.py).+"""++import asyncio+import os+from contextlib import asynccontextmanager+from typing import AsyncIterator++from fastapi import FastAPI, Depends+from pydantic import BaseModel+from sse_starlette.sse import EventSourceResponse++from cubepi import Agent+from cubepi.checkpointer import PostgresCheckpointer++from _provider import MODEL_ID, provider++_checkpointer: PostgresCheckpointer | None = None+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _checkpointer+ _checkpointer = await PostgresCheckpointer(+ os.environ["DATABASE_URL"],+ min_pool_size=2,+ max_pool_size=20,+ ).__aenter__()+ yield+ await _checkpointer.__aexit__(None, None, None)+++app = FastAPI(lifespan=lifespan)+++async def current_user_id() -> str:+ # Replace with real auth (JWT decode, session lookup, etc.)+ return "demo-user"+++class PromptBody(BaseModel):+ text: str++[email protected]("/chat/{conversation_id}/messages")+async def post_message(+ conversation_id: str,+ body: PromptBody,+ user_id: str = Depends(current_user_id),+):+ thread_id = f"{user_id}:{conversation_id}"++ async def event_generator() -> AsyncIterator[dict]:+ agent = Agent(+ model=provider.model(MODEL_ID),+ system_prompt="You are a helpful assistant.",+ checkpointer=_checkpointer,+ thread_id=thread_id,+ )++ queue: asyncio.Queue = asyncio.Queue()+ agent.subscribe(lambda e, s=None: queue.put_nowait(e))++ async def run():+ try:+ await agent.prompt(body.text)+ finally:+ queue.put_nowait(None)++ task = asyncio.create_task(run())+ try:+ while True:+ event = await queue.get()+ if event is None:+ break+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ yield {"event": "delta", "data": event.stream_event.delta}+ elif event.type == "tool_execution_start":+ yield {"event": "tool_start", "data": event.tool_name}+ elif event.type == "agent_end":+ yield {"event": "done", "data": ""}+ finally:+ await task++ return EventSourceResponse(event_generator())++[email protected]("/chat/{conversation_id}/history")+async def get_history(+ conversation_id: str,+ user_id: str = Depends(current_user_id),+):+ thread_id = f"{user_id}:{conversation_id}"+ data = await _checkpointer.load(thread_id)+ if data is None:+ return {"messages": []}+ return {"messages": [m.model_dump(mode="json") for m in data.messages]}diff --git a/examples/resumable_tasks.py b/examples/resumable_tasks.pynew file mode 100644index 0000000..c5b3bc2--- /dev/null+++ b/examples/resumable_tasks.py@@ -0,0 +1,102 @@+"""Resumable tasks — recipe example.++Demonstrates crash-resilient long tasks with checkpointing. Tools are+idempotent (backed by a file-based job store) so re-running after a crash+skips already-completed work.++ # Start a job:+ uv run python examples/resumable_tasks.py job-1 start++ # Kill mid-flight with Ctrl-C, then resume:+ uv run python examples/resumable_tasks.py job-1++Requires: cubepi[sqlite]+Uses the Ark coding endpoint by default — override via CUBEPI_* env vars (see _provider.py).+"""++import asyncio+import json+import os+import sys+from pathlib import Path++from cubepi import Agent, AgentToolResult, TextContent, tool+from cubepi.checkpointer import SQLiteCheckpointer++from _provider import MODEL_ID, provider++JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))+JOB_DIR.mkdir(parents=True, exist_ok=True)+++@tool(execution_mode="sequential")+async def process_item(item_id: str, *, signal=None) -> AgentToolResult:+ "Process a work item. Idempotent — safe to retry after a crash."+ job_file = JOB_DIR / f"item-{item_id}.json"++ if job_file.exists():+ state = json.loads(job_file.read_text())+ return AgentToolResult(+ content=[TextContent(text=f"Item {item_id} already done: {state['result']}.")],+ )++ # Simulate slow work (1 second per item).+ print(f" [processing item {item_id}...]")+ await asyncio.sleep(1)++ result = f"processed-{item_id}"+ job_file.write_text(json.dumps({"item_id": item_id, "result": result}))++ return AgentToolResult(+ content=[TextContent(text=f"Item {item_id} done: {result}.")],+ )+++async def main(thread_id: str, start: bool) -> None:+ async with SQLiteCheckpointer("resumable_jobs.db") as cp:+ agent = Agent(+ model=provider.model(MODEL_ID),+ system_prompt=(+ "You orchestrate batch processing jobs. "+ "Process all items one by one using the process_item tool, "+ "then summarize the results."+ ),+ tools=[process_item],+ checkpointer=cp,+ thread_id=thread_id,+ )++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "tool_execution_start":+ print(f"\n[tool: {event.tool_name}({event.args})]")+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ if start:+ await agent.prompt("Process items A, B, C, and D.")+ else:+ # Resume: hydrate state from checkpointer then resume.+ data = await cp.load(thread_id)+ if data is None:+ print(f"No saved state for thread {thread_id!r}. Use 'start' to begin.")+ return+ agent.state.messages = list(data.messages)+ last = agent.state.messages[-1] if agent.state.messages else None+ last_type = type(last).__name__ if last else "none"+ print(f"Resuming thread {thread_id!r} ({len(agent.state.messages)} messages, last={last_type})")+ if last_type == "AssistantMessage":+ # Run already completed naturally — nothing to resume.+ # In a real workflow you'd ask the user for the next prompt.+ print("Run already completed. Nothing to resume (last turn was a model reply).")+ return+ await agent.resume()+++if __name__ == "__main__":+ thread_id = sys.argv[1] if len(sys.argv) > 1 else "job-1"+ start = len(sys.argv) > 2 and sys.argv[2] == "start"+ asyncio.run(main(thread_id, start))diff --git a/examples/sandbox_confirm.py b/examples/sandbox_confirm.pynew file mode 100644index 0000000..ab1af84--- /dev/null+++ b/examples/sandbox_confirm.py@@ -0,0 +1,106 @@+"""Sandbox confirm — recipe example.++Demonstrates ApprovalPolicyMiddleware: a policy function classifies each+tool call as auto-allow, hard-deny, or human-confirm. The host loop handles+human-confirm requests by auto-approving them (simulating a UI).++ uv run python examples/sandbox_confirm.py++Uses the Ark coding endpoint by default — override via CUBEPI_* env vars (see _provider.py).+"""++import asyncio+from pydantic import BaseModel++from cubepi import Agent, AgentToolResult, TextContent, tool+from cubepi.hitl import (+ Approve,+ AskUser,+ Deny,+ ApprovalPolicyMiddleware,+ InMemoryChannel,+ ApproveAnswer,+)++from _provider import MODEL_ID, provider+++# --- Simulated bash tool ------------------------------------------------++class BashInput(BaseModel):+ cmd: str+++@tool+async def bash(cmd: str) -> AgentToolResult:+ "Run a shell command (simulated — not a real shell)."+ print(f" [bash executing: {cmd!r}]")+ return AgentToolResult(content=[TextContent(text=f"$ {cmd}\nok")])+++# --- Policy function ----------------------------------------------------++def sandbox_policy(ctx):+ cmd: str = ctx.args.cmd+ if cmd.startswith(("ls", "cat", "head", "grep", "find", "echo")):+ print(f" [policy: auto-allow {cmd!r}]")+ return Approve()+ if "rm -rf /" in cmd or cmd.startswith("dd "):+ print(f" [policy: hard-deny {cmd!r}]")+ return Deny(reason="destructive I/O blocked by policy")+ print(f" [policy: ask-user for {cmd!r}]")+ return AskUser(timeout_seconds=60, details={"cmd": cmd})+++# --- Host loop ----------------------------------------------------------++async def host(channel: InMemoryChannel) -> None:+ async for req in channel.subscribe():+ if req.payload.kind == "approve":+ print(f" [host: auto-approving tool={req.payload.tool_name}]")+ await channel.answer(+ req.question_id,+ ApproveAnswer(decision="approve"),+ )+++# --- Main ---------------------------------------------------------------++async def main() -> None:+ channel = InMemoryChannel()++ agent = Agent(+ model=provider.model(MODEL_ID),+ system_prompt=(+ "You have access to a bash tool. "+ "Run: echo hello, then ls /tmp, then rm -rf /important (to show deny), "+ "then cat /etc/hostname. Each as a separate tool call."+ ),+ tools=[bash],+ middleware=[ApprovalPolicyMiddleware(channel, policy=sandbox_policy)],+ channel=channel,+ )++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "tool_execution_start":+ print(f"\n[tool: {event.tool_name}]")+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ host_task = asyncio.create_task(host(channel))+ try:+ await agent.prompt("Run all four commands and summarize the results.")+ finally:+ host_task.cancel()+ try:+ await host_task+ except asyncio.CancelledError:+ pass+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/weather_agent.py b/examples/weather_agent.pynew file mode 100644index 0000000..fd15597--- /dev/null+++ b/examples/weather_agent.py@@ -0,0 +1,90 @@+"""Weather agent — recipe example.++A complete, runnable agent that calls a real weather API as a tool.+Demonstrates HTTP-calling tools, error handling, streaming UI, and cancellation.++ uv run python examples/weather_agent.py++Requires: httpx (pip install httpx)+Uses the Ark coding endpoint by default — override via CUBEPI_* env vars (see _provider.py).+"""++import asyncio+from typing import Annotated++import httpx+from pydantic import Field++from cubepi import Agent, AgentToolResult, TextContent, tool++from _provider import MODEL_ID, provider+++@tool+async def get_weather(+ city: Annotated[str, Field(description="The city to look up weather for")],+ units: Annotated[str, Field(pattern="^(metric|imperial)$")] = "metric",+) -> str | AgentToolResult:+ "Get current weather for a city. Returns a short text summary."+ async with httpx.AsyncClient(timeout=10) as client:+ try:+ geo = await client.get(+ "https://geocoding-api.open-meteo.com/v1/search",+ params={"name": city, "count": 1, "language": "en"},+ )+ geo.raise_for_status()+ results = geo.json().get("results")+ if not results:+ return AgentToolResult(+ content=[TextContent(text=f"Couldn't find a city named {city!r}.")],+ is_error=True,+ )+ lat, lon = results[0]["latitude"], results[0]["longitude"]++ wx = await client.get(+ "https://api.open-meteo.com/v1/forecast",+ params={+ "latitude": lat,+ "longitude": lon,+ "current_weather": True,+ "temperature_unit": "celsius" if units == "metric" else "fahrenheit",+ },+ )+ wx.raise_for_status()+ cw = wx.json()["current_weather"]+ unit = "°C" if units == "metric" else "°F"+ return f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {city}."+ except httpx.HTTPError as e:+ return AgentToolResult(+ content=[TextContent(text=f"Weather API error: {e}")],+ is_error=True,+ )+++async def main() -> None:+ agent = Agent(+ model=provider.model(MODEL_ID),+ system_prompt="You are a concise weather assistant. Always use the tool; don't guess.",+ tools=[get_weather],+ )++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "tool_execution_start":+ print(f"\n[calling {event.tool_name}({event.args})]")+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ task = asyncio.create_task(agent.prompt("Weather in Tokyo and São Paulo, please."))+ try:+ await task+ except KeyboardInterrupt:+ agent.abort()+ await agent.wait_for_idle()+++if __name__ == "__main__":+ asyncio.run(main())