@blockrun/llm 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 BlockRun
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 ADDED
@@ -0,0 +1,320 @@
1
+ # @blockrun/llm
2
+
3
+ Pay-per-request access to GPT-4o, Claude 4, Gemini 2.5, and more via x402 micropayments on Base and Solana.
4
+
5
+ **Networks:** Base (Chain ID: 8453) and Solana Mainnet
6
+ **Payment:** USDC
7
+ **Protocol:** x402 v2 (CDP Facilitator)
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ # Base and Solana support (optional Solana deps auto-installed)
13
+ npm install @blockrun/llm
14
+ # or
15
+ pnpm add @blockrun/llm
16
+ # or
17
+ yarn add @blockrun/llm
18
+ ```
19
+
20
+ ## Quick Start (Base - Default)
21
+
22
+ ```typescript
23
+ import { LLMClient } from '@blockrun/llm';
24
+
25
+ const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
26
+ const response = await client.chat('openai/gpt-4o', 'Hello!');
27
+ ```
28
+
29
+ That's it. The SDK handles x402 payment automatically.
30
+
31
+ ## Quick Start (Solana)
32
+
33
+ ```typescript
34
+ import { LLMClient } from '@blockrun/llm';
35
+
36
+ const client = new LLMClient({ network: 'solana' }); // Uses BLOCKRUN_SOLANA_KEY
37
+ const response = await client.chat('openai/gpt-4o', 'Hello!');
38
+ ```
39
+
40
+ For Solana, set `BLOCKRUN_SOLANA_KEY` environment variable with your base58-encoded Solana secret key.
41
+
42
+ ## How It Works
43
+
44
+ 1. You send a request to BlockRun's API
45
+ 2. The API returns a 402 Payment Required with the price
46
+ 3. The SDK automatically signs a USDC payment on Base
47
+ 4. The request is retried with the payment proof
48
+ 5. You receive the AI response
49
+
50
+ **Your private key never leaves your machine** - it's only used for local signing.
51
+
52
+ ## Available Models
53
+
54
+ ### OpenAI GPT-5 Family
55
+ | Model | Input Price | Output Price |
56
+ |-------|-------------|--------------|
57
+ | `openai/gpt-5.2` | $1.75/M | $14.00/M |
58
+ | `openai/gpt-5.1` | $1.25/M | $10.00/M |
59
+ | `openai/gpt-5` | $1.25/M | $10.00/M |
60
+ | `openai/gpt-5-mini` | $0.25/M | $2.00/M |
61
+ | `openai/gpt-5-nano` | $0.05/M | $0.40/M |
62
+ | `openai/gpt-5.2-pro` | $21.00/M | $168.00/M |
63
+ | `openai/gpt-5-pro` | $15.00/M | $120.00/M |
64
+
65
+ ### OpenAI GPT-4 Family
66
+ | Model | Input Price | Output Price |
67
+ |-------|-------------|--------------|
68
+ | `openai/gpt-4.1` | $2.00/M | $8.00/M |
69
+ | `openai/gpt-4.1-mini` | $0.40/M | $1.60/M |
70
+ | `openai/gpt-4.1-nano` | $0.10/M | $0.40/M |
71
+ | `openai/gpt-4o` | $2.50/M | $10.00/M |
72
+ | `openai/gpt-4o-mini` | $0.15/M | $0.60/M |
73
+
74
+ ### OpenAI O-Series (Reasoning)
75
+ | Model | Input Price | Output Price |
76
+ |-------|-------------|--------------|
77
+ | `openai/o1` | $15.00/M | $60.00/M |
78
+ | `openai/o1-mini` | $1.10/M | $4.40/M |
79
+ | `openai/o3` | $2.00/M | $8.00/M |
80
+ | `openai/o3-mini` | $1.10/M | $4.40/M |
81
+ | `openai/o4-mini` | $1.10/M | $4.40/M |
82
+
83
+ ### Anthropic Claude
84
+ | Model | Input Price | Output Price |
85
+ |-------|-------------|--------------|
86
+ | `anthropic/claude-opus-4` | $15.00/M | $75.00/M |
87
+ | `anthropic/claude-sonnet-4` | $3.00/M | $15.00/M |
88
+ | `anthropic/claude-haiku-4.5` | $1.00/M | $5.00/M |
89
+
90
+ ### Google Gemini
91
+ | Model | Input Price | Output Price |
92
+ |-------|-------------|--------------|
93
+ | `google/gemini-3-pro-preview` | $2.00/M | $12.00/M |
94
+ | `google/gemini-2.5-pro` | $1.25/M | $10.00/M |
95
+ | `google/gemini-2.5-flash` | $0.15/M | $0.60/M |
96
+
97
+ ### Image Generation
98
+ | Model | Price |
99
+ |-------|-------|
100
+ | `openai/dall-e-3` | $0.04-0.08/image |
101
+ | `openai/gpt-image-1` | $0.02-0.04/image |
102
+ | `google/nano-banana` | $0.05/image |
103
+ | `google/nano-banana-pro` | $0.10-0.15/image |
104
+ | `black-forest/flux-1.1-pro` | $0.04/image |
105
+
106
+ ## Usage Examples
107
+
108
+ ### Simple Chat
109
+
110
+ ```typescript
111
+ import { LLMClient } from '@blockrun/llm';
112
+
113
+ const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
114
+
115
+ const response = await client.chat('openai/gpt-4o', 'Explain quantum computing');
116
+ console.log(response);
117
+
118
+ // With system prompt
119
+ const response2 = await client.chat('anthropic/claude-sonnet-4', 'Write a haiku', {
120
+ system: 'You are a creative poet.',
121
+ });
122
+ ```
123
+
124
+ ### Full Chat Completion
125
+
126
+ ```typescript
127
+ import { LLMClient, type ChatMessage } from '@blockrun/llm';
128
+
129
+ const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
130
+
131
+ const messages: ChatMessage[] = [
132
+ { role: 'system', content: 'You are a helpful assistant.' },
133
+ { role: 'user', content: 'How do I read a file in Node.js?' },
134
+ ];
135
+
136
+ const result = await client.chatCompletion('openai/gpt-4o', messages);
137
+ console.log(result.choices[0].message.content);
138
+ ```
139
+
140
+ ### List Available Models
141
+
142
+ ```typescript
143
+ import { LLMClient } from '@blockrun/llm';
144
+
145
+ const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
146
+ const models = await client.listModels();
147
+
148
+ for (const model of models) {
149
+ console.log(`${model.id}: $${model.inputPrice}/M input`);
150
+ }
151
+ ```
152
+
153
+ ### Multiple Requests
154
+
155
+ ```typescript
156
+ import { LLMClient } from '@blockrun/llm';
157
+
158
+ const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
159
+
160
+ const [gpt, claude, gemini] = await Promise.all([
161
+ client.chat('openai/gpt-4o', 'What is 2+2?'),
162
+ client.chat('anthropic/claude-sonnet-4', 'What is 3+3?'),
163
+ client.chat('google/gemini-2.5-flash', 'What is 4+4?'),
164
+ ]);
165
+ ```
166
+
167
+ ## Configuration
168
+
169
+ ```typescript
170
+ // Default: reads BASE_CHAIN_WALLET_KEY from environment
171
+ const client = new LLMClient();
172
+
173
+ // Or pass options explicitly
174
+ const client = new LLMClient({
175
+ privateKey: '0x...', // Your wallet key (never sent to server)
176
+ apiUrl: 'https://blockrun.ai/api', // Optional
177
+ timeout: 60000, // Optional (ms)
178
+ });
179
+ ```
180
+
181
+ ## Environment Variables
182
+
183
+ | Variable | Description |
184
+ |----------|-------------|
185
+ | `BASE_CHAIN_WALLET_KEY` | Your Base chain wallet private key (for Base) |
186
+ | `BLOCKRUN_SOLANA_KEY` | Your Solana wallet secret key - base58 (for Solana) |
187
+ | `BLOCKRUN_NETWORK` | Default network: `base` or `solana` (optional, default: base) |
188
+ | `BLOCKRUN_API_URL` | API endpoint (optional, default: https://blockrun.ai/api) |
189
+
190
+ ## Error Handling
191
+
192
+ ```typescript
193
+ import { LLMClient, APIError, PaymentError } from '@blockrun/llm';
194
+
195
+ const client = new LLMClient();
196
+
197
+ try {
198
+ const response = await client.chat('openai/gpt-4o', 'Hello!');
199
+ } catch (error) {
200
+ if (error instanceof PaymentError) {
201
+ console.error('Payment failed - check USDC balance');
202
+ } else if (error instanceof APIError) {
203
+ console.error(`API error: ${error.message}`);
204
+ }
205
+ }
206
+ ```
207
+
208
+ ## Testing
209
+
210
+ ### Running Unit Tests
211
+
212
+ Unit tests do not require API access or funded wallets:
213
+
214
+ ```bash
215
+ npm test # Run tests in watch mode
216
+ npm test run # Run tests once
217
+ npm test -- --coverage # Run with coverage report
218
+ ```
219
+
220
+ ### Running Integration Tests
221
+
222
+ Integration tests call the production API and require:
223
+ - A funded Base wallet with USDC ($1+ recommended)
224
+ - `BASE_CHAIN_WALLET_KEY` environment variable set
225
+ - Estimated cost: ~$0.05 per test run
226
+
227
+ ```bash
228
+ export BASE_CHAIN_WALLET_KEY=0x...
229
+ npm test -- test/integration # Run integration tests only
230
+ ```
231
+
232
+ Integration tests are automatically skipped if `BASE_CHAIN_WALLET_KEY` is not set.
233
+
234
+ ## Setting Up Your Wallet
235
+
236
+ ### Base (EVM)
237
+ 1. Create a wallet on Base (Coinbase Wallet, MetaMask, etc.)
238
+ 2. Get USDC on Base for API payments
239
+ 3. Export your private key and set as `BASE_CHAIN_WALLET_KEY`
240
+
241
+ ```bash
242
+ # .env
243
+ BASE_CHAIN_WALLET_KEY=0x...
244
+ ```
245
+
246
+ ### Solana
247
+ 1. Create a Solana wallet (Phantom, Backpack, Solflare, etc.)
248
+ 2. Get USDC on Solana for API payments
249
+ 3. Export your secret key and set as `BLOCKRUN_SOLANA_KEY`
250
+
251
+ ```bash
252
+ # .env
253
+ BLOCKRUN_SOLANA_KEY=...your_base58_secret_key
254
+ ```
255
+
256
+ Note: Solana transactions are gasless for the user - the CDP facilitator pays for transaction fees.
257
+
258
+ ## Security
259
+
260
+ ### Private Key Safety
261
+
262
+ - **Private key stays local**: Your key is only used for signing on your machine
263
+ - **No custody**: BlockRun never holds your funds
264
+ - **Verify transactions**: All payments are on-chain and verifiable
265
+
266
+ ### Best Practices
267
+
268
+ **Private Key Management:**
269
+ - Use environment variables, never hard-code keys
270
+ - Use dedicated wallets for API payments (separate from main holdings)
271
+ - Set spending limits by only funding payment wallets with small amounts
272
+ - Never commit `.env` files to version control
273
+ - Rotate keys periodically
274
+
275
+ **Input Validation:**
276
+ The SDK validates all inputs before API requests:
277
+ - Private keys (format, length, valid hex)
278
+ - API URLs (HTTPS required for production, HTTP allowed for localhost)
279
+ - Model names and parameters (ranges for max\_tokens, temperature, top\_p)
280
+
281
+ **Error Sanitization:**
282
+ API errors are automatically sanitized to prevent sensitive information leaks.
283
+
284
+ **Monitoring:**
285
+ ```typescript
286
+ const address = client.getWalletAddress();
287
+ console.log(`View transactions: https://basescan.org/address/${address}`);
288
+ ```
289
+
290
+ **Keep Updated:**
291
+ ```bash
292
+ npm update @blockrun/llm # Get security patches
293
+ ```
294
+
295
+ ## TypeScript Support
296
+
297
+ Full TypeScript support with exported types:
298
+
299
+ ```typescript
300
+ import {
301
+ LLMClient,
302
+ type ChatMessage,
303
+ type ChatResponse,
304
+ type ChatOptions,
305
+ type Model,
306
+ APIError,
307
+ PaymentError,
308
+ } from '@blockrun/llm';
309
+ ```
310
+
311
+ ## Links
312
+
313
+ - [Website](https://blockrun.ai)
314
+ - [Documentation](https://docs.blockrun.ai)
315
+ - [GitHub](https://github.com/blockrun/blockrun-llm-ts)
316
+ - [Discord](https://discord.gg/blockrun)
317
+
318
+ ## License
319
+
320
+ MIT
@@ -0,0 +1,90 @@
1
+ // src/validation.ts
2
+ var LOCALHOST_DOMAINS = ["localhost", "127.0.0.1"];
3
+ function validatePrivateKey(key) {
4
+ if (typeof key !== "string") {
5
+ throw new Error("Private key must be a string");
6
+ }
7
+ if (!key.startsWith("0x")) {
8
+ throw new Error("Private key must start with 0x");
9
+ }
10
+ if (key.length !== 66) {
11
+ throw new Error(
12
+ "Private key must be 66 characters (0x + 64 hexadecimal characters)"
13
+ );
14
+ }
15
+ if (!/^0x[0-9a-fA-F]{64}$/.test(key)) {
16
+ throw new Error(
17
+ "Private key must contain only hexadecimal characters (0-9, a-f, A-F)"
18
+ );
19
+ }
20
+ }
21
+ function validateApiUrl(url) {
22
+ let parsed;
23
+ try {
24
+ parsed = new URL(url);
25
+ } catch (error) {
26
+ throw new Error("Invalid API URL format");
27
+ }
28
+ const isLocalhost = LOCALHOST_DOMAINS.includes(parsed.hostname);
29
+ if (parsed.protocol !== "https:" && !isLocalhost) {
30
+ throw new Error(
31
+ `API URL must use HTTPS for non-localhost endpoints. Use https:// instead of ${parsed.protocol}//`
32
+ );
33
+ }
34
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
35
+ throw new Error(
36
+ `Invalid protocol: ${parsed.protocol}. Use http:// or https://`
37
+ );
38
+ }
39
+ }
40
+ function sanitizeErrorResponse(errorBody) {
41
+ if (typeof errorBody !== "object" || errorBody === null) {
42
+ return { message: "API request failed" };
43
+ }
44
+ const body = errorBody;
45
+ return {
46
+ message: typeof body.error === "string" ? body.error : "API request failed",
47
+ code: typeof body.code === "string" ? body.code : void 0
48
+ };
49
+ }
50
+ function validateResourceUrl(url, baseUrl) {
51
+ try {
52
+ const parsed = new URL(url);
53
+ const baseParsed = new URL(baseUrl);
54
+ if (parsed.hostname !== baseParsed.hostname) {
55
+ console.warn(
56
+ `Resource URL hostname mismatch: ${parsed.hostname} vs ${baseParsed.hostname}. Using safe default instead.`
57
+ );
58
+ return `${baseUrl}/v1/chat/completions`;
59
+ }
60
+ if (parsed.protocol !== baseParsed.protocol) {
61
+ console.warn(
62
+ `Resource URL protocol mismatch: ${parsed.protocol} vs ${baseParsed.protocol}. Using safe default instead.`
63
+ );
64
+ return `${baseUrl}/v1/chat/completions`;
65
+ }
66
+ return url;
67
+ } catch (error) {
68
+ console.warn(`Invalid resource URL format: ${url}. Using safe default.`);
69
+ return `${baseUrl}/v1/chat/completions`;
70
+ }
71
+ }
72
+ function extractPrivateKey(account) {
73
+ if ("source" in account && typeof account.source === "string") {
74
+ return account.source;
75
+ }
76
+ if ("key" in account && typeof account.key === "string") {
77
+ return account.key;
78
+ }
79
+ throw new Error(
80
+ "Unable to extract private key from account. This may indicate an incompatible viem version."
81
+ );
82
+ }
83
+
84
+ export {
85
+ validatePrivateKey,
86
+ validateApiUrl,
87
+ sanitizeErrorResponse,
88
+ validateResourceUrl,
89
+ extractPrivateKey
90
+ };
@@ -0,0 +1,48 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ };
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
39
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
40
+
41
+ export {
42
+ __require,
43
+ __esm,
44
+ __commonJS,
45
+ __export,
46
+ __toESM,
47
+ __toCommonJS
48
+ };