cascadeflow

lemony-aiMIT活跃维护

面向 AI Agent 的级联运行时,在 Agent 循环内按成本、延迟、质量和策略动态调度模型与决策,帮你在不牺牲效果的前提下省下推理开销。

Cascading runtime for AI agents. Optimize cost, latency, quality, and policy decisions inside the agent loop.

v1.2.0发布于 2026-04-02 17:56 UTC3,926star881fork同步于 2026-11-10 11:39 UTC

怎么上手

由 README 提炼,执行前请确认
pip install cascadeflow[all]
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

在 Agent 执行循环内做模型级联的运行时库,按成本、延迟、质量动态选模型

面向 AI Agent 的级联运行时,在 Agent 循环内按成本、延迟、质量和策略动态调度模型与决策,帮你在不牺牲效果的前提下省下推理开销。

核心能力

  • 按查询或工具调用做投机执行,先跑便宜模型再按需升级
  • 在 Agent 循环内做逐步模型决策与逐工具调用预算门控
  • 支持 stop、deny_tool、switch_model 等运行时动作
  • 记录每步决策轨迹,可审计每次模型与工具调用
  • 提供可选的语义相似度与毒性质量校验

容易踩的坑

语义质量校验需额外安装 cascadeflow[semantic],首次使用会下载约 80MB 模型;GPT-5 流式调用需完成 OpenAI 组织验证,非流式不受影响;示例默认走 OpenAI 兼容接口,需自备 API Key 与可用模型名

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v1.2.0
  1. v1.2.0Release 1.2.0最新正式版2026-04-02 · 2026-04-02 17:56 UTC
    • feat(n8n): wire up PreRouter for complexity-based routing (#172) (c2f60a0)
    • fix(n8n): remove obsolete eslint-disable for no-var-requires (47e251b)
    • feat(harness): add trace export and offline cascade simulation (2ebab43)
    • fix(harness): wire query into instrumentation records for session.save -> simulate compatibility (54f65fc)
    • fix(harness): add query parameter to Anthropic stream wrapper (ad34841)
    • chore(n8n): bump to v1.3.0, move @langchain/core to peerDependencies (53b433f)
    • style: apply Black formatting to simulate.py and trace_simulation.py (ee7ca55)
    • feat(openclaw): add opt-in harness mode flags and docs (#173) (d6d6cf8)
    • docs: add cascadeflow vs LiteLLM comparison (#174) (fdda12a)
    • fix(docs): use valid compliance presets in litellm comparison (#175) (c1e0eee)
    • fix: expose agent module via cascadeflow.agent attribute (699f74c)
    • feat(integrations): add full cascade PydanticAI Model integration (#179) (c89e402)
    • chore: bump version to 1.2.0 (6412166)
  2. v1.1.02026-03-08 · 2026-03-08 17:17 UTC
    查看更新说明

    cascadeflow v1.1.0 — Hardening Release

    Highlights

    • 10x faster import: ~20ms via PEP 562 lazy loading (down from ~1900ms)
    • Proxy security: CORS opt-in, 10MB body limit, Bearer auth with constant-time comparison
    • Thread safety: Locking for SDK patch/unpatch, run counters, and record()
    • Performance: Pre-compiled regex in ComplexityDetector (~4x faster)
    • DX improvements: Actionable ImportError for missing integrations, removed deprecated CascadeAgent params, langchain optional extra

    Breaking Changes

    • CascadeAgent no longer accepts deprecated config, tiers, workflows, enable_caching, cache_size, enable_callbacks params
    • Proxy CORS default changed from * to None (opt-in via cors_allow_origin)
    • rich moved to optional extra (pip install cascadeflow[rich])

    npm Packages

    • @cascadeflow/core 1.1.0
    • @cascadeflow/ml 1.1.0
    • @cascadeflow/langchain 1.1.0
    • @cascadeflow/vercel-ai 1.1.0
    • @cascadeflow/paygentic 1.1.0
    • @cascadeflow/n8n-nodes-cascadeflow 1.2.0

    Full Changelog

    https://github.com/lemony-ai/cascadeflow/compare/v1.0.0...v1.1.0

  3. v1.0.02026-02-22 · 2026-02-22 17:13 UTC
    查看更新说明

    What's Changed

    Full Changelog: https://github.com/lemony-ai/cascadeflow/compare/v0.7.1...v1.0.0

  4. v0.7.1Release 0.7.12026-02-14 · 2026-02-14 20:52 UTC
    查看更新说明
    • fix: add drafter+verifier Anthropic models to all presets (242866d)
    • fix: use Sonnet 4.5 as verifier in anthropic-only config (9cc5f9d)
    • Restore anthropic-only preset to Opus-first verifier defaults (3989b7c)
    • bump all packages to v0.7.1 (#124) (97b234b)
  5. v0.7.0Release 0.7.02026-02-14 · 2026-02-14 19:59 UTC
    查看更新说明
    • docs: update README with 15 domains and add Banking77 benchmark (8e17e44)
    • fix: correct version to 0.6.5 and update Banking77 benchmark (ca26798)
    • fix: resolve Ruff lint errors in banking77_benchmark.py (223e777)
    • docs: consistent cascadeflow naming + domain routing image (#94) (c6554a2)
    • feat: Full Integration - Vercel AI SDK, n8n, Proxy, All Providers (#95) (a923702)
    • fix: resolve proxy import conflict for CI (bd26bc1)
    • fix: Black formatting + Python 3.9 compatibility (6bc7512)
    • fix: correct AI SDK package names + regenerate pnpm-lock (0ac09c4)
    • fix: black format errors.py (e8ae386)
    • fix: ignore UP045 ruff rule for Python 3.9 compat (2ff1853)
    • fix: resolve duplicate ValidationResult + ruff lint errors (450e2b3)
    • fix: apply Codex CI fixes - clean imports, vitest config (530d4dc)
    • feat(quality): v14 function call validation + agentic benchmark (#96) (6ce735e)
    • fix: resolve core build and typecheck failures (#97) (24bb33d)
    • OpenClaw integration: production readiness + OpenAI-compatible server hardening (#99) (da0a96e)
    • feat(skills): add cascadeflow skill for OpenClaw/ClaWHub (404b0f3)
    • fix(skills): make cascadeflow skill generic for ClaWHub users (be7b959)
    • fix: add OpenAI-compatible streaming chunks (initial role + final finish_reason) (bf8627e)
    • fix: OpenAI streaming compatibility + add working gpt-4o config (a1c2842)
    • fix: GPT-5 streaming + OpenAI-compatible SSE format (494d7f5)
    • fix(skills): update anthropic-only config - code/general/reasoning use Opus verifier (e1d1d10)
    • feat: map heartbeat/cron to Haiku-only domains for cost efficiency (96d398d)
    • fix(skills): sync anthropic-only config template (afacd10)
    • feat(skills): add heartbeat/cron domains to all config templates (9eca566)
    • fix(health): Return degraded status when no providers initialized (6b8e8be)
    • fix: track routing decisions (cascade/direct) in streaming telemetry (118a689)
    • feat(vercel-ai): useChat integration + agentic tool-loop parity (#101) (1344468)
    • fix(benchmarks): repair MMLU runner + use GSM8K config (#103) (9a397f8)
    • Fix OpenClaw GPT-5 Responses + Anthropic tool loop (#100) (1e8251a)
    • LangChain v2: tool-risk verifier gating + tool-safe streaming (#105) (269c946)
    • Gateway proxy consolidation + DX cleanup (#104) (21e30f1)
    • feat(config): update anthropic-only preset with correct model names (e4c04e3)
    • fix(config): use Haiku 4.5 as default drafter (6da94c4)
    • fix(config): use Sonnet 4.5 for code/reasoning/creative drafters (f48c372)
    • fix(anthropic): preserve non-empty text across multi-block responses (#107) (59a126b)
    • feat(n8n): CascadeFlow Agent node + model highlighting (#102) (325e055)
    • fix(openclaw): emit parser-safe streaming final chunk (#108) (329dd8f)
    • fix(openclaw): use HTTP/1.1 protocol for OpenAI-compat server (6864fc2)
    • fix(openclaw): add Connection: close header for SSE streaming (4261b11)
    • fix(openclaw): include content in delta of final streaming chunk (f3a7b14)
    • fix(streaming): discard draft chunks when cascading to verifier (7ba4898)
    • test(openclaw): align final streaming delta assertion (#109) (adaabd8)
    • fix(streaming): dont duplicate content in final delta chunk (24a8746)
    • fix(openclaw): handle tool text streams and avoid mixed cascade output (#110) (7ae1b44)
    • fix(openclaw): add stream_options.include_usage support for OpenClaw/pi-ai compatibility (#111) (44d2fb3)
    • fix: OpenAI streaming spec compliance for all cascadeflow users (#112) (26c6087)
    • fix: handle tool call events in streaming mode (#113) (b5be027)
    • fix: surface upstream provider errors to OpenClaw users and normalize no-logprobs confidence (e1416cf)
    • fix(alignment): add paraphrase floor to prevent 0% Anthropic acceptance (eab6fa4)
    • fix(telemetry): track draft acceptance and cost in streaming mode (095f4d1)
    • style: fix Black formatting and Ruff lint errors for CI (e0912bc)
    • fix: record draft acceptance telemetry in stream_events (a90333f)
    • Revert "fix: record draft acceptance telemetry in stream_events" (55c6832)
    • fix(strea

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Agent Runtime Intelligence Layer

    PyPI version npm version LangChain version Vercel AI version n8n version License: MIT PyPI Downloads npm Downloads Tests Docs Python Docs TypeScript Docs X Follow GitHub Stars

    Cost Savings: 69% (MT-Bench), 93% (GSM8K), 52% (MMLU), 80% (TruthfulQA) savings, retaining 96% GPT-5 quality.

    Python • TypeScript • LangChain • OpenAI Agents • CrewAI • PydanticAI • Google ADK • n8n • Vercel AI • OpenClaw • Hermes Agent • 📖 Docs • 💡 Examples


    The in-process intelligence layer for AI agents. Optimize cost, latency, quality, budget, compliance, and energy — inside the execution loop, not at the HTTP boundary.

    cascadeflow works where external proxies can't: per-step model decisions based on agent state, per-tool-call budget gating, runtime stop/continue/escalate actions, and business KPI injection during agent loops. It accumulates insight from every model call, tool result, and quality score — the agent gets smarter the more it runs. Sub-5ms overhead. Works with LangChain, OpenAI Agents SDK, CrewAI, PydanticAI, Google ADK, n8n, Vercel AI SDK, and Hermes Agent.

    Update

    Hermes Agent delegation cascading

    CascadeFlow now provides a Hermes Agent integration for per-skill model cascading, task-complexity cascading, topic-aware subagent cascading, observe-mode rollout, and auditable decisions without taking over provider credentials, base URLs, fallback chains, or API modes.

    pip install cascadeflow
    
    npm install @cascadeflow/core
    

    Why cascadeflow?

    Proxy vs In-Process Harness

    DimensionExternal Proxycascadeflow Harness
    ScopeHTTP request boundaryInside agent execution loop
    DimensionsCost onlyCost + quality + latency + budget + compliance + energy
    Latency overhead10-50ms network RTT<5ms in-process
    Business logicNoneKPI weights and targets
    EnforcementNone (observe only)stop, deny_tool, switch_model
    AuditabilityRequest logsPer-step decision traces

    cascadeflow is a library and agent harness — an intelligent AI model cascading package that dynamically selects the optimal model for each query or tool call through speculative execution. It's based on the research that 40-70% of queries don't require slow, expensive flagship models, and domain-specific smaller models often outperform large general-purpose models on specialized tasks. For the remaining queries that need advanced reasoning, cascadeflow automatically escalates to flagship models if needed.

    • Inside-the-Loop Control. Influence decisions at every agent step — model call, tool call, sub-agent handoff — where most cost, delay, and failure actually happen. External proxies only see request boundaries; cascadeflow sees decision boundaries.
    • Multi-Dimensional Optimization. Optimize across cost, latency, quality, budget, compliance/risk, and energy simultaneously — relevant to engineering, finance, security, operations, and sustainability stakeholders.
    • Business Logic Injection. Embed KPI weights and policy intent directly into agent behavior at runtime. Shift AI control from static prompt design to live business governance.
    • Runtime Enforcement. Directly steer outcomes with four actions: allow, switch_model, deny_tool, stop — based on current context and policy state. Closes the gap between analytics and execution.
    • Auditability & Transparency. Every runtime decision is traceable and attributable. Supports audit requirements, faster tuning cycles, and trust in regulated or high-stakes workflows.
    • Measurable Value. Prove impact with reproducible metrics on realistic agent workflows — better economics and latency while preserving quality thresholds.
    • Latency Advantage. Proxy-based optimization adds 40-60ms per call. In a 10-step agent loop, that is 400-600ms of avoidable overhead. cascadeflow runs in-process with sub-5ms overhead — critical for real-time UX, task throughput, and enterprise SLAs.
    • Framework & Provider Neutral. Works with LangChain, OpenAI Agents SDK, CrewAI, PydanticAI, Google ADK, Vercel AI SDK, n8n, Hermes Agent, and custom frameworks. Unified API across OpenAI, Anthropic, Groq, Ollama, vLLM, Together, and more.
    • Self-Improving Agent Intelligence. Because cascadeflow runs inside the agent loop, it accumulates deep insight into every model call, tool result, quality score, and routing decision over time. This enables cascadeflow to learn which models perform best for which tasks, adapt routing strategies, and continuously improve cost-quality tradeoffs — without manual tuning. The agent gets smarter the more it runs.
    • Edge & Local-Hosted AI. Handle most queries with local models (vLLM, Ollama), automatically escalate complex queries to cloud providers only when needed.

    ℹ️ Note: SLMs (under 10B parameters) are sufficiently powerful for 60-70% of agentic AI tasks. Research paper


    How cascadeflow Works

    cascadeflow uses speculative execution with quality validation:

    1. Speculatively executes small, fast models first - optimistic execution ($0.15-0.30/1M tokens)
    2. Validates quality of responses using configurable thresholds (completeness, confidence, correctness)
    3. Dynamically escalates to larger models only when quality validation fails ($1.25-3.00/1M tokens)
    4. Learns patterns to optimize future cascading decisions and domain specific routing

    Zero configuration. Works with YOUR existing models (>17 providers currently supported).

    In practice, 60-70% of queries are handled by small, efficient models (8-20x cost difference) without requiring escalation

    Result: 40-85% cost reduction, 2-10x faster responses, zero quality loss.

    ┌─────────────────────────────────────────────────────────────┐
    │                      cascadeflow Stack                      │
    ├─────────────────────────────────────────────────────────────┤
    │                                                             │
    │  ┌───────────────────────────────────────────────────────┐  │
    │  │  Cascade Agent                                        │  │
    │  │                                                       │  │
    │  │  Orchestrates the entire cascade execution            │  │
    │  │  • Query routing & model selection                    │  │
    │  │  • Drafter -> Verifier coordination                   │  │
    │  │  • Cost tracking & telemetry                          │  │
    │  └───────────────────────────────────────────────────────┘  │
    │                          ↓                                  │
    │  ┌───────────────────────────────────────────────────────┐  │
    │  │  Domain Pipeline                                      │  │
    │  │                                                       │  │
    │  │  Automatic domain classification                      │  │
    │  │  • Rule-based detection (CODE, MATH, DATA, etc.)      │  │
    │  │  • Optional ML semantic classification                │  │
    │  │  • Domain-optimized pipelines & model selection       │  │
    │  └───────────────────────────────────────────────────────┘  │
    │                          ↓                                  │
    │  ┌───────────────────────────────────────────────────────┐  │
    │  │  Quality Validation Engine                            │  │
    │  │                                                       │  │
    │  │  Multi-dimensional quality checks                     │  │
    │  │  • Length validation (too short/verbose)              │  │
    │  │  • Confidence scoring (logprobs analysis)             │  │
    │  │  • Format validation (JSON, structured output)        │  │
    │  │  • Semantic alignment (intent matching)               │  │
    │  └───────────────────────────────────────────────────────┘  │
    │                          ↓                                  │
    │  ┌───────────────────────────────────────────────────────┐  │
    │  │  Cascading Engine (<2ms overhead)                     │  │
    │  │                                                       │  │
    │  │  Smart model escalation strategy                      │  │
    │  │  • Try cheap models first (speculative execution)     │  │
    │  │  • Validate quality instantly                         │  │
    │  │  • Escalate only when needed                          │  │
    │  │  • Automatic retry & fallback                         │  │
    │  └───────────────────────────────────────────────────────┘  │
    │                          ↓                                  │
    │  ┌───────────────────────────────────────────────────────┐  │
    │  │  Provider Abstraction Layer                           │  │
    │  │                                                       │  │
    │  │  Unified interface for >17 providers                   │  │
    │  │  • OpenAI • Anthropic • Groq • Ollama                 │  │
    │  │  • Together • vLLM • HuggingFace • LiteLLM            │  │
    │  │  • Vercel AI SDK (17+ additional providers)            │  │
    │  └───────────────────────────────────────────────────────┘  │
    │                                                             │
    └─────────────────────────────────────────────────────────────┘
    

    Harness API

    Three tiers of integration — zero-change observability to full policy control:

    Tier 1: Zero-change observability

    import cascadeflow
    cascadeflow.init(mode="observe")
    # All OpenAI/Anthropic SDK calls are now tracked. No code changes needed.
    

    Tier 2: Scoped runs with budget

    with cascadeflow.run(budget=0.50, max_tool_calls=10) as session:
        result = await agent.run("Analyze this dataset")
        print(session.summary())  # cost, latency, energy, steps, tool calls
        print(session.trace())    # full decision audit trail
    

    Tier 3: Decorated agents with policy

    @cascadeflow.agent(budget=0.20, compliance="gdpr", kpi_weights={"quality": 0.6, "cost": 0.3, "latency": 0.1})
    async def my_agent(query: str):
        return await llm.complete(query)
    

    Quick Start

    Python

    pip install cascadeflow[all]
    
    from cascadeflow import CascadeAgent, ModelConfig
    
    # Define your cascade - try cheap model first, escalate if needed
    agent = CascadeAgent(models=[
        ModelConfig(name="nous/hermes-flash", provider="openai", cost=0.000375),  # Draft model (~$0.375/1M tokens)
        ModelConfig(name="gpt-5", provider="openai", cost=0.00562),         # Verifier model (~$5.62/1M tokens)
    ])
    
    # Run query - automatically routes to optimal model
    result = await agent.run("What's the capital of France?")
    
    print(f"Answer: {result.content}")
    print(f"Model used: {result.model_used}")
    print(f"Cost: ${result.total_cost:.6f}")
    

    For advanced use cases, you can add ML-based semantic similarity checking to validate that responses align with queries.

    Step 1: Install the optional ML package:

    pip install cascadeflow[semantic]  # Adds semantic similarity via FastEmbed (~80MB model)
    

    Step 2: Use semantic quality validation:

    from cascadeflow.quality.semantic import SemanticQualityChecker
    
    # Initialize semantic checker (downloads model on first use)
    checker = SemanticQualityChecker(
        similarity_threshold=0.5,  # Minimum similarity score (0-1)
        toxicity_threshold=0.7     # Maximum toxicity score (0-1)
    )
    
    # Validate query-response alignment
    query = "Explain Python decorators"
    response = "Decorators are a way to modify functions using @syntax..."
    
    result = checker.validate(query, response, check_toxicity=True)
    
    print(f"Similarity: {result.similarity:.2%}")
    print(f"Passed: {result.passed}")
    print(f"Toxic: {result.is_toxic}")
    

    What you get:

    • 🎯 Semantic similarity scoring (query ↔ response alignment)
    • 🛡️ Optional toxicity detection
    • 🔄 Automatic model download and caching
    • 🚀 Fast inference (~100ms per check)

    Full example: See semantic_quality_domain_detection.py

    ⚠️ GPT-5 Note: GPT-5 streaming requires organization verification. Non-streaming works for all users. Verify here if needed (~15 min). Basic cascadeflow examples work without - GPT-5 is only called when needed (typically 20-30% of requests).

    📖 Learn more: Python Documentation | Quickstart Guide | Providers Guide

    TypeScript

    npm install @cascadeflow/core
    
    import { CascadeAgent, ModelConfig } from '@cascadeflow/core';
    
    // Same API as Python!
    const agent = new CascadeAgent({
      models: [
        { name: 'nous/hermes-flash', provider: 'openai', cost: 0.000375 },
        { name: 'gpt-4o', provider: 'openai', cost: 0.00625 },
      ],
    });
    
    const result = await agent.run('What is TypeScript?');
    console.log(`Model: ${result.modelUsed}`);
    console.log(`Cost: $${result.totalCost}`);
    console.log(`Saved: ${result.savingsPercentage}%`);
    

    For advanced quality validation, enable ML-based semantic similarity checking to ensure responses align with queries.

    Step 1: Install the optional ML packages:

    npm install @cascadeflow/ml @huggingface/transformers
    

    Step 2: Enable semantic validation in your cascade:

    import { CascadeAgent, SemanticQualityChecker } from '@cascadeflow/core';
    
    const agent = new CascadeAgent({
      models: [
        { name: 'nous/hermes-flash', provider: 'openai', cost: 0.000375 },
        { name: 'gpt-4o', provider: 'openai', cost: 0.00625 },
      ],
      quality: {
        threshold: 0.40,                    // Traditional confidence threshold
        requireMinimumTokens: 5,            // Minimum response length
        useSemanticValidation: true,        // Enable ML validation
        semanticThreshold: 0.5,             // 50% minimum similarity
      },
    });
    
    // Responses now validated for semantic alignment
    const result = await agent.run('Explain TypeScript generics');
    

    Step 3: Or use semantic validation directly:

    import { SemanticQualityChecker } from '@cascadeflow/core';
    
    const checker = new SemanticQualityChecker();
    
    if (await checker.isAvailable()) {
      const result = await checker.checkSimilarity(
        'What is TypeScript?',
        'TypeScript is a typed superset of JavaScript.'
      );
    
      console.log(`Similarity: ${(result.similarity * 100).toFixed(1)}%`);
      console.log(`Passed: ${result.passed}`);
    }
    

    What you get:

    • 🎯 Query-response semantic alignment detection
    • 🚫 Off-topic response filtering
    • 📦 BGE-small-en-v1.5 embeddings (~40MB, auto-downloads)
    • ⚡ Fast CPU inference (~50-100ms with caching)
    • 🔄 Request-scoped caching (50% latency reduction)
    • 🌐 Works in Node.js, Browser, and Edge Functions

    Example: semantic-quality.ts

    📖 Learn more: TypeScript Documentation | Quickstart Guide | Node.js Examples

    🔄 Migration Example

    Migrate in 5min from direct Provider implementation to cost savings and full cost control and transparency.

    Before (Standard Approach)

    Cost: $0.000113, Latency: 850ms

    # Using expensive model for everything
    result = openai.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "What's 2+2?"}]
    )
    
    After (With cascadeflow)

    Cost: $0.000007, Latency: 234ms

    agent = CascadeAgent(models=[
        ModelConfig(name="nous/hermes-flash", provider="openai", cost=0.000375),
        ModelConfig(name="gpt-4o", provider="openai", cost=0.00625),
    ])
    
    result = await agent.run("What's 2+2?")
    

    🔥 Saved: $0.000106 (94% reduction), 3.6x faster

    📊 Learn more: Cost Tracking Guide | Production Best Practices | Performance Optimization

    If you already have an app using the OpenAI or Anthropic APIs and want the fastest integration, run the gateway and point your existing client at it:

    python -m cascadeflow.server --mode auto --port 8084
    

    Use cascadeflow in n8n workflows for no-code AI automation with automatic cost optimization!

    Installation

    1. Open n8n
    2. Go to Settings → Community Nodes
    3. Search for: @cascadeflow/n8n-nodes-cascadeflow
    4. Click Install

    Two Nodes

    NodeTypeUse case
    CascadeFlow (Model)Language Model sub-nodeDrop-in for any Chain/LLM node
    CascadeFlow AgentStandalone agent (main in/out)Tool calling, memory, multi-step reasoning

    Quick Start (Model):

    1. Add two AI Chat Model nodes (cheap drafter + powerful verifier)
    2. Add CascadeFlow (Model) and connect both models
    3. Connect to Basic LLM Chain or Chain node
    4. Check Logs tab on the Chain node to see cascade decisions

    Quick Start (Agent):

    1. Add a Chat Trigger node
    2. Add CascadeFlow Agent and connect it to the trigger
    3. Connect Drafter, Verifier, optional Memory and Tools
    4. Check the Agent Output tab for cascade metadata and trace

    Result: 40-85% cost savings in your n8n workflows!

    Features:

    • Works with any AI Chat Model node (OpenAI, Anthropic, Ollama, Azure, etc.)
    • Mix providers (e.g., Ollama drafter + GPT-4o verifier)
    • Agent node: tool calling, memory, per-tool routing, tool call validation
    • 16-domain cascading for specialized model routing
    • Real-time flow visualization in Logs/Output tabs

    🔌 Learn more: n8n Integration Guide | n8n Package


    Use CascadeFlow as an optional Hermes Agent delegation router for subagents. Hermes keeps provider credentials, base URLs, fallback chains, and API modes; CascadeFlow returns a structured routing decision before Hermes spawns a child agent.

    This works as a released CascadeFlow module even before a native Hermes PR is accepted. Users can call the router from a local wrapper, local Hermes fork, or small hook script and keep Hermes' current provider configuration as the final source of truth.

    from cascadeflow.integrations.hermes import (
        HermesDelegationRequest,
        HermesDelegationRouter,
    )
    
    router = HermesDelegationRouter.from_dict({
        "enabled": True,
        "mode": "observe",
        "routes": {
            "code": {
                "provider": "nous",
                "model": "nous/hermes-4.1",
                "reasoning_effort": "high",
            },
            "simple": {
                "provider": "openai",
                "model": "gpt-4.1-mini",
                "reasoning_effort": "low",
            },
        },
    })
    
    decision = router.route_delegation(HermesDelegationRequest(
        goal="Debug the failing unit test and propose a patch",
        toolsets=("terminal", "git"),
        loaded_skills=("python", "debugging"),
    ))
    print(decision.to_dict())
    

    What Hermes gets:

    • Per-skill model routing: coding, research, legal/finance, and lightweight utility skills can receive different model and reasoning profiles instead of inheriting one global default.
    • Task-complexity routing: simple delegated tasks can use cheaper/faster models, while hard debugging, architecture, research, or code-generation tasks route to stronger models.
    • Topic-aware subagent routing: subagents can route differently for code, research, data, creative, ops, medical, legal, finance, and other domains.
    • Better subagent economics: Hermes avoids paying flagship-model prices for simple worker tasks.
    • Better quality for hard tasks: difficult subagent work no longer has to inherit a weak or cheap default model.
    • Dry-run/observe mode: Hermes users can see what CascadeFlow would route without changing runtime behavior.
    • Auditability: routing decisions include reason, confidence, domain, complexity, and selected model.
    • Safer rollout: missing CascadeFlow, disabled config, low confidence, high-stakes gaps, or bad routing inputs fall back to Hermes' current behavior.
    • No credential rewrite: Hermes still owns provider credentials, base URLs, fallback chains, and API modes.

    Learn more: Hermes Agent Integration Guide

    Standalone example: examples/integrations/hermes_delegation_router.py


    Use cascadeflow with LangChain for intelligent model cascading with full LCEL, streaming, and tools support!

    Installation

    TypeScript

    npm install @cascadeflow/langchain @langchain/core @langchain/openai
    

    Python

    pip install cascadeflow langchain-openai
    

    Quick Start

    import { ChatOpenAI } from '@langchain/openai';
    import { ChatAnthropic } from '@langchain/anthropic';
    import { withCascade } from '@cascadeflow/langchain';
    
    const cascade = withCascade({
      drafter: new ChatOpenAI({ model: 'nous/hermes-flash' }),      // $0.15/$0.60 per 1M tokens
      verifier: new ChatAnthropic({ model: 'claude-sonnet-4-5' }),  // $3/$15 per 1M tokens
      qualityThreshold: 0.8, // 80% queries use drafter
    });
    
    // Use like any LangChain chat model
    const result = await cascade.invoke('Explain quantum computing');
    
    // Optional: Enable LangSmith tracing (see https://smith.langchain.com)
    // Set LANGSMITH_API_KEY, LANGSMITH_PROJECT, LANGSMITH_TRACING=true
    
    // Or with LCEL chains
    const chain = prompt.pipe(cascade).pipe(new StringOutputParser());
    
    from langchain_openai import ChatOpenAI
    from langchain_anthropic import ChatAnthropic
    from cascadeflow.integrations.langchain import CascadeFlow
    
    cascade = CascadeFlow(
        drafter=ChatOpenAI(model="nous/hermes-flash"),      # $0.15/$0.60 per 1M tokens
        verifier=ChatAnthropic(model="claude-sonnet-4-5"),  # $3/$15 per 1M tokens
        quality_threshold=0.8,  # 80% queries use drafter
    )
    
    # Use like any LangChain chat model
    result = await cascade.ainvoke("Explain quantum computing")
    
    # Optional: Enable LangSmith tracing (see https://smith.langchain.com)
    # Set LANGSMITH_API_KEY, LANGSMITH_PROJECT, LANGSMITH_TRACING=true
    
    # Or with LCEL chains
    chain = prompt | cascade | StrOutputParser()
    

    Track costs, tokens, and cascade decisions with LangChain-compatible callbacks:

    from cascadeflow.integrations.langchain.langchain_callbacks import get_cascade_callback
    
    # Track costs similar to get_openai_callback()
    with get_cascade_callback() as cb:
        response = await cascade.ainvoke("What is Python?")
    
        print(f"Total cost: ${cb.total_cost:.6f}")
        print(f"Drafter cost: ${cb.drafter_cost:.6f}")
        print(f"Verifier cost: ${cb.verifier_cost:.6f}")
        print(f"Total tokens: {cb.total_tokens}")
        print(f"Successful requests: {cb.successful_requests}")
    

    Features:

    • 🎯 Compatible with get_openai_callback() pattern
    • 💰 Separate drafter/verifier cost tracking
    • 📊 Token usage (including streaming)
    • 🔄 Works with LangSmith tracing
    • ⚡ Near-zero overhead

    Full example: See langchain_cost_tracking.py

    For discovering optimal cascade pairs from your existing LangChain models, use the built-in discovery helpers:

    import {
      discoverCascadePairs,
      findBestCascadePair,
      analyzeModel,
      validateCascadePair
    } from '@cascadeflow/langchain';
    
    // Your existing LangChain models (configured with YOUR API keys)
    const myModels = [
      new ChatOpenAI({ model: 'gpt-3.5-turbo' }),
      new ChatOpenAI({ model: 'nous/hermes-flash' }),
      new ChatOpenAI({ model: 'gpt-4o' }),
      new ChatAnthropic({ model: 'claude-3-haiku' }),
      // ... any LangChain chat models
    ];
    
    // Quick: Find best cascade pair
    const best = findBestCascadePair(myModels);
    console.log(`Best pair: ${best.analysis.drafterModel} → ${best.analysis.verifierModel}`);
    console.log(`Estimated savings: ${best.estimatedSavings}%`);
    
    // Use it immediately
    const cascade = withCascade({
      drafter: best.drafter,
      verifier: best.verifier,
    });
    
    // Advanced: Discover all valid pairs
    const pairs = discoverCascadePairs(myModels, {
      minSavings: 50,              // Only pairs with ≥50% savings
      requireSameProvider: false,  // Allow cross-provider cascades
    });
    
    // Validate specific pair
    const validation = validateCascadePair(drafter, verifier);
    console.log(`Valid: ${validation.valid}`);
    console.log(`Warnings: ${validation.warnings}`);
    

    What you get:

    • 🔍 Automatic discovery of optimal cascade pairs from YOUR models
    • 💰 Estimated cost savings calculations
    • ⚠️ Validation warnings for misconfigured pairs
    • 📊 Model tier analysis (drafter vs verifier candidates)

    Full example: See model-discovery.ts

    Features:

    • ✅ Full LCEL support (pipes, sequences, batch)
    • ✅ Streaming with pre-routing
    • ✅ Tool calling and structured output
    • ✅ LangSmith cost tracking metadata
    • ✅ Cost tracking callbacks (Python)
    • ✅ Works with all LangChain features

    🦜 Learn more: LangChain Integration Guide | TypeScript Package | Python Examples


    Resources

    Examples

    Python Examples:

    ExampleDescriptionLink
    Basic UsageSimple cascade setup with OpenAI modelsView
    Preset UsageUse built-in presets for quick setupView
    Tool ExecutionFunction calling and tool usageView
    Streaming TextStream responses from cascade agentsView
    Cost TrackingTrack and analyze costs across queriesView
    Agentic Multi-AgentMulti-turn tool loops & agent-as-a-tool delegationView
    Multi-Step CascadeMulti-step agent loops with tool callsView
    ExampleDescriptionLink
    Budget EnforcementBudget caps with stop actions in enforce modeView
    User Budget TrackingPer-user budget enforcement and trackingView
    GuardrailsSafety and content guardrailsView
    Rate LimitingRate limiting for cascadesView
    User Profile UsageUser-specific routing and configurationsView
    Stripe IntegrationBilling integration with budget enforcementView
    ExampleDescriptionLink
    LangChain Harnesscascadeflow harness with LangChain callback handlerView
    OpenAI Agents Harnesscascadeflow harness with OpenAI Agents SDKView
    CrewAI Harnesscascadeflow harness with CrewAI hooksView
    PydanticAI Harnesscascadeflow cascade Model with PydanticAI agentsView
    Google ADK Harnesscascadeflow harness with Google ADK pluginView
    LangChain BasicSimple LangChain cascade setupView
    LangChain LCEL PipelineLCEL chains with cascade routingView
    LangGraph Multi-AgentLangGraph multi-agent orchestrationView
    ExampleDescriptionLink
    Production PatternsBest practices for production deploymentsView
    Multi-ProviderMix multiple AI providers in one cascadeView
    Reasoning ModelsUse reasoning models (o1/o3, Claude Sonnet 4, DeepSeek-R1)View
    Streaming ToolsStream tool calls and responsesView
    Batch ProcessingProcess multiple queries efficientlyView
    FastAPI IntegrationIntegrate cascades with FastAPIView
    Edge DeviceRun cascades on edge devices with local modelsView
    vLLM ExampleUse vLLM for local model deploymentView
    Multi-Instance OllamaRun draft/verifier on separate Ollama instancesView
    Custom CascadeBuild custom cascade strategiesView
    Custom ValidationImplement custom quality validatorsView
    Semantic Quality DetectionML-based domain and quality detectionView
    Cost ForecastingForecast costs and detect anomaliesView

    TypeScript Examples:

    ExampleDescriptionLink
    Basic UsageSimple cascade setup (Node.js)View
    Tool CallingFunction calling with tools (Node.js)View
    Multi-ProviderMix providers in TypeScript (Node.js)View
    Reasoning ModelsUse reasoning models (o1/o3, Claude Sonnet 4, DeepSeek-R1)View
    Cost TrackingTrack and analyze costs across queriesView
    Semantic QualityML-based semantic validation with embeddingsView
    StreamingStream responses in TypeScriptView
    Tool ExecutionTool execution engine and result handlingView
    Streaming ToolsStream tool calls with event detectionView
    Agentic Multi-AgentMulti-turn tool loops & multi-agent orchestrationView
    ExampleDescriptionLink
    Production PatternsProduction best practices (Node.js)View
    Multi-Instance OllamaRun draft/verifier on separate Ollama instancesView
    Multi-Instance vLLMRun draft/verifier on separate vLLM instancesView
    Browser/EdgeVercel Edge runtime exampleView
    LangChain BasicSimple LangChain cascade setupView
    LangChain Cross-ProviderHaiku → GPT-5 with PreRouterView
    LangChain LangSmithCost tracking with LangSmithView
    LangChain Cost TrackingCompare cascadeflow vs LangSmith cost trackingView
    LangGraph Multi-AgentLangGraph multi-agent orchestrationView
    LangChain Tool Risk GatingTool routing based on risk and complexityView

    📂 View All Python Examples → | View All TypeScript Examples →

    Documentation

    GuideDescriptionLink
    QuickstartGet started with cascadeflow in 5 minutesRead
    Providers GuideConfigure and use different AI providersRead
    Presets GuideUsing and creating custom presetsRead
    Streaming GuideStream responses from cascade agentsRead
    Tools GuideFunction calling and tool usageRead
    Cost TrackingTrack and analyze API costsRead
    Agentic PatternsTool loops, multi-agent, agent-as-a-tool delegationRead
    Agent HarnessBudget, compliance, KPI, and energy controlsRead
    Rollout GuidePlan your production rolloutRead
    GuideDescriptionLink
    Production GuideBest practices for production deploymentsRead
    Enterprise NetworkingProxy, TLS, and network configurationRead
    CustomizationCustom cascade strategies and validatorsRead
    ObservabilityTelemetry, logging, and privacy controlsRead
    LangChain IntegrationUse cascadeflow with LangChainRead
    OpenAI Agents SDKUse cascadeflow with OpenAI AgentsRead
    CrewAI IntegrationUse cascadeflow with CrewAIRead
    PydanticAI IntegrationCascade Model for PydanticAI agentsRead
    Google ADKUse cascadeflow with Google ADKRead
    Hermes AgentPer-skill, complexity, and topic-aware subagent routingRead
    n8n IntegrationUse cascadeflow in n8n workflowsRead
    Vercel AI SDKMiddleware for Vercel AI SDKRead

    📚 View All Documentation →


    Features

    FeatureBenefit
    🎯 Speculative CascadingTries cheap models first, escalates intelligently
    💰 40-85% Cost SavingsResearch-backed, proven in production
    ⚡ 2-10x FasterSmall models respond in <50ms vs 500-2000ms
    ⚡ Low LatencySub-2ms framework overhead, negligible performance impact
    🔄 Mix Any ProvidersOpenAI, Anthropic, Groq, Ollama, vLLM, Together + LiteLLM (optional) + LangChain integration
    👤 User Profile SystemPer-user budgets, tier-aware routing, enforcement callbacks
    ✅ Quality ValidationAutomatic checks + semantic similarity (optional ML, ~80MB, CPU)
    🎨 Cascading PoliciesDomain-specific pipelines, multi-step validation strategies
    🧠 Domain Understanding15 domains auto-detected (code, medical, legal, finance, math, etc.), routes to specialists
    🤖 Drafter/Validator Pattern20-60% savings for agent/tool systems
    🔧 Tool Calling SupportUniversal format, works across all providers
    📊 Cost TrackingBuilt-in analytics + OpenTelemetry export (vendor-neutral)
    🚀 3-Line IntegrationZero architecture changes needed
    🔁 Agent LoopsMulti-turn tool execution with automatic tool call, result, re-prompt cycles
    🧭 Hermes Agent RoutingPer-skill, task-complexity, and topic-aware subagent routing with observe-mode rollout
    📋 Message & Tool Call ListsFull conversation history with tool_calls and tool_call_id preservation across turns
    🪝 Hooks & CallbacksTelemetry callbacks, cost events, and streaming hooks for observability
    🏭 Production ReadyStreaming, batch processing, tool handling, reasoning model support, caching, error recovery, anomaly detection
    💳 Budget EnforcementPer-run and per-user budget caps with automatic stop actions when limits are exceeded
    🔒 Compliance GatingGDPR, HIPAA, PCI, and strict model allowlists — block non-compliant models before execution
    📊 KPI-Weighted RoutingInject business priorities (quality, cost, latency, energy) as weights into every model decision
    🌱 Energy TrackingDeterministic compute-intensity coefficients for carbon-aware AI operations
    🔍 Decision TracesFull per-step audit trail: action, reason, model, cost, budget state, enforcement status
    ⚙️ Harness Modesoff / observe / enforce — roll out safely with observe, then switch to enforce when ready

    License

    MIT © see LICENSE file.

    Free for commercial use. Attribution appreciated but not required.


    Contributing

    We ❤️ contributions!

    📝 Contributing Guide - Python & TypeScript development setup


    Recently Shipped

    • ✅ Agent Loops & Multi-Agent - Multi-turn tool execution, agent-as-a-tool delegation, LangGraph orchestration
    • ✅ Tool Execution Engine - Automatic tool call routing, parallel execution, risk gating
    • ✅ Hooks & Callbacks - Telemetry callbacks, cost events, streaming hooks for observability
    • ✅ Vercel AI SDK Integration - 17+ additional providers with automatic provider detection
    • ✅ OpenClaw Provider - Custom provider for OpenClaw deployments
    • ✅ Gateway Server - Drop-in OpenAI/Anthropic-compatible proxy endpoint
    • ✅ User Tier Management - Cost controls and limits per user tier with advanced routing
    • ✅ Semantic Quality Validators - Lightweight local quality scoring via FastEmbed
    • ✅ Code Complexity Detection - Dynamic cascading based on task complexity analysis
    • ✅ Domain Aware Cascading - ML-based semantic domain detection with per-domain routing

    Support


    Citation

    If you use cascadeflow in your research or project, please cite:

    @software{cascadeflow2025,
      author = {Lemony Inc., Sascha Buehrle and Contributors},
      title = {cascadeflow: Agent runtime intelligence layer for AI agent workflows},
      year = {2025},
      publisher = {GitHub},
      url = {https://github.com/lemony-ai/cascadeflow}
    }
    

    Ready to cut your AI costs by 40-85%?

    pip install cascadeflow
    
    npm install @cascadeflow/core
    

    Read the Docs • View Python Examples • View TypeScript Examples • Join Discussions


    About

    Built with ❤️ by Lemony Inc. and the cascadeflow Community

    One cascade. Hundreds of specialists.

    New York | Zurich

    ⭐ Star us on GitHub if cascadeflow helps you save money!