Examples
A curated index of runnable @statelyai/agent examples, grouped by what they demonstrate.
Alpha:
@statelyai/agent2.0 is in alpha. APIs can change between releases; pin an exact version. Feedback: github.com/statelyai/agent.
Running the examples
Examples live under examples/, one flat directory per example with an index.ts entrypoint. Clone the repo, install dependencies, and run any one with tsx:
OPENAI_API_KEY=... npx tsx examples/<name>/index.tsEvery example is dual-mode: run it directly with a real model as above, while its tests use injected mocks. Most expect a provider key in the environment (e.g. OPENAI_API_KEY); each file notes what it needs at the top.
Start here
These cover the core ideas: text requests, decisions, messages, and JSON authoring.
- twenty-questions: a decision loop where the model picks one legal event (ASK or GUESS) each turn; guard-enforced legality, machine-held score, play-again reset, machine-owned user prompts.
- joke: a minimal streaming text workflow.
- email-drafter: reusable text logic, parts-based messages, schema-typed state and transition meta.
- game-agent:
allowedEventsnarrowed as a function of input, gating moves by HP. - go-fish: hidden-information play with a checking-win → agent → human loop; the model chooses requests, the machine enforces the rules.
- json-agent: a full workflow (decision, text request, idle human step) authored as a real
.jsonfile, run withrunAgent. See Machines as data. - described-workflow: a plain XState machine with zero invokes (prompts live in state
descriptions andmeta), run viarunAgent'sgetRequestsoption, message log aggregated ontosnapshot.messages.
Human in the loop and persistence
These show the idle-first pause for human input and resuming a run by snapshot. See Human in the loop.
- human-in-the-loop: a machine that settles idle to wait for a human, then resumes with the human's event, persisting a snapshot between iterations and resuming in a later process.
- long-running-onboarding: a multi-day onboarding coordinator with durable typed state, two idle dormancy gates, delegated IT provisioning, JSON snapshot resume.
- file-snapshot-store: a file-backed snapshot store for durable threads across processes.
Host adapters and the step path
These implement the executor contract against different SDKs and runtimes, and use the lower-level step path for durable checkpointing. See Hosts and Steps.
- ai-sdk-host: running with Vercel AI SDK host actors.
- ai-sdk-game-host: a Vercel AI SDK step runner that checkpoints every model call.
- openai-sdk-host: the same executor contract against the raw
openaipackage (Chat Completions), no AI SDK in between. - anthropic-sdk-host: the same contract against the raw
@anthropic-ai/sdkpackage (Messages API). - cloudflare-workers-ai-host: a step runner against Cloudflare Workers AI's binding.
- cloudflare-agent-host: a Cloudflare Agents host persisting snapshots in Durable Object state.
Sub-agents and composition
These compose agent machines as sub-agents or child actors. See Multi-agent.
- subflows: a nested child machine keeping its own executor binding.
- ai-sdk-sub-agents: Vercel AI SDK ToolLoopAgent workers exposed as host-owned tools.
- debate-sub-agents: a facilitator scheduling two event-based debater sub-agents.
- long-running-onboarding: a coordinator invoking typed IT provisioning between two event-driven waits.
- supervisor: a routing request whose structured output hands off to a format-specific worker.
- swarm-handoff: a persistent multi-agent network handing off between typed child actors across turns.
- hierarchical-teams: a coordinator invokes research and writing child-team machines; each team owns specialist states and a typed boundary.
- trading-team: parallel analysts, bull/bear debate, trader proposal, risk review, and final approval as one composite workflow.
Multi-step agent patterns
Common agent workflows expressed as explicit XState machines.
- react-agent: ReAct as an explicit loop: one reason-or-act request per iteration (discriminated union: call a tool or answer), typed tool actors execute, a step-budget guard breaks the loop with a best-effort answer.
- tool-calling: the model selects a tool (structured output), typed tool actors execute, progress reported via transitions.
- rag: retrieve (typed plain actor over a sample corpus) then a grounded answer, with conversational memory in context.
- adaptive-rag: routes local vs web, grades evidence, rewrites weak queries once, then grades the generated answer.
- deep-research: plans three searches, researches concurrently, reflects on coverage, optionally follows up once, then writes a sourced report.
- context-compaction: a chat loop that bounds its own context window; a
compactingstate folds stale turns into a running summary once history passes a threshold, keeps the last N messages verbatim, and feeds the summary back as a system message. - plan-and-execute: a planner request produces structured output, execution states iterate the plan (the ReWOO evidence-map idea).
- sql-agent: query generation, DB execution, and answer synthesis as separate typed states.
- triage: structured-output support ticket triage.
- parallel-streams: fan-out over parallel worker streams relayed through a side channel.
- sse-transport: relaying provider stream chunks over an SSE transport.
- lats: bounded tree search with UCB-style leaf selection, candidate expansion, and reflection scoring.
Evaluation
- simulated-user-evaluation: a target chatbot and simulated user alternate under a turn bound, then an independent judge scores the transcript. LangSmith dataset and experiment services are intentionally excluded.
Migration and observability
- retrofit: a genuinely tangled hand-rolled agent (
before.ts) refactored stepwise into a machine, each step shippable, withsimulateAgenttests pinning the before/after behavior. The worked proof for Migrating from a loop. - langsmith-otel: the
onTracestream mapped to OpenTelemetry spans and exported to LangSmith; prints the trace stream to stdout without keys. See Observability.
AI SDK pattern set
The Vercel AI SDK agent patterns, each rebuilt as an explicit XState machine.
- ai-sdk-marketing-chain: a sequential chain.
- ai-sdk-routing: routing.
- ai-sdk-parallel-review: parallel review.
- ai-sdk-orchestrator-worker: an orchestrator-worker fan-out.
- ai-sdk-evaluator-optimizer: an evaluator-optimizer loop.
Note: The full example index, including framework-comparison notes, lives in examples/README.md.