Skip to content

17 · Full framework showcase (real-world map)

This page is a single narrative that touches every major capability in confused-ai: one fictional product, with imports you can copy into your own app. Deep dives live in the numbered examples and guides linked throughout.


The story: NorthPeak StoreOps Copilot

NorthPeak Retail ships an internal assistant for store managers:

  • Answers policy and procedure questions from uploaded PDFs (RAG).
  • Runs safe tools (calculator, HTTP lookups, optional MCP integrations).
  • Remembers the conversation per store via sessions; profiles repeat users.
  • Uses workflows (plan → compose), pipelines for handoffs, and optional supervisor / team patterns for escalation.
  • Ships behind HTTP + OpenAPI, with health checks, rate limits, circuit breakers, guardrails, and observability (logs, metrics, evals, optional Langfuse/LangSmith batches).

You do not need one monolith file in production—this page shows how each concern maps to a module so you can adopt pieces incrementally.


Architecture (how the pieces fit)

mermaid
flowchart TB
    subgraph client [Clients]
        Web[Web / mobile]
        Curl[API clients]
    end

    subgraph runtime [HTTP runtime]
        API[createHttpService]
        OAI[OpenAPI /health]
    end

    subgraph agent [Agent layer]
        CA[createAgent]
        AA[Agent / AgenticRunner]
        DA[defineAgent + workflows]
    end

    subgraph data [Data plane]
        Sess[SessionStore]
        Mem[Memory / profiles]
        RAG[KnowledgeEngine + vector store]
        Art[Artifacts]
    end

    subgraph safety [Safety and ops]
        GR[Guardrails]
        RL[RateLimiter / RedisRateLimiter]
        CB[CircuitBreaker]
        Obs[Metrics / tracing / eval]
    end

    Web --> API
    Curl --> API
    API --> CA
    CA --> Sess
    CA --> RAG
    CA --> GR
    CA --> Obs
    DA --> Mem
    CA --> Art
    API --> OAI
    RL --> API

Runnable scripts in this repo

Run these from the repository root (they import src/ paths; published apps use confused-ai imports instead).

ScriptCommandWhat it demonstrates
Full LLM tourbun run example:showcasecreateAgent, sessions, tools, guardrails, logger, streaming hooks, defineAgent + createWorkflow (sequential + parallel), createPipeline + asOrchestratorAgent, planner + memory, health, metrics, OpenAPI; add --http for createHttpService
Module sampler (no LLM)bun run example:potentialsplitText, circuit breaker, rate limiter, artifacts, learning profiles, eval metrics, loadConfig
Minimal agentbun run example:simpleSmallest createAgent setup

Capability checklist → imports

Use this as a coverage map against CAPABILITIES.md at the repository root (same checklist the maintainers update with each release).

Core agent loop

CapabilityExample import
Opinionated agentimport { createAgent } from 'confused-ai'
ReAct / tool loop (bring your own LLM)import { createAgent } from 'confused-ai/agentic'
Class-based Agentimport { Agent } from 'confused-ai'
Fluent DX builderimport { defineAgent } from 'confused-ai' (DX chain under confused-ai — see Creating Agents)
Typed Zod agents (SDK)import { defineAgent, createWorkflow, asOrchestratorAgent } from 'confused-ai'
ts
import { createAgent, resolveLlmForCreateAgent } from 'confused-ai';
import { CalculatorAddTool } from 'confused-ai/tool';
import { InMemorySessionStore } from 'confused-ai/session';

const agent = createAgent({
  name: 'StoreOps',
  instructions: 'Help store managers with policy and math. Use calculator_add when adding numbers.',
  sessionStore: new InMemorySessionStore(),
  tools: [new CalculatorAddTool()],
  llm: resolveLlmForCreateAgent(
    { name: 'StoreOps', instructions: '_' },
    { model: 'gpt-4o-mini', apiKey: process.env.OPENAI_API_KEY! }
  ),
});

Tools & integrations

