cascadeflow README

The project's README from github.com/lemony-ai/cascadeflow. As one markdown file: README.md.

cascadeflow Logo

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 Python • TypeScript TypeScript • LangChain LangChain • OpenAI OpenAI Agents • CrewAI CrewAI • PydanticAI PydanticAI • Google ADK Google ADK • n8n n8n • Vercel AI Vercel AI • OpenClaw 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

Dimension External Proxy cascadeflow Harness
Scope HTTP request boundary Inside agent execution loop
Dimensions Cost only Cost + quality + latency + budget + compliance + energy
Latency overhead 10-50ms network RTT <5ms in-process
Business logic None KPI weights and targets
Enforcement None (observe only) stop, deny_tool, switch_model
Auditability Request logs Per-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.

Use Cases
  • 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 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}")
💡 Optional: Use ML-based Semantic Quality Validation

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 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}%`);
💡 Optional: ML-based Semantic Quality Validation

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 valida

cascadeflow (lemony-ai/cascadeflow)

Searching Database…

这是什么?一个开源的进程内智能层(级联运行时),面向 AI agent:它位于 agent 执行循环内部,从成本、延迟、质量、预算、合规和能耗各方面优化每一次模型调用。
那它是放在我 LLM 调用前面的代理,还是嵌在我 agent 代码里的库?是运行在你 agent 代码里的库,不是 HTTP 代理:代理只能看到请求边界,而 cascadeflow 能看到决策边界(模型调用、工具调用、子 agent 交接),并且只增加不到 5 毫秒的开销,而不是代理 40-60 毫秒的往返延迟。
怎么把它接进我已有的 agent?安装 Python 或 TypeScript 包并包装你的 agent——Harness API 提供三个集成层级,从零改动的可观测性(不改任何代码)一直到带装饰器的 agent,可以完全掌控策略。
它支持哪些 agent 框架和模型提供商?框架和提供商中立:支持 LangChain、OpenAI Agents SDK、CrewAI、PydanticAI、Google ADK、n8n、Vercel AI SDK、Hermes Agent 以及自定义框架,通过统一 API 覆盖 OpenAI、Anthropic、Groq、Ollama、vLLM、Together 等更多提供商(17 家以上)。
在试用之前有什么坑吗,比如 GPT-5 相关的?GPT-5 的流式输出需要组织验证(约 15 分钟);非流式对所有人都可用,而且反正 GPT-5 只在需要时才被调用——通常只占 20-30% 的请求。
对一个简单的聊天机器人来说这是不是杀鸡用牛刀?到底谁需要它?它面向在生产环境运行 agent 的团队:README 提到了工程、财务、安全、运维和可持续发展等利益相关方,因为它同时优化成本、延迟、质量、预算、合规/风险和能耗。
它怎么决定什么时候升级到更大的模型?采用投机执行加质量校验:先用一个小而快的模型跑(每百万 token 0.15-0.30 美元),根据可配置的阈值(完整性、置信度、正确性)检查响应,只有校验不通过时才升级到更大的模型(每百万 token 1.25-3.00 美元)。实际使用中 60-70% 的查询根本不需要升级。
它实际报告哪些效果?README 宣称在零质量损失的情况下,成本降低 40-85%,响应最快提升 10 倍(2-10 倍);基准测试方面,MT-Bench 节省 69%、GSM8K 节省 93%、MMLU 节省 52%、TruthfulQA 节省 80%,同时保留 GPT-5 的 96% 质量。
它能在运行中途强制执行决策,而不只是做度量吗?可以——它通过四种运行时动作来引导结果:allow、switchmodel、denytool 和 stop,依据当前的上下文和策略状态。每个决策都可追踪、可归因,这对受监管或高风险的工作流很重要。
它运行得越久会越聪明吗?会——因为它运行在循环内部,能从每一次模型调用、工具结果、质量评分和路由决策中积累洞见,学会哪些模型最适合哪类任务,无需人工调优就能自适应路由。
它能用本地模型进一步省钱吗?可以——它能用本地模型(vLLM、Ollama)处理大部分查询,只把复杂查询自动升级到云厂商。README 指出,参数量在 10B 以下的小语言模型足以胜任 60-70% 的 agentic AI 任务。
Hermes Agent 的集成是怎么回事?这是新加入的功能:为 Hermes Agent 提供按技能的模型级联、按任务复杂度的级联、按主题感知的子 agent 级联,以及观察模式的灰度上线——同时不会接管提供商凭证、base URL、回退链或 API 模式。
Creator
lemony-ai
Size
32.1 MB
Stars
3.9K
Age
11mo
Commits · 90 Days