Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Predge agent tools

Framework adapters for the [Predge API](https://predge.io/docs). They give an agent a signed settlement-risk check for any Polymarket market (free, no key), offline verification of Predge records, and x402-paid Polymarket data.
Dispute and refund verdicts for AI-agent payments, as framework tools for the [Predge API](https://predge.io/docs). An agent that paid for a call can ask for a signed verdict (`delivered` / `not_delivered` / `inconclusive`, with a refund recommendation) and re-read any verdict by id. Also: a signed settlement-risk check for any Polymarket market (free, no key), offline verification of Predge records, and x402-paid Polymarket data.

| Package | Framework |
|---|---|
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 36 additions & 4 deletions packages/ai-sdk/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# @predge/ai-sdk

[Predge](https://predge.io) tools for the [Vercel AI SDK](https://ai-sdk.dev). Before your agent trades, pays or settles on a Polymarket market, it can check whether that market's resolution is settled, disputed or at risk. Records are read live from UMA's Optimistic Oracle on Polygon and signed with ed25519. Every signature is verified against Predge's published key.
Dispute and refund verdicts for AI-agent payments, as [Vercel AI SDK](https://ai-sdk.dev) tools. When your agent pays for a call and the result looks wrong, it sends what was promised, what came back and what was paid, and gets a signed [Predge](https://predge.io) verdict: `delivered`, `not_delivered` or `inconclusive`, with reason codes and a refund recommendation. Every verdict is ed25519-signed and checked against Predge's published key.

The free tools need no API key and no wallet.
Also included: a free signed settlement-risk check for Polymarket markets (read live from UMA's Optimistic Oracle on Polygon) and x402-paid Polymarket data.

## Get a free key

Expand Down Expand Up @@ -32,10 +32,40 @@ npm install @predge/ai-sdk ai zod

## Usage

### Verdicts with a pilot key

```ts
import { generateText, stepCountIs } from "ai";
import { predgeTools } from "@predge/ai-sdk";

const { text } = await generateText({
model: "openai/gpt-5-mini",
tools: predgeTools({ apiKey: process.env.PREDGE_KEY }), // free pilot key: https://predge.io/start
stopWhen: stepCountIs(3),
prompt:
"I paid $0.25 to https://api.example.com/v1/report for JSON with a `rows` field. " +
'It answered 200 with body {"error":"timeout"}. Ask Predge for a verdict and tell me if I should get a refund.',
});
```

Without `apiKey` the tool reads `PREDGE_KEY` from the environment. Or call the client directly:

```ts
import { PredgeAPI } from "@predge/ai-sdk";

const verdict = await new PredgeAPI({ apiKey: process.env.PREDGE_KEY }).requestVerdict(undefined, {
job: { endpoint: "https://api.example.com/v1/report", expected_content_type: "application/json", required_fields: ["rows"] },
delivery: { status: 200, headers: { "content-type": "application/json" }, body: '{"error":"timeout"}' },
payment: { amount_usd: 0.25, payer: "0xBuyer", payee: "0xMerchant" },
});
// verdict.verdict === "not_delivered", verdict.refund.recommended === true, verdict.signature.valid === true
```

The refund is a recommendation the merchant executes. Predge does not move money.

### Settlement risk (free, no key)

```ts
const { text } = await generateText({
model: "openai/gpt-5-mini",
prompt: "Is Polymarket market 5608010 safe to settle against? Check its settlement risk first.",
Expand All @@ -48,7 +78,7 @@ console.log(text);

### Paid tools (x402, USDC on Base)

Pass an account and the paid tools are added. Any viem account works, e.g. `privateKeyToAccount`.
Pass an account and the paid tools are added. Any viem account works, e.g. `privateKeyToAccount`. With an account and no key, `predgeRequestVerdict` pays per verdict over x402 ($0.05 when the paid call is under $1; $0.50 at $1 or more, which needs `maxPaymentUsd: 0.5`).

```ts
import { privateKeyToAccount } from "viem/accounts";
Expand All @@ -66,6 +96,8 @@ Payments use x402 v2 (`exact` scheme, EIP-3009 USDC authorization on Base). The

| Key | Tool name | Price | What it does |
|---|---|---|---|
| `predgeRequestVerdict` | `predge_request_verdict` | free with a pilot key; else $0.05 (< $1) / $0.50 (>= $1) | Signed delivery verdict for a paid call: `delivered` / `not_delivered` / `inconclusive`, reason codes, per-check results, refund recommendation, `verify_url`. Returned when a key or an account is configured |
| `predgeGetVerdict` | `predge_get_verdict` | free | Reads a stored verdict by id (`vrd_...`) and checks its signature |
| `predgeSettlementRisk` | `predge_get_settlement_risk` | free | Signed settlement-risk record for a market (condition id, numeric id or slug): `risk_level` (`ok`, `watch`, `caution`, `resolved`), UMA state, disputes, signature check |
| `predgeVerifyRecord` | `predge_verify_record` | free | Verifies a Predge signed record offline against the pinned key |
| `predgeSettlementEstimate` | `predge_get_settlement_estimate` | $0.02 | Same record plus `settlement_estimate`: for a disputed market, the calibrated probability that it settles differently from the disputed proposal. Failed requests are not charged |
Expand All @@ -79,7 +111,7 @@ An error, or a record whose signature does not verify, is never a "no risk" answ
import { verifyPredgeRecord } from "@predge/ai-sdk";

const res = await fetch("https://api.predge.io/v1/settlement-risk/5608010");
console.log(verifyPredgeRecord(await res.json())); // { valid: true, kid: "13fa3d18a369e6c7", checks: {...} }
console.log(verifyPredgeRecord(await res.json())); // { valid: true, kid: "3b6551a6439b9bda", checks: {...} }
```

## Links
Expand Down
6 changes: 3 additions & 3 deletions packages/ai-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@predge/ai-sdk",
"version": "0.1.0",
"description": "Predge tools for the Vercel AI SDK: signed settlement-risk checks for Polymarket markets (free) and x402-paid Polymarket data",
"version": "0.2.0",
"description": "Dispute and refund verdicts for AI-agent payments: Predge tools for the Vercel AI SDK, plus signed Polymarket settlement-risk checks",
"license": "MIT",
"author": "Predge <hello@predge.io>",
"homepage": "https://github.com/predgeAI/predge-agent-tools/tree/main/packages/ai-sdk#readme",
Expand All @@ -11,7 +11,7 @@
"directory": "packages/ai-sdk"
},
"bugs": "https://github.com/predgeAI/predge-agent-tools/issues",
"keywords": ["ai-sdk", "vercel-ai-sdk", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"],
"keywords": ["agent-payments", "disputes", "refunds", "verdicts", "ai-sdk", "vercel-ai-sdk", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"],
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
Expand Down
5 changes: 4 additions & 1 deletion packages/ai-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { type PredgeToolsOptions, resolveTools } from "../../../shared/tools";
export * from "../../../shared/index";

const KEYS: Record<string, string> = {
predge_request_verdict: "predgeRequestVerdict",
predge_get_verdict: "predgeGetVerdict",
predge_get_settlement_risk: "predgeSettlementRisk",
predge_verify_record: "predgeVerifyRecord",
predge_get_settlement_estimate: "predgeSettlementEstimate",
Expand All @@ -14,9 +16,10 @@ const KEYS: Record<string, string> = {
* Predge tools for the Vercel AI SDK.
*
* Free tools are always returned. Paid tools (x402, USDC on Base) are returned only when an `account` is given.
* The verdict tool is also returned with a Predge key (`apiKey` or env PREDGE_KEY; free pilot key at predge.io/start).
*
* @example
* const { text } = await generateText({ model, tools: predgeTools(), prompt: "Is market 5608010 safe to settle?" });
* const { text } = await generateText({ model, tools: predgeTools({ apiKey: process.env.PREDGE_KEY }), prompt: "Was this paid call delivered?" });
*/
export function predgeTools(options: PredgeToolsOptions = {}): ToolSet {
const { api, signer, specs } = resolveTools(options);
Expand Down
21 changes: 16 additions & 5 deletions packages/langchain/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# @predge/langchain

[Predge](https://predge.io) tools for [LangChain.js](https://js.langchain.com) and LangGraph.js. Before your agent trades, pays or settles on a Polymarket market, it can check whether that market's resolution is settled, disputed or at risk. Records are read live from UMA's Optimistic Oracle on Polygon and signed with ed25519. Every signature is verified against Predge's published key.
Dispute and refund verdicts for AI-agent payments, as [LangChain.js](https://js.langchain.com) and LangGraph.js tools. When your agent pays for a call and the result looks wrong, it sends what was promised, what came back and what was paid, and gets a signed [Predge](https://predge.io) verdict: `delivered`, `not_delivered` or `inconclusive`, with reason codes and a refund recommendation. Every verdict is ed25519-signed and checked against Predge's published key.

The free tools need no API key and no wallet.
Also included: a free signed settlement-risk check for Polymarket markets (read live from UMA's Optimistic Oracle on Polygon) and x402-paid Polymarket data.

## Get a free key

Expand Down Expand Up @@ -39,14 +39,23 @@ import { createPredgeTools } from "@predge/langchain";

const agent = createReactAgent({
llm: new ChatOpenAI({ model: "gpt-5-mini" }),
tools: createPredgeTools(),
tools: createPredgeTools({ apiKey: process.env.PREDGE_KEY }), // free pilot key: https://predge.io/start
});

const result = await agent.invoke({
messages: [{ role: "user", content: "Check the settlement risk of Polymarket market 5608010." }],
messages: [
{
role: "user",
content:
"I paid $0.25 to https://api.example.com/v1/report for JSON with a `rows` field. " +
'It answered 200 with body {"error":"timeout"}. Ask Predge for a verdict and tell me if I should get a refund.',
},
],
});
```

Without `apiKey` the tools read `PREDGE_KEY` from the environment. Without any key, `predge_request_verdict` is only returned when an account is configured (x402, below); the free tools need nothing. The refund is a recommendation the merchant executes. Predge does not move money.

Each tool returns a JSON string.

### Paid tools (x402, USDC on Base)
Expand All @@ -60,12 +69,14 @@ const tools = createPredgeTools({
});
```

Payments use x402 v2 (`exact` scheme, EIP-3009 USDC authorization on Base). The tool pays only USDC on the account's chain and never more than `maxPaymentUsd` per call.
With an account and no key, `predge_request_verdict` pays per verdict ($0.05 when the paid call is under $1; $0.50 at $1 or more, which needs `maxPaymentUsd: 0.5`). Payments use x402 v2 (`exact` scheme, EIP-3009 USDC authorization on Base). The tool pays only USDC on the account's chain and never more than `maxPaymentUsd` per call.

## Tools

| Tool | Price | What it does |
|---|---|---|
| `predge_request_verdict` | free with a pilot key; else $0.05 (< $1) / $0.50 (>= $1) | Signed delivery verdict for a paid call: `delivered` / `not_delivered` / `inconclusive`, reason codes, per-check results, refund recommendation, `verify_url` |
| `predge_get_verdict` | free | Reads a stored verdict by id (`vrd_...`) and checks its signature |
| `predge_get_settlement_risk` | free | Signed settlement-risk record for a market: `risk_level` (`ok`, `watch`, `caution`, `resolved`), UMA state, disputes, signature check |
| `predge_verify_record` | free | Verifies a Predge signed record offline against the pinned key |
| `predge_get_settlement_estimate` | $0.02 | Same record plus `settlement_estimate` for a disputed market. Failed requests are not charged |
Expand Down
6 changes: 3 additions & 3 deletions packages/langchain/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@predge/langchain",
"version": "0.1.0",
"description": "Predge tools for LangChain.js: signed settlement-risk checks for Polymarket markets (free) and x402-paid Polymarket data",
"version": "0.2.0",
"description": "Dispute and refund verdicts for AI-agent payments: Predge tools for LangChain.js, plus signed Polymarket settlement-risk checks",
"license": "MIT",
"author": "Predge <hello@predge.io>",
"homepage": "https://github.com/predgeAI/predge-agent-tools/tree/main/packages/langchain#readme",
Expand All @@ -11,7 +11,7 @@
"directory": "packages/langchain"
},
"bugs": "https://github.com/predgeAI/predge-agent-tools/issues",
"keywords": ["langchain", "langgraph", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"],
"keywords": ["agent-payments", "disputes", "refunds", "verdicts", "langchain", "langgraph", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"],
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
Expand Down
1 change: 1 addition & 0 deletions packages/langchain/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from "../../../shared/index";
* Predge tools for LangChain.js / LangGraph.js.
*
* Free tools are always returned. Paid tools (x402, USDC on Base) are returned only when an `account` is given.
* The verdict tool is also returned with a Predge key (`apiKey` or env PREDGE_KEY; free pilot key at predge.io/start).
* Each tool returns a JSON string.
*
* @example
Expand Down
130 changes: 130 additions & 0 deletions shared/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,27 @@ export type PredgePluginOptions = {
maxPaymentUsd?: number;
/** Trusted ed25519 public keys (hex). Defaults to Predge's published attestation key. */
trustedKeys?: string[];
/**
* Predge API key, sent as the `x-predge-key` header on verdict requests. A free 30-day pilot key is at
* https://predge.io/start . Defaults to the PREDGE_KEY environment variable. Without a key, verdicts are paid over x402.
*/
apiKey?: string;
};

/** Header that carries a Predge API key (pilot / Desk key). */
export const PREDGE_KEY_HEADER = "x-predge-key";
/** A paid call of this many USD or more is a large-tier verdict (POST /v1/verdicts/large, $0.50). */
export const LARGE_VERDICT_THRESHOLD_USD = 1;

/** Body of POST /v1/verdicts: what was promised, what was delivered, and what was paid. */
export type VerdictRequest = {
job: Json & { endpoint: string };
delivery: Json;
payment: Json & { amount_usd: number };
buyer_id?: string;
merchant_id?: string;
agent?: Json;
provider_agent?: Json;
};

type Json = Record<string, unknown>;
Expand Down Expand Up @@ -53,6 +74,30 @@ export function summarizeSettlementRisk(record: Json): Json {
};
}

/** The fields of a signed verdict an agent needs to act on it. */
export function summarizeVerdict(record: Json): Json {
const refund = (record.refund ?? {}) as Json;
return {
id: record.id,
verdict: record.verdict,
method: record.method,
reason_codes: record.reason_codes,
checks: record.checks,
refund_recommended: record.refund_recommended,
refund: {
recommended: refund.recommended ?? record.refund_recommended,
amount_usd: refund.amount_usd ?? record.refund_amount_usd,
from: refund.from,
to: refund.to,
status: refund.status,
instructions: refund.instructions,
},
issued_at: record.issued_at,
verify_url: record.verify_url,
fee: record.fee,
};
}

function apiError(status: number, data: Json | null, url: string) {
return {
error: true,
Expand All @@ -68,11 +113,96 @@ export class PredgeAPI {
private readonly baseUrl: string;
private readonly maxPaymentUsd: number;
private readonly trustedKeys: string[];
readonly apiKey: string | undefined;

constructor(options: PredgePluginOptions = {}) {
this.baseUrl = (options.baseUrl ?? "https://api.predge.io").replace(/\/+$/, "");
this.maxPaymentUsd = options.maxPaymentUsd ?? 0.05;
this.trustedKeys = options.trustedKeys ?? [PREDGE_ATTESTATION_PUBLIC_KEY];
const envKey = typeof process !== "undefined" ? process.env?.PREDGE_KEY : undefined;
this.apiKey = (options.apiKey ?? envKey)?.trim() || undefined;
}

/**
* Ask Predge for a signed delivery verdict: was the paid work delivered as promised?
* Sends the key (x-predge-key) when one is configured; otherwise, or when the key has no free verdicts left
* (402), pays over x402 from the signer, never above maxPaymentUsd. Calls of $1 or more go to the large tier.
*/
async requestVerdict(signer: X402Signer | undefined, request: VerdictRequest) {
const amount = Number(request.payment?.amount_usd);
const large = Number.isFinite(amount) && amount >= LARGE_VERDICT_THRESHOLD_USD;
const url = `${this.baseUrl}/v1/verdicts${large ? "/large" : ""}`;
const body = JSON.stringify(request);
const headers: Record<string, string> = { "Content-Type": "application/json", Accept: "application/json" };
if (this.apiKey) headers[PREDGE_KEY_HEADER] = this.apiKey;

let response: Response;
if (this.apiKey) {
response = await fetch(url, { method: "POST", headers, body });
if (response.status === 402 && !(signer && this.maxPaymentUsd > 0)) {
return {
error: true,
status: 402,
message:
"This key has no free verdicts left (pilot window over). Pay per verdict over x402 by configuring an EVM account, " +
"or get a key at https://predge.io/start . Nothing was charged.",
url,
};
}
} else {
if (this.maxPaymentUsd <= 0 || !signer) {
return {
error: true,
message:
"A verdict needs a Predge key (free pilot key at https://predge.io/start, option apiKey or env PREDGE_KEY) " +
"or an EVM account to pay over x402 ($0.05 under $1, $0.50 at $1 or more).",
};
}
response = new Response(null, { status: 402 });
}
if (response.status === 402 && signer) {
try {
({ response } = await fetchWithX402(
url,
signer,
BigInt(Math.floor(this.maxPaymentUsd * 1_000_000)),
fetch,
{ method: "POST", body, headers },
));
} catch (e) {
return { error: true, message: (e as Error).message, url };
}
}
const text = await response.text();
const data = parseJson(text);
if (!response.ok || !data) return apiError(response.status, data, url);
return { ...this.verdictResult(data, text, response), source: url };
}

/** Re-read a stored verdict by id (free, no key). Verifies its signature. */
async getVerdict(id: string) {
const url = `${this.baseUrl}/v1/verdicts/${encodeURIComponent(id)}`;
const response = await fetch(url, { headers: { Accept: "application/json" } });
const text = await response.text();
const data = parseJson(text);
if (!response.ok || !data) return apiError(response.status, data, url);
return { ...this.verdictResult(data, text, response), source: url };
}

private verdictResult(data: Json, text: string, response: Response) {
const paymentHeader = response.headers.get("payment-response");
let payment: unknown = null;
if (paymentHeader) {
payment = parseJson(Buffer.from(paymentHeader, "base64").toString("utf8")) ?? { raw: paymentHeader };
}
return {
...summarizeVerdict(data),
signature: {
...verifyPredgeRecord(data, this.trustedKeys),
bodySignature: verifyBodySignature(text, response.headers.get("x-predge-body-signature"), this.trustedKeys),
},
payment,
};
}

async getSettlementRisk(market: string) {
Expand Down
Loading
Loading