CapabilityExample import
Built-in toolsimport { … } from 'confused-ai/tool'
Registryimport { ToolRegistryImpl, toToolRegistry } from 'confused-ai/tool'
MCP HTTP clientimport { HttpMcpClient, loadMcpToolsFromUrl } from 'confused-ai/tool'
MCP HTTP serverimport { McpHttpServer, createMcpServer } from 'confused-ai/tool'
MCP stdio (minimal)import { runMcpStdioToolServer, handleMcpStdioLine } from 'confused-ai/tool'
JSON tool gatewayimport { handleToolGatewayRequest } from 'confused-ai/tool'
Playwright (optional peer)import { PlaywrightPageTitleTool } from 'confused-ai/tool'
ts
import { createWorkflow, defineAgent } from 'confused-ai';
import { CalculatorAddTool } from 'confused-ai/tool';
import { z } from 'zod';

const analyst = defineAgent({
  name: 'analyst',
  inputSchema: z.object({ question: z.string() }),
  outputSchema: z.object({ answer: z.string() }),
  tools: [new CalculatorAddTool()],
  handler: async (input) => ({ answer: `Thought about: ${input.question}` }),
});

const wf = createWorkflow();
const out = await wf.task('analyst', analyst).sequential().execute({ question: 'Q4 foot traffic?' });

Session, memory, knowledge

CapabilityExample import
Sessions (memory / SQL / SQLite / Redis)import { InMemorySessionStore, RedisSessionStore, createSqliteSessionStore } from 'confused-ai/session'
Redis LLM cacheimport { RedisLlmCache } from 'confused-ai/session'
Semantic / episodic memoryimport { InMemoryStore, MemoryType } from 'confused-ai'
Vector storesimport { PineconeVectorStore, QdrantVectorStore, PgVectorStore, InMemoryVectorStore } from 'confused-ai/memory'
User profilesimport { InMemoryUserProfileStore } from 'confused-ai/learning'
RAGimport { KnowledgeEngine, TextLoader, splitText } from 'confused-ai/knowledge'
ts
import { KnowledgeEngine, splitText } from 'confused-ai/knowledge';
import { InMemoryVectorStore } from 'confused-ai/memory';
import { OpenAIEmbeddingProvider } from 'confused-ai/memory';

const chunks = splitText('Return policy: 30 days. Receipt required.', { chunkSize: 40, chunkOverlap: 8 });

const rag = new KnowledgeEngine({
  vectorStore: new InMemoryVectorStore(),
  embeddingProvider: new OpenAIEmbeddingProvider({ apiKey: process.env.OPENAI_API_KEY! }),
});

await rag.ingest([
  {
    content: chunks.join('\n'),
    metadata: { store: 'northpeak' },
    source: 'return-policy-v3',
  },
]);

Safety & planning

CapabilityExample import
Guardrailsimport { GuardrailValidator, createSensitiveDataRule, createPiiDetectionRule } from 'confused-ai/guardrails'
Plannersimport { ClassicalPlanner, PlanningAlgorithm } from 'confused-ai/planner'
Execution graphsimport { … } from 'confused-ai/execution'
ts
import { GuardrailValidator, createSensitiveDataRule } from 'confused-ai/guardrails';

const guardrails = new GuardrailValidator({
  rules: [createSensitiveDataRule()],
});

Orchestration

CapabilityExample import
Pipelineimport { createPipeline } from 'confused-ai/workflow'
Supervisor, swarm, team, toolkitimport { … } from 'confused-ai/workflow'
Agent router (orchestration strategy type)import type { AgentRoutingStrategy } from 'confused-ai/workflow'
A2A clientimport { HttpA2AClient, createHttpA2AClient } from 'confused-ai/workflow'

TIP

The LLM router uses RoutingStrategy from confused-ai/llm. The multi-agent router uses AgentRoutingStrategy from confused-ai/orchestration—do not confuse the two.

Observability & quality

