PHΛSE Docs PHASE.XYZ

SDKs

#phase-x402 (Python)

Pay-per-request client for the Phase AI gateway. No API keys, no balances: the gateway answers with HTTP 402 and a quote, the SDK signs a one-time USDT authorization (x402 upto/exact on Phase L1) with your wallet key and retries. You only pay for what the request actually used.

Terminal
pip install phase-x402
export PHASE_WALLET_KEY=0x...       # a wallet holding USDT on Phase L1

#With the official OpenAI SDK

Python
import 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": "user", "content": "hello"}])
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="")

Free models (layer: free in the catalog) never trigger a 402, so a plain OpenAI(base_url=...) without the transport works for them.

#Plain httpx

Python
import os
import httpx
from phase_x402 import PayingTransport, read_settlement

KEY = os.environ["PHASE_WALLET_KEY"]
gateway = "https://<gateway>"

with httpx.Client(transport=PayingTransport(private_key=KEY)) as http:
    resp = http.post(gateway + "/v1/chat/completions", json={"model": "gpt-oss-120b", "messages": [{"role": "user", "content": "hello"}]})
    print(resp.json()["phase"], read_settlement(resp))

#LangChain

Python
import os
from langchain_openai import ChatOpenAI
from phase_x402 import paying_http_client, async_paying_http_client

KEY = os.environ["PHASE_WALLET_KEY"]

llm = ChatOpenAI(model="gpt-oss-120b", base_url="https://<gateway>/v1", api_key="x402",
                 http_client=paying_http_client(private_key=KEY),
                 http_async_client=async_paying_http_client(private_key=KEY))

#Options

OptionMeaning
private_key / accountwallet key (hex) or an eth_account LocalAccount
max_amountrefuse quotes above this many micro-USDT (QuoteTooExpensiveError)
networksCAIP-2 allowlist, e.g. ["eip155:1015"]
allowed_pay_to / allowed_assetspin the recipient (InferencePayments) and token (USDT) contracts the client signs for
allow_insecurepay a plain-http non-loopback gateway (dev only; default False, NoAcceptableRequirementError)
on_quote(req)called with the chosen quote; return False to cancel (QuoteRejectedError)
validity_secondsauthorization validity (default 600, capped by the gateway's maxTimeoutSeconds)

format_usd("2639") → "0.002639"; parse_payment_required(resp) returns the raw 402 quote.

#@phase/x402-fetch

A fetch that pays for Phase AI gateway requests with x402: on 402 Payment Required it signs a one-time USDT authorization (EIP-712, upto or exact scheme) for the quoted ceiling and retries once with PAYMENT-SIGNATURE. The wallet never sends a transaction; the gateway settles after the response and reports the actual price in phase.price_micro_usd.

#API

TypeScript
import { createPayingFetch, formatUsd } from "@phase/x402-fetch";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.PHASE_WALLET_KEY);
const payingFetch = createPayingFetch({
  signer,                         // viem Account (private key) or WalletClient (browser wallet)
  maxAmount: 50_000n,             // optional: refuse quotes above 0.05 USDT → QuoteTooExpensiveError
  networks: ["eip155:1015"],    // optional CAIP-2 allowlist (default: any eip155 network)
  address: "0x…",                 // optional payer override for wallet clients without a default account
  allowedPayTo: ["0x…"],          // optional: only sign for this InferencePayments contract
  allowedAssets: ["0x…"],         // optional: only sign for this USDT contract
  allowInsecure: false,           // plain-http gateways are refused unless loopback (dev) or this is true
  onQuote: async (q) => {         // optional: inspect/confirm before signing; `false` cancels
    console.log(`up to ${formatUsd(q.amount)} for ${q.quote?.model}`);
    return true;
  },
  validitySeconds: 600,           // optional; default min(600, maxTimeoutSeconds)
  fetch: globalThis.fetch,        // optional underlying fetch
});

payingFetch(input, init) behaves like fetch. Non-402 responses are returned untouched; a second 402 (e.g. payment rejected: insufficient balance) is also returned as-is so the caller can show the reason. Errors thrown before signing: QuoteTooExpensiveError, QuoteRejectedError, NoAcceptableRequirementError (all carry .response, the original 402).

Helpers:

  • parsePaymentRequired(response) — PaymentRequired from the PAYMENT-REQUIRED header or body (response stays readable).
  • readSettlement(response) — decodes the PAYMENT-RESPONSE header ({ success, transaction, network, payer }), or null. For streaming responses use the phase object of the final SSE chunk instead.
  • formatUsd("1600") → "$0.0016" (micro-USD → dollars, no rounding).
  • buildTypedAuthorization, selectRequirement, EIP712_TYPES — the pieces, for custom flows.

Signers: a viem local account (privateKeyToAccount) signs in-process; a WalletClient (createWalletClient({ transport: custom(window.ethereum) })) signs through the wallet's eth_signTypedData_v4. Wallets check the domain chainId, so the wallet must be on the Phase network (eip155:1015) when it signs.

#LangChain

TypeScript
import { ChatOpenAI } from "@langchain/openai";
import { createPayingFetch } from "@phase/x402-fetch";
import { privateKeyToAccount } from "viem/accounts";

const payingFetch = createPayingFetch({ signer: privateKeyToAccount(process.env.PHASE_WALLET_KEY) });
const llm = new ChatOpenAI({
  model: "gpt-oss-120b",
  apiKey: "x402",
  configuration: { baseURL: "https://<gateway>/v1", fetch: payingFetch },
});
console.log((await llm.invoke("hello")).content);

#Notes

  • The request body is replayed on the retry, so it must be replayable (strings, FormData, Blob; not a one-shot ReadableStream).
  • validBefore = now + validitySeconds is clamped to the requirement's maxTimeoutSeconds.
  • accepted in the payload is the chosen requirement verbatim, including extra.taskId; the gateway rejects a payload whose requirement it did not issue.
© 2026 Phase Labs Technologies Inc. All rights reserved. Phase is a product of Phase Labs Technologies Inc.ir-sdks.md