Repository navigation
Expand file tree
/
Copy pathagent.ts
More file actions
167 lines (154 loc) · 9.45 KB
/
Copy pathagent.ts
File metadata and controls
167 lines (154 loc) · 9.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// A minimal AI agent that pays Inferit per request with x402 (HTTP 402): no account, no API key, no native gas.
//
// It uses only the official x402 client (@x402/fetch, @x402/evm) and viem. Discovery, the 402 quote and the payment are
// standard x402 v2; only the testnet faucet claim and the x-inferit-* cost headers are Inferit's.
//
// npm install
// export AGENT_KEY=0x... # the payer's private key (optional: a fresh throwaway key is made if unset)
// npm start
//
// Environment (all optional):
// AGENT_KEY the payer's private key, 0x + 64 hex characters. Never commit it. Unset: a fresh random key,
// used for this run only (only its address is printed).
// INFERIT_BASE_URL the OpenAI-compatible base URL (default https://api-production-c74b9.up.railway.app/v1,
// the hosted testnet API)
// INFERIT_MODEL a model id (default qwen/qwen-2.5-14b-instruct). GET /v1/models lists the models with a live
// seller (rows with a best_price). "auto" lets Inferit pick the model when GET /v1/routing lists
// a candidate in candidates_now.
// PROMPT what to ask
// MAX_TOKENS the answer's token limit (default 64; the 402 quote is the worst case for this body)
// STREAM=1 stream the answer
// MAX_PAYMENT the most the agent pays per request, in token base units (default 1000000 = 1 ITC)
// RPC_URL a Whitechain Sepolia RPC, to read the agent's token balance (default
// https://rpc.testnet.whitechain.io)
//
// What happens:
// 1. Discovery: GET /.well-known/x402 says what is paid and how: scheme `exact` (EIP-3009
// transferWithAuthorization), the network (eip155:1874 = Whitechain Sepolia), the token (`asset`) and
// `payTo` = the market's escrow contract.
// 2. Test tokens without gas: on the testnet the API sponsors a faucet. When the agent holds less than the
// minimum payment, POST /v1/faucet {address} mints 1,000 test ITC to it; the server pays the gas; once per 24 h
// per address.
// 3. Pay per request: the first POST /v1/chat/completions (no Authorization header) answers 402 with a quote for
// this exact request (header PAYMENT-REQUIRED). wrapFetchWithPayment signs an EIP-3009 authorization for that
// amount, to the escrow, and retries with PAYMENT-SIGNATURE. The API deposits it into the escrow as the agent's
// own balance, serves the request, and answers with PAYMENT-RESPONSE (the deposit transaction).
// 4. The request is charged its metered cost (x-inferit-buyer-cost-micro, settled on chain in batches later); the
// rest of the payment stays the agent's escrow balance, to spend later or withdraw.
import { decodePaymentResponseHeader, wrapFetchWithPayment, x402Client } from '@x402/fetch';
import { ExactEvmScheme } from '@x402/evm/exact/client';
import { createPublicClient, erc20Abi, http, type Hex } from 'viem';
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
const BASE = (process.env.INFERIT_BASE_URL ?? 'https://api-production-c74b9.up.railway.app/v1').replace(/\/+$/, '');
const API = BASE.replace(/\/v1$/, '');
const MODEL = process.env.INFERIT_MODEL ?? 'qwen/qwen-2.5-14b-instruct';
const PROMPT = process.env.PROMPT ?? 'In one sentence: why does pay-per-request suit AI agents?';
const MAX_TOKENS = Number(process.env.MAX_TOKENS ?? 64);
const STREAM = process.env.STREAM === '1';
const MAX_PAYMENT = process.env.MAX_PAYMENT ?? '1000000';
const RPC_URL = process.env.RPC_URL ?? 'https://rpc.testnet.whitechain.io';
const EXPLORER = 'https://explorer.testnet.whitechain.io';
interface Discovery {
enabled: boolean;
testnet?: boolean;
network: `${string}:${string}`;
networkName?: string;
asset: string;
assetSymbol?: string;
assetDecimals?: number;
payTo: string;
minAmount?: string;
faucet: { url: string } | null;
}
interface FaucetBody {
amountMicro?: string;
transaction?: string;
error?: { code: string; message: string };
}
/** The payer key comes from the environment only. A malformed key is refused without echoing it. */
function payerKey(): { key: Hex; fresh: boolean } {
const raw = process.env.AGENT_KEY?.trim();
if (!raw) return { key: generatePrivateKey(), fresh: true };
if (!/^0x[0-9a-fA-F]{64}$/.test(raw)) throw new Error('AGENT_KEY must be a private key: 0x followed by 64 hex characters');
return { key: raw as Hex, fresh: false };
}
async function claimTestTokens(url: string, address: string, symbol: string): Promise<void> {
const claim = async () => {
const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ address }) });
return { res, body: (await res.json().catch(() => ({}))) as FaucetBody };
};
let { res, body } = await claim();
// The faucet shares a per-IP rate limit with sign-in: after a burst, wait once and retry.
if (res.status === 429 && body.error?.code === 'rate_limit_exceeded') {
const waitSec = Math.min(Math.max(Number(res.headers.get('retry-after')) || 10, 1), 65);
console.log(`faucet: rate limited, retrying in ${waitSec} s`);
await new Promise((done) => setTimeout(done, waitSec * 1000));
({ res, body } = await claim());
}
if (res.ok) console.log(`faucet: ${Number(body.amountMicro) / 1e6} ${symbol} minted (tx ${body.transaction})`);
// faucet_cooldown: this address claimed within 24 h; it can still pay with what it holds.
else console.log(`faucet: ${body.error?.code ?? res.status} (${body.error?.message ?? 'no message'})`);
}
async function main(): Promise<void> {
// 0. The agent's wallet. It never needs native gas: the API pays for the faucet claim and the deposit.
const { key, fresh } = payerKey();
const account = privateKeyToAccount(key);
console.log(`agent ${account.address}${fresh ? ' (a fresh key for this run; set AGENT_KEY to reuse one)' : ''} -> ${API}`);
// 1. Discovery.
const d = (await (await fetch(`${API}/.well-known/x402`)).json()) as Discovery;
if (!d.enabled) throw new Error('x402 is not enabled on this API; use an API key instead');
const symbol = d.assetSymbol ?? 'tokens';
console.log(`pays ${symbol} on ${d.networkName ?? d.network} (${d.network}) into the escrow ${d.payTo}`);
// 2. Test tokens, when the agent holds less than the minimum payment and the API sponsors a faucet (testnets only).
const rpc = createPublicClient({ transport: http(RPC_URL) });
const held = await rpc.readContract({ address: d.asset as Hex, abi: erc20Abi, functionName: 'balanceOf', args: [account.address] });
const decimals = d.assetDecimals ?? 6;
console.log(`holds ${Number(held) / 10 ** decimals} ${symbol}`);
if (held < BigInt(d.minAmount ?? '1')) {
if (d.faucet) await claimTestTokens(d.faucet.url, account.address, symbol);
else throw new Error(`the agent holds no ${symbol} and this API has no faucet`);
}
// 3. The official x402 client: the exact EVM scheme for every eip155 network. Recent clients (with spend controls,
// such as 2.28) pay only assets they know by default, so allow this one explicitly, with a per-payment cap.
const client = new x402Client()
.register('eip155:*', new ExactEvmScheme(account))
.setSpendControls({ allowedAssets: [{ network: d.network, asset: d.asset, maxAmountPerPayment: MAX_PAYMENT }] });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
// An ordinary OpenAI-style call; the 402 -> sign -> retry happens inside fetchWithPayment.
const res = await fetchWithPayment(`${BASE}/chat/completions`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ model: MODEL, messages: [{ role: 'user', content: PROMPT }], max_tokens: MAX_TOKENS, stream: STREAM }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 500)}`);
let answer = '';
if (STREAM) {
// Server-sent events in the OpenAI format.
const text = await res.text();
for (const event of text.split('\n\n')) {
if (!event.startsWith('data: ') || event === 'data: [DONE]') continue;
answer += (JSON.parse(event.slice(6)) as { choices?: { delta?: { content?: string } }[] }).choices?.[0]?.delta?.content ?? '';
}
} else {
answer = ((await res.json()) as { choices: { message: { content: string } }[] }).choices[0]?.message.content ?? '';
}
console.log(`\n${answer.trim()}\n`);
console.log(`model: ${res.headers.get('x-inferit-model') ?? MODEL}`);
// 4. The receipt: the deposit transaction that credited the payment to the agent's escrow balance.
const header = res.headers.get('PAYMENT-RESPONSE');
if (!header) {
console.log('no PAYMENT-RESPONSE header: this request was not paid with x402');
return;
}
const receipt = decodePaymentResponseHeader(header);
const paid = res.headers.get('x-inferit-x402-credited-micro') ?? receipt.amount;
const cost = res.headers.get('x-inferit-buyer-cost-micro');
console.log(`paid ${paid} base units of ${symbol} (deposit tx ${EXPLORER}/tx/${receipt.transaction})`);
if (cost) console.log(`charged ${cost} base units for this request; the rest stays ${account.address}'s escrow balance`);
// A streamed answer's cost arrives as an HTTP trailer (x-inferit-buyer-cost-micro), which fetch does not expose.
else if (STREAM) console.log("streamed: the metered cost came as an HTTP trailer, which fetch does not show; the rest stays the agent's escrow balance");
}
main().catch((err: unknown) => {
console.error(err instanceof Error ? err.message : err);
process.exit(1);
});