@blockrun/llm 1.4.3 → 1.6.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/dist/index.d.ts CHANGED
@@ -140,10 +140,48 @@ interface SearchParameters {
140
140
  toDate?: string;
141
141
  maxSearchResults?: number;
142
142
  }
143
+ /** Usage info for Live Search sources */
144
+ interface SearchUsage {
145
+ /** Number of search sources used in the response */
146
+ numSourcesUsed?: number;
147
+ }
143
148
  interface Spending {
144
149
  totalUsd: number;
145
150
  calls: number;
146
151
  }
152
+ /** Pre-request cost estimate for a chat call */
153
+ interface CostEstimate {
154
+ /** Model ID used for the estimate */
155
+ model: string;
156
+ /** Estimated input token count */
157
+ estimatedInputTokens: number;
158
+ /** Estimated output token count */
159
+ estimatedOutputTokens: number;
160
+ /** Estimated cost in USD */
161
+ estimatedCostUsd: number;
162
+ }
163
+ /** Per-call spending report with running session totals */
164
+ interface SpendingReport {
165
+ /** Model ID used */
166
+ model: string;
167
+ /** Input tokens consumed */
168
+ inputTokens: number;
169
+ /** Output tokens consumed */
170
+ outputTokens: number;
171
+ /** Cost of this call in USD */
172
+ costUsd: number;
173
+ /** Cumulative session spend in USD */
174
+ sessionTotalUsd: number;
175
+ /** Total number of calls in this session */
176
+ sessionCalls: number;
177
+ }
178
+ /** Chat response bundled with its spending report */
179
+ interface ChatResponseWithCost {
180
+ /** The chat completion response */
181
+ response: ChatResponse;
182
+ /** Spending report for this call */
183
+ spendingReport: SpendingReport;
184
+ }
147
185
  interface ResourceInfo {
148
186
  url: string;
149
187
  description?: string;
@@ -184,9 +222,9 @@ interface ChatOptions {
184
222
  temperature?: number;
185
223
  /** Nucleus sampling parameter */
186
224
  topP?: number;
187
- /** Enable xAI Live Search (shortcut for searchParameters.mode = "on") */
225
+ /** Enable Live Search (shortcut for searchParameters.mode = "on") */
188
226
  search?: boolean;
189
- /** Full xAI Live Search configuration (for Grok models) */
227
+ /** Full Live Search configuration (for search-enabled models) */
190
228
  searchParameters?: SearchParameters;
191
229
  }
192
230
  interface ChatCompletionOptions {
@@ -196,9 +234,9 @@ interface ChatCompletionOptions {
196
234
  temperature?: number;
197
235
  /** Nucleus sampling parameter */
198
236
  topP?: number;
199
- /** Enable xAI Live Search (shortcut for searchParameters.mode = "on") */
237
+ /** Enable Live Search (shortcut for searchParameters.mode = "on") */
200
238
  search?: boolean;
201
- /** Full xAI Live Search configuration (for Grok models) */
239
+ /** Full Live Search configuration (for search-enabled models) */
202
240
  searchParameters?: SearchParameters;
203
241
  /** Tool definitions for function calling */
204
242
  tools?: Tool[];
@@ -258,6 +296,68 @@ interface SearchOptions {
258
296
  /** End date filter (YYYY-MM-DD) */
259
297
  toDate?: string;
260
298
  }
299
+ interface ExaSearchOptions {
300
+ /** Number of results to return (default: 10, max: 100) */
301
+ numResults?: number;
302
+ /** Restrict to a content category */
303
+ category?: "github" | "news" | "research paper" | "linkedin profile" | "personal site" | "tweet" | "financial report" | "pdf" | "company";
304
+ /** Only include pages published after this date (ISO 8601) */
305
+ startPublishedDate?: string;
306
+ /** Only include pages published before this date (ISO 8601) */
307
+ endPublishedDate?: string;
308
+ /** Only search within these domains */
309
+ includeDomains?: string[];
310
+ /** Exclude these domains from results */
311
+ excludeDomains?: string[];
312
+ }
313
+ interface ExaSearchItem {
314
+ id: string;
315
+ url: string;
316
+ title: string;
317
+ publishedDate?: string;
318
+ author?: string;
319
+ score?: number;
320
+ }
321
+ interface ExaSearchResponse {
322
+ requestId: string;
323
+ resolvedSearchType: string;
324
+ results: ExaSearchItem[];
325
+ searchTime: number;
326
+ costDollars: {
327
+ total: number;
328
+ };
329
+ }
330
+ interface ExaAnswerCitation {
331
+ id: string;
332
+ title: string;
333
+ url: string;
334
+ publishedDate?: string;
335
+ favicon?: string;
336
+ }
337
+ interface ExaAnswerResponse {
338
+ requestId: string;
339
+ answer: string;
340
+ citations: ExaAnswerCitation[];
341
+ }
342
+ interface ExaContentItem {
343
+ id: string;
344
+ url: string;
345
+ title: string;
346
+ text: string;
347
+ author?: string | null;
348
+ }
349
+ interface ExaContentsResponse {
350
+ results: ExaContentItem[];
351
+ costDollars: {
352
+ total: number;
353
+ };
354
+ }
355
+ interface ExaFindSimilarOptions {
356
+ /** Number of results to return (default: 10, max: 100) */
357
+ numResults?: number;
358
+ /** Exclude pages from the same domain as the reference URL */
359
+ excludeSourceDomain?: boolean;
360
+ }
261
361
  interface XUser {
262
362
  id: string;
263
363
  userName: string;
@@ -406,7 +506,7 @@ declare class APIError extends BlockrunError {
406
506
  * // Option 2: Pass private key directly
407
507
  * const client = new LLMClient({ privateKey: '0x...' });
408
508
  *
409
- * const response = await client.chat('openai/gpt-4o', 'Hello!');
509
+ * const response = await client.chat('openai/gpt-5.2', 'Hello!');
410
510
  * console.log(response);
411
511
  */
412
512
 
@@ -445,6 +545,8 @@ declare class LLMClient {
445
545
  private sessionCalls;
446
546
  private modelPricingCache;
447
547
  private modelPricingPromise;
548
+ private preAuthCache;
549
+ private static readonly PRE_AUTH_TTL_MS;
448
550
  /**
449
551
  * Initialize the BlockRun LLM client.
450
552
  *
@@ -454,13 +556,13 @@ declare class LLMClient {
454
556
  /**
455
557
  * Simple 1-line chat interface.
456
558
  *
457
- * @param model - Model ID (e.g., 'openai/gpt-4o', 'anthropic/claude-sonnet-4')
559
+ * @param model - Model ID (e.g., 'openai/gpt-5.2', 'anthropic/claude-sonnet-4.6')
458
560
  * @param prompt - User message
459
561
  * @param options - Optional chat parameters
460
562
  * @returns Assistant's response text
461
563
  *
462
564
  * @example
463
- * const response = await client.chat('gpt-4o', 'What is the capital of France?');
565
+ * const response = await client.chat('gpt-5.2', 'What is the capital of France?');
464
566
  * console.log(response); // 'The capital of France is Paris.'
465
567
  */
466
568
  chat(model: string, prompt: string, options?: ChatOptions): Promise<string>;
@@ -521,6 +623,21 @@ declare class LLMClient {
521
623
  * Handle 402 response: parse requirements, sign payment, retry.
522
624
  */
523
625
  private handlePaymentAndRetry;
626
+ /**
627
+ * Sign a payment header and return the PAYMENT-SIGNATURE value.
628
+ * Extracted to share logic between streaming and non-streaming flows.
629
+ */
630
+ private signPayment;
631
+ /**
632
+ * Streaming chat completion with automatic x402 payment.
633
+ *
634
+ * Uses a pre-auth cache so repeat calls to the same model skip the 402
635
+ * round-trip (~200ms savings). Falls back to the normal 402 flow on cache
636
+ * miss or if the pre-signed payment is rejected.
637
+ *
638
+ * @returns Raw fetch Response with a streaming SSE body.
639
+ */
640
+ chatCompletionStream(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<Response>;
524
641
  /**
525
642
  * Make a request with automatic x402 payment handling, returning raw JSON.
526
643
  * Used for non-ChatResponse endpoints (X/Twitter, search, image edit, etc.).
@@ -584,6 +701,36 @@ declare class LLMClient {
584
701
  * @returns SearchResult with summary and citations
585
702
  */
586
703
  search(query: string, options?: SearchOptions): Promise<SearchResult>;
704
+ /**
705
+ * Neural web search via Exa. Returns semantically relevant URLs and metadata.
706
+ * Understands meaning, not just keywords. $0.01/call.
707
+ *
708
+ * @param query - Natural language search query
709
+ * @param options - Optional filters (numResults, category, date range, domains)
710
+ */
711
+ exaSearch(query: string, options?: ExaSearchOptions): Promise<ExaSearchResponse>;
712
+ /**
713
+ * Ask a question and get a cited, synthesized answer grounded in real web sources.
714
+ * No hallucinations — every claim is backed by a citation. $0.01/call.
715
+ *
716
+ * @param query - The question to answer
717
+ */
718
+ exaAnswer(query: string): Promise<ExaAnswerResponse>;
719
+ /**
720
+ * Fetch full Markdown text content from a list of URLs. $0.002 per URL.
721
+ * Returns clean text ready to feed into an LLM context window.
722
+ *
723
+ * @param urls - Array of URLs to fetch (up to 100)
724
+ */
725
+ exaContents(urls: string[]): Promise<ExaContentsResponse>;
726
+ /**
727
+ * Find pages semantically similar to a given URL. $0.01/call.
728
+ * Useful for discovering competitors, alternatives, and related resources.
729
+ *
730
+ * @param url - Reference URL
731
+ * @param options - Optional filters (numResults, excludeSourceDomain)
732
+ */
733
+ exaFindSimilar(url: string, options?: ExaFindSimilarOptions): Promise<ExaSearchResponse>;
587
734
  /**
588
735
  * Get USDC balance on Base network.
589
736
  *
@@ -1108,7 +1255,7 @@ declare const WALLET_DIR_PATH: string;
1108
1255
  * // Or pass key directly
1109
1256
  * const client = new SolanaLLMClient({ privateKey: 'your-bs58-key' });
1110
1257
  *
1111
- * const response = await client.chat('openai/gpt-4o', 'gm Solana');
1258
+ * const response = await client.chat('openai/gpt-5.2', 'gm Solana');
1112
1259
  */
1113
1260
 
1114
1261
  interface SolanaLLMClientOptions {
@@ -1166,6 +1313,44 @@ declare class SolanaLLMClient {
1166
1313
  xCompareAuthors(handle1: string, handle2: string): Promise<XCompareAuthorsResponse>;
1167
1314
  pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
1168
1315
  pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>;
1316
+ /**
1317
+ * Generic Exa endpoint proxy (POST, Solana payment). Powered by Exa.
1318
+ *
1319
+ * @param path - Exa endpoint: "search" | "find-similar" | "contents" | "answer"
1320
+ * @param body - Request body (see Exa API docs)
1321
+ *
1322
+ * @example
1323
+ * const results = await client.exa("search", { query: "latest AI research", numResults: 5 });
1324
+ */
1325
+ exa(path: string, body: Record<string, unknown>): Promise<Record<string, unknown>>;
1326
+ /**
1327
+ * Neural and keyword web search via Exa (Solana payment, $0.01/request).
1328
+ *
1329
+ * @example
1330
+ * const results = await client.exaSearch("latest AI papers", { numResults: 5 });
1331
+ */
1332
+ exaSearch(query: string, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
1333
+ /**
1334
+ * Find pages semantically similar to a given URL via Exa (Solana payment, $0.01/request).
1335
+ *
1336
+ * @example
1337
+ * const results = await client.exaFindSimilar("https://openai.com/research/gpt-4", { numResults: 5 });
1338
+ */
1339
+ exaFindSimilar(url: string, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
1340
+ /**
1341
+ * Extract full text content from URLs via Exa (Solana payment, $0.002/URL).
1342
+ *
1343
+ * @example
1344
+ * const data = await client.exaContents(["https://arxiv.org/abs/2303.08774"]);
1345
+ */
1346
+ exaContents(urls: string[], options?: Record<string, unknown>): Promise<Record<string, unknown>>;
1347
+ /**
1348
+ * AI-generated answer grounded in live web search via Exa (Solana payment, $0.01/request).
1349
+ *
1350
+ * @example
1351
+ * const answer = await client.exaAnswer("What is the current state of AI safety research?");
1352
+ */
1353
+ exaAnswer(query: string, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
1169
1354
  /** Get session spending. */
1170
1355
  getSpending(): Spending;
1171
1356
  /** True if using sol.blockrun.ai. */
@@ -1228,6 +1413,11 @@ declare function getCachedByRequest(endpoint: string, body: Record<string, unkno
1228
1413
  declare function setCache(key: string, data: unknown, ttlMs: number): void;
1229
1414
  declare function saveToCache(endpoint: string, body: Record<string, unknown>, response: unknown, costUsd?: number): void;
1230
1415
  declare function clearCache(): number;
1416
+ declare function getCostLogSummary(): {
1417
+ totalUsd: number;
1418
+ calls: number;
1419
+ byEndpoint: Record<string, number>;
1420
+ };
1231
1421
 
1232
1422
  /**
1233
1423
  * Agent wallet setup utilities.
@@ -1277,7 +1467,7 @@ declare function getCostSummary(): {
1277
1467
  *
1278
1468
  * // Rest of your code stays exactly the same!
1279
1469
  * const response = await client.chat.completions.create({
1280
- * model: 'gpt-4o',
1470
+ * model: 'gpt-5.2',
1281
1471
  * messages: [{ role: 'user', content: 'Hello!' }]
1282
1472
  * });
1283
1473
  */
@@ -1384,7 +1574,7 @@ declare class Chat {
1384
1574
  * const client = new OpenAI({ walletKey: '0x...' });
1385
1575
  *
1386
1576
  * const response = await client.chat.completions.create({
1387
- * model: 'gpt-4o',
1577
+ * model: 'gpt-5.2',
1388
1578
  * messages: [{ role: 'user', content: 'Hello!' }]
1389
1579
  * });
1390
1580
  *
@@ -1419,4 +1609,59 @@ declare class AnthropicClient {
1419
1609
  getWalletAddress(): string;
1420
1610
  }
1421
1611
 
1422
- export { APIError, AnthropicClient, BASE_CHAIN_ID, type BlockRunAnthropicOptions, BlockrunError, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatUsage, type CostEntry, type CreatePaymentOptions, type FunctionCall, type FunctionDefinition, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, LLMClient, type LLMClientOptions, type Model, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PaymentError, type PaymentLinks, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type Spending, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsResponse, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, testnetClient };
1612
+ /**
1613
+ * Input validation and security utilities for BlockRun LLM SDK.
1614
+ *
1615
+ * This module provides validation functions to ensure:
1616
+ * - Private keys are properly formatted
1617
+ * - API URLs use HTTPS
1618
+ * - Server responses don't leak sensitive information
1619
+ * - Resource URLs match expected domains
1620
+ */
1621
+
1622
+ /**
1623
+ * Known LLM providers (for optional validation).
1624
+ */
1625
+ declare const KNOWN_PROVIDERS: Set<string>;
1626
+ /**
1627
+ * Validates that a model ID is a non-empty string.
1628
+ *
1629
+ * @param model - The model ID (e.g., "openai/gpt-5.2", "anthropic/claude-sonnet-4.5")
1630
+ * @throws {Error} If the model is invalid
1631
+ *
1632
+ * @example
1633
+ * validateModel("openai/gpt-5.2");
1634
+ */
1635
+ declare function validateModel(model: string): void;
1636
+ /**
1637
+ * Validates that max_tokens is an integer between 1 and 100,000.
1638
+ *
1639
+ * @param maxTokens - Maximum number of tokens to generate
1640
+ * @throws {Error} If maxTokens is invalid
1641
+ *
1642
+ * @example
1643
+ * validateMaxTokens(1000);
1644
+ */
1645
+ declare function validateMaxTokens(maxTokens?: number): void;
1646
+ /**
1647
+ * Validates that temperature is a number between 0 and 2.
1648
+ *
1649
+ * @param temperature - Sampling temperature (0-2)
1650
+ * @throws {Error} If temperature is invalid
1651
+ *
1652
+ * @example
1653
+ * validateTemperature(0.7);
1654
+ */
1655
+ declare function validateTemperature(temperature?: number): void;
1656
+ /**
1657
+ * Validates that top_p is a number between 0 and 1.
1658
+ *
1659
+ * @param topP - Top-p sampling parameter (0-1)
1660
+ * @throws {Error} If topP is invalid
1661
+ *
1662
+ * @example
1663
+ * validateTopP(0.9);
1664
+ */
1665
+ declare function validateTopP(topP?: number): void;
1666
+
1667
+ export { APIError, AnthropicClient, BASE_CHAIN_ID, type BlockRunAnthropicOptions, BlockrunError, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, type FunctionCall, type FunctionDefinition, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type Model, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PaymentError, type PaymentLinks, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type Spending, type SpendingReport, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsResponse, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, testnetClient, validateMaxTokens, validateModel, validateTemperature, validateTopP };