agent402-function-calling 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/index.d.ts +42 -0
- package/index.js +209 -0
- package/package.json +58 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cardhavok LLC (doing business as Havok Holdings LLC)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,113 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent402-function-calling
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Agent402](https://agent402.tools) tools as **function-calling tool definitions**, for use with the OpenAI API and other function-calling APIs. Agent402 is the open-source, self-hostable x402 + MCP server with 500+ pay-per-call web tools (browser, web search, PDF, images, live data, payment helpers, wallet-keyed memory).
|
|
4
|
+
|
|
5
|
+
Works with the OpenAI API (`chat.completions`, the Responses API). Agent402 is not affiliated with or endorsed by OpenAI.
|
|
6
|
+
|
|
7
|
+
Formerly `agent402-openai-tools`: the same API under a new name. Change the dependency and the import specifier; nothing else changes.
|
|
8
|
+
|
|
9
|
+
> **Agent402 is the applied layer of [Agentic Finance](https://agent402.tools/agentic-finance)** - agents that pay and get paid on their own over the two open wires, [x402](https://agent402.tools/what-is-x402) and [MPP](https://agent402.tools/what-is-mpp) (Machine Payments Protocol). Every paid endpoint answers both on the same 402; wallet-only tools take any payment-wrapped fetch (`@x402/fetch`, or a stock `mppx` fetch).
|
|
10
|
+
|
|
11
|
+
- **Zero new infra.** Get back a ready-to-pass `tools` array for `chat.completions`, Assistants v2, or the Responses API.
|
|
12
|
+
- **Free tier by default.** No wallet needed - the compute-payable tools settle with a built-in proof-of-work (sub-second sha256 puzzle).
|
|
13
|
+
- **Wallet-only tools optional.** Pass an `@x402/fetch`-wrapped fetch and the model can call any tool in the catalog.
|
|
14
|
+
- **Doesn't burn discovery tokens.** Stop the model from "exploring" the web to find a tool - give it the catalog up front.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install openai agent402-function-calling @x402/fetch @x402/core @x402/evm viem
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The `@x402/*` and `viem` packages pay wallet-only tools from your wallet; the free tier needs only the first two.
|
|
23
|
+
|
|
24
|
+
## Use with `chat.completions`
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
import OpenAI from "openai";
|
|
28
|
+
import { agent402Tools } from "agent402-function-calling";
|
|
29
|
+
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
30
|
+
import { x402Client } from "@x402/core/client";
|
|
31
|
+
import { registerExactEvmScheme } from "@x402/evm/exact/client";
|
|
32
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
33
|
+
|
|
34
|
+
const payClient = new x402Client();
|
|
35
|
+
registerExactEvmScheme(payClient, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
|
|
36
|
+
const payFetch = wrapFetchWithPayment(fetch, payClient);
|
|
37
|
+
|
|
38
|
+
const openai = new OpenAI();
|
|
39
|
+
|
|
40
|
+
// Pick the tools you want the model to know about. Smaller list = better tool-selection.
|
|
41
|
+
// Web search, then a cited answer: both wallet-only, paid per call through payFetch.
|
|
42
|
+
const { tools, execute } = await agent402Tools({ slugs: ["search", "answer"], freeOnly: false, fetch: payFetch });
|
|
43
|
+
|
|
44
|
+
const messages = [{ role: "user", content: "Search the web for x402 payment protocol adoption, then answer with citations: what is the x402 payment protocol?" }];
|
|
45
|
+
for (let turn = 0; turn < 4; turn++) {
|
|
46
|
+
const res = await openai.chat.completions.create({ model: "gpt-6-luna", messages, tools });
|
|
47
|
+
const msg = res.choices[0].message;
|
|
48
|
+
messages.push(msg);
|
|
49
|
+
if (!msg.tool_calls?.length) { console.log(msg.content); break; }
|
|
50
|
+
for (const call of msg.tool_calls) {
|
|
51
|
+
const result = await execute(call.function.name, JSON.parse(call.function.arguments));
|
|
52
|
+
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**No wallet yet?** The pure-CPU tools (hash, uuid, base64, markdown, JSON and more) run free with proof-of-work and no wallet. Leave out `fetch`; the default (`freeOnly: true`) keeps only those tools:
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
const { tools, execute } = await agent402Tools({ slugs: ["hash", "uuid", "json-to-csv"] });
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Use with Assistants v2 or the Responses API
|
|
64
|
+
|
|
65
|
+
The shape returned by `agent402Tools()` is the same OpenAI function-calling JSON used by every flavor of the OpenAI API. Pass `tools` directly to `assistants.create({ tools })` or to `responses.create({ tools })`.
|
|
66
|
+
|
|
67
|
+
## More wallet-only tools
|
|
68
|
+
|
|
69
|
+
The rest of the wallet-only catalog (browser, network, memory) is paid the same way: list the slugs beside `freeOnly: false` and the same `payFetch`.
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
const { tools, execute } = await agent402Tools({
|
|
73
|
+
slugs: ["extract", "render", "screenshot"],
|
|
74
|
+
freeOnly: false,
|
|
75
|
+
fetch: payFetch,
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Spending caps
|
|
80
|
+
|
|
81
|
+
agent402-client 0.10.0 and later hold one ceiling by default: `maxPerCallUsd`
|
|
82
|
+
of $5, above every catalog price (`0` or `"off"` turns it off). The rolling
|
|
83
|
+
caps are opt-in. Pass agent402-client's caps through (since 0.2.0); a paid
|
|
84
|
+
call over one is refused before anything is signed, with a
|
|
85
|
+
`SpendingLimitError`:
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
const { tools, execute } = await agent402Tools({
|
|
89
|
+
slugs: ["search", "answer"], freeOnly: false, fetch: payFetch,
|
|
90
|
+
x402Client: client, // the @x402/core client payFetch wraps: caps hold at signing
|
|
91
|
+
maxPerCallUsd: 0.05, // per call
|
|
92
|
+
dailyLimitUsd: 5, // rolling 24 hours
|
|
93
|
+
maxPerHostUsd: 1, // rolling 24 hours, per seller host
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`agent402Execute` takes the same options.
|
|
98
|
+
|
|
99
|
+
## Self-hosted Agent402
|
|
100
|
+
|
|
101
|
+
Point at your own instance:
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
const { tools, execute } = await agent402Tools({ baseUrl: "https://agent402.example.com" });
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Trust & `baseUrl`
|
|
108
|
+
|
|
109
|
+
The catalog server you point `baseUrl` at controls the **name, description, and JSON Schema** of every generated tool - and tool descriptions are passed to your LLM. Only point `baseUrl` at an Agent402 instance you operate or trust. The default (`https://agent402.tools`) is the maintained, open-source hosted instance.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Type declarations for agent402-function-calling. The runtime is index.js (plain ES modules on
|
|
2
|
+
// agent402-client); these declarations describe its public API.
|
|
3
|
+
import type { Agent402, FetchLike } from "agent402-client";
|
|
4
|
+
|
|
5
|
+
export interface Agent402ToolOptions {
|
|
6
|
+
/** Default "https://agent402.tools". */
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
/** Only these slugs (recommended: every tool is a definition the model reads). */
|
|
9
|
+
slugs?: string[];
|
|
10
|
+
/** Only the tools that run free with proof of work (default true). */
|
|
11
|
+
freeOnly?: boolean;
|
|
12
|
+
/** An x402- or MPP-wrapped fetch that pays wallet-only tools. */
|
|
13
|
+
fetch?: FetchLike;
|
|
14
|
+
/** Spending caps passed to agent402-client: one paid call (default 5; 0 or "off" turns it off). */
|
|
15
|
+
maxPerCallUsd?: number | string | null;
|
|
16
|
+
/** Rolling 24-hour total for paid calls (opt-in). */
|
|
17
|
+
dailyLimitUsd?: number | null;
|
|
18
|
+
/** Rolling 24-hour total per seller host (opt-in). */
|
|
19
|
+
maxPerHostUsd?: number | null;
|
|
20
|
+
/** The @x402/core x402Client the fetch wraps, so the caps hold on the payment that is signed. */
|
|
21
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
22
|
+
x402Client?: any;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type ExecuteOptions = Omit<Agent402ToolOptions, "slugs" | "freeOnly">;
|
|
26
|
+
|
|
27
|
+
/** Runs a tool by its tool name (or slug) and resolves to its JSON answer. */
|
|
28
|
+
export type Agent402Execute = (name: string, args?: Record<string, unknown>) => Promise<unknown>;
|
|
29
|
+
|
|
30
|
+
/** An OpenAI Chat Completions function tool. */
|
|
31
|
+
export interface OpenAIFunctionTool {
|
|
32
|
+
type: "function";
|
|
33
|
+
function: { name: string; description: string; parameters: Record<string, unknown> };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Agent402 tools in the OpenAI function-calling shape, the client, and an executor. */
|
|
37
|
+
export function agent402Tools(opts?: Agent402ToolOptions): Promise<{ client: Agent402; tools: OpenAIFunctionTool[]; execute: Agent402Execute }>;
|
|
38
|
+
|
|
39
|
+
/** An executor for a tool list built another way. */
|
|
40
|
+
export function agent402Execute(opts?: ExecuteOptions): Agent402Execute;
|
|
41
|
+
|
|
42
|
+
export default agent402Tools;
|
package/index.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// agent402-function-calling (formerly agent402-openai-tools): Agent402 tools as
|
|
2
|
+
// function-calling definitions for use with the OpenAI API.
|
|
3
|
+
//
|
|
4
|
+
// Turn the Agent402 catalog (500+ pay-per-call web tools) into OpenAI tool
|
|
5
|
+
// definitions the model can invoke, with payment handled for you under the
|
|
6
|
+
// hood by agent402-client (proof-of-work for the free tier, x402+USDC for
|
|
7
|
+
// wallet-only tools when you pass a payFetch).
|
|
8
|
+
//
|
|
9
|
+
// import OpenAI from "openai";
|
|
10
|
+
// import { agent402Tools, agent402Execute } from "agent402-function-calling";
|
|
11
|
+
//
|
|
12
|
+
// const openai = new OpenAI();
|
|
13
|
+
// const { tools, execute } = await agent402Tools({ slugs: ["extract","hash","render"] });
|
|
14
|
+
//
|
|
15
|
+
// const res = await openai.chat.completions.create({
|
|
16
|
+
// model: "gpt-4o-mini",
|
|
17
|
+
// messages: [{ role: "user", content: "Get the title of https://example.com/article" }],
|
|
18
|
+
// tools,
|
|
19
|
+
// });
|
|
20
|
+
// // when the model returns a tool call:
|
|
21
|
+
// // const out = await execute(call.function.name, JSON.parse(call.function.arguments));
|
|
22
|
+
//
|
|
23
|
+
// Works with chat.completions, the Assistants v2 API, and the Responses API,
|
|
24
|
+
// they all consume the same OpenAI function-calling JSON shape.
|
|
25
|
+
|
|
26
|
+
import { Agent402 } from "agent402-client";
|
|
27
|
+
|
|
28
|
+
const DEFAULT_BASE = "https://agent402.tools";
|
|
29
|
+
// Keep in lockstep with package.json: the User-Agent product token that names
|
|
30
|
+
// this package on every call it sends.
|
|
31
|
+
const USER_AGENT = "agent402-function-calling/0.3.0";
|
|
32
|
+
|
|
33
|
+
// Discovery reads (catalog, find, route, manifest, a proof-of-work challenge)
|
|
34
|
+
// settle nothing, so a 503 the server sheds under load is safe to repeat. It
|
|
35
|
+
// is retried only when it names its own delay (a Retry-After header or a
|
|
36
|
+
// retryAfterSeconds body field), at most DISCOVERY_ATTEMPTS tries in all,
|
|
37
|
+
// each wait capped at DISCOVERY_MAX_WAIT_MS. A paid call never goes through
|
|
38
|
+
// here: a repeat of one could settle twice.
|
|
39
|
+
const DISCOVERY_ATTEMPTS = 3;
|
|
40
|
+
const DISCOVERY_MAX_WAIT_MS = 5000;
|
|
41
|
+
|
|
42
|
+
async function shedRetryWaitMs(r) {
|
|
43
|
+
if (!r || r.status !== 503) return null;
|
|
44
|
+
const header = r.headers && typeof r.headers.get === "function" ? r.headers.get("retry-after") : null;
|
|
45
|
+
let seconds = header != null && String(header).trim() !== "" ? Number(header) : NaN;
|
|
46
|
+
if (!Number.isFinite(seconds)) {
|
|
47
|
+
try {
|
|
48
|
+
const body = await (typeof r.clone === "function" ? r.clone() : r).json();
|
|
49
|
+
seconds = Number(body && body.retryAfterSeconds);
|
|
50
|
+
} catch { seconds = NaN; }
|
|
51
|
+
}
|
|
52
|
+
if (!Number.isFinite(seconds) || seconds < 0) return null;
|
|
53
|
+
return Math.min(seconds * 1000, DISCOVERY_MAX_WAIT_MS);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Resolves with the 2xx response, or throws `${label}: HTTP <status>` (plus
|
|
57
|
+
// "after N attempts" when it retried, and the server's `error` text) with
|
|
58
|
+
// `.status`, `.body` and `.attempts` set.
|
|
59
|
+
// `init` may be a function, so each attempt gets its own timeout signal.
|
|
60
|
+
async function discoveryFetch(fetchImpl, label, url, init) {
|
|
61
|
+
let r;
|
|
62
|
+
let attempts = 0;
|
|
63
|
+
for (;;) {
|
|
64
|
+
attempts++;
|
|
65
|
+
const i = (typeof init === "function" ? init() : init) || {};
|
|
66
|
+
r = await fetchImpl(url, { ...i, headers: { "User-Agent": USER_AGENT, ...(i.headers || {}) } });
|
|
67
|
+
if (r.ok) return r;
|
|
68
|
+
if (attempts >= DISCOVERY_ATTEMPTS) break;
|
|
69
|
+
const wait = await shedRetryWaitMs(r);
|
|
70
|
+
if (wait == null) break;
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
72
|
+
}
|
|
73
|
+
const err = await responseError(`${label}: HTTP ${r.status}${attempts > 1 ? ` after ${attempts} attempts` : ""}`, r);
|
|
74
|
+
err.attempts = attempts;
|
|
75
|
+
throw err;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// The server's own answer to a failed request, on the thrown error: its
|
|
79
|
+
// `error` text joins the message, and `.status` and `.body` (the parsed JSON,
|
|
80
|
+
// else the text, at most ERROR_BODY_MAX characters) are set, so a caller sees
|
|
81
|
+
// why the call failed (a refusal, a limit, a missing parameter).
|
|
82
|
+
const ERROR_BODY_MAX = 4000;
|
|
83
|
+
async function responseError(message, r) {
|
|
84
|
+
let text = "";
|
|
85
|
+
try { text = typeof r?.text === "function" ? String(await r.text()) : ""; } catch { text = ""; }
|
|
86
|
+
text = text.slice(0, ERROR_BODY_MAX);
|
|
87
|
+
let body = null;
|
|
88
|
+
try { body = text ? JSON.parse(text) : null; } catch { body = null; }
|
|
89
|
+
const said = body && typeof body === "object" && typeof body.error === "string" ? body.error.slice(0, 500) : (!body ? text.trim().slice(0, 300) : "");
|
|
90
|
+
const err = new Error(said ? `${message}: ${said}` : message);
|
|
91
|
+
err.status = r?.status;
|
|
92
|
+
err.body = body ?? (text || null);
|
|
93
|
+
return err;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// OpenAI's function-calling spec requires names matching ^[a-zA-Z0-9_-]{1,64}$.
|
|
97
|
+
// Agent402 slugs already conform, but be defensive in case of self-hosted catalogs.
|
|
98
|
+
const sanitizeName = (s) => String(s).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Fetch the Agent402 catalog and return:
|
|
102
|
+
* - `tools`: OpenAI function-calling tool definitions (array)
|
|
103
|
+
* - `execute`: async (name, args) => result, pays under the hood
|
|
104
|
+
* - `client`: the underlying Agent402 client (use for find()/clearCache())
|
|
105
|
+
*
|
|
106
|
+
* @param {object} [opts]
|
|
107
|
+
* @param {string} [opts.baseUrl="https://agent402.tools"]
|
|
108
|
+
* @param {string[]} [opts.slugs] Restrict to these slugs (recommended; smaller tool list = better tool-selection)
|
|
109
|
+
* @param {boolean} [opts.freeOnly=true] Default: only include compute-payable tools (no wallet needed)
|
|
110
|
+
* @param {typeof fetch} [opts.fetch] An x402-wrapped fetch (only needed for wallet-only tools)
|
|
111
|
+
* @param {number} [opts.maxPerCallUsd] Spending caps passed to agent402-client ($5 per call by default from 0.10.0):
|
|
112
|
+
* @param {number} [opts.dailyLimitUsd] a paid call over one is refused before anything is signed
|
|
113
|
+
* @param {number} [opts.maxPerHostUsd]
|
|
114
|
+
* @param {object} [opts.x402Client] The @x402/core client your fetch wraps, so the caps hold at signing
|
|
115
|
+
*/
|
|
116
|
+
export async function agent402Tools({ baseUrl = DEFAULT_BASE, slugs, freeOnly = true, fetch: payFetch, maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client } = {}) {
|
|
117
|
+
const client = new Agent402({ userAgent: USER_AGENT, baseUrl, fetch: payFetch, ...capOptions({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client }) });
|
|
118
|
+
// Bounded discovery fetch: caller picks baseUrl, so cap the wait. Node ≥18
|
|
119
|
+
// exposes AbortSignal.timeout() (declared in package.json engines).
|
|
120
|
+
const r = await discoveryFetch(globalThis.fetch, `Could not load ${baseUrl}/openapi.json`, `${baseUrl}/openapi.json`, () => ({ signal: AbortSignal.timeout(15000) }));
|
|
121
|
+
const spec = await r.json();
|
|
122
|
+
|
|
123
|
+
const wanted = slugs ? new Set(slugs) : null;
|
|
124
|
+
const tools = [];
|
|
125
|
+
const slugByName = new Map();
|
|
126
|
+
|
|
127
|
+
for (const [path, methods] of Object.entries(spec.paths || {})) {
|
|
128
|
+
for (const [method, op] of Object.entries(methods)) {
|
|
129
|
+
const slug = op.operationId?.replace(/Get$/, "");
|
|
130
|
+
if (!slug) continue;
|
|
131
|
+
if (wanted && !wanted.has(slug)) continue;
|
|
132
|
+
|
|
133
|
+
const parameters = method.toLowerCase() === "get"
|
|
134
|
+
? {
|
|
135
|
+
type: "object",
|
|
136
|
+
properties: Object.fromEntries((op.parameters || []).map((p) => [p.name, { type: p.schema?.type || "string", description: p.description }])),
|
|
137
|
+
required: (op.parameters || []).filter((p) => p.required).map((p) => p.name),
|
|
138
|
+
}
|
|
139
|
+
: op.requestBody?.content?.["application/json"]?.schema || { type: "object", properties: {} };
|
|
140
|
+
|
|
141
|
+
const computePayable = !!op["x-compute-payable"] || op.summary?.includes("FREE");
|
|
142
|
+
// If freeOnly and we can't tell, fall back to /api/pricing for the truth.
|
|
143
|
+
// We do that lookup once below.
|
|
144
|
+
const name = sanitizeName(slug);
|
|
145
|
+
slugByName.set(name, slug);
|
|
146
|
+
tools.push({
|
|
147
|
+
type: "function",
|
|
148
|
+
function: {
|
|
149
|
+
name,
|
|
150
|
+
description: shortDesc(op.summary, op.description),
|
|
151
|
+
parameters,
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Authoritative freeOnly filter: /openapi.json doesn't carry computePayable,
|
|
158
|
+
// but /api/pricing does. One extra HTTP call, cached for the life of the result.
|
|
159
|
+
if (freeOnly) {
|
|
160
|
+
const pr = await discoveryFetch(globalThis.fetch, `Could not load ${baseUrl}/api/pricing`, `${baseUrl}/api/pricing`, () => ({ signal: AbortSignal.timeout(15000) }));
|
|
161
|
+
const pricing = await pr.json();
|
|
162
|
+
const free = new Set((pricing.endpoints || []).filter((e) => e.computePayable).map((e) => e.slug));
|
|
163
|
+
return {
|
|
164
|
+
client,
|
|
165
|
+
tools: tools.filter((t) => free.has(slugByName.get(t.function.name))),
|
|
166
|
+
execute: makeExecute(client, slugByName),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return { client, tools, execute: makeExecute(client, slugByName) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function makeExecute(client, slugByName) {
|
|
174
|
+
return async function execute(name, args) {
|
|
175
|
+
const slug = slugByName.get(name) || name;
|
|
176
|
+
return client.call(slug, args ?? {});
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Standalone executor for users who built their tool list a different way
|
|
182
|
+
* (e.g. generated server-side, persisted in a database). Returns an
|
|
183
|
+
* `execute(name, args)` that calls Agent402 with PoW or x402 payment.
|
|
184
|
+
*/
|
|
185
|
+
export function agent402Execute({ baseUrl = DEFAULT_BASE, fetch: payFetch, maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client } = {}) {
|
|
186
|
+
const client = new Agent402({ userAgent: USER_AGENT, baseUrl, fetch: payFetch, ...capOptions({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client }) });
|
|
187
|
+
return async function execute(name, args) {
|
|
188
|
+
return client.call(name, args ?? {});
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function shortDesc(summary, description) {
|
|
193
|
+
// OpenAI tool descriptions should be concise, long descriptions hurt
|
|
194
|
+
// tool-selection. Take the first sentence of the description.
|
|
195
|
+
const d = (description || summary || "").split("\n\n")[0].trim();
|
|
196
|
+
return d.length > 280 ? d.slice(0, 277) + "..." : d;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export default agent402Tools;
|
|
200
|
+
|
|
201
|
+
/** The opt-in spending caps a caller passed, as agent402-client options.
|
|
202
|
+
* None are set by default: a caller who sets none is never refused a
|
|
203
|
+
* purchase. */
|
|
204
|
+
function capOptions({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client } = {}) {
|
|
205
|
+
const out = {};
|
|
206
|
+
for (const [k, v] of Object.entries({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd })) if (v != null) out[k] = v;
|
|
207
|
+
if (x402Client) out.x402Client = x402Client;
|
|
208
|
+
return out;
|
|
209
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent402-function-calling",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Agent402 tools as function-calling tool definitions, for use with the OpenAI API (chat.completions, Responses) and other function-calling APIs (Agentic Finance over x402 or MPP): turn tools from Agent402's catalog of 500+ pay-per-call tools and skill packs into tool definitions, one per catalog tool, with payment handled by agent402-client. Free via proof-of-work for the pure-CPU tools, or pay per call in USDC on 13 chains or USDG on Robinhood Chain. Formerly agent402-openai-tools.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"types": "index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./index.d.ts",
|
|
11
|
+
"default": "./index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"index.js",
|
|
16
|
+
"index.d.ts",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=18"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"test": "node test.js"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"openai",
|
|
27
|
+
"function-calling",
|
|
28
|
+
"tools",
|
|
29
|
+
"x402",
|
|
30
|
+
"ai-agents",
|
|
31
|
+
"agent-tools",
|
|
32
|
+
"llm-tools",
|
|
33
|
+
"usdc",
|
|
34
|
+
"base",
|
|
35
|
+
"proof-of-work",
|
|
36
|
+
"http-402",
|
|
37
|
+
"micropayments",
|
|
38
|
+
"agent402",
|
|
39
|
+
"tool-discovery",
|
|
40
|
+
"smart-order-router",
|
|
41
|
+
"mcp",
|
|
42
|
+
"agentic-commerce",
|
|
43
|
+
"agentic-finance",
|
|
44
|
+
"aifi",
|
|
45
|
+
"mpp",
|
|
46
|
+
"machine-payments-protocol",
|
|
47
|
+
"agentic-payments"
|
|
48
|
+
],
|
|
49
|
+
"author": "Cardhavok LLC (doing business as Havok Holdings LLC) <mike@agent402.tools> (https://github.com/MikeyPetrillo/Agent402)",
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "git+https://github.com/MikeyPetrillo/Agent402.git",
|
|
54
|
+
"directory": "adapters/openai-tools"
|
|
55
|
+
},
|
|
56
|
+
"homepage": "https://agent402.tools",
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"agent402-client": ">=0.8.21 <1.0.0"
|
|
59
|
+
}
|
|
60
|
+
}
|