CapabilityExample import
Logging / metrics / tracerimport { ConsoleLogger, MetricsCollectorImpl, InMemoryTracer } from 'confused-ai/observe'
Eval metricsimport { wordOverlapF1, rougeLWords, ExactMatchAccuracy } from 'confused-ai/observe'
LLM-as-judgeimport { runLlmAsJudge } from 'confused-ai/observe'
Langfuse / LangSmith (HTTP helpers)import { sendLangfuseBatch, sendLangSmithRunBatch } from 'confused-ai/observe'
OTLPimport { OTLPTraceExporter, OTLPMetricsExporter } from 'confused-ai/observe'
ts
import { MetricsCollectorImpl } from 'confused-ai/observe';

const metrics = new MetricsCollectorImpl();
metrics.counter('northpeak_queries', 1, { region: 'us-west' });

Production & resilience

CapabilityExample import
Healthimport { HealthCheckManager, createSessionStoreHealthCheck } from 'confused-ai/guard'
Rate limiting (process)import { RateLimiter, createOpenAIRateLimiter } from 'confused-ai/guard'
Rate limiting (Redis)import { RedisRateLimiter } from 'confused-ai/guard'
Circuit breakerimport { CircuitBreaker, createLLMCircuitBreaker } from 'confused-ai/guard'
Streams / shutdownimport { ResumableStreamManager, GracefulShutdown } from 'confused-ai/guard'

Artifacts & media

CapabilityExample import
Versioned outputsimport { InMemoryArtifactStorage, createTextArtifact } from 'confused-ai/artifacts'
Media / video helpersimport { … } from 'confused-ai' (video module)

HTTP service

CapabilityExample import
API + SSE + OpenAPIimport { createHttpService, listenService, getRuntimeOpenApiJson } from 'confused-ai/serve'
ts
import { createHttpService, listenService } from 'confused-ai/serve';

const service = createHttpService(
  { agents: { storeops: agent }, tracing: true, cors: '*' },
  8787
);
await listenService(service, 8787);

Config

CapabilityExample import
Env-based configimport { loadConfig, validateConfig } from 'confused-ai/config'

LLM providers & structured streaming

CapabilityExample import
OpenAI / Anthropic / Google / compatimport { OpenAIProvider, AnthropicProvider, GoogleProvider, … } from 'confused-ai/model'
Bedrock (optional SDK)import { BedrockConverseProvider } from 'confused-ai/model'
Smart model routing (no extra LLM call)import { createSmartRouter, scoreTaskTypesForRouting } from 'confused-ai/model'
Stream → Zodimport { collectStreamText, collectStreamThenValidate } from 'confused-ai/model'
Context limitsimport { getContextLimitForModel, ContextWindowManager } from 'confused-ai/model'
ts
import { z } from 'zod';
import { collectStreamThenValidate, type StreamDelta } from 'confused-ai/model';

async function structuredFromStream(stream: AsyncIterable<StreamDelta>) {
  const schema = z.object({ summary: z.string(), risk: z.enum(['low', 'medium', 'high']) });
  return collectStreamThenValidate(stream, { schema });
}

Where to go next

TopicDoc
Step-by-step tutorialsExamples index · Getting Started
RAG detailsRAG guide · Example 05 · RAG
Multi-agentOrchestration · Example 08 · 09
ProductionResilience · Example 13
MCPMCP guide · Example 14
Full-stack shapeExample 15
Model routingExample 16

NorthPeak “minimum viable” stack (opinionated)

If you only wire one path first:

  1. createAgent + InMemorySessionStore (or Redis in production).
  2. KnowledgeEngine + a real vector store for policy docs.
  3. GuardrailValidator + at least one PII or sensitive-data rule.
  4. createHttpService + HealthCheckManager for deploys.
  5. RateLimiter or RedisRateLimiter on hot routes.
  6. MetricsCollectorImpl (or OTLP) for dashboards.

Then add workflows, MCP, A2A, and Bedrock when a concrete integration requires them.

The runnable examples/framework-showcase.ts file in the repo is the closest end-to-end code counterpart to this page; diff it against your app’s package.json imports when you migrate from repo-relative paths to confused-ai.

Released under the MIT License.