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…

Что это такое?Открытая in-process библиотека (каскадный рантайм) для ИИ-агентов: она встроена в цикл выполнения агента и оптимизирует каждый вызов модели по стоимости, задержке, качеству, бюджету, комплаенсу и энергопотреблению.
Так это прокси перед моими вызовами к LLM или библиотека внутри кода агента?Это библиотека, которая работает внутри кода вашего агента, а не HTTP-прокси: прокси видит только границы запросов, а cascadeflow — границы принятия решений (вызовы моделей, вызовы инструментов, передача задач субагентам), и даёт накладные расходы меньше 5 мс вместо 40–60 мс задержки прокси.
Как подключить её к агенту, который у меня уже есть?Установите пакет для Python или TypeScript и оберните своего агента — Harness API предлагает три уровня интеграции: от наблюдаемости без единого изменения кода до агентов с декораторами и полным контролем политик.
С какими агентскими фреймворками и провайдерами моделей она работает?Она нейтральна к фреймворкам и провайдерам: 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% запросов.
Это не избыточно для простого чат-бота? Кому это вообще нужно?Она рассчитана на команды, которые выводят агентов в продакшен: в README названы инженерия, финансы, безопасность, эксплуатации и устойчивое развитие, потому что она одновременно оптимизирует стоимость, задержку, качество, бюджет, комплаенс/риски и энергопотребление.
Как она решает, когда переключиться на модель побольше?Спекулятивное выполнение с проверкой качества: сначала запускается небольшая быстрая модель ($0,15–0,30 за 1 млн токенов), ответ сверяется с настраиваемыми порогами (полнота, уверенность, корректность), и только при провале проверки запрос уходит более крупной модели ($1,25–3,00 за 1 млн токенов). На практике 60–70% запросов никогда не требуют эскалации.
Какие результаты она вообще показывает?В README заявлено снижение затрат на 40–85% и ускорение ответов в 2–10 раз без потери качества, плюс экономия на бенчмарках: 69% на MT-Bench, 93% на GSM8K, 52% на MMLU и 80% на TruthfulQA при сохранении 96% качества GPT-5.
Она может вмешиваться по ходу работы, а не просто замерять?Да — она управляет исходом с помощью четырёх действий в рантайме: allow, switchmodel, denytool и stop, исходя из текущего контекста и состояния политик. Каждое решение можно отследить и атрибутировать, что важно для регулируемых или ответственных рабочих процессов.
Со временем она становится умнее?Да — поскольку она работает внутри цикла, она накапливает знания из каждого вызова модели, результата инструмента, оценки качества и решения о маршрутизации, учится, какие модели лучше справляются с какими задачами, и подстраивает маршрутизацию без ручной настройки.
А локальные модели можно использовать, чтобы сэкономить ещё больше?Да — она может обрабатывать большинство запросов локальными моделями (vLLM, Ollama) и автоматически эскалирует к облачным провайдерам только сложные запросы. В README отмечается, что SLM меньше 10B параметров достаточно мощны для 60–70% агентных задач.
Что за интеграция с Hermes Agent?Недавнее дополнение: каскадирование моделей на уровне каждого скилла, каскадирование по сложности задачи, каскадирование субагентов с учётом темы и плавное включение в режиме observe для Hermes Agent — без перехвата учётных данных провайдеров, базовых URL, цепочек фолбэков или режимов API.
Creator
lemony-ai
Size
32.1 MB
Stars
3.9K
Age
11mo
Commits · 90 Days