コンテンツにスキップ

OpenAI Agents SDK

OpenAI Agents SDK では、有料の API 呼び出しは関数ツールになります。そのツールの中で fetch を spendctl のクライアントで包めば、すべての支払いがまずサイドカーのポリシーを通ります。エージェントは鍵を持ちません。

サイドカーを起動します。初めて試すときは、モックの売り手も起動してください(クイックスタート)。

ターミナルウィンドウ
npx spendctl init
npx spendctl mock # ターミナル 1
npx spendctl start # ターミナル 2
ターミナルウィンドウ
npm install @openai/agents @spendctl/client zod

wrapFetch は、指定した名前のエージェントとしてリクエストをサイドカー経由で送る fetch を返します。readRefusal は、spendctl が支払わなかったときにその理由を返します。

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

ツールはデータと一緒に金額を返すので($0.01 · {…})、モデルはタスクにいくらかかったかを把握できます。

  • 支払い済み:金額と、売り手の応答です。
  • 拒否:Not paid: と spendctl の文です。拒否を回避しないようにという指示は作法としては良いものですが、管理の手段ではありません。モデルは鍵を持たないので、ほかの方法では支払えません。
  • 人間の判断待ちで保留:既定では、ツール呼び出しは spendctl approve を待ちます(最長 4 分)。待たずに承認 ID をすぐ受け取るには、spendctl.yaml で approvals.hold: false にしてください(承認フロー)。

Python 版の Agents SDK でも、spendctl-sdk で同じようにできます。呼び出しを関数ツールで包み、その中で httpx_client(agent="researcher") か pay(url, agent="researcher") を使ってください(組み込み方)。