为AI代理调用设置美元预算上限的拦截方案
shekel 是一个 Python 库,通过拦截 OpenAI 与 Anthropic 的调用入口来统计花费,并在达到设定的美元上限时中止代理运行。它支持上下文管理器、装饰器和命令行三种用法,并可将成本指标导出到 Langfuse 与 OpenTelemetry。
# 谢克尔 **阻止你的AI代理 破产你。** [](https://pypi.org/project/shekel/) [](https://pypi.org/project/shekel/) [](https://github.com/arieradle/shekel/actions/workflows/ci.yml) [](https://codecov.io/gh/arieradle/shekel) [](https://pypi.org/project/shekel/) [](https://pypi.org/project/shekel/) [](https://github.com/arieradle/shekel/stargazers) [](https://arieradle.github.io/shekel/latest/) ```python with budget(max_usd=5.00): run_my_agent() # hard stop at $5. no SDK changes. no config. just works. ``` ```python with budget(max_usd=5.00, loop_guard=True, max_velocity="$1/min"): run_my_agent() # also stops infinite loops and bursty burn ``` ```bash shekel run agent.py --budget 5 # or enforce without touching code at all ``` --- 我醒来时 **$47 OpenAI 法案** 调自 aLangGraph我建了Shekel 这样你就不用自己学了 --- ## 安装 ```bash pip install shekel[openai] # OpenAI pip install shekel[anthropic] # Anthropic pip install shekel[all] # OpenAI + Anthropic + LiteLLM + Gemini + HuggingFace pip install shekel[cli] # shekel run — enforce budgets without touching code ``` --- ## 什么都行,都行,都行,都行,都行 如果它叫OpenAI或Anthropic 在引擎盖下,谢克尔看到它—— **零集成代码需要。** | 供应商 | 框架 | | |---|---|---| | OpenAI • 双子座 | LangChain · LangGraph | 自动标注 | | HuggingFace ^ LiteLLM 格罗克 | - CrewAI - OpenAI 特工 SDK | 自动标注 | | MCP · AutoGen · LlamaIndex | 任意自定义包装 | 自动标注 | | — | AutoGen(每剂盖) | `b.agent("name", max_usd=X)` | | — | OpenAI 代理 SDK (每代理机盖) | `b.agent("name", max_usd=X)` | --- ## 所有你实际使用的图案 ### 硬帽 - 救你的那个 ```python from shekel import budget with budget(max_usd=5.00): run_my_agent() # raises BudgetExceededError the moment spend crosses $5 ``` 没有包装您的 OpenAI 客户端。 没有装饰器 。 没有 SDK 替换 。 Shekel 猴子按住上下文条目, 并在退出时恢复它 。 您现有的代码运行不变 。 ### 在限值命中前警告 ```python with budget(max_usd=5.00, warn_at=0.8) as b: run_my_agent() # logs a warning at $4.00, raises at $5.00 ``` ### 不执行的音轨支出 ```python with budget() as b: run_my_agent() print(f"that cost ${b.spent:.4f}") ``` ### 切换到更便宜的模型,而不是崩溃 ```python with budget(max_usd=1.00, fallback={"at_pct": 0.8, "model": "gpt-4o-mini"}) as b: run_my_agent() # switches gpt-4o → gpt-4o-mini at $0.80, hard stops at $1.00 ``` ### Cap 工具调用——停止无限搜索循环 ```python from shekel import tool @tool(price=0.01) # charge $0.01 per call + count toward the cap def web_search(query: str) -> str: ... @tool # free — just count calls def read_file(path: str) -> str: ... with budget(max_usd=5.00, max_tool_calls=20) as b: run_my_agent() # ToolBudgetExceededError on call 21 — before the tool runs print(b.summary()) # LLM spend + tool spend broken out by tool name ``` 以零配置自动截取 : **LangChain, MCP, CrewAI, OpenAI 特工 SDK**. ### 每阶段预算控制 ```python with budget(max_usd=10.00, name="pipeline") as pipeline: with budget(max_usd=2.00, name="research"): results = search_web(query) # capped at $2 with budget(max_usd=5.00, name="analysis"): report = analyze(results) # capped at $5 print(pipeline.tree()) # pipeline: $4.80 / $10.00 # research: $1.20 / $2.00 # analysis: $3.60 / $5.00 ``` 孩子们自动盖到父母的剩余余额。 `b.tree()` 让你的视觉崩溃。 ### LangGraph——每个节点断路 ```python with budget(max_usd=10.00, name="graph") as b: b.node("fetch_data", max_usd=0.50) # NodeBudgetExceededError before node runs b.node("summarize", max_usd=1.00) app = graph.compile() app.invoke({"query": "..."}) print(b.tree()) # graph: $0.84 / $10.00 # [node] fetch_data: $0.12 / $0.50 (24%) # [node] summarize: $0.72 / $1.00 (72%) ``` 谢克尔补丁 `StateGraph.add_node()` 透明——不需要图表变化. ### LangChain——每链路断裂 ```python with budget(max_usd=5.00, name="pipeline") as b: b.chain("retriever", max_usd=0.20) # ChainBudgetExceededError before chain runs b.chain("summarizer", max_usd=1.00) retriever_chain.invoke({"query": "..."}) summarizer_chain.invoke({"doc": "..."}) ``` 谢克尔补丁 `Runnable._call_with_config` 财务报告和财务报告 `RunnableSequence.invoke` - 你的链子零变化。 ### CrewAI——每名特工和每任务断路 ```python from shekel.exceptions import AgentBudgetExceededError, TaskBudgetExceededError try: with budget(max_usd=5.00, name="crew") as b: b.agent(researcher.role, max_usd=2.00) # use agent.role directly b.agent(writer.role, max_usd=1.00) b.task(research_task.name, max_usd=1.50) # use task.name directly b.task(write_task.name, max_usd=0.80) crew.kickoff(inputs={"topic": "AI"}) except TaskBudgetExceededError as e: print(f"Task '{e.task_name}' over budget: ${e.spent:.4f} / ${e.limit:.2f}") except AgentBudgetExceededError as e: print(f"Agent '{e.agent_name}' over budget") print(b.tree()) # crew: $2.84 / $5.00 # [agent] Senior Researcher: $1.92 / $2.00 (96.0%) # [agent] Content Writer: $0.92 / $1.00 (92.0%) # [task] research: $1.92 / $1.50 (128.0%) # [task] write: $0.92 / $0.80 (115.0%) ``` 谢克尔补丁 `Agent.execute_task` 透明 门阶:任务上限 ~代理上限 ~ 全局(最具体第一). ### 循环和高速保护 ```python with budget( max_usd=50.00, loop_guard=True, # AgentLoopError if any tool repeats 5x in 60s max_velocity="$1/min", # SpendVelocityExceededError if burn > $1/min ) as b: run_my_agent() print(b.loop_guard_counts) # {'web_search': 3, 'read_file': 1} ``` ### 分配预算——跨多个进程执行 ```python from shekel.backends.redis import RedisBackend backend = RedisBackend() # reads REDIS_URL from env; fail-closed by default with budget("$5/hr + 100 calls/hr", name="api-tier", backend=backend) as b: response = client.chat.completions.create(...) # Atomic Lua-script enforcement — one Redis round-trip per call # BudgetConfigMismatchError if the same name is reused with different limits ``` 与 `AsyncRedisBackend` 用于 Aync 工作流程 。 电路断路器在 – 可配置阈值 + 冷却。 失败打开或失效关闭 。 ### 用户/每租户强制执行 ```python from shekel.backends.redis import RedisBackend backend = RedisBackend() # reads REDIS_URL from env with budget(max_usd=0.10, tenant_id=user.id, name="api", backend=backend) as b: run_agent() # Each user gets their own isolated $0.10 cap — same Redis, zero per-tenant config ``` 配额管理: `backend.set_tenant_limit(...)`, `backend.get_tenant_spend(...)`, `backend.reset_tenant(...)`, `backend.list_tenants(...)`。从命令行中检查 `shekel tenants list --name api`. ### 滚动窗口利率限制 ```python with budget("$5/hr", name="api-tier") as b: response = await client.chat.completions.create(...) # BudgetExceededError carries retry_after so callers know when the window resets ``` 多顶 : `budget("$5/hr + 100 calls/hr")` ——USD和呼叫计数窗口是独立的. ### 各届会议累积 ```python session = budget(max_usd=20.00, name="session") with session: run_step_1() # $3.20 with session: run_step_2() # $8.10 with session: run_step_3() # raises at $20 print(f"total: ${session.spent:.2f}") ``` --- ## 从 CLI 执行——零代码更改 完全不想碰密码? ```bash pip install shekel[cli] shekel run agent.py --budget 5 # exit 0 = under budget | exit 1 = budget exceeded ← CI-friendly ``` 扔进任何管道: ```bash # Shell / cron / Docker AGENT_BUDGET_USD=5 shekel run agent.py # GitHub Actions - run: shekel run agent.py --budget 5 # Docker — operator sets budget at runtime, no rebuild needed ENTRYPOINT ["shekel", "run", "agent.py"] # docker run -e AGENT_BUDGET_USD=5 my-agent-image ``` 密钥旗 : ```bash --budget 5 # hard stop in USD --warn-at 0.8 # log warning at 80%, hard stop at 100% --max-llm-calls 20 # cap by call count instead of spend --max-tool-calls 50 # cap agent tool calls --warn-only # log but never exit 1 (soft guardrail) --dry-run # track costs, no enforcement --output json # machine-readable spend summary for log pipelines --budget-file shekel.toml # load limits from config file ``` --- ## 开支摘要是什么样子的 ```python with budget(max_usd=5.00) as b: run_my_agent() print(b.summary()) ``` ``` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ shekel spend summary ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Total: $1.2450 / $5.00 (25%) gpt-4o: $1.1320 (5 calls) Input: 45.2k tokens → $0.1130 Output: 11.3k tokens → $1.1320 Tool spend: $0.1130 (9 tool calls) web_search $0.090 (9 calls) [langchain] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` 或机可读: ```bash shekel run agent.py --budget 5 --output json # {"spent": 1.245, "limit": 5.0, "calls": 5, "tool_calls": 9, "status": "ok", "model": "gpt-4o"} ``` --- ## 装饰者 ```python from shekel import with_budget @with_budget(max_usd=0.10) def summarize(text: str) -> str: return client.chat.completions.create(...).choices[0].message.content # budget enforced independently on every call ``` --- ## 如何运作 雪克尔猴拍 `openai.chat.completions.create` 财务报告和财务报告 `anthropic.messages.create` 打开 `__enter__` 并恢复原件 `__exit__`支出在 `ContextVar` ——同一过程中同时存在的代理人从不共享状态. `with budget()` 块组成了树; 孩子花花自动滚滚。 **没有背景线程, 没有外部服务, 没有 API 密钥。 没有任何东西离开您的机器 。** --- ## 观察性 - **兰福斯** ——成本流,断电事件,朗福斯跨度的预算层次. - **OpenTelemetry** - 9仪器: `shekel.llm.cost_usd`, `shekel.budget.utilization`, `shekel.budget.spend_rate`, `shekel.tool.calls_total`中,还有更多 ```python from shekel.otel import ShekelMeter meter = ShekelMeter() # attaches to global MeterProvider; silent no-op if OTel absent ``` --- ## 支持的模型 GPT-4o, GPT-4o-mini, o1, o3, Claude 3.5 / 3 / 3.7 Sonnet, Claude 3 Haiku / Opus, Gemini 2.0 / 2.5 Flash/Pro等的内置定价, 以及更多. ```bash pip install shekel[all-models] # 400+ models via tokencost shekel models # list all bundled models and pricing shekel estimate --model gpt-4o --input-tokens 1000 --output-tokens 500 ``` --- ## API 快速参考 ```python budget( max_usd=5.00, # hard USD cap warn_at=0.8, # warn at 80% max_llm_calls=50, # cap by call count max_tool_calls=100, # cap tool dispatches tool_prices={"web_search": 0.01}, # charge per tool fallback={"at_pct": 0.8, "model": "gpt-4o-mini"}, # switch instead of crash name="my-agent", # required for nesting + temporal budgets backend=RedisBackend(), # distributed enforcement across processes ) budget("$5/hr + 100 calls/hr", name="api-tier") # multi-cap rolling-window ``` **组件上限** ——所有可链式,在组件执行前全部加高: ```python b.node("fetch_data", max_usd=0.50) # LangGraph node → NodeBudgetExceededError b.chain("retriever", max_usd=0.20) # LangChain chain → ChainBudgetExceededError b.agent("researcher", max_usd=1.00) # CrewAI agent → AgentBudgetExceededError b.task("summarize", max_usd=0.50) # CrewAI task → TaskBudgetExceededError ``` **例外** ——所有子类 `BudgetExceededError`,所以一个 `except` 捕捉到所有东西: | 例外 | 升起时 | 主要字段 | |---|---|---| | `BudgetExceededError` | 全局封顶命中 | `spent`, `limit`, `model`, `retry_after` | | `NodeBudgetExceededError` | LangGraph 节点盖被击中 | `node_name`, `spent`, `limit` | | `AgentBudgetExceededError` | CrewAI / OAI 代理机盖被击中 | `agent_name`, `spent`, `limit` | | `TaskBudgetExceededError` | CrewAI 任务上限命中 | `task_name`, `spent`, `limit` | | `ChainBudgetExceededError` | LangChain 连锁盖击打 | `chain_name`, `spent`, `limit` | | `ToolBudgetExceededError` | 工具调用盖打中 | `tool_name`, `calls_used`, `calls_limit` | | `AgentLoopError` | 工具在窗口中调用过多次 | `tool_name`, `call_count`, `window_seconds` | | `SpendVelocityExceededError` | 燃烧率超过 `max_velocity` | `velocity_per_min`, `limit_per_min` | | `BudgetConfigMismatchError` | 重新使用不同限制的名称 | — | --- ## 警卫 每个PR 并推向 `main` 运行CodeQL、Trivy、Turit和Pip-audit。 [安全标签](https://github.com/arieradle/shekel/security/code-scanning) 为了结果。 --- ## 文档 **[arieradle.github.io/shekel 互联网档案馆的存檔,存档日期2014-09-02.](https://arieradle.github.io/shekel/latest/)** - [快速启动](https://arieradle.github.io/shekel/latest/quickstart/) - [CLI 参考文献](https://arieradle.github.io/shekel/latest/cli/) - [挂载容器( C)](https://arieradle.github.io/shekel/latest/docker/) - [零用预算](https://arieradle.github.io/shekel/latest/usage/nested-budgets/) - [工具预算](https://arieradle.github.io/shekel/latest/usage/tool-budgets/) - [临时预算](https://arieradle.github.io/shekel/latest/usage/temporal-budgets/) - [LangGraph 整合](https://arieradle.github.io/shekel/latest/integrations/langgraph/) - [CrewAI 整合](https://arieradle.github.io/shekel/latest/integrations/crewai/) - [AutoGen 整合](https://arieradle.github.io/shekel/latest/integrations/autogen/) - [API 参考文献](https://arieradle.github.io/shekel/latest/api-reference/) --- ## 捐款 见 [CONTRIBUTING . md (英语).](<https://github.com/arieradle/shekel/blob/main/CONTRIBUTING.md>). 公关欢迎——特别是新的框架适配器。 ## 许可证 MIT
查看原始来源