Skip to content

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.

Run the sidecar and, for a first try, the mock sellers (Quickstart):

Terminal window
npx spendctl init
npx spendctl mock # terminal 1
npx spendctl start # terminal 2
Terminal window
npm install @openai/agents @spendctl/client zod

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.

  • 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). Set approvals.hold: false in spendctl.yaml to get the approval id back at once instead (Approvals).

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).