OpenAI Agents SDK
With the OpenAI Agents SDK, a paid API call is a function tool. Wrap fetch with spendctl’s client inside that tool and every payment goes through the sidecar’s policy first. The agent holds no key.
Before you start
Section titled “Before you start”Run the sidecar and, for a first try, the mock sellers (Quickstart):
npx spendctl initnpx spendctl mock # terminal 1npx spendctl start # terminal 2npm install @openai/agents @spendctl/client zodThe tool
Section titled “The tool”wrapFetch returns a fetch that sends requests through the sidecar as the named agent. readRefusal returns the reason when spendctl did not pay.
import { Agent, run, tool } from "@openai/agents";import { readRefusal, wrapFetch } from "@spendctl/client";import { z } from "zod";
const paidFetch = wrapFetch({ agent: "researcher" });
const fetchPaid = tool({ name: "fetch_paid_url", description: "GET a URL that may charge per request (HTTP 402). spendctl enforces the budget; refusals explain why.", parameters: z.object({ url: z.string().url() }), execute: async ({ url }) => { const response = await paidFetch(url); const refusal = await readRefusal(response); if (refusal) return `Not paid: ${refusal.message}`; return `${response.headers.get("x-spendctl-amount") ?? "free"} · ${await response.text()}`; },});
const agent = new Agent({ name: "Researcher", instructions: "Use fetch_paid_url for paid data. Never try to work around a refusal.", tools: [fetchPaid],});
const result = await run(agent, "What's the weather in Tokyo? Use http://localhost:4021/weather?city=Tokyo");console.log(result.finalOutput);The tool returns the amount with the data ($0.01 · {…}), so the model can keep track of what a task has cost.
What the model sees
Section titled “What the model sees”- Paid: the amount and the seller’s response.
- Refused:
Not paid:and spendctl’s sentence. The instruction not to work around a refusal is good manners, and it is not the control: the model cannot pay any other way, because it has no key. - Held for a human: by default the tool call waits for
spendctl approve(up to 4 minutes). Setapprovals.hold: falseinspendctl.yamlto get the approval id back at once instead (Approvals).
Python
Section titled “Python”The Python Agents SDK works the same way with spendctl-sdk: wrap the call in a function tool and use httpx_client(agent="researcher") or pay(url, agent="researcher") inside it (Integrations).
- The policy behind the tool: Budgets for AI agents.
- Why the instruction alone is not enough: Why prompts are not spending controls.