Baar-Core 在请求前实施本地预算硬限制的代理治理机制
Baar-Core 面向 LLM 代理的预执行治理,在请求到达服务商前于本地执行硬性预算与调用上限,并提供循环检测、输出超限策略、预算感知收尾与提示缓存计量,用于控制失控代理的调用成本。
# 巴尔-科雷 对LLM代理机的飞行前运行时间治理. 在当地执行硬执行限制——在请求到达提供者之前. **停止LLM API的通话发生前,不是发生后.** [](https://github.com/orvi2014/Baar-Core/actions/workflows/ci.yml) [](https://codecov.io/gh/orvi2014/Baar-Core) [](https://badge.fury.io/py/baar-core) [](https://pepy.tech/project/baar-core) [](https://github.com/orvi2014/Baar-Core/stargazers) [](https://www.python.org/downloads/) [](https://opensource.org/licenses/MIT) ```bash pip install baar-core ``` > 我留了个特工连锁店 > 醒来到一个 **$47 法案** ——20,000 GPT-4o 代号回答"几点了?"查询. > > 巴尔 -科雷本该阻止的 **$0.10**在第一次超龄之前 > 没有提出网络要求。 **$0花费.** ```python from baar import BAARRouter router = BAARRouter(budget=0.10) # hard cap: $0.10 total router.chat("What time is it?") # → cheap model, ~$0.0001 router.chat("Write a CUDA matmul kernel") # → capable model if budget allows # budget exhausted → raises BudgetExhausted, zero API calls made ``` > 84 – 94% 基准成本降低 – [参见基准](#benchmarks) ## 建造时间 - 在生产中部署自主制剂的小组 - SaaS 创建者给予用户 LLM 使用每个用户配额的访问权限 - 任何曾经(或担心)有离家出走代理人法案的人 ## 所有其他解决办法的问题 成本最高的工具 **田径在事后花费。** 账单已经大了,你就会得到警报。 LiteLLM的预算管理者,Portkey的费率限制,提供商花费警报——他们都告诉你发生了什么,他们不会阻止它中途飞行. 希利酮观察灾难 事后的波特凯利率限制 **巴尔阻止它。** **Baar-Core是一个当地的杀手。** 每次通话之前,它都会估算成本,如果剩余预算太低,就会产生例外. **当地** ——没有DNS的查询,没有TCP的连接,也没有消耗任何符号. 呼叫从不离开你的机器. ## 如何运作 ``` User task │ ▼ ┌─────────────────────────────────┐ │ Pre-flight budget check │ ← if estimated cost > remaining budget │ (local, zero network) │ raise BudgetExhausted immediately └────────────┬────────────────────┘ │ affordable ▼ ┌─────────────────────────────────┐ │ Semantic complexity router │ ← cheap LLM scores complexity 0.0–1.0 │ (gpt-4o-mini, ~$0.000015/call) │ └────────────┬────────────────────┘ │ ┌──────┴───────┐ │ │ simple complex │ │ ▼ ▼ Cheap model Budget check (fast, $) ├─ affordable → Capable model ($$$) └─ too close → Downgrade to cheap model ($) ``` 1. **飞行前检查** ——在任何网络呼叫之前,当地估计成本。如果请求会过度拍摄,则将取消请求。 2. **语义路线** ——一个快速,廉价的模型得分任务复杂度,不是关键词匹配——实际语义理解. 3. **预算的降级** 硬性任务会自动回到更便宜的模型 所以转弯还是会完成的 ## 快速启动 ```python from baar import BAARRouter, BudgetExhausted # Basic usage router = BAARRouter(budget=0.10) reply = router.chat("Explain recursion with a Python example") print(reply) print(f"Spent: ${router.spent:.5f} / Remaining: ${router.remaining:.5f}") # Multi-step with a report log = router.run([ "What is 42 * 17?", "Translate 'good morning' to Japanese", "Design a distributed rate-limiter for 100k RPS — include trade-offs", "Convert 72°F to Celsius", ]) log.print_report() # Async import asyncio async def main(): router = BAARRouter(budget=0.05) reply = await router.achat("Summarize the CAP theorem") print(reply) asyncio.run(main()) # Kill-switch in action router = BAARRouter(budget=0.00001) try: router.chat("Any prompt at all") except BudgetExhausted as e: print(f"Blocked before API call. Remaining: ${e.remaining:.6f}") # Zero network calls made. $0 spent. ``` 工作与任何 [LitelLM 支持的提供者](https://docs.litellm.ai/docs/providers):OpenAI,Anthropic,Groq,合力,Ollama,OpenRouter,Azure,等等. ## LangChain & LangGraph 集成 ```bash pip install baar-core[langchain] ``` **模式 1 — 在现有链条中添加 kill- switch** (零重构结果): ```python from baar import BAARRouter from baar.integrations.langchain import BaarCallbackHandler from langchain_openai import ChatOpenAI router = BAARRouter(budget=0.05) handler = BaarCallbackHandler(router) llm = ChatOpenAI(model="gpt-4o", callbacks=[handler]) chain = prompt | llm | StrOutputParser() # BudgetExhausted is raised before the API call when budget is too low ``` **图案 2 — BaarChatModel 作为滴入式 ChatModel** (全程+降级): ```python from baar.integrations.langchain import BaarChatModel router = BAARRouter(budget=0.10, small_model="gpt-4o-mini", big_model="gpt-4o") llm = BaarChatModel(router=router) chain = prompt | llm | StrOutputParser() # works anywhere ChatOpenAI would ``` **模式 3 — 具有预算保护的 LangGraph 剂**: ```python from langgraph.prebuilt import create_react_agent agent = create_react_agent(model=llm, tools=[...]) # every tool-call iteration is budget-checked before the LLM is invoked # BudgetExhausted stops the loop locally — no dangling API calls ``` 完整实例 : [langchain_guardrail .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/langchain_guardrail.py>) ## LangGraph 中间软件 `BaarMiddleware` 包装任何编译的LangGraph图,并在外环级执行硬限制——在单个节点执行之前. ```python from baar import BAARRouter from baar.integrations.langgraph import BaarMiddleware, StepLimitExceeded router = BAARRouter(budget=0.50) graph = workflow.compile() # your compiled LangGraph graph protected = BaarMiddleware( graph=graph, router=router, max_steps=10, # stop after 10 outer invocations max_budget=0.05, # block if less than $0.05 remaining recursion_limit=25, # injected into LangGraph config automatically ) try: result = protected.invoke({"messages": [...]}) print(f"Steps used: {protected.steps}/10") except StepLimitExceeded as e: print(f"Stopped at {e.steps}/{e.max_steps} steps") except BudgetExhausted as e: print(f"Budget gate: ${e.remaining:.6f} remaining") ``` 所有四种调用模式的工作 : `invoke`, `stream`, `ainvoke`, `astream`. 完整实例 : [langgraph_middleware .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/langgraph_middleware.py>) ## 工具执行守护符 `@baar_guard` 将任何工具功能——同步或async——用硬调用限制和预算门包裹起来. 与克劳德,OpenAI/Codex,LangChain,LangGraph,或Plain Python合作. AI从不知道守卫在那里. ```python from baar.integrations.tools import baar_guard, ToolCallLimitExceeded @baar_guard(router=router, max_calls=5, cost_per_call=0.001) def web_search(query: str) -> str: return search_api(query) @baar_guard(router=router, max_calls=3, min_budget=0.02) async def generate_image(prompt: str) -> str: return await image_api(prompt) ``` - `max_calls` ——每个会话硬调数限制. `None` = 无限. - `min_budget` - 如果 `router.remaining` 低于此阈值。 - `cost_per_call` - 从预算中扣除每笔固定数额 **成功( E)** 拨打电话 故障时不收费 在您的代理调度器中抓取限制例外, 所以 AI 得到一个可读错误而不是崩溃 : ```python try: result = web_search(query) except ToolCallLimitExceeded as e: result = f"Tool '{e.tool_name}' limit reached ({e.calls}/{e.max_calls})." except BudgetExhausted as e: result = f"Budget too low. Remaining: ${e.remaining:.6f}." ``` 与 OpenAI 编码器 CLI —— 设定 `openai_base_url = "http://localhost:8000/v1"` 输入 `~/.codex/config.toml` 以引导所有通过 Baar 的 Codex 调用。 全部实例: [tool_guard .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/tool_guard.py>) · [claude_tool_guard .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/claude_tool_guard.py>) · [openai_tool_guard .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/openai_tool_guard.py>) ## 循环检测 一旦钱没了,预算就停止了循环代理。 `LoopDetector` 在几通被浪费的电话后停止它。 它会注意每个工具的名称 。 **返回( E)**, 不只是它被叫, 所以一个重复一个电话 不断给出相同的答案 被停止 同一电话 正在取得进展(一个工作正在进行中) `queued → running → done`,则使用新光标进行搜索)。 ```python from baar import BAARRouter, LoopDetector, LoopDetected from baar.integrations.tools import baar_guard router = BAARRouter(budget=0.50) loops = LoopDetector(on_loop=lambda e: log.warning("possible loop: %s", e)) # one per run @baar_guard(router=router, loop_detector=loops) def web_search(query: str) -> str: return search_api(query) @baar_guard(router=router, loop_detector=loops) def read_file(path: str) -> str: return open(path).read() try: result = web_search(query) except LoopDetected as e: result = f"Stopped: '{e.tool_name}' {e.pattern} loop ({e.count}x). Try a different approach." ``` 它拒绝继续循环的电话 **在它运行之前**更早一点 **告诉模特儿**在第一次重复时, `baar_guard` 在工具的字符串结果中添加一个注释( Name`[baar] The tool 'web_search' has returned the same result 2 times… Change the arguments, use a different tool, or answer with what you already have.`),以及 `on_loop` 在实时基准中, 注释是最重要的: 模型在 19 中更改了 20 运行的航向, 而停止时却不告诉它比完全没有检测到更糟糕。 pass 。 `loop_nudge=False` 改为: `baar_guard` 使结果不受影响;非字符串结果永远不会改变。 三种模式: | 图案 | 拒绝时 | 默认 | |---|---|---| | `repeat` | 同一电话已返回同样的结果 N 次( 运行中的任何地点) | `max_repeats=2` (第3次相同的电话被拒绝) | | `error` | 相同的调用失败了, 与 N 次相同( 成功重排) | `max_error_repeats=3` | | `ping_pong` | 两个步骤交替进行,结果与N全周期相同 | `max_ping_pong=3` | - **等待不是循环 :** 短结果( QQ 200 字符) 表示 `running`, `pending`, `queued`, `in progress`, `processing`, `booting`, `starting`, `initializing`, `waiting` 或 时 间 `not ready` 从来不算,所以投票 一个工作没有停止。 `in_progress=re.compile(...)` 更改词; `in_progress=False` 数着呢 - `exempt_tools=["job_status"]` ——永远不要算作一个合法地多次归还同样东西的工具. - `ignore_args=["request_id", "timestamp"]` ——在任何深度都放弃多变的论据,然后再进行比较. - `normalize_result=fn` ——在散装前绘制结果图,例如,将它携带的时间戳降下来. - `loops.tighten()` ——总结代理人历史后,将每个阈值降低一个(总结大致为双倍循环,按DeLoop. - 不是框架用户吗? 调用 `loops.before(tool, args)` 财务报告和财务报告 `loops.after(tool, args, result=...)` (或 减) `error=exc`) 自己,你是谁? **它不能捕捉到的东西:** 一个循环,它重新表达自己每个步骤(新措辞,相同空结果),永远不会完全重复。为这些步骤保留一个运行的预算:两者一起停止了下面的eval中的每个循环,而不停止健康运行。 ### 循环 eval `python benchmarks/loop_eval.py` 重播180标签,定型代理跟踪(无API密钥):75循环(精确重复,错误重复,乒乓球,重复请求id,重写)和105健康运行被构建成类似循环(波浪,降级,限速重播,片状API失效或关闭,重读更改的文件,长研究). Loops运行到有东西阻止它们;运行预算大小在最长的健康运行之上. | 方法 | 抓获 | 虚假停止 | 中途被浪费的电话 | 浪费的$ | |---|---|---|---|---| | 探测器 | 80.0% | 0.0% | 2 | $15.16 | | 探测器+ 豁免 | 80.0% | 0.0% | 2 | $15.16 | | 探测器+预算 | 100.0% | 0.0% | 2 | $6.16 | | call_hash_only | 80.0% | 39.0% | 3 | $16.51 | | max_calls | 100.0% | 41.0% | 7 | $5.12 | | budget_only | 100.0% | 0.0% | 35 | $26.14 | `max_calls` 只有同时停止 41% 的健康运行(分页、长时间研究、不稳定的 API),才能少浪费钱。只统计调用而不看其结果,会停掉所有不稳定的 API 运行;而检测器一个都不会停,因为错误只有在连续出现时才会计数。 `detector+budget` 探测器外加一台$0.40 运行预算 6 - 相同`running` 投票不再停止,即使没有了 `exempt_tools` (它们都是14.3%在0.9之前的假站). Overhead大约是每个工具呼叫的10 μs. 头条为从1到50(100%被抓住,0%假站,中位数2被浪费的呼叫)的每个发电机种子保留头条. 分类结果: `python benchmarks/loop_eval.py`. ## MCP 服务器( Claude Code / cursor) `examples/mcp_server.py` 向任何MCP客户端曝光三个预算保障工具——客户端不需要API密钥. ```python # pip install baar-core mcp firecrawl-py from baar import BAARRouter from baar.integrations.tools import baar_guard router = BAARRouter(budget=0.10, use_llm_router=False) @baar_guard(router=router, max_calls=20, cost_per_call=0.001) async def web_search(query: str) -> str: ... @baar_guard(router=router, max_calls=10, min_budget=0.005) async def run_python(code: str) -> str: ... ``` 与Claude 代码登记——加入 `~/.claude/claude.json`: ```json { "mcpServers": { "baar": { "command": "python3", "args": ["/path/to/examples/mcp_server.py"], "env": { "BAAR_BUDGET": "0.10" } } } } ``` 克劳德代码会显示 `get_budget_status`, `web_search`,以及 `run_python` 每次通话都是按预算拨钱的——会话停止在顶点被击中时花费时间。 ## OpenAI 兼容的 HTTP 服务器(Vercel AI SDK,LlamaIndex,卷曲) ```bash pip install baar-core[vercel] ``` 环绕 BAAR 路透器 `/v1/chat/completions` endpoint – 任何OpenAI兼容客户端的工程都无需更改代码. ```python from baar import BAARRouter from baar.integrations.vercel import create_app import uvicorn router = BAARRouter(budget=0.10) app = create_app(router, api_key="your-secret") # api_key optional uvicorn.run(app, host="0.0.0.0", port=8000) ``` **Vercel AI SDK(TypeScript): 维基百科中的相关条目: 维基语录链接:名人名言 - 文学作品 - 谚语 - 电影对白 - 主题 - 主题 - 分类** ```typescript import { createOpenAI } from '@ai-sdk/openai'; import { streamText } from 'ai'; const baar = createOpenAI({ baseURL: 'http://localhost:8000/v1', apiKey: 'your-secret' }); const { textStream } = streamText({ model: baar('baar'), messages: [{ role: 'user', content: 'Hello!' }], }); ``` **LlamaIndex (蟒蛇语):** ```python # pip install llama-index-llms-openai from llama_index.llms.openai import OpenAI as LlamaOpenAI from llama_index.core import Settings llm = LlamaOpenAI( model="baar", api_base="http://localhost:8000/v1", api_key="your-secret", ) Settings.llm = llm # drop-in for any LlamaIndex agent, RAG pipeline, or query engine response = llm.complete("Explain the GIL in Python") ``` 预算错误作为标准HTTP代码表面—— `402` 当预算用完的时候, `422` 当值门拒绝任务时。在 SSE 流中发送流出错误,所以连接保持干净。 ## 现实世界实例 | 示例 | 使用大小写 | |---|---| | [langchain_guardrail .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/langchain_guardrail.py>) | LangChain调用处理器, BaarChatModel, LangGraph 代理 | | [langgraph_middleware .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/langgraph_middleware.py>) | BaarMiddleware : 台阶限制,预算门,星流 | | [tool_guard .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/tool_guard.py>) | @baar_guard: 呼叫限制,费用扣除,安全调度器 | | [claude_tool_guard .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/claude_tool_guard.py>) | 使用 Anthropic Claude 工具的 @baar_guard | | [openai_tool_guard .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/openai_tool_guard.py>) | @baar_guard与OpenAI/ 编码函数调用 | | [mcp_server .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/mcp_server.py>) | 用于 Claude 代码/ cursor 的 MCP 服务器 — 预算保障的 web_search & run_python | | [vercel_server .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/vercel_server.py>) | 用于 Vercel AI 的 HTTP 服务器 SDK, LlamaIndex, 卷曲 | | [fastapi_per_user_budget .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/fastapi_per_user_budget.py>) | SaaS:用户人均$0.10配额持SQLite恒定. | | [agent_loop .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/agent_loop.py>) | 自动代理循环, 优雅的预算停止 | | [流媒体.py](<https://github.com/orvi2014/Baar-Core/blob/main/examples/streaming.py>) | 以实时预算跟踪方式进行应对 | | [multi_tenant .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/multi_tenant.py>) | 并行的多用户预算隔离,配额报告 | | [basic_usage .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/basic_usage.py>) | 开始 | ## 多租户和每个用户的预算 给每个用户自己的硬配额——在当地执行,在重启过程中坚持,不需要代理或外部服务。 ```python from baar import BAARRouter, BudgetExhausted from baar.core.stores import SQLiteBudgetStore def router_for(user_id: str) -> BAARRouter: return BAARRouter( budget=0.10, store=SQLiteBudgetStore("budgets.db", namespace=user_id), ) # Alice and Bob share one database file — budgets are fully isolated alice = router_for("alice") bob = router_for("bob") alice.chat("Summarise this document") # deducted from Alice's $0.10 only bob.chat("Translate to French") # Bob's quota untouched ``` 命名空间隔离在存储层执行——一个用户耗尽配额不会影响另一个用户。同步写入跨线条 **和跨OS进程** (gunicorn/uvicorn工人)是安全的: `SQLiteBudgetStore` 使用 WAL 模式和 check-and-reserve 步骤的独家交易,消除了 TOCTOU 种族影响大多数多租户预算执行。 [追着许多工人跑](#running-on-many-workers-redis-or-postgresql). **SaaS模式——当用户配额用完后返回HTTP 402:** ```python @app.post("/chat") async def chat(req: ChatRequest): try: reply = await router_for(req.user_id).achat(req.message) except BudgetExhausted as e: raise HTTPException(status_code=402, detail={ "error": "quota_exhausted", "remaining_usd": e.remaining, }) return {"reply": reply} ``` 没有计费服务, 没有代理, 一个 SQLite 文件。 完整的例子 : [fastapi_per_user_budget .py (英语).](<https://github.com/orvi2014/Baar-Core/blob/main/examples/fastapi_per_user_budget.py>) **时间限制配额** - 范围预算,通过在命名空间中编码时段,直到一天或一个月: ```python import datetime period = datetime.date.today().strftime("%Y-%m") # "2026-05" store = SQLiteBudgetStore("budgets.db", namespace=f"user:{user_id}:{period}") # quota resets automatically next month — no cron job needed ``` **单进程脚本** ——JSON文件商店,不需要SQLite: ```python from baar.core.stores import FileBudgetStore router = BAARRouter(budget=1.00, store=FileBudgetStore("my_budget.json")) ``` ### 运行在很多工人身上(Redis或PostgreSQL). 当您的代理员运行在几台机器上时, 每个工人必须从同样的预算中提取。 把他们都指向一个 Redis 或 PostgreSQL 命名空间 : ```python from baar import BAARRouter, RedisBudgetStore, PostgresBudgetStore # pip install "baar-core[redis]" store = RedisBudgetStore("redis://cache:6379/0", namespace=f"tenant:{tenant_id}") # or: pip install "baar-core[postgres]" store = PostgresBudgetStore("postgresql://app@db/app", namespace=f"tenant:{tenant_id}") router = BAARRouter(budget=5.00, store=store, call_timeout=60) ``` - **不得加倍开销.** 支票和预订发生在服务器上的一步(Redis的Lua脚本,PostgreSQL的一排锁),因此两个工人永远不能同时拿走最后一美元. - **一个坠机的工人不会把预算锁上** 在每次通话之前,Baar保留了电话最坏的情况成本 *租赁*,如果工人中途死亡,则租约到期,资金又可用,过期时间由服务器的时钟计时,所以工人的时钟不需要同意. - **租约持续多久?** 默认为持续 `3 × call_timeout + 60` 秒(三次尝试加后退),或 15分钟,无 `call_timeout`。当块到达时,流线调用会更新它。设置( S) `lease_ttl=` 电话比租借时间长,如不及时挂断的连接,可能会失去对另一工人的预订,因此,预算可以被该电话的费用所超过。 `call_timeout`. - `router.reserved` (或 减) `router.budget_summary()["reserved"]`),显示目前航班中通话所持有的金额. `window=BudgetWindow.DAILY` 而其他的窗户则与两家商店一起工作. - `SQLiteBudgetStore` 使用同样的租赁,用于一台机器上的几个程序。 PostgreSQL 表格 (中文(简体) ).`baar_budget_spend`, `baar_budget_leases`)在第一次使用时创建。通过 a `psycopg_pool.ConnectionPool` 当许多线程共用一个商店时, 而不是一个 URL 。 ### 租户、团队和用户限制 一个跑步 `budget` 盖上一个代理运行。 `limits` 添加许多经营股份的上限,例如租户的每月开支或用户的每日津贴: ```python from baar import BAARRouter, BudgetExhausted, BudgetLimit, BudgetWindow, RedisBudgetStore store = RedisBudgetStore("redis://cache:6379/0", namespace=f"run:{run_id}") router = BAARRouter( budget=0.50, # this run store=store, limits=[ BudgetLimit("tenant:acme", 100.00, window=BudgetWindow.MONTHLY), BudgetLimit("team:acme/search", 30.00, window=BudgetWindow.MONTHLY), BudgetLimit("user:alice", 10.00, window=BudgetWindow.DAILY), ], ) try: router.chat("...") except BudgetExhausted as e: print(e.scope) # "user:alice" when her daily limit ran out; None for the run's own budget ``` - 只有在符合跑步预算的情况下才能打电话 **财务报告和财务报告** 费用全部由他们承担。 - 每个限制在路由器的商店里 以自己的名字,所以所有运行的名字 `"user:alice"` 共享一个允许 : 在 Redis, PostgreSQL , SQLite 或一个 JSON 文件, 以及一个进程路由器的内存。 pass 。 `BudgetLimit(..., store=...)` 以保持一个限制 其他地方。 - `router.remaining` 所以降级和降级对最紧的 反应。 `router.budget_summary()` 列出每个限制的预算、支出、持有额和剩余额,并列出最紧的 `binding_limit`. - 订房是各级的租约,所以一个崩溃的工人也会腾出房客和用户的钱. - 关卡被一个接一个地保留。 如果后关关拒绝, 前面的关卡会被立即放出, 所以没有关卡被超额消耗。 虽然这样, 数毫秒后, 可能因为即将放出的钱而拒绝再打一次电话 。 ## 基准 ### 确定成本基准——模拟模式 模拟模式运行全程管道,并模拟完成量度 **路由间接费用和费用分配** 使用这个来调和最低点 之前的直播。 > **说明:** 模拟模式中的精确数字反映了模拟任务响应,而不是真实的模型能力。使用实时模式进行精确度测量。成本数字和路由分割百分比是这里有意义的产出。 ```bash baar-bench --dataset all --limit 200 --budget 10 --mock \ --complexity-threshold 0.80 --coding-threshold 0.75 --seed 42 ``` | 数据集 | 战略 | % 路由到廉价 | 费用共计 | 储蓄总是很大 | | :--- | :--- | :---: | :---: | :---: | | **MMLU** | 总是大 | 0% | $1.0005 | — | | **MMLU** | **巴尔-科雷** | **81%** | **$0.157** | **84.3% 便宜点** | | **GSM8K** | 总是大 | 0% | $1.0005 | — | | **GSM8K** | **巴尔-科雷** | **87%** | **$0.129** | **87.1% 便宜点** | | **HumanEval** | 总是大 | 0% | $1.0005 | — | | **HumanEval** | **巴尔-科雷** | **39%** | **$0.614** | **38.6% 便宜点** | HumanEval向廉价阶梯的路径较少,因为编码问题得分复杂度很高——路由器正确识别出它们为硬. ### 直播基准——真实的API呼叫(每个数据集的10任务). ```bash baar-bench --dataset all --limit 10 --budget 2 \ --complexity-threshold 0.80 --coding-threshold 0.75 --seed 42 ``` | 数据集 | 战略 | 费用共计 | 储蓄总是很大 | | :--- | :--- | :---: | :---: | | **MMLU** | 总是大 | $0.002337 | — | | **MMLU** | **巴尔-科雷** | **$0.000137** | **94.1% 便宜点** | | **GSM8K** | 总是大 | $0.027615 | — | | **GSM8K** | **巴尔-科雷** | **$0.002097** | **92.4% 便宜点** | | **HumanEval** | 总是大 | $0.032125 | — | | **HumanEval** | **巴尔-科雷** | **$0.002743** | **91.5% 便宜点** | 自己开吧: `pip install baar-core datasets` 那样吧 `baar-bench --limit 10 --mock` (free)或添加您的 API 键以获取现场结果. ## v. 替代品 | | **巴尔-科雷** | RouteLLM | LiteLLM | 端口键 | |---|:---:|:---:|:---:|:---:| | 硬本地 kill- switch( 0 网络呼叫) | ✅ | ❌ | ❌ | ❌ | | 防止拒绝Wallet(OWASP LLM10:2025). | ✅ | ❌ | ❌ | ❌ | | 工程全线下线 | ✅ | ❌ | ❌ | ❌ | | 用户指定间距预算( 无代理) | QQLite/文件 | ❌ | ❌(需要代理) | ❌(仅云端) | | 跨程序TOCTOU安全保留 | ✅ | ❌ | ❌ | N/A | | LangGraph 步骤限制 + 预算中间软件 | ✅ | ❌ | ❌ | ❌ | | 工具执行守护符(@baar_guard). | ✅ | ❌ | ❌ | ❌ | | 语义复杂路由 | ✅ | ✅ | ✅ | ✅ | | 没有代理 / 不需要服务器 | ✅ | ✅ | ❌ | ❌ | | 开源( MIT ) | ✅ | ✅ | ✅ | ❌ | 关键区别: 每一条替代路线和轨道。 Baar-Core **防止** 例外是在一个字节离开你的机器之前提出的。 ## 产出限制 飞行前的检查覆盖了即时,但反应是成本可以跑掉的地方:一个长的答案,或者推理模型的隐藏思维符,成本可能比估计值还要高. `on_output_overrun` 确定Baar如何处理: ```python router = BAARRouter(budget=0.10, on_output_overrun="preflight", max_output_tokens=2000) # or per call router.chat("Write the full report", on_output_overrun="truncate") ``` | 模式 | 反应被切断了? | 预算过剩? | 行为 | |---|---|---|---| | `"estimate"` (默认) | 永远 | 可能 | 保留预期产出,与以前相同。 | | `"preflight"` | 永远 | 永远* | 在调用前保留最糟糕的输出。 如果调用不合适, 则降级到小模型或升级 。 `BudgetExhausted` 当地。 | | `"truncate"` | 只有您选择加入 | 永远* | 设定 `max_tokens` 降级第一;只有小模型的反应才能被切断,并标出 `truncated_by_budget=True`. | | `"continue"` | 只有钱用完了 | 永远* | 生成按 `segment_tokens` (2000),一次保留一个段;停止在极限的段继续("继续确切的你停止的地方"). 结束于模型完成时, `max_output_tokens` 达到(总数), `max_segments` (8)被击中,或者另一段无法支付费用——然后返回至今的文字,标记 `truncated_by_budget=True`. | | `"calibrated"` | 永远 | 每跑一次的概率为 {} | `preflight` 保留您记录的输出长度的四分位数, 且在您代理的真实运行( 低于) 上认证的四分位数 β 。 当没有认证时, 将回到最糟糕的状态 。 | \* 提示符号是一种估计值(精确到OpenAI文本; Claude、双子座、图像和工具图案的近似值),因此这些模式以一个20%边距( E)`prompt_margin=0.2`)一个比这个还小的比这个小的点数,还可以略微过量。 `preflight` 对自己最有用 `max_output_tokens`:如果没有一个,最糟糕的情况就是模型的全最大输出(16k + 符號),它阻断了接近预算末端的更多调用. 或让Baar学习: `overrun_risk=0.05` 保留这个模型的95%的响应所停留的长度(是最后一次500完成的呼叫的分门别类的量子),而不是最糟糕的情况. `max_tokens` 保留全部限制, 所以没有被切断; 最多只能通过预定的 5% 呼叫。 在一个模型完成 20 呼叫之前, 最坏的情况是保留。 共享路由器之间学到的东西 。 `output_lengths=OutputLengths()`。限制总是由模型上下文窗口中留下的房间封顶。您自己的 `max_output_tokens` 从未在模型的真正最大输出上方发送。 `truncate` 模式, `max_call_share=0.5` 停止一个呼叫 从保留 超过一半的剩下的, 所以并行的呼叫 接近顶部仍然通过。 ### 校准模式:每跑一次的保证,而不是每次呼叫一次 `overrun_risk=r` 每个边框 *电话* 分开,所以很多的电话 仍然可以超额使用 比 `r` (2 / 30运行于以下基准). `calibrated` 约束整个 *运行*: 选择容忍 QQ, Baar 选择保留多少产出, 这样您的代理商最多就会超额使用, 充满信心 1 — — — 。 校准一次您自己的工作量 : ```python from baar import BAARRouter, QuantileTable, ltt_select table = QuantileTable.from_records(logged_calls) # dicts with model, completion_tokens def run_batch(beta, n): # run n agent tasks with this beta, ... # return how many overspent res = ltt_select([0.01, 0.05, 0.1, 0.2, 0.3, 0.5], run_batch, n=1000, eps=0.05, delta=0.05) router = BAARRouter(budget=0.10, on_output_overrun="calibrated", output_quantiles=table, calibration_beta=res) ``` `ltt_select` 以精确的二元p值(Learn-when-Test)测试从大多数到最保守的水平,并在第一次测试时停止,它无法认证;如果无一经认证, `calibrated` 假设未来运行看起来像校准运行。 [B. 研究/研究/研究](<https://github.com/orvi2014/Baar-Core/blob/main/research/>). 内 `truncate` 模式中,大模型只有在其 *满* 响应符合,所以最大输出量非常大的模型(GPT-5, o系列)通常会降级,除非设置 `max_output_tokens`. **隐藏的推理。** `thinking_budget=4000` 限制推理模型的思维而不触及可见的答案: ```python router = BAARRouter.anthropic(budget=0.50, on_output_overrun="preflight", thinking_budget=4000, max_output_tokens=2000) ``` | 提供者(通过LiteLLM) | 巴尔送来的东西 | 硬限制? | |---|---|---| | 克劳德,双子座,DeepSeek | `thinking={"type": "enabled", "budget_tokens": 4000}`, `max_tokens` = 答题限制 + 4000 | 对——和 `max_output_tokens` 意思是说 **回复**所以,思考不能 进它 | | OpenAI 欧系列, GPT-5 | `reasoning_effort` (`low` < 4096 ≤ `medium` < 16384 ≤ `high`) | 没有——提示;最坏情况是保留不变 | | 其他模式 | 无 | — | 在克劳德身上,这也使 `preflight` 实用性:最糟糕的病例从模型的全64k – 128k输出符来回答 + 思维. `thinking_budget` 是 1024 (Anthropic 的地板) ; 设置为每个呼叫 `router.chat(..., thinking_budget=2048)`。这是从 *弹性原因* (arXiv 2505.05315):思考得到自己的预算,答案保留一个保留的预算. 流线调用记录提供者报告的使用情况,包括隐藏的推理符号。如果你早点停止读取流线,Baar会关闭流线,然后在 `preflight` / `truncate`,记录保留的输出,而不是只记录您读到的文本。值门(`value_fn`)比较任务的价值与它的价值。 *预期* 成本,不是最坏的情况 这些模式储备。 ### OverThink eval (英语). `python benchmarks/overthink_eval.py` 重放运行在 *OverThink* 攻击(arXiv 2502.02542):隐藏在模型所读内容中的诱饵 乘以其隐藏推理(X 10 – 这里的46,最高为x 46,而答案看起来正常. 150任务,30%中毒,一个$5.00预算,一个模拟的克劳德级推理模型($3 / $15 每百万个符号,64k 最大输出). Baar的真实定价和限制运行未修改;只有提供者是模拟的,它遵守了. `max_tokens` 与真实的API一样的思考预算。种子 7 : | 设置 | 完成( E) | 限量断绝 | 过度射击 | 使用的预算 | |---|---|---|---|---| | 仅提醒( 后 Hoc) | 51 | 0 | $0.2132 | 100.0% | | `estimate` (默认) | 51 | 0 | $0.2132 | 100.0% | | `preflight` | 35 | 0 | $0.0000 | 81.0% | | `preflight` + `thinking_budget=2048`, `max_output_tokens=2000` | 150 | 0 | $0.0000 | 72.3% | | `preflight` + `overrun_risk=0.05` | 40 | 0 | $0.0000 | 92.1% | | `truncate` | 51 | 1 | $0.0000 | 100.0% | 在种子1 上 – 30:在30 / 30 运行和默认情况下的后Hoc警告过度射击 `estimate` 在27 / 30(最高为$0.66)中. `preflight`, `preflight` + 思考和讨论 `truncate` 从不过度射击, `preflight` 从来没有切断一个答案。 `overrun_risk=0.05` 2 / 30 运行中的过度射击( 最高为 $0.16 ) —— 它接受的风险换取更多的预算使用. 抓取思维完成每一项任务, 因为有毒任务不再昂贵; 模拟假设答案不受上限的影响, 而真实的模型无法保证。 如果您期望有对抗性的内容, 请使用 `preflight` (或 减) `truncate`)并设置一个 `thinking_budget` 关于推理模型。 ### 从日志到一个命令中的证书 使用任一认证特性的最快方式: 让路由器记录整个运行, 然后运行 `baar-calibrate`. **1. 日志运行** 如果预算没有约束性(所以每次运行都显示成本),每运行一个路由器: ```python from baar import BAARRouter router = BAARRouter(budget=100.0, run_log_path="runs.jsonl") with router.recording_run() as run: ... # your agent loop: router.chat(...), router.record_event("tool_error") run.finished = True # the agent gave a final answer run.resolved = tests_pass # optional: was it correct? ``` **2. 认证** 它至少需要 QQln / IN( 1 – ε) QQ 校准运行( 59 at QQ = δ = 0.05 ) , 并告诉你, 如果您太少, 还要登录多少个 : ```bash baar-calibrate runs.jsonl --budget 0.50 --eps 0.05 # calibrated reservation level baar-calibrate runs.jsonl --budget 0.50 --eps 0.05 --early-stop \ --harm resolve --counter tool_error -o early_stop.json # certified early stopping ``` **3. 用这个**,并注意它一直坚持着: ```python from baar import BAARRouter, Certificate, GuaranteeMonitor cert = Certificate.load("baar_cert.json") monitor = GuaranteeMonitor.for_certificate(cert) # share one monitor across runs router = BAARRouter(budget=0.50, guarantee_monitor=monitor, **cert.router_kwargs()) ... router.finish_run(finished=True) # or use router.recording_run() ``` 监视器升起一个 `GuaranteeAlarm` 警告(或电话) `on_alarm`当直播运行显示其中超过QQ超时, 当代理、 提示或任务自校准后发生变化时, 就会发生超时。 它的测试是随时有效的 : 每次运行后检查会将假警报概率保持在下方 。 `alpha`。在 Python 中可使用相同的步骤。 `load_runs`, `certify_calibrated` 财务报告和财务报告 `certify_early_stop`. ### 认证提前停止 长期代理经营会破坏他们的预算,否则只有在钱没了时才会拒绝。 `EarlyStopPolicy` 检查固定检查站的运行情况,并在预计超过预算的下一次呼叫之前停止运行,并附有证书:最多停止了所有运行,尽管它们在预算范围内会完成运行(信心1 − )。由于完成运行的比例高于通常运行的比例。适合一组记录运行,认证另一套运行: ```python from baar import BAARRouter, fit_early_stop, calibrate_early_stop, RunStopped policy = fit_early_stop(train_runs, budget=5.0, counter_keys=["tool_error"]) policy = calibrate_early_stop(policy, calibration_runs, eps=0.05, delta=0.05) router = BAARRouter(budget=5.0, early_stop=policy) router.record_event("tool_error") # report behaviour as the run goes; RunStopped ends the run early ``` 打开3,000实际编码代理运行, at QQ =0.05此已保存11–23%当受保护的运行是能够完成任务的运行时,所有开支中(`harm="resolve"`),以及4.5–16%当保护每一个会完成的运行时( Q)`harm="finish"`,默认值),视预算的紧缺程度而定。在校准运行上安装与校准运行脱节的运行模式,并在校准运行前固定预算;保证假设未来运行看起来像校准运行。 [B. 研究/研究/研究](<https://github.com/orvi2014/Baar-Core/blob/main/research/>). ## 预算意识和收尾 单是杀手就阻止了特工的中途任务,没有显示所花的钱。Baar也可以让特工知道。 *看见了* (BATS, arXiv 2511.17006: 预算状况短促, 每一步都让代理商支出更好, 没有培训) ```python from baar import BAARRouter, WindDown, BudgetExhausted router = BAARRouter( budget=1.00, budget_awareness=True, # or a formatter: lambda status: "..." wind_down=WindDown(at=0.9, reserve=0.05), # final call past 90% used / 5% left ) try: while True: reply = router.chat(next_step()) except BudgetExhausted as e: answer = e.partial_result # the final, wrapped-up answer ``` - `router.budget_status()` → `BudgetStatus(total, spent, remaining, utilization, calls, avg_call_cost, calls_left, winding_down)`. LangChain's `BaarChatModel`, CrewAI's `BaarCrewLLM` 和 LangGraph 's 的密码 `BaarMiddleware` 曝光为 `.budget_status`. - `budget_awareness=True` 添加 `[budget] $0.3200 of $1.00 used (32%) · ~17 calls left at the current rate` 至每个电话的结尾 **上一个用户消息** ——不是系统提示,所以缓存的提示前缀保持不变. - `WindDown`: 一旦达到利用率 `at`,或仅此 `reserve` 预算左侧,下一个呼叫是 **最终** 其一,它包含一个总结性说明(A/CN.9/WG.III/WP.18)。`instruction=` 改变它。 `BudgetExhausted` 本地的答案为: `.partial_result`,直到预算重设或新窗口启动。 `reserve` 决定 *何时* 它不会从之前的电话中扣钱 所以用它配对 `on_output_overrun="preflight"` 如果最后的通话不能过度。 - 政策: `Rule(when={"utilization": ">= 0.8", "plan": "free"}, then="wrap_up")` 给最后一个打电话。 ## 快速缓存 提供商开出一个快速的前缀,他们最近看到折扣(OpenAI和DeepSeek自动,Anthropic与) `cache_control`,双子座隐含的)——在一个每条提示中大多数都是的代理环. Baar读取了缓存的代号,每个调用报告(英语:`StepResult.cached_prompt_tokens`),以缓存速率记录流,并报告命中速率(`log.summary()["cache_hit_rate_pct"]`中,并在 `print_report()`) 保留保留仍然使用未标价,因此缓存永远不会削弱预算保证. **当切换模型将缓存丢弃时, 路由是否仍然支付费用 ?** `python benchmarks/cache_eval.py` 重播 24 对话 × 12 与 2k – 80k – token 上下文,真实的 gpt-5 / gpt-5 - mini 定价, 以及像 OpenAI (每个型号,前缀 ~ 1024 令牌) 这样的缓存提供者. 30% 转弯很硬. 种子 7: | 设置 | 费用 | 从缓存中提示符号 | 型号开关 | |---|---|---|---| | 总是gpt-5 | $3.1976 | 91.1% | 0 | | BAR 径路 | $2.2029 | 82.5% | 110 | 运行保存31%即使在缓存损失之后:每个模型都保留自己的缓存,以及gpt-5-米尼已经到了5× 每行价格更便宜(输入,缓存输入和输出). 我们还尝试了"粘着"的路由——保持一个轻松的开关.gpt-5当其缓存前缀制作时 *转弯* 更便宜的——而且总体成本更高($2.34):重建小模型的缓存一旦在一两个转弯内支付自己,而一个转弯规则是看不到的,所以Baar不提供. ## 警卫 Baar-Core 地图到 [OWASP LLM10:2025 — 无限制消费.](https://owasp.org/www-project-top-10-for-llm-applications-2/). 飞行前的杀人开关是对拒绝Wallet攻击的直接缓解:即使对手手艺迅速触发昂贵的模型呼叫,当地预算上限在供应商提出要求之前就抓住了它。 细节 : [RESEARCH . md (英语).](https://github.com/orvi2014/Baar-Core/blob/main/RESEARCH.md) ## 配置 ```python router = BAARRouter( budget=0.10, # hard cap in USD small_model="gpt-4o-mini", # cheap tier (any LiteLLM model) big_model="gpt-4o", # capable tier complexity_threshold=0.80, # 0.0–1.0: higher = more traffic to cheap model min_cost_threshold=0.0001, # kill-switch floor — reject if any call costs more routing_task_char_limit=500, # chars sent to routing LLM (head+mid+tail sample) use_llm_router=True, # False = rule-based heuristic only (no routing cost) small_fallback_models=["gpt-4o-mini-2024-07-18"], # failover chain big_fallback_models=["gpt-4o-2024-08-06"], telemetry_jsonl_path="telemetry.jsonl", # optional audit log ) ``` **预算压力** 随着支出接近上限,有效的复杂性阈值会自动上升。大模型在运行低迷时变得更难证明合理性,因此,流量会更多地自然地转向廉价。 **遥测** 检查支出、路由分割和拒收费率: ```bash baar-telemetry telemetry.jsonl ``` **复原能力测试** 对抗性假设(复杂游戏、预算紧张、固定攻击): ```bash baar-stress ``` ## 许可证 **MIT** — [LICENSE](https://github.com/orvi2014/Baar-Core/blob/main/LICENSE)
查看原始来源