Back to Academy
Level 315 min

OpenAI Function Calling

Use x402 services as OpenAI function calls. Your GPT agent discovers and pays for APIs on the fly.

1

Define the x402 tool

Register a tool that your OpenAI agent can call to interact with 402bazaar.com services.

TypeScript
const tools = [{
  type: "function",
  function: {
    name: "call_402_service",
    description: "Call a paid API service via x402 protocol",
    parameters: {
      type: "object",
      properties: {
        slug: { type: "string", description: "Service slug" },
        body: { type: "object", description: "Request body" }
      },
      required: ["slug"]
    }
  }
}];
2

Handle the tool call

When GPT invokes the tool, make the x402 payment flow: call → 402 → sign → retry.

TypeScript
async function handleToolCall(slug: string, body: unknown) {
  // 1. Call proxy
  const res = await fetch(`/api/v1/proxy/${slug}`, {
    method: "POST",
    body: JSON.stringify(body)
  });

  if (res.status === 402) {
    // 2. Sign payment
    const payment = await signUsdcPayment(res.headers);
    // 3. Retry with payment
    return fetch(`/api/v1/proxy/${slug}`, {
      method: "POST",
      headers: { "X-PAYMENT": payment },
      body: JSON.stringify(body)
    });
  }
  return res;
}
3

Add budget controls

Limit per-request and total spending to keep your agent's costs under control.

TypeScript
const budgetConfig = {
  maxPerRequest: "0.05",   // Max $0.05 per call
  dailyLimit: "5.00",      // Max $5/day total
  totalLimit: "100.00",    // Lifetime cap
  allowedCategories: ["data", "analyze", "fetch"]
};