Call a model
The examples call a paid model through the Phase SDKs.
GET /v1/models returns the catalog with prices and needs no payment; use it to choose a model and a max_amount.
# A paid model answers 402 with the quote (ceiling, price per 1M, task id);
# sign it with an SDK below — or look at the quote first:
curl -s -i -X POST https://<gateway>/v1/chat/completions -H 'content-type: application/json' \
-d '{"model":"gpt-oss-120b","messages":[{"role":"user","content":"hello world"}]}'
# The catalog with prices (no payment):
curl -s https://<gateway>/v1/modelsimport os
from openai import OpenAI
from phase_x402 import paying_http_client
client = OpenAI(
base_url="https://<gateway>/v1",
api_key="x402", # ignored by the gateway; the wallet is the identity
http_client=paying_http_client(private_key=os.environ["PHASE_WALLET_KEY"], max_amount=50_000), # ≤ $0.05 per request
)
r = client.chat.completions.create(
model="gpt-oss-120b",
messages=[{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hello"}],
max_tokens=400, # also caps the price ceiling you sign
temperature=0.7,
)
print(r.choices[0].message.content)
print(r.model_extra["phase"]) # {'task_id', 'provider', 'price_micro_usd', 'payment': 'settled', 'tx_hash', ...}
# streaming works the same way
with client.chat.completions.stream(model="gpt-oss-120b", messages=[{"role": "user", "content": "hello"}]) as s:
for ev in s:
if ev.type == "content.delta":
print(ev.delta, end="")import { createPayingFetch, formatUsd } from "@phase/x402-fetch";
import { privateKeyToAccount } from "viem/accounts";
const payingFetch = createPayingFetch({ signer: privateKeyToAccount(process.env.PHASE_WALLET_KEY) });
const r = await payingFetch("https://<gateway>/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "gpt-oss-120b",
messages: [{ role: "system", content: "Be brief." }, { role: "user", content: "hello" }],
max_tokens: 400, // also caps the price ceiling you sign
temperature: 0.7,
}),
});
const j = await r.json();
console.log(j.choices[0].message.content, formatUsd(j.phase.price_micro_usd), j.phase.payment, j.phase.tx_hash);package main
import (
"context"
"fmt"
"io"
"math/big"
"os"
"strings"
"github.com/ethereum/go-ethereum/crypto"
"phase-router/sdk/go/phasex402"
)
func main() {
key, err := crypto.HexToECDSA(strings.TrimPrefix(os.Getenv("PHASE_WALLET_KEY"), "0x"))
if err != nil {
panic(err)
}
client := &phasex402.Client{Key: key, MaxAmount: big.NewInt(50_000)} // ≤ $0.05 per request
resp, err := client.PostJSON(context.Background(), "https://<gateway>/v1/chat/completions", map[string]any{
"model": "gpt-oss-120b",
"messages": []map[string]string{{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hello"}},
"max_tokens": 400, // also caps the price ceiling you sign
})
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body)) // OpenAI shape + "phase": price, payment, tx_hash
fmt.Println(phasex402.Settlement(resp)) // the decoded PAYMENT-RESPONSE header
}#OpenAI Node SDK
import OpenAI from "openai";
import { createPayingFetch } from "@phase/x402-fetch";
import { privateKeyToAccount } from "viem/accounts";
const payingFetch = createPayingFetch({ signer: privateKeyToAccount(process.env.PHASE_WALLET_KEY) });
const openai = new OpenAI({ baseURL: "https://<gateway>/v1", apiKey: "x402", fetch: payingFetch });
const stream = await openai.chat.completions.create({ model: "gpt-oss-120b", stream: true, messages: [{ role: "user", content: "hi" }] });
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
if (chunk.phase) console.log("\npaid", chunk.phase.price_micro_usd, "µUSD", chunk.phase.payment, chunk.phase.tx_hash);
}#Model classes
Instead of a model id you can name a class: auto (balanced, default), eco (cheapest), premium (best quality) or agentic (multi-step tool use). The router picks a model of that class for each message and buys it from the cheapest healthy provider; you pay the routed model's own price plus the per-call fee.
curl -s -i -X POST https://<gateway>/v1/chat/completions -H 'content-type: application/json' \
-d '{"model":"auto","messages":[{"role":"user","content":"hello world"}]}'Free models need no payment, but a gateway may disable them.
#This gateway
The network, the recipient (InferencePayments) and the asset (USDT) are in every 402 response (accepts[0]); the gateway signer is in GET /health.
Pin the recipient, the asset and the network in your SDK (allowed_pay_to / allowedPayTo, allowed_assets / allowedAssets, networks) using values from an independent source, not values read from the same gateway URL: then a wrong or hijacked gateway URL cannot make your wallet sign for another recipient. The SDKs also refuse to pay a plain-http gateway unless it is loopback (dev) or you opt in with allow_insecure.
#SDK options
All options and more examples: SDKs.