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)

n8n
Searching Database…

What is this?An open-source in-process intelligence layer (cascading runtime) for AI agents: it sits inside the agent execution loop and optimizes every model call for cost, latency, quality, budget, compliance, and energy.
So is this a proxy in front of my LLM calls, or a library inside my agent code?A library you run inside your agent code, not an HTTP proxy: proxies only see request boundaries, cascadeflow sees decision boundaries (model calls, tool calls, sub-agent handoffs), and it adds sub-5ms overhead instead of 40-60ms of proxy RTT.
How do I wire it into an agent I already have?Install the Python or TypeScript package and wrap your agent — the Harness API offers three integration tiers, from zero-change observability (no code changes) up to decorated agents with full policy control.
Which agent frameworks and model providers does it work with?Framework- and provider-neutral: LangChain, OpenAI Agents SDK, CrewAI, PydanticAI, Google ADK, n8n, Vercel AI SDK, Hermes Agent, and custom frameworks, with a unified API across OpenAI, Anthropic, Groq, Ollama, vLLM, Together, and more (17+ providers).
Are there any gotchas before I try it, like with GPT-5?GPT-5 streaming requires organization verification (~15 min); non-streaming works for everyone, and GPT-5 is only called when needed anyway — typically 20-30% of requests.
Is this overkill for a simple chatbot, or who actually needs it?It targets teams running production agents: the README names engineering, finance, security, operations, and sustainability stakeholders, since it optimizes cost, latency, quality, budget, compliance/risk, and energy simultaneously.
How does it decide when to escalate to a bigger model?Speculative execution with quality validation: it runs a small, fast model first ($0.15-0.30/1M tokens), checks the response against configurable thresholds (completeness, confidence, correctness), and escalates to a larger model ($1.25-3.00/1M tokens) only when validation fails. In practice 60-70% of queries never need escalation.
What results does it actually report?The README claims 40-85% cost reduction and 2-10x faster responses with zero quality loss, plus benchmark savings of 69% on MT-Bench, 93% on GSM8K, 52% on MMLU and 80% on TruthfulQA while retaining 96% of GPT-5 quality.
Can it enforce decisions mid-run, not just measure them?Yes — it steers outcomes with four runtime actions: allow, switchmodel, denytool, and stop, based on current context and policy state. Every decision is traceable and attributable, which matters for regulated or high-stakes workflows.
Does it get smarter the longer it runs?Yes — because it runs inside the loop, it accumulates insight from every model call, tool result, quality score, and routing decision, learning which models perform best for which tasks and adapting routing without manual tuning.
Can it use local models to save even more?Yes — it can handle most queries with local models (vLLM, Ollama) and automatically escalate only complex queries to cloud providers. The README notes SLMs under 10B parameters are powerful enough for 60-70% of agentic AI tasks.
What is the Hermes Agent integration about?A recent addition: per-skill model cascading, task-complexity cascading, topic-aware subagent cascading, and observe-mode rollout for Hermes Agent — without taking over provider credentials, base URLs, fallback chains, or API modes.
Creator
lemony-ai
Size
32.1 MB
Stars
3.9K
Age
11mo
Commits · 90 Days