The 80% of the API you’ll use, all on one page. For full signatures and option types, see the Builder API reference .
import { ReactiveAgents } from " reactive-agents " ;
const agent = await ReactiveAgents . create ()
. withProvider ( " anthropic " )
const result = await agent . run ( " What's 2 + 2? " );
console . log (result . output );
That’s it. Provider key from .env, model auto-picked, direct LLM loop.
Method Status What it does .withName(name)recommended Identifier for logs, telemetry, A2A .withProvider(p)essential "anthropic" · "openai" · "gemini" · "ollama" · "litellm" · "test".withModel(id)recommended e.g. "claude-sonnet-4-6", "gpt-4o", "qwen3:14b" .withSystemPrompt(s)opt-in Persona / instructions for the agent
Method Status What it does .withReasoning()essential ReAct loop (default). Pass { defaultStrategy: "tree-of-thought" } to switch. .withTools()recommended Built-in tools + meta-tools (recall, find, brief, pulse) .withTools({ tools: [myTool] })opt-in Add custom tools to the registry .withMemory()recommended 4-layer memory, tier "standard" (FTS5 keyword search) .withMemory({ tier: "enhanced" })opt-in + vector embeddings (needs EMBEDDING_PROVIDER) .withSkills({ paths: ["./skills/"] })opt-in Living Skills System — agentskills.io compatible
Method Status What it does .withGuardrails()recommended Pre-LLM injection / PII / toxicity blocking .withVerification()opt-in Post-LLM fact-check (semantic entropy, NLI) .withCostTracking()recommended Complexity routing + budget enforcement .withIdentity()advanced Ed25519 certificates + RBAC + delegation .withKillSwitch()recommended Per-agent + global emergency halt .withRequiredTools({ tools: ["web-search"] })opt-in Force critical tool calls before answering
Method What it does .withObservability({ verbosity: "normal", live: true })Metrics dashboard + live phase logs + tracing .withLogging({ level, format, filePath })Structured logs (rotates at maxFileSizeMb) .withCortex()Stream telemetry to Cortex Studio over WebSocket .withHealthCheck()Adds agent.health() probe
Method What it does .withTimeout(ms)Hard execution timeout .withRetryPolicy({ maxRetries, backoffMs })Retry on transient LLM failures .withFallbacks({ providers, errorThreshold })Provider/model fallback chain .withErrorHandler(fn)Global error callback .withMinIterations(n)Force at least N reasoning steps .withVerificationStep({ mode: "reflect" })LLM self-review before answering .withOutputValidator(fn)Retry until output passes a predicate .withCustomTermination(fn)User-defined “done” check
Method What it does .withDynamicSubAgents({ maxIterations })Model-spawned sub-agents at runtime .withAgentTool(name, config)Named purpose-built sub-agent .withOrchestration()Sequential / parallel / pipeline / map-reduce .withA2A()Agent Cards + JSON-RPC + SSE for cross-agent calls .withGateway({ heartbeat, crons, webhooks, policies })Persistent autonomous harness
Method What it does .withHook({ phase, timing, handler })Intercept any of the 12 phases
handler : ( ctx ) => Effect . succeed (ctx),
Phases: bootstrap · guardrail · cost-route · strategy-select · think · act · observe · verify · memory-flush · cost-track · audit · complete
Method Returns agent.run(task)Promise<AgentResult> — full executionagent.runStream(task, { signal })AsyncGenerator<AgentEvent> — token streamingagent.chat(question)Promise<string> — single-turn Q&A with adaptive routingagent.session()Multi-turn session with memory agent.subscribe(tag, fn)Listen to EventBus events agent.registerTool(def, handler)Add a tool at runtime agent.unregisterTool(name)Remove a tool at runtime agent.health(){ status, checks[] } — readiness probeagent.dispose()Cleanup MCP + open resources
AgentResult shape:
debrief ?: { summary, keyFindings, metrics },
terminatedBy: " final_answer " | " max_iterations " | " error " ,
metadata: { duration, cost, tokensUsed, stepsCount, strategyUsed },
Tag Fires when AgentStarted / AgentCompletedTask begins / ends ReasoningStepCompletedEach thought / action / observation ToolCallCompletedEach tool call ({ toolName, durationMs, success }) IterationProgressEvery reasoning loop iteration (streaming) StrategySwitchedAuto-strategy-switch triggered GuardrailViolationDetectedInput blocked LLMRequestStarted / LLMRequestCompletedEach LLM API call MemoryBootstrapped / MemoryFlushedMemory loaded / written FinalAnswerProducedFinal answer extracted from loop ContextSynthesizedContext curation step ran TextDeltaToken-level streaming chunk (runStream only) StreamCompleted / StreamCancelledStream end states
const controller = new AbortController ();
for await ( const event of agent . runStream ( " Analyze this " , { signal: controller . signal })) {
if (event . _tag === " TextDelta " ) process . stdout . write (event . text );
if (event . _tag === " IterationProgress " ) console . log ( ` Step ${ event . iteration } / ${ event . maxIterations } ` );
if (event . _tag === " StreamCompleted " ) {
console . log (event . toolSummary ); // Array<{ toolName, calls, successRate }>
One-line SSE endpoint:
import { AgentStream } from " reactive-agents " ;
Bun . serve ({ fetch : ( req ) => AgentStream . toSSE (agent . runStream ( " Hello " )) });
import { agentFn, pipe, parallel, race } from " reactive-agents " ;
const researcher = agentFn ( { name: " researcher " , provider: " anthropic " }, ( b ) =>
b . withReasoning () . withTools ()
const pipeline = pipe (researcher , summarizer);
const result = await pipeline ( " Find latest AI news " );
// Parallel fan-out — output contains labeled results from all 3
const multi = parallel (sentimentAgent , keywordAgent , summaryAgent);
const fastest = race (claudeAgent , gpt4Agent);
await pipeline . dispose ();
import { agentConfigToJSON, ReactiveAgents } from " reactive-agents " ;
const builder = ReactiveAgents . create ()
. withProvider ( " anthropic " )
. withReasoning ({ defaultStrategy: " plan-execute-reflect " })
. withTools ({ adaptive: true })
. withMemory ({ tier: " enhanced " });
const json = agentConfigToJSON (builder . toConfig ());
// Save to DB / send over wire / commit to repo
const restored = await ReactiveAgents . fromJSON (json);
const agent = await restored . build ();
# Pick one provider key (or run local Ollama)
ANTHROPIC_API_KEY = sk-ant-...
# Optional — enables built-in tools
TAVILY_API_KEY = tvly-... # Web search
SERPER_API_KEY = ... # Web search (alt)
# Optional — vector memory ("enhanced" tier)
EMBEDDING_PROVIDER = openai # or "ollama"
EMBEDDING_MODEL = text-embedding-3-small
LLM_DEFAULT_MODEL = claude-sonnet-4-6
LLM_DEFAULT_TEMPERATURE = 0.7
bunx rax init my-app --template standard # Scaffold a project
rax create agent researcher --recipe researcher # Generate from recipe
rax run " Explain X " --provider anthropic # Run an agent
rax serve --port 4111 # Expose as A2A HTTP server
rax cortex # Launch Cortex Studio
rax playground # Interactive REPL
rax eval run --suite ./eval-suite.yaml # Run an evaluation
rax inspect <agent-id> # Debug a session
rax health # Check provider readiness
Full reference: CLI Commands .
A ReactiveAgent is a runtime built from composable Layers. Each .with*() adds a Layer. build() composes them into the ExecutionEngine’s 12-phase lifecycle. agent.run() flows a task through all 12 phases. Hooks intercept any phase. Events fire from every phase. No singletons, no global state — each agent is its own isolated runtime.
.withProvider() · .withReasoning() · .withTools() · .withMemory()
bootstrap → guardrail → cost-route → strategy-select
⟲ think → act → observe ⟲
verify → memory-flush → cost-track → audit → complete
For the deep dive, see Architecture and Layer System .