Observed since 20 Oct, 22:01 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
Intelligent LLM agent cost optimization runtime — per-run budget enforcement, semantic caching, model routing across 15 providers
Intelligent LLM Agent Cost Optimization Runtime
AgentFuse is a production-grade Python SDK that optimizes LLM costs through intelligent model routing, semantic caching, graduated budget enforcement, and unified observability across OpenAI, Anthropic, Google Gemini, DeepSeek, Mistral, and 15+ providers. Built with insights from LiteLLM, Portkey, and Helicone architectures, and backed by research from 8 academic papers.
AI agents burn money without warning. A stuck loop can cost $50 in 10 minutes. Retries on a failed call can triple your bill. There is no built-in way to enforce per-run budgets across LLM providers.
AgentFuse intercepts every LLM call with a two-tier semantic cache (Redis L1 exact-match + FAISS L2 vector similarity) achieving 87.5% hit rate, and enforces graduated budget policies that downgrade models, compress context, and terminate gracefully instead of burning your budget.
| Metric | Value |
|---|---|
| Cache hit rate | 87.5% on repeated and paraphrased prompts |
| Cost reduction | 71.8% ($0.24 vs $0.87 for same workload) |
| Model routing savings | Up to 85% via intelligent complexity routing (RouteLLM-inspired) |
| Tokens saved | 179,445 per 100 calls |
| Integration effort | 1 line of code (completion() gateway) |
| Test suite | 1099 unit tests, 93% core coverage |
| Models supported | 34 with hot-reloadable pricing (GPT-5, Claude Opus 4.6, Gemini 2.5 Pro) |
| Providers supported | 15 (OpenAI, Anthropic, Gemini, DeepSeek, Mistral, Groq, Together, xAI, Fireworks, OpenRouter, Ollama, vLLM, Azure, Bedrock, SiliconFlow) |
| Framework integrations | 8 (OpenAI, Anthropic, LangChain, CrewAI, OpenAI Agents SDK, LangGraph, MCP, Pydantic AI) |
| Production subsystems | 45 core modules (cache, budget, routing, retry, dedup, alerting, anomaly detection, predictive routing, prompt compression, tool cost tracking, conversation estimation, hierarchical budgets) |
pip install agentfuse-runtime
from agentfuse import completion
# One function for ANY provider — budget-enforced, cached, cost-tracked
response = completion(
model="gpt-4o",
messages=[{"role": "user", "content": "What is Python?"}],
budget_id="my_agent",
budget_usd=5.00,
)
# Works with ANY provider — just change the model name:
response = completion(model="claude-sonnet-4-6", messages=[...], budget_id="run_2", budget_usd=3.00)
response = completion(model="gemini-2.5-pro", messages=[...], budget_id="run_3", budget_usd=1.00)
response = completion(model="deepseek/deepseek-chat", messages=[...])
# Enable intelligent routing — sends simple queries to cheap models automatically:
response = completion(model="gpt-4o", messages=[...], auto_route=True)
Session API — all-in-one context manager (recommended):
from agentfuse import AgentSession
with AgentSession("my_agent", budget_usd=5.00) as session:
response = session.completion(messages=[{"role": "user", "content": "What is Python?"}])
session.record_tool_call("web_search", cost=0.01) # track tool costs too
receipt = session.get_receipt()
# {'total_cost_usd': 0.52, 'llm_cost_usd': 0.51, 'tool_cost_usd': 0.01, 'cache_hit_rate': 0.3, ...}
Check your spend (persists across restarts):
from agentfuse import get_spend_report
report = get_spend_report()
# {'total_usd': 4.52, 'by_model': {'gpt-4o': 3.1, 'claude-sonnet-4-6': 1.42}, ...}
Legacy monkey-patch API (still supported):
from agentfuse import wrap_openai
import openai
wrap_openai(budget_usd=5.00, run_id="my_agent")
# All subsequent openai.chat.completions.create() calls are now
# budget-enforced and semantically cached
┌──────────────────────────────────┐
│ AgentFuse Gateway │
│ completion() / acompletion() │
└───────────────┬──────────────────┘
│
┌───────────────▼──────────────────┐
│ 1. Kill Switch Check │
│ 2. Input Validation (fail-fast) │
│ 3. Deprecation Warning │
│ 4. Rate Limiting (GCRA) │
└───────────────┬──────────────────┘
│
┌───────────────▼──────────────────┐
│ 5. Request Optimization │
│ 6. Intelligent Model Routing │
│ (RouteLLM complexity-based) │
│ 7. Context Window Guard │
└───────────────┬──────────────────┘
│
┌────────────────────────────▼────────────────────────────┐
│ 8. Budget Check (Graduated) │
│ │
│ ┌────────┐ ┌───────────┐ ┌──────────┐ ┌────────────┐ │
│ │ 60% │ │ 80% │ │ 90% │ │ 100% │ │
│ │ Alert │ │ Downgrade │ │ Compress │ │ Terminate │ │
│ │ │ │ GPT-4o → │ │+ degrade │ │ graceful │ │
│ │ │ │ 4o-mini │ │ │ │ shutdown │ │
│ └────────┘ └───────────┘ └──────────┘ └────────────┘ │
└────────────────────────────┬────────────────────────────┘
│
┌────────────────────────────▼────────────────────────────┐
│ 9. Cache Lookup (Two-Tier) │
│ │
│ L1: Redis exact-match (SHA-256) → HIT? Return cached │
│ L2: FAISS semantic (768d, 0.90) → HIT? Return cached │
└────────────────────────────┬────────────────────────────┘
│ MISS
┌───────────────▼──────────────────┐
│ 10. Key Pool Selection │
│ 11. Request Deduplication │
└───────────────┬──────────────────┘
│
┌────────────────────────────▼────────────────────────────┐
│ 12. Provider API Call │
│ │
│ OpenAI · Anthropic · Gemini · DeepSeek · Mistral │
│ Groq · Together · xAI · Fireworks · OpenRouter │
│ Ollama · vLLM · Azure · Bedrock · SiliconFlow │
│ │
│ 13. Automatic Fallback on errors │
└────────────────────────────┬────────────────────────────┘
│
┌───────────────▼──────────────────┐
│ 14. Cost Recording (normalized) │
│ 15. Cost Alerts (webhook) │
│ 16. Anomaly Detection (EMA) │
│ 17. Prometheus + OTel spans │
│ 18. SpendLedger (JSONL) │
└───────────────┬──────────────────┘
│
┌───────────────▼──────────────────┐
│ 19. Response Validation │
│ (XSS, PII, security) │
│ 20. Cache Store │
│ (L1+L2, CacheAttack defense) │
└───────────────┬──────────────────┘
│
┌───────────────▼──────────────────┐
│ Response │
└──────────────────────────────────┘
Graduated Budget Policies:
asyncio.LockTTLCache when Redis is unavailableIndexFlatIP vector similarity search with redis/langcache-embed-v2 embeddings (768-dim, purpose-built for semantic caching), 2-5ms latencytemperature > 0.5 or side-effect tools (send_email, execute_trade, etc.) skip cache entirelysave_l2_index / load_l2_index)o200k_base, GPT-4/GPT-3.5 use cl100k_basetiktoken cl100k_base with safety margins — Anthropic 1.20x, Gemini 1.25x, Mistral 1.15x, DeepSeek/Llama 1.10x, Grok 1.15xlen(text) / 3.5) for unknown modelscached_input_cost() for provider cache discounts (Anthropic 90% off, DeepSeek 90% off)AGENTFUSE_REGISTRY_REFRESH_HOURS environment variableft:gpt-4o:org:name resolves to OpenAIlist_providers() to enumerate all configured providersclassify_error() across OpenAI, Anthropic, Google GenAI, and httpx exceptionsinsufficient_quota (429) is not retryable (billing issue, not rate limit)OverloadedError (529) is always retryableRetry-After header extraction from provider responsesagentfuse_retry() decorator with tenacity exponential backoffmask_api_key() for safe logging, validate_api_key_format() per providercheck_prompt_injection() flags known injection patternspip-audit on all dependencieseval(), exec(), subprocess, pickle in codebasecache_control markers on static system messages above model-specific thresholds| Framework | Integration | Cache Support |
|---|---|---|
| OpenAI | wrap_openai() monkey-patch | Full (intercept + return cached) |
| Anthropic | wrap_anthropic() monkey-patch | Full (intercept + return cached) |
| LangChain | AgentFuseChatModel (BaseChatModel wrapper) | Full (wrapper checks cache before delegating) |
| CrewAI | create_agentfuse_hooks() (before/after hooks) | Full (before hook blocks call on cache hit) |
| OpenAI Agents SDK | AgentFuseModel / AgentFuseModelProvider | Full (async cache check in get_response) |
| LangGraph | AgentFuseNode + budget_guard conditional edge | Full (node-level cost tracking + budget guard) |
| MCP | MCP tool server (budget_check, estimate_cost, spend_report, kill) | N/A (exposes budget tools to MCP clients) |
| Pydantic AI | wrap_pydantic_agent() wrapper | Full (cost tracking + budget enforcement) |
gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.model attributesstructlog JSON output with automatic OTel trace/span ID injection and Datadog dd.trace_id / dd.span_id correlationgen_ai_client_token_usage — histogram, tokens per operationgen_ai_client_operation_duration_seconds — histogram, latencyagentfuse_cache_hits_total / agentfuse_cache_lookups_total — counters by model and tieragentfuse_cost_usd_total — counter by model and provideragentfuse_cost_per_request_usd — histogram with buckets [0.0001 ... 10.0]agentfuse_budget_remaining_usd — gauge per budgetagentfuse_errors_total — counter by error type and provideragentfuse_model_fallbacks_total — counter by original and fallback modelNormalizedUsage dataclass across all providersinput_tokens excludes cached tokens — AgentFuse adds cache_read_input_tokens + cache_creation_input_tokens for correct totalcompletion_tokens already includes reasoning_tokens — no double-countingthoughts_token_count billed as output — added to candidates_token_countfrom agentfuse import wrap_openai
wrap_openai(budget_usd=5.00, run_id="my_agent")
from agentfuse import wrap_anthropic
wrap_anthropic(budget_usd=5.00, run_id="my_agent")
from agentfuse.integrations.langchain import AgentFuseChatModel
model = AgentFuseChatModel(inner=ChatOpenAI(), budget=5.00)
response = model.invoke([HumanMessage(content="Hello")])
from agentfuse.integrations.crewai import create_agentfuse_hooks
before_hook, after_hook = create_agentfuse_hooks(budget=5.00)
from agentfuse.integrations.openai_agents import AgentFuseModelProvider
provider = AgentFuseModelProvider(inner=your_provider, budget=5.00)
result = await Runner.run(agent, run_config=RunConfig(model_provider=provider))
from agentfuse.integrations.langgraph import AgentFuseNode, budget_guard
node = AgentFuseNode(my_llm_node, budget_id="graph_run", budget_usd=5.00)
graph.add_conditional_edges("llm_node", budget_guard("graph_run"))
from agentfuse.integrations.mcp import MCP_TOOLS, handle_mcp_tool_call
# Register AgentFuse tools with any MCP-compatible agent
# Tools: agentfuse_budget_check, agentfuse_estimate_cost,
# agentfuse_spend_report, agentfuse_kill
result = handle_mcp_tool_call("agentfuse_budget_check", {"run_id": "my_agent"})
from agentfuse.integrations.pydantic_ai import wrap_pydantic_agent
agent = wrap_pydantic_agent(my_agent, budget_usd=5.00)
from agentfuse import BudgetEngine, ModelPricingEngine, TokenCounterAdapter
engine = BudgetEngine("run_123", budget_usd=5.00, model="gpt-4o")
pricing = ModelPricingEngine()
tokenizer = TokenCounterAdapter()
messages = [{"role": "user", "content": "What is the capital of France?"}]
tokens = tokenizer.count_messages(messages, "gpt-4o")
estimated_cost = pricing.input_cost("gpt-4o", tokens)
result_messages, active_model = engine.check_and_act(estimated_cost, messages)
# active_model may be downgraded if budget is running low
| Feature | AgentFuse | AgentBudget | LiteLLM | Portkey |
|---|---|---|---|---|
| Per-run budget enforcement | Yes | Yes | No | No |
| Semantic caching (87.5% hit rate) | Yes | No | No | Basic |
| Two-tier cache (Redis + FAISS) | Yes | No | No | No |
| Cross-model contamination prevention | Yes | No | No | No |
| Mid-run model switching (at 80% budget) | Yes | No | No | No |
| Context compression (at 90% budget) | Yes | No | No | No |
| Graceful termination + partial results | Yes | No | No | No |
| Semantic loop detection | Yes | No | No | No |
| Retry storm prevention with model downgrade | Yes | No | Yes | Yes |
| Streaming cost abort | Yes | No | No | No |
| Auto Anthropic prompt caching | Yes | No | No | No |
| Unified error classifier (3+ providers) | Yes | No | Partial | No |
| Anthropic/Gemini overflow pricing | Yes | No | No | No |
| OTel GenAI spans + Prometheus metrics | Yes | No | Yes | Yes |
| Structured cost receipts (JSON) | Yes | No | Basic | Basic |
| Framework integrations (LangChain, CrewAI, OpenAI Agents, LangGraph, MCP, Pydantic AI) | Yes | No | Yes | Yes |
| Hot-reloadable model pricing (34 models) | Yes | No | Yes | No |
| Atomic Redis Lua budget enforcement | Yes | No | No | No |
| Provider-aware token counting (6 providers) | Yes | No | Partial | No |
| FAISS index persistence | Yes | No | No | No |
| Framework integrations (8 frameworks) | Yes | No | Yes | Yes |
| Provider support (15 providers) | Yes | No | Yes | Partial |
pip install agentfuse-runtime # Core (in-memory cache + budget)
pip install agentfuse-runtime[redis] # + Redis cache and budget store
pip install agentfuse-runtime[otel] # + OpenTelemetry tracing
pip install agentfuse-runtime[openai] # + OpenAI SDK
pip install agentfuse-runtime[anthropic] # + Anthropic SDK
pip install agentfuse-runtime[gemini] # + Google Gemini SDK
pip install agentfuse-runtime[langchain] # + LangChain Core
pip install agentfuse-runtime[all] # Everything
Requirements: Python 3.11+
agentfuse-runtimeAGENTFUSE_RATE_LIMIT_RPS) now works correctlyconfigure(output_guardrails=...) now properly sets module-level guardrailsacompletion() now has automatic fallback chain matching sync completion()asyncio.get_running_loop() (deprecated get_event_loop removed)stream_options for OpenAI usage trackingAgentSession async context manager (async with)examples/e2e_real_test.py)New Modules:
TwoTierCacheMiddleware — Redis L1 exact-match + FAISS L2 semantic search with redis/langcache-embed-v2ModelRegistry — hot-reloadable pricing for 22+ models with LiteLLM remote refreshProviderRouter — automatic provider detection and base URL routing for 12 providersRedisBudgetStore — atomic budget enforcement via Redis Lua scripts with microdollar precisionInMemoryBudgetStore / AsyncInMemoryBudgetStore — thread-safe budget stores with TTL and LRUNormalizedUsage / extract_usage() — unified token usage extraction across all providersclassify_error() / ClassifiedError — unified error classification with Retry-After extractionagentfuse_retry() — tenacity-based retry decorator with provider-aware predicateFramework Integrations (rebuilt):
AgentFuseChatModel — BaseChatModel wrapper (callbacks are observe-only and cannot return cached responses)create_agentfuse_hooks() — before/after hooks with side-channel cached response injectionAgentFuseModel / AgentFuseModelProvider — async Model interface with non-blocking cache storeBug Fixes:
o200k_base (was incorrectly using cl100k_base)ContextVar for per-run isolation (was using class-level locks causing serialization)classify_error() instead of string matching on exception nameswrap_openai() / wrap_anthropic()Pricing:
Quality:
py.typed marker for type checking supportwrap_openai(), wrap_anthropic() monkey-patchesgit clone https://github.com/vinaybudideti/agentfuse.git
cd agentfuse
pip install -e ".[all]"
pytest tests/unit/ -v
MIT
Built by @vinaybudideti
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 0.2.2 | 29 Mar 2026 | 16 |
This describes our collected data; it is not a security assessment.
Observed since 20 Oct, 22:01 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:dff244df71508b9979b80fc2091fc575093e26d396f125ea2bfa4b709f9d5c37