@blockrun/llm
Advanced tools
+1
-1
| { | ||
| "name": "@blockrun/llm", | ||
| "version": "1.4.0", | ||
| "version": "1.4.1", | ||
| "type": "module", | ||
@@ -5,0 +5,0 @@ "description": "BlockRun LLM Gateway SDK - Pay-per-request AI via x402 on Base and Solana", |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
-1343
| import * as _anthropic_ai_sdk from '@anthropic-ai/sdk'; | ||
| /** | ||
| * Type definitions for BlockRun LLM SDK | ||
| */ | ||
| interface FunctionDefinition { | ||
| name: string; | ||
| description?: string; | ||
| parameters?: Record<string, unknown>; | ||
| strict?: boolean; | ||
| } | ||
| interface Tool { | ||
| type: "function"; | ||
| function: FunctionDefinition; | ||
| } | ||
| interface FunctionCall { | ||
| name: string; | ||
| arguments: string; | ||
| } | ||
| interface ToolCall { | ||
| id: string; | ||
| type: "function"; | ||
| function: FunctionCall; | ||
| } | ||
| type ToolChoice = "none" | "auto" | "required" | { | ||
| type: "function"; | ||
| function: { | ||
| name: string; | ||
| }; | ||
| }; | ||
| interface ChatMessage { | ||
| role: "system" | "user" | "assistant" | "tool"; | ||
| content?: string | null; | ||
| name?: string; | ||
| tool_call_id?: string; | ||
| tool_calls?: ToolCall[]; | ||
| } | ||
| interface ChatChoice { | ||
| index: number; | ||
| message: ChatMessage; | ||
| finish_reason?: "stop" | "length" | "content_filter" | "tool_calls"; | ||
| } | ||
| interface ChatUsage { | ||
| prompt_tokens: number; | ||
| completion_tokens: number; | ||
| total_tokens: number; | ||
| num_sources_used?: number; | ||
| } | ||
| interface ChatResponse { | ||
| id: string; | ||
| object: string; | ||
| created: number; | ||
| model: string; | ||
| choices: ChatChoice[]; | ||
| usage?: ChatUsage; | ||
| citations?: string[]; | ||
| } | ||
| interface Model { | ||
| id: string; | ||
| name: string; | ||
| provider: string; | ||
| description: string; | ||
| inputPrice: number; | ||
| outputPrice: number; | ||
| contextWindow: number; | ||
| maxOutput: number; | ||
| available: boolean; | ||
| type?: "llm" | "image"; | ||
| } | ||
| interface ImageData { | ||
| url: string; | ||
| revised_prompt?: string; | ||
| b64_json?: string; | ||
| } | ||
| interface ImageResponse { | ||
| created: number; | ||
| data: ImageData[]; | ||
| } | ||
| interface ImageModel { | ||
| id: string; | ||
| name: string; | ||
| provider: string; | ||
| description: string; | ||
| pricePerImage: number; | ||
| supportedSizes?: string[]; | ||
| maxPromptLength?: number; | ||
| available: boolean; | ||
| type?: "llm" | "image"; | ||
| } | ||
| interface ImageClientOptions { | ||
| /** EVM wallet private key (hex string starting with 0x) */ | ||
| privateKey?: `0x${string}` | string; | ||
| /** API endpoint URL (default: https://blockrun.ai/api) */ | ||
| apiUrl?: string; | ||
| /** Request timeout in milliseconds (default: 120000 for images) */ | ||
| timeout?: number; | ||
| } | ||
| interface ImageGenerateOptions { | ||
| /** Model ID (default: "google/nano-banana") */ | ||
| model?: string; | ||
| /** Image size (default: "1024x1024") */ | ||
| size?: string; | ||
| /** Number of images to generate (default: 1) */ | ||
| n?: number; | ||
| /** Image quality (for supported models) */ | ||
| quality?: "standard" | "hd"; | ||
| } | ||
| interface WebSearchSource { | ||
| type: "web"; | ||
| country?: string; | ||
| excludedWebsites?: string[]; | ||
| allowedWebsites?: string[]; | ||
| safeSearch?: boolean; | ||
| } | ||
| interface XSearchSource { | ||
| type: "x"; | ||
| includedXHandles?: string[]; | ||
| excludedXHandles?: string[]; | ||
| postFavoriteCount?: number; | ||
| postViewCount?: number; | ||
| } | ||
| interface NewsSearchSource { | ||
| type: "news"; | ||
| country?: string; | ||
| excludedWebsites?: string[]; | ||
| allowedWebsites?: string[]; | ||
| safeSearch?: boolean; | ||
| } | ||
| interface RssSearchSource { | ||
| type: "rss"; | ||
| links: string[]; | ||
| } | ||
| type SearchSource = WebSearchSource | XSearchSource | NewsSearchSource | RssSearchSource; | ||
| interface SearchParameters { | ||
| mode?: "off" | "auto" | "on"; | ||
| sources?: SearchSource[]; | ||
| returnCitations?: boolean; | ||
| fromDate?: string; | ||
| toDate?: string; | ||
| maxSearchResults?: number; | ||
| } | ||
| interface Spending { | ||
| totalUsd: number; | ||
| calls: number; | ||
| } | ||
| interface LLMClientOptions { | ||
| /** EVM wallet private key (hex string starting with 0x). Optional if BASE_CHAIN_WALLET_KEY env var is set. */ | ||
| privateKey?: `0x${string}` | string; | ||
| /** API endpoint URL (default: https://blockrun.ai/api) */ | ||
| apiUrl?: string; | ||
| /** Request timeout in milliseconds (default: 60000) */ | ||
| timeout?: number; | ||
| } | ||
| interface ChatOptions { | ||
| /** System prompt */ | ||
| system?: string; | ||
| /** Max tokens to generate */ | ||
| maxTokens?: number; | ||
| /** Sampling temperature */ | ||
| temperature?: number; | ||
| /** Nucleus sampling parameter */ | ||
| topP?: number; | ||
| /** Enable xAI Live Search (shortcut for searchParameters.mode = "on") */ | ||
| search?: boolean; | ||
| /** Full xAI Live Search configuration (for Grok models) */ | ||
| searchParameters?: SearchParameters; | ||
| } | ||
| interface ChatCompletionOptions { | ||
| /** Max tokens to generate */ | ||
| maxTokens?: number; | ||
| /** Sampling temperature */ | ||
| temperature?: number; | ||
| /** Nucleus sampling parameter */ | ||
| topP?: number; | ||
| /** Enable xAI Live Search (shortcut for searchParameters.mode = "on") */ | ||
| search?: boolean; | ||
| /** Full xAI Live Search configuration (for Grok models) */ | ||
| searchParameters?: SearchParameters; | ||
| /** Tool definitions for function calling */ | ||
| tools?: Tool[]; | ||
| /** Tool selection strategy */ | ||
| toolChoice?: ToolChoice; | ||
| } | ||
| type RoutingProfile = "free" | "eco" | "auto" | "premium"; | ||
| type RoutingTier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING"; | ||
| interface RoutingDecision { | ||
| model: string; | ||
| tier: RoutingTier; | ||
| confidence: number; | ||
| method: "rules" | "llm"; | ||
| reasoning: string; | ||
| costEstimate: number; | ||
| baselineCost: number; | ||
| savings: number; | ||
| } | ||
| interface SmartChatOptions extends ChatOptions { | ||
| /** Routing profile: free (zero cost), eco (budget), auto (balanced), premium (best quality) */ | ||
| routingProfile?: RoutingProfile; | ||
| /** Maximum output tokens (used for cost estimation) */ | ||
| maxOutputTokens?: number; | ||
| } | ||
| interface SmartChatResponse { | ||
| /** The AI response text */ | ||
| response: string; | ||
| /** Which model was selected by smart routing */ | ||
| model: string; | ||
| /** Routing decision metadata */ | ||
| routing: RoutingDecision; | ||
| } | ||
| interface SearchResult { | ||
| query: string; | ||
| summary: string; | ||
| citations?: Array<Record<string, string>>; | ||
| sources_used?: number; | ||
| model?: string; | ||
| } | ||
| interface ImageEditOptions { | ||
| /** Model ID (default: "openai/gpt-image-1") */ | ||
| model?: string; | ||
| /** Optional base64-encoded mask image */ | ||
| mask?: string; | ||
| /** Image size (default: "1024x1024") */ | ||
| size?: string; | ||
| /** Number of images to generate (default: 1) */ | ||
| n?: number; | ||
| } | ||
| interface SearchOptions { | ||
| /** Source types to search (e.g. ["web", "x", "news"]) */ | ||
| sources?: string[]; | ||
| /** Maximum number of results (default: 10) */ | ||
| maxResults?: number; | ||
| /** Start date filter (YYYY-MM-DD) */ | ||
| fromDate?: string; | ||
| /** End date filter (YYYY-MM-DD) */ | ||
| toDate?: string; | ||
| } | ||
| interface XUser { | ||
| id: string; | ||
| userName: string; | ||
| name: string; | ||
| profilePicture?: string; | ||
| description?: string; | ||
| followers?: number; | ||
| following?: number; | ||
| isBlueVerified?: boolean; | ||
| verifiedType?: string; | ||
| location?: string; | ||
| joined?: string; | ||
| } | ||
| interface XUserLookupResponse { | ||
| users: XUser[]; | ||
| not_found?: string[]; | ||
| total_requested?: number; | ||
| total_found?: number; | ||
| } | ||
| interface XFollower { | ||
| id: string; | ||
| name?: string; | ||
| screen_name?: string; | ||
| userName?: string; | ||
| location?: string; | ||
| description?: string; | ||
| protected?: boolean; | ||
| verified?: boolean; | ||
| followers_count?: number; | ||
| following_count?: number; | ||
| favourites_count?: number; | ||
| statuses_count?: number; | ||
| created_at?: string; | ||
| profile_image_url_https?: string; | ||
| can_dm?: boolean; | ||
| } | ||
| interface XFollowersResponse { | ||
| followers: XFollower[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| username?: string; | ||
| } | ||
| interface XFollowingsResponse { | ||
| followings: XFollower[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| username?: string; | ||
| } | ||
| interface XUserInfoResponse { | ||
| data: Record<string, unknown>; | ||
| username?: string; | ||
| } | ||
| interface XVerifiedFollowersResponse { | ||
| followers: XFollower[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XTweet { | ||
| id: string; | ||
| text?: string; | ||
| created_at?: string; | ||
| author?: Record<string, unknown>; | ||
| favorite_count?: number; | ||
| retweet_count?: number; | ||
| reply_count?: number; | ||
| view_count?: number; | ||
| lang?: string; | ||
| entities?: Record<string, unknown>; | ||
| media?: Array<Record<string, unknown>>; | ||
| [key: string]: unknown; | ||
| } | ||
| interface XTweetsResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XMentionsResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| username?: string; | ||
| } | ||
| interface XTweetLookupResponse { | ||
| tweets: XTweet[]; | ||
| not_found?: string[]; | ||
| total_requested?: number; | ||
| total_found?: number; | ||
| } | ||
| interface XTweetRepliesResponse { | ||
| replies: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XTweetThreadResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XSearchResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XTrendingResponse { | ||
| data: Record<string, unknown>; | ||
| } | ||
| interface XArticlesRisingResponse { | ||
| data: Record<string, unknown>; | ||
| } | ||
| interface XAuthorAnalyticsResponse { | ||
| data: Record<string, unknown>; | ||
| handle?: string; | ||
| } | ||
| interface XCompareAuthorsResponse { | ||
| data: Record<string, unknown>; | ||
| } | ||
| declare class BlockrunError extends Error { | ||
| constructor(message: string); | ||
| } | ||
| declare class PaymentError extends BlockrunError { | ||
| constructor(message: string); | ||
| } | ||
| declare class APIError extends BlockrunError { | ||
| statusCode: number; | ||
| response?: unknown; | ||
| constructor(message: string, statusCode: number, response?: unknown); | ||
| } | ||
| /** | ||
| * BlockRun LLM Client - Main SDK entry point. | ||
| * | ||
| * Usage: | ||
| * import { LLMClient } from '@blockrun/llm'; | ||
| * | ||
| * // Option 1: Use BASE_CHAIN_WALLET_KEY env var | ||
| * const client = new LLMClient(); | ||
| * | ||
| * // Option 2: Pass private key directly | ||
| * const client = new LLMClient({ privateKey: '0x...' }); | ||
| * | ||
| * const response = await client.chat('openai/gpt-4o', 'Hello!'); | ||
| * console.log(response); | ||
| */ | ||
| /** | ||
| * BlockRun LLM Gateway Client. | ||
| * | ||
| * Provides access to multiple LLM providers (OpenAI, Anthropic, Google, etc.) | ||
| * with automatic x402 micropayments on Base chain. | ||
| * | ||
| * Networks: | ||
| * - Mainnet: https://blockrun.ai/api (Base, Chain ID 8453) | ||
| * - Testnet: https://testnet.blockrun.ai/api (Base Sepolia, Chain ID 84532) | ||
| * | ||
| * @example Testnet usage | ||
| * ```ts | ||
| * // Use testnet convenience function | ||
| * import { testnetClient } from '@blockrun/llm'; | ||
| * const client = testnetClient({ privateKey: '0x...' }); | ||
| * const response = await client.chat('openai/gpt-oss-20b', 'Hello!'); | ||
| * | ||
| * // Or configure manually | ||
| * const client = new LLMClient({ | ||
| * privateKey: '0x...', | ||
| * apiUrl: 'https://testnet.blockrun.ai/api' | ||
| * }); | ||
| * ``` | ||
| */ | ||
| declare class LLMClient { | ||
| static readonly DEFAULT_API_URL = "https://blockrun.ai/api"; | ||
| static readonly TESTNET_API_URL = "https://testnet.blockrun.ai/api"; | ||
| private account; | ||
| private privateKey; | ||
| private apiUrl; | ||
| private timeout; | ||
| private sessionTotalUsd; | ||
| private sessionCalls; | ||
| private modelPricingCache; | ||
| private modelPricingPromise; | ||
| /** | ||
| * Initialize the BlockRun LLM client. | ||
| * | ||
| * @param options - Client configuration options (optional if BASE_CHAIN_WALLET_KEY env var is set) | ||
| */ | ||
| constructor(options?: LLMClientOptions); | ||
| /** | ||
| * Simple 1-line chat interface. | ||
| * | ||
| * @param model - Model ID (e.g., 'openai/gpt-4o', 'anthropic/claude-sonnet-4') | ||
| * @param prompt - User message | ||
| * @param options - Optional chat parameters | ||
| * @returns Assistant's response text | ||
| * | ||
| * @example | ||
| * const response = await client.chat('gpt-4o', 'What is the capital of France?'); | ||
| * console.log(response); // 'The capital of France is Paris.' | ||
| */ | ||
| chat(model: string, prompt: string, options?: ChatOptions): Promise<string>; | ||
| /** | ||
| * Smart chat with automatic model routing. | ||
| * | ||
| * Uses ClawRouter's 14-dimension rule-based scoring algorithm (<1ms, 100% local) | ||
| * to select the cheapest model that can handle your request. | ||
| * | ||
| * @param prompt - User message | ||
| * @param options - Optional chat and routing parameters | ||
| * @returns SmartChatResponse with response text, selected model, and routing metadata | ||
| * | ||
| * @example Simple usage (auto profile) | ||
| * ```ts | ||
| * const result = await client.smartChat('What is 2+2?'); | ||
| * console.log(result.response); // '4' | ||
| * console.log(result.model); // 'google/gemini-2.5-flash-lite' | ||
| * console.log(result.routing.savings); // 0.78 (78% savings) | ||
| * ``` | ||
| * | ||
| * @example With routing profile | ||
| * ```ts | ||
| * // Free tier only (zero cost) | ||
| * const result = await client.smartChat('Hello!', { routingProfile: 'free' }); | ||
| * | ||
| * // Eco mode (budget optimized) | ||
| * const result = await client.smartChat('Explain quantum computing', { routingProfile: 'eco' }); | ||
| * | ||
| * // Premium mode (best quality) | ||
| * const result = await client.smartChat('Write a business plan', { routingProfile: 'premium' }); | ||
| * ``` | ||
| */ | ||
| smartChat(prompt: string, options?: SmartChatOptions): Promise<SmartChatResponse>; | ||
| /** | ||
| * Get model pricing map (cached). | ||
| * Fetches from API on first call, then returns cached result. | ||
| */ | ||
| private getModelPricing; | ||
| /** | ||
| * Fetch model pricing from API. | ||
| */ | ||
| private fetchModelPricing; | ||
| /** | ||
| * Full chat completion interface (OpenAI-compatible). | ||
| * | ||
| * @param model - Model ID | ||
| * @param messages - Array of messages with role and content | ||
| * @param options - Optional completion parameters | ||
| * @returns ChatResponse object with choices and usage | ||
| */ | ||
| chatCompletion(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<ChatResponse>; | ||
| /** | ||
| * Make a request with automatic x402 payment handling. | ||
| */ | ||
| private requestWithPayment; | ||
| /** | ||
| * Handle 402 response: parse requirements, sign payment, retry. | ||
| */ | ||
| private handlePaymentAndRetry; | ||
| /** | ||
| * Make a request with automatic x402 payment handling, returning raw JSON. | ||
| * Used for non-ChatResponse endpoints (X/Twitter, search, image edit, etc.). | ||
| */ | ||
| private requestWithPaymentRaw; | ||
| /** | ||
| * Handle 402 response for raw endpoints: parse requirements, sign payment, retry. | ||
| */ | ||
| private handlePaymentAndRetryRaw; | ||
| /** | ||
| * GET with automatic x402 payment handling, returning raw JSON. | ||
| * Used for Predexon prediction market endpoints that use GET + query params. | ||
| */ | ||
| private getWithPaymentRaw; | ||
| /** | ||
| * Handle 402 response for GET endpoints: parse requirements, sign payment, retry with GET. | ||
| */ | ||
| private handleGetPaymentAndRetryRaw; | ||
| /** | ||
| * Fetch with timeout. | ||
| */ | ||
| private fetchWithTimeout; | ||
| /** | ||
| * List available LLM models with pricing. | ||
| */ | ||
| listModels(): Promise<Model[]>; | ||
| /** | ||
| * List available image generation models with pricing. | ||
| */ | ||
| listImageModels(): Promise<ImageModel[]>; | ||
| /** | ||
| * List all available models (both LLM and image) with pricing. | ||
| * | ||
| * @returns Array of all models with 'type' field ('llm' or 'image') | ||
| * | ||
| * @example | ||
| * const models = await client.listAllModels(); | ||
| * for (const model of models) { | ||
| * if (model.type === 'llm') { | ||
| * console.log(`LLM: ${model.id} - $${model.inputPrice}/M input`); | ||
| * } else { | ||
| * console.log(`Image: ${model.id} - $${model.pricePerImage}/image`); | ||
| * } | ||
| * } | ||
| */ | ||
| listAllModels(): Promise<(Model | ImageModel)[]>; | ||
| /** | ||
| * Edit an image using img2img. | ||
| * | ||
| * @param prompt - Text description of the desired edit | ||
| * @param image - Base64-encoded image or URL of the source image | ||
| * @param options - Optional edit parameters | ||
| * @returns ImageResponse with edited image URLs | ||
| */ | ||
| imageEdit(prompt: string, image: string, options?: ImageEditOptions): Promise<ImageResponse>; | ||
| /** | ||
| * Standalone search (web, X/Twitter, news). | ||
| * | ||
| * @param query - Search query | ||
| * @param options - Optional search parameters | ||
| * @returns SearchResult with summary and citations | ||
| */ | ||
| search(query: string, options?: SearchOptions): Promise<SearchResult>; | ||
| /** | ||
| * Get USDC balance on Base network. | ||
| * | ||
| * Automatically detects mainnet vs testnet based on API URL. | ||
| * | ||
| * @returns USDC balance as a float (6 decimal places normalized) | ||
| * | ||
| * @example | ||
| * const balance = await client.getBalance(); | ||
| * console.log(`Balance: $${balance.toFixed(2)} USDC`); | ||
| */ | ||
| getBalance(): Promise<number>; | ||
| /** | ||
| * Look up X/Twitter user profiles by username. | ||
| * | ||
| * Powered by AttentionVC. $0.002 per user (min $0.02, max $0.20). | ||
| * | ||
| * @param usernames - Single username or array of usernames (without @) | ||
| */ | ||
| xUserLookup(usernames: string | string[]): Promise<XUserLookupResponse>; | ||
| /** | ||
| * Get followers of an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.05 per page (~200 accounts). | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xFollowers(username: string, cursor?: string): Promise<XFollowersResponse>; | ||
| /** | ||
| * Get accounts an X/Twitter user is following. | ||
| * | ||
| * Powered by AttentionVC. $0.05 per page (~200 accounts). | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xFollowings(username: string, cursor?: string): Promise<XFollowingsResponse>; | ||
| /** | ||
| * Get detailed profile info for a single X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.002 per request. | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| */ | ||
| xUserInfo(username: string): Promise<XUserInfoResponse>; | ||
| /** | ||
| * Get verified (blue-check) followers of an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.048 per page. | ||
| * | ||
| * @param userId - X/Twitter user ID (not username) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xVerifiedFollowers(userId: string, cursor?: string): Promise<XVerifiedFollowersResponse>; | ||
| /** | ||
| * Get tweets posted by an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param includeReplies - Include reply tweets (default: false) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xUserTweets(username: string, includeReplies?: boolean, cursor?: string): Promise<XTweetsResponse>; | ||
| /** | ||
| * Get tweets that mention an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param sinceTime - Start time filter (ISO8601 or Unix timestamp) | ||
| * @param untilTime - End time filter (ISO8601 or Unix timestamp) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xUserMentions(username: string, sinceTime?: string, untilTime?: string, cursor?: string): Promise<XMentionsResponse>; | ||
| /** | ||
| * Fetch full tweet data for up to 200 tweet IDs. | ||
| * | ||
| * Powered by AttentionVC. $0.16 per batch. | ||
| * | ||
| * @param tweetIds - Single tweet ID or array of tweet IDs (max 200) | ||
| */ | ||
| xTweetLookup(tweetIds: string | string[]): Promise<XTweetLookupResponse>; | ||
| /** | ||
| * Get replies to a specific tweet. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param tweetId - The tweet ID to get replies for | ||
| * @param queryType - Sort order: 'Latest' or 'Default' | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xTweetReplies(tweetId: string, queryType?: string, cursor?: string): Promise<XTweetRepliesResponse>; | ||
| /** | ||
| * Get the full thread context for a tweet. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param tweetId - The tweet ID to get thread for | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xTweetThread(tweetId: string, cursor?: string): Promise<XTweetThreadResponse>; | ||
| /** | ||
| * Search X/Twitter with advanced query operators. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param query - Search query (supports Twitter search operators) | ||
| * @param queryType - Sort order: 'Latest', 'Top', or 'Default' | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xSearch(query: string, queryType?: string, cursor?: string): Promise<XSearchResponse>; | ||
| /** | ||
| * Get current trending topics on X/Twitter. | ||
| * | ||
| * Powered by AttentionVC. $0.002 per request. | ||
| */ | ||
| xTrending(): Promise<XTrendingResponse>; | ||
| /** | ||
| * Get rising/viral articles from X/Twitter. | ||
| * | ||
| * Powered by AttentionVC intelligence layer. $0.05 per request. | ||
| */ | ||
| xArticlesRising(): Promise<XArticlesRisingResponse>; | ||
| /** | ||
| * Get author analytics and intelligence metrics for an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC intelligence layer. $0.02 per request. | ||
| * | ||
| * @param handle - X/Twitter handle (without @) | ||
| */ | ||
| xAuthorAnalytics(handle: string): Promise<XAuthorAnalyticsResponse>; | ||
| /** | ||
| * Compare two X/Twitter authors side-by-side with intelligence metrics. | ||
| * | ||
| * Powered by AttentionVC intelligence layer. $0.05 per request. | ||
| * | ||
| * @param handle1 - First X/Twitter handle (without @) | ||
| * @param handle2 - Second X/Twitter handle (without @) | ||
| */ | ||
| xCompareAuthors(handle1: string, handle2: string): Promise<XCompareAuthorsResponse>; | ||
| /** | ||
| * Query Predexon prediction market data (GET endpoints). | ||
| * | ||
| * Access real-time data from Polymarket, Kalshi, dFlow, and Binance Futures. | ||
| * Powered by Predexon. $0.001 per request. | ||
| * | ||
| * @param path - Endpoint path, e.g. "polymarket/events", "kalshi/markets/12345" | ||
| * @param params - Query parameters passed to the endpoint | ||
| * | ||
| * @example | ||
| * const events = await client.pm("polymarket/events"); | ||
| * const market = await client.pm("kalshi/markets/KXBTC-25MAR14"); | ||
| * const results = await client.pm("polymarket/search", { q: "bitcoin" }); | ||
| */ | ||
| pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>; | ||
| /** | ||
| * Structured query for Predexon prediction market data (POST endpoints). | ||
| * | ||
| * For complex queries that require a JSON body. $0.005 per request. | ||
| * | ||
| * @param path - Endpoint path, e.g. "polymarket/query", "kalshi/query" | ||
| * @param query - JSON body for the structured query | ||
| * | ||
| * @example | ||
| * const data = await client.pmQuery("polymarket/query", { filter: "active", limit: 10 }); | ||
| */ | ||
| pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>; | ||
| /** | ||
| * Get current session spending. | ||
| * | ||
| * @returns Object with totalUsd and calls count | ||
| * | ||
| * @example | ||
| * const spending = client.getSpending(); | ||
| * console.log(`Spent $${spending.totalUsd.toFixed(4)} across ${spending.calls} calls`); | ||
| */ | ||
| getSpending(): Spending; | ||
| /** | ||
| * Get the wallet address being used for payments. | ||
| */ | ||
| getWalletAddress(): string; | ||
| /** | ||
| * Check if client is configured for testnet. | ||
| */ | ||
| isTestnet(): boolean; | ||
| } | ||
| /** | ||
| * Create a testnet LLM client for development and testing. | ||
| * | ||
| * This is a convenience function that creates an LLMClient configured | ||
| * for the BlockRun testnet (Base Sepolia). | ||
| * | ||
| * @param options - Client options (privateKey required unless BASE_CHAIN_WALLET_KEY env var is set) | ||
| * @returns LLMClient configured for testnet | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * import { testnetClient } from '@blockrun/llm'; | ||
| * | ||
| * const client = testnetClient({ privateKey: '0x...' }); | ||
| * const response = await client.chat('openai/gpt-oss-20b', 'Hello!'); | ||
| * ``` | ||
| * | ||
| * Testnet Setup: | ||
| * 1. Get testnet ETH from https://www.alchemy.com/faucets/base-sepolia | ||
| * 2. Get testnet USDC from https://faucet.circle.com/ | ||
| * 3. Use your wallet with testnet funds | ||
| * | ||
| * Available Testnet Models: | ||
| * - openai/gpt-oss-20b | ||
| * - openai/gpt-oss-120b | ||
| */ | ||
| declare function testnetClient(options?: Omit<LLMClientOptions, 'apiUrl'>): LLMClient; | ||
| /** | ||
| * BlockRun Image Client - Generate images via x402 micropayments. | ||
| * | ||
| * SECURITY NOTE - Private Key Handling: | ||
| * Your private key NEVER leaves your machine. Here's what happens: | ||
| * 1. Key stays local - only used to sign an EIP-712 typed data message | ||
| * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header | ||
| * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator | ||
| * | ||
| * Usage: | ||
| * import { ImageClient } from '@blockrun/llm'; | ||
| * | ||
| * const client = new ImageClient({ privateKey: '0x...' }); | ||
| * const result = await client.generate('A cute cat in space'); | ||
| * console.log(result.data[0].url); | ||
| */ | ||
| /** | ||
| * BlockRun Image Generation Client. | ||
| * | ||
| * Generate images using Nano Banana (Google Gemini), DALL-E 3, or GPT Image | ||
| * with automatic x402 micropayments on Base chain. | ||
| */ | ||
| declare class ImageClient { | ||
| private account; | ||
| private privateKey; | ||
| private apiUrl; | ||
| private timeout; | ||
| private sessionTotalUsd; | ||
| private sessionCalls; | ||
| /** | ||
| * Initialize the BlockRun Image client. | ||
| * | ||
| * @param options - Client configuration options | ||
| */ | ||
| constructor(options?: ImageClientOptions); | ||
| /** | ||
| * Generate an image from a text prompt. | ||
| * | ||
| * @param prompt - Text description of the image to generate | ||
| * @param options - Optional generation parameters | ||
| * @returns ImageResponse with generated image URLs | ||
| * | ||
| * @example | ||
| * const result = await client.generate('A sunset over mountains'); | ||
| * console.log(result.data[0].url); | ||
| */ | ||
| generate(prompt: string, options?: ImageGenerateOptions): Promise<ImageResponse>; | ||
| /** | ||
| * Edit an image using img2img. | ||
| * | ||
| * @param prompt - Text description of the desired edit | ||
| * @param image - Base64-encoded image or URL of the source image | ||
| * @param options - Optional edit parameters | ||
| * @returns ImageResponse with edited image URLs | ||
| * | ||
| * @example | ||
| * const result = await client.edit('Make it a painting', imageBase64); | ||
| * console.log(result.data[0].url); | ||
| */ | ||
| edit(prompt: string, image: string, options?: ImageEditOptions): Promise<ImageResponse>; | ||
| /** | ||
| * List available image generation models with pricing. | ||
| */ | ||
| listImageModels(): Promise<ImageModel[]>; | ||
| /** | ||
| * Make a request with automatic x402 payment handling. | ||
| */ | ||
| private requestWithPayment; | ||
| /** | ||
| * Handle 402 response: parse requirements, sign payment, retry. | ||
| */ | ||
| private handlePaymentAndRetry; | ||
| /** | ||
| * Fetch with timeout. | ||
| */ | ||
| private fetchWithTimeout; | ||
| /** | ||
| * Get the wallet address being used for payments. | ||
| */ | ||
| getWalletAddress(): string; | ||
| /** | ||
| * Get session spending information. | ||
| */ | ||
| getSpending(): Spending; | ||
| } | ||
| /** | ||
| * x402 Payment Protocol v2 Implementation for BlockRun. | ||
| * | ||
| * This module handles creating signed payment payloads for the x402 v2 protocol. | ||
| * The private key is used ONLY for local signing and NEVER leaves the client. | ||
| */ | ||
| declare const BASE_CHAIN_ID = 8453; | ||
| declare const USDC_BASE: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; | ||
| declare const SOLANA_NETWORK = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"; | ||
| declare const USDC_SOLANA = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; | ||
| interface CreateSolanaPaymentOptions { | ||
| resourceUrl?: string; | ||
| resourceDescription?: string; | ||
| maxTimeoutSeconds?: number; | ||
| extra?: Record<string, unknown>; | ||
| extensions?: Record<string, unknown>; | ||
| rpcUrl?: string; | ||
| } | ||
| /** | ||
| * Create a signed Solana x402 v2 payment payload. | ||
| * | ||
| * This creates an SPL TransferChecked transaction for USDC payment | ||
| * that the CDP facilitator can verify and settle. | ||
| * | ||
| * Requires @solana/web3.js and @solana/spl-token dependencies. | ||
| * | ||
| * @param secretKey - Solana secret key (Uint8Array, 64 bytes) | ||
| * @param fromAddress - Sender wallet address (base58) | ||
| * @param recipient - Payment recipient address (base58) | ||
| * @param amount - Amount in micro USDC (6 decimals) | ||
| * @param feePayer - CDP facilitator fee payer address (base58) | ||
| * @param options - Additional options | ||
| * @returns Base64-encoded signed payment payload | ||
| */ | ||
| declare function createSolanaPaymentPayload(secretKey: Uint8Array, fromAddress: string, recipient: string, amount: string, feePayer: string, options?: CreateSolanaPaymentOptions): Promise<string>; | ||
| /** | ||
| * BlockRun Wallet Management - Auto-create and manage wallets. | ||
| * | ||
| * Provides frictionless wallet setup for new users: | ||
| * - Auto-creates wallet if none exists | ||
| * - Stores key securely at ~/.blockrun/.session | ||
| * - Generates EIP-681 URIs for easy MetaMask funding | ||
| */ | ||
| declare const USDC_BASE_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; | ||
| interface WalletInfo { | ||
| privateKey: string; | ||
| address: string; | ||
| isNew: boolean; | ||
| } | ||
| interface PaymentLinks { | ||
| basescan: string; | ||
| walletLink: string; | ||
| ethereum: string; | ||
| blockrun: string; | ||
| } | ||
| /** | ||
| * Create a new Ethereum wallet. | ||
| * | ||
| * @returns Object with address and privateKey | ||
| */ | ||
| declare function createWallet(): { | ||
| address: string; | ||
| privateKey: string; | ||
| }; | ||
| /** | ||
| * Save wallet private key to ~/.blockrun/.session | ||
| * | ||
| * @param privateKey - Private key string (with 0x prefix) | ||
| * @returns Path to saved wallet file | ||
| */ | ||
| declare function saveWallet(privateKey: string): string; | ||
| /** | ||
| * Scan ~/.<dir>/wallet.json files from any provider (agentcash, etc.). | ||
| * | ||
| * Each file should contain JSON with "privateKey" and "address" fields. | ||
| * Results are sorted by modification time (most recent first). | ||
| * | ||
| * @returns Array of wallet objects with privateKey and address | ||
| */ | ||
| declare function scanWallets(): Array<{ | ||
| privateKey: string; | ||
| address: string; | ||
| }>; | ||
| /** | ||
| * Load wallet private key from file. | ||
| * | ||
| * Priority: | ||
| * 1. Scan ~/.* /wallet.json (any provider) | ||
| * 2. Legacy ~/.blockrun/.session | ||
| * 3. Legacy ~/.blockrun/wallet.key | ||
| * | ||
| * @returns Private key string or null if not found | ||
| */ | ||
| declare function loadWallet(): string | null; | ||
| /** | ||
| * Get existing wallet or create new one. | ||
| * | ||
| * Priority: | ||
| * 1. BLOCKRUN_WALLET_KEY environment variable | ||
| * 2. Scan wallet.json files from providers | ||
| * 3. ~/.blockrun/.session file | ||
| * 4. ~/.blockrun/wallet.key file - legacy | ||
| * 5. Create new wallet | ||
| * | ||
| * @returns WalletInfo with address, privateKey, and isNew flag | ||
| */ | ||
| declare function getOrCreateWallet(): WalletInfo; | ||
| /** | ||
| * Get wallet address without exposing private key. | ||
| * | ||
| * @returns Wallet address or null if no wallet configured | ||
| */ | ||
| declare function getWalletAddress(): string | null; | ||
| /** | ||
| * Generate EIP-681 URI for USDC transfer on Base. | ||
| * | ||
| * @param address - Recipient Ethereum address | ||
| * @param amountUsdc - Amount in USDC (default 1.0) | ||
| * @returns EIP-681 URI string for MetaMask/wallet scanning | ||
| */ | ||
| declare function getEip681Uri(address: string, amountUsdc?: number): string; | ||
| /** | ||
| * Generate payment links for the wallet address. | ||
| * | ||
| * @param address - Ethereum address | ||
| * @returns Object with various payment links | ||
| */ | ||
| declare function getPaymentLinks(address: string): PaymentLinks; | ||
| /** | ||
| * Format the message shown when a new wallet is created. | ||
| * | ||
| * @param address - New wallet address | ||
| * @returns Formatted message string | ||
| */ | ||
| declare function formatWalletCreatedMessage(address: string): string; | ||
| /** | ||
| * Format the message shown when wallet needs more funds. | ||
| * | ||
| * @param address - Wallet address | ||
| * @returns Formatted message string | ||
| */ | ||
| declare function formatNeedsFundingMessage(address: string): string; | ||
| /** | ||
| * Compact funding message (no QR) for repeated displays. | ||
| * | ||
| * @param address - Wallet address | ||
| * @returns Short formatted message string | ||
| */ | ||
| declare function formatFundingMessageCompact(address: string): string; | ||
| declare const WALLET_FILE_PATH: string; | ||
| declare const WALLET_DIR_PATH: string; | ||
| /** | ||
| * BlockRun Solana LLM Client. | ||
| * | ||
| * Usage: | ||
| * import { SolanaLLMClient } from '@blockrun/llm'; | ||
| * | ||
| * // SOLANA_WALLET_KEY env var (bs58-encoded Solana secret key) | ||
| * const client = new SolanaLLMClient(); | ||
| * | ||
| * // Or pass key directly | ||
| * const client = new SolanaLLMClient({ privateKey: 'your-bs58-key' }); | ||
| * | ||
| * const response = await client.chat('openai/gpt-4o', 'gm Solana'); | ||
| */ | ||
| interface SolanaLLMClientOptions { | ||
| /** bs58-encoded Solana secret key (64 bytes). Optional if SOLANA_WALLET_KEY env var is set. */ | ||
| privateKey?: string; | ||
| /** API endpoint URL (default: https://sol.blockrun.ai/api) */ | ||
| apiUrl?: string; | ||
| /** Solana RPC URL (default: https://api.mainnet-beta.solana.com) */ | ||
| rpcUrl?: string; | ||
| /** Request timeout in milliseconds (default: 60000) */ | ||
| timeout?: number; | ||
| } | ||
| declare class SolanaLLMClient { | ||
| static readonly SOLANA_API_URL = "https://sol.blockrun.ai/api"; | ||
| private privateKey; | ||
| private apiUrl; | ||
| private rpcUrl; | ||
| private timeout; | ||
| private sessionTotalUsd; | ||
| private sessionCalls; | ||
| private addressCache; | ||
| constructor(options?: SolanaLLMClientOptions); | ||
| /** Get Solana wallet address (public key in base58). */ | ||
| getWalletAddress(): Promise<string>; | ||
| /** Simple 1-line chat. */ | ||
| chat(model: string, prompt: string, options?: ChatOptions): Promise<string>; | ||
| /** Full chat completion (OpenAI-compatible). */ | ||
| chatCompletion(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<ChatResponse>; | ||
| /** List available models. */ | ||
| listModels(): Promise<Model[]>; | ||
| /** | ||
| * Get Solana USDC balance. | ||
| * | ||
| * @returns USDC balance as a float | ||
| */ | ||
| getBalance(): Promise<number>; | ||
| /** Edit an image using img2img (Solana payment). */ | ||
| imageEdit(prompt: string, image: string, options?: ImageEditOptions): Promise<ImageResponse>; | ||
| /** Standalone search (Solana payment). */ | ||
| search(query: string, options?: SearchOptions): Promise<SearchResult>; | ||
| xUserLookup(usernames: string | string[]): Promise<XUserLookupResponse>; | ||
| xFollowers(username: string, cursor?: string): Promise<XFollowersResponse>; | ||
| xFollowings(username: string, cursor?: string): Promise<XFollowingsResponse>; | ||
| xUserInfo(username: string): Promise<XUserInfoResponse>; | ||
| xVerifiedFollowers(userId: string, cursor?: string): Promise<XVerifiedFollowersResponse>; | ||
| xUserTweets(username: string, includeReplies?: boolean, cursor?: string): Promise<XTweetsResponse>; | ||
| xUserMentions(username: string, sinceTime?: string, untilTime?: string, cursor?: string): Promise<XMentionsResponse>; | ||
| xTweetLookup(tweetIds: string | string[]): Promise<XTweetLookupResponse>; | ||
| xTweetReplies(tweetId: string, queryType?: string, cursor?: string): Promise<XTweetRepliesResponse>; | ||
| xTweetThread(tweetId: string, cursor?: string): Promise<XTweetThreadResponse>; | ||
| xSearch(query: string, queryType?: string, cursor?: string): Promise<XSearchResponse>; | ||
| xTrending(): Promise<XTrendingResponse>; | ||
| xArticlesRising(): Promise<XArticlesRisingResponse>; | ||
| xAuthorAnalytics(handle: string): Promise<XAuthorAnalyticsResponse>; | ||
| xCompareAuthors(handle1: string, handle2: string): Promise<XCompareAuthorsResponse>; | ||
| pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>; | ||
| pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>; | ||
| /** Get session spending. */ | ||
| getSpending(): Spending; | ||
| /** True if using sol.blockrun.ai. */ | ||
| isSolana(): boolean; | ||
| private requestWithPayment; | ||
| private handlePaymentAndRetry; | ||
| private requestWithPaymentRaw; | ||
| private handlePaymentAndRetryRaw; | ||
| private getWithPaymentRaw; | ||
| private handleGetPaymentAndRetryRaw; | ||
| private fetchWithTimeout; | ||
| } | ||
| /** | ||
| * Convenience function: create SolanaLLMClient for sol.blockrun.ai. | ||
| */ | ||
| declare function solanaClient(options?: SolanaLLMClientOptions): SolanaLLMClient; | ||
| declare const SOLANA_WALLET_FILE: string; | ||
| interface SolanaWalletInfo { | ||
| privateKey: string; | ||
| address: string; | ||
| isNew: boolean; | ||
| } | ||
| /** | ||
| * Create a new Solana wallet. | ||
| * Requires @solana/web3.js (optional dep). | ||
| */ | ||
| declare function createSolanaWallet(): { | ||
| address: string; | ||
| privateKey: string; | ||
| }; | ||
| /** | ||
| * Convert a bs58 private key string to Uint8Array (64 bytes). | ||
| * Accepts: bs58-encoded 64-byte key (standard Solana format). | ||
| */ | ||
| declare function solanaKeyToBytes(privateKey: string): Promise<Uint8Array>; | ||
| /** | ||
| * Get Solana public key (address) from bs58 private key. | ||
| */ | ||
| declare function solanaPublicKey(privateKey: string): Promise<string>; | ||
| declare function saveSolanaWallet(privateKey: string): string; | ||
| /** | ||
| * Scan ~/.<dir>/solana-wallet.json files from any provider. | ||
| * | ||
| * Each file should contain JSON with "privateKey" and "address" fields. | ||
| * Also checks ~/.brcc/wallet.json for BRCC wallets. | ||
| * Results are sorted by modification time (most recent first). | ||
| * | ||
| * @returns Array of wallet objects with secretKey and publicKey | ||
| */ | ||
| declare function scanSolanaWallets(): Array<{ | ||
| secretKey: string; | ||
| publicKey: string; | ||
| }>; | ||
| declare function loadSolanaWallet(): string | null; | ||
| declare function getOrCreateSolanaWallet(): Promise<SolanaWalletInfo>; | ||
| declare function getCached(key: string): unknown | null; | ||
| declare function getCachedByRequest(endpoint: string, body: Record<string, unknown>): unknown | null; | ||
| declare function setCache(key: string, data: unknown, ttlMs: number): void; | ||
| declare function saveToCache(endpoint: string, body: Record<string, unknown>, response: unknown, costUsd?: number): void; | ||
| declare function clearCache(): number; | ||
| /** | ||
| * Agent wallet setup utilities. | ||
| * | ||
| * Convenience functions for agent runtimes (Claude Code skills, etc.) | ||
| * that auto-create wallets and return configured clients. | ||
| */ | ||
| declare function setupAgentWallet(options?: { | ||
| silent?: boolean; | ||
| }): LLMClient; | ||
| declare function setupAgentSolanaWallet(options?: { | ||
| silent?: boolean; | ||
| }): Promise<SolanaLLMClient>; | ||
| declare function status(): Promise<{ | ||
| address: string; | ||
| balance: number; | ||
| }>; | ||
| interface CostEntry { | ||
| timestamp: string; | ||
| model: string; | ||
| inputTokens: number; | ||
| outputTokens: number; | ||
| costUsd: number; | ||
| } | ||
| declare function logCost(entry: CostEntry): void; | ||
| declare function getCostSummary(): { | ||
| totalUsd: number; | ||
| calls: number; | ||
| byModel: Record<string, number>; | ||
| }; | ||
| /** | ||
| * OpenAI-compatible API wrapper for BlockRun LLM SDK. | ||
| * | ||
| * Drop-in replacement for OpenAI SDK - just change the import and use walletKey instead of apiKey. | ||
| * | ||
| * @example | ||
| * // Before (OpenAI) | ||
| * import OpenAI from 'openai'; | ||
| * const client = new OpenAI({ apiKey: 'sk-...' }); | ||
| * | ||
| * // After (BlockRun) | ||
| * import { OpenAI } from '@blockrun/llm'; | ||
| * const client = new OpenAI({ walletKey: '0x...' }); | ||
| * | ||
| * // Rest of your code stays exactly the same! | ||
| * const response = await client.chat.completions.create({ | ||
| * model: 'gpt-4o', | ||
| * messages: [{ role: 'user', content: 'Hello!' }] | ||
| * }); | ||
| */ | ||
| interface OpenAIClientOptions { | ||
| /** EVM wallet private key (replaces apiKey) */ | ||
| walletKey?: `0x${string}` | string; | ||
| /** Alternative: use privateKey like LLMClient */ | ||
| privateKey?: `0x${string}` | string; | ||
| /** API endpoint URL (default: https://blockrun.ai/api) */ | ||
| baseURL?: string; | ||
| /** Request timeout in milliseconds */ | ||
| timeout?: number; | ||
| } | ||
| interface OpenAIChatCompletionParams { | ||
| model: string; | ||
| messages: Array<{ | ||
| role: "system" | "user" | "assistant" | "tool"; | ||
| content?: string | null; | ||
| name?: string; | ||
| tool_call_id?: string; | ||
| tool_calls?: ToolCall[]; | ||
| }>; | ||
| max_tokens?: number; | ||
| temperature?: number; | ||
| top_p?: number; | ||
| stream?: boolean; | ||
| n?: number; | ||
| stop?: string | string[]; | ||
| presence_penalty?: number; | ||
| frequency_penalty?: number; | ||
| user?: string; | ||
| tools?: Tool[]; | ||
| tool_choice?: ToolChoice; | ||
| } | ||
| interface OpenAIChatCompletionChoice { | ||
| index: number; | ||
| message: { | ||
| role: "assistant"; | ||
| content?: string | null; | ||
| tool_calls?: ToolCall[]; | ||
| }; | ||
| finish_reason: "stop" | "length" | "content_filter" | "tool_calls" | null; | ||
| } | ||
| interface OpenAIChatCompletionResponse { | ||
| id: string; | ||
| object: "chat.completion"; | ||
| created: number; | ||
| model: string; | ||
| choices: OpenAIChatCompletionChoice[]; | ||
| usage?: { | ||
| prompt_tokens: number; | ||
| completion_tokens: number; | ||
| total_tokens: number; | ||
| }; | ||
| } | ||
| interface OpenAIChatCompletionChunk { | ||
| id: string; | ||
| object: "chat.completion.chunk"; | ||
| created: number; | ||
| model: string; | ||
| choices: Array<{ | ||
| index: number; | ||
| delta: { | ||
| role?: "assistant"; | ||
| content?: string; | ||
| }; | ||
| finish_reason: string | null; | ||
| }>; | ||
| } | ||
| /** | ||
| * Chat completions API (OpenAI-compatible) | ||
| */ | ||
| declare class ChatCompletions { | ||
| private client; | ||
| private apiUrl; | ||
| private timeout; | ||
| constructor(client: LLMClient, apiUrl: string, timeout: number); | ||
| /** | ||
| * Create a chat completion (OpenAI-compatible). | ||
| */ | ||
| create(params: OpenAIChatCompletionParams): Promise<OpenAIChatCompletionResponse>; | ||
| create(params: OpenAIChatCompletionParams & { | ||
| stream: true; | ||
| }): Promise<AsyncIterable<OpenAIChatCompletionChunk>>; | ||
| private createStream; | ||
| private transformResponse; | ||
| } | ||
| /** | ||
| * Chat API namespace | ||
| */ | ||
| declare class Chat { | ||
| completions: ChatCompletions; | ||
| constructor(client: LLMClient, apiUrl: string, timeout: number); | ||
| } | ||
| /** | ||
| * OpenAI-compatible client for BlockRun. | ||
| * | ||
| * Drop-in replacement for the OpenAI SDK. | ||
| * | ||
| * @example | ||
| * import { OpenAI } from '@blockrun/llm'; | ||
| * | ||
| * const client = new OpenAI({ walletKey: '0x...' }); | ||
| * | ||
| * const response = await client.chat.completions.create({ | ||
| * model: 'gpt-4o', | ||
| * messages: [{ role: 'user', content: 'Hello!' }] | ||
| * }); | ||
| * | ||
| * console.log(response.choices[0].message.content); | ||
| */ | ||
| declare class OpenAI { | ||
| chat: Chat; | ||
| private client; | ||
| constructor(options?: OpenAIClientOptions); | ||
| /** | ||
| * Get the wallet address being used for payments. | ||
| */ | ||
| getWalletAddress(): string; | ||
| } | ||
| interface BlockRunAnthropicOptions { | ||
| privateKey?: `0x${string}` | string; | ||
| apiUrl?: string; | ||
| timeout?: number; | ||
| } | ||
| declare class AnthropicClient { | ||
| private _client; | ||
| private _clientPromise; | ||
| private _privateKey; | ||
| private _account; | ||
| private _apiUrl; | ||
| private _timeout; | ||
| constructor(options?: BlockRunAnthropicOptions); | ||
| private _getClient; | ||
| private _x402Fetch; | ||
| get messages(): _anthropic_ai_sdk.default['messages']; | ||
| getWalletAddress(): string; | ||
| } | ||
| export { APIError, AnthropicClient, BASE_CHAIN_ID, type BlockRunAnthropicOptions, BlockrunError, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatUsage, type CostEntry, 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, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, testnetClient }; |
-1343
| import * as _anthropic_ai_sdk from '@anthropic-ai/sdk'; | ||
| /** | ||
| * Type definitions for BlockRun LLM SDK | ||
| */ | ||
| interface FunctionDefinition { | ||
| name: string; | ||
| description?: string; | ||
| parameters?: Record<string, unknown>; | ||
| strict?: boolean; | ||
| } | ||
| interface Tool { | ||
| type: "function"; | ||
| function: FunctionDefinition; | ||
| } | ||
| interface FunctionCall { | ||
| name: string; | ||
| arguments: string; | ||
| } | ||
| interface ToolCall { | ||
| id: string; | ||
| type: "function"; | ||
| function: FunctionCall; | ||
| } | ||
| type ToolChoice = "none" | "auto" | "required" | { | ||
| type: "function"; | ||
| function: { | ||
| name: string; | ||
| }; | ||
| }; | ||
| interface ChatMessage { | ||
| role: "system" | "user" | "assistant" | "tool"; | ||
| content?: string | null; | ||
| name?: string; | ||
| tool_call_id?: string; | ||
| tool_calls?: ToolCall[]; | ||
| } | ||
| interface ChatChoice { | ||
| index: number; | ||
| message: ChatMessage; | ||
| finish_reason?: "stop" | "length" | "content_filter" | "tool_calls"; | ||
| } | ||
| interface ChatUsage { | ||
| prompt_tokens: number; | ||
| completion_tokens: number; | ||
| total_tokens: number; | ||
| num_sources_used?: number; | ||
| } | ||
| interface ChatResponse { | ||
| id: string; | ||
| object: string; | ||
| created: number; | ||
| model: string; | ||
| choices: ChatChoice[]; | ||
| usage?: ChatUsage; | ||
| citations?: string[]; | ||
| } | ||
| interface Model { | ||
| id: string; | ||
| name: string; | ||
| provider: string; | ||
| description: string; | ||
| inputPrice: number; | ||
| outputPrice: number; | ||
| contextWindow: number; | ||
| maxOutput: number; | ||
| available: boolean; | ||
| type?: "llm" | "image"; | ||
| } | ||
| interface ImageData { | ||
| url: string; | ||
| revised_prompt?: string; | ||
| b64_json?: string; | ||
| } | ||
| interface ImageResponse { | ||
| created: number; | ||
| data: ImageData[]; | ||
| } | ||
| interface ImageModel { | ||
| id: string; | ||
| name: string; | ||
| provider: string; | ||
| description: string; | ||
| pricePerImage: number; | ||
| supportedSizes?: string[]; | ||
| maxPromptLength?: number; | ||
| available: boolean; | ||
| type?: "llm" | "image"; | ||
| } | ||
| interface ImageClientOptions { | ||
| /** EVM wallet private key (hex string starting with 0x) */ | ||
| privateKey?: `0x${string}` | string; | ||
| /** API endpoint URL (default: https://blockrun.ai/api) */ | ||
| apiUrl?: string; | ||
| /** Request timeout in milliseconds (default: 120000 for images) */ | ||
| timeout?: number; | ||
| } | ||
| interface ImageGenerateOptions { | ||
| /** Model ID (default: "google/nano-banana") */ | ||
| model?: string; | ||
| /** Image size (default: "1024x1024") */ | ||
| size?: string; | ||
| /** Number of images to generate (default: 1) */ | ||
| n?: number; | ||
| /** Image quality (for supported models) */ | ||
| quality?: "standard" | "hd"; | ||
| } | ||
| interface WebSearchSource { | ||
| type: "web"; | ||
| country?: string; | ||
| excludedWebsites?: string[]; | ||
| allowedWebsites?: string[]; | ||
| safeSearch?: boolean; | ||
| } | ||
| interface XSearchSource { | ||
| type: "x"; | ||
| includedXHandles?: string[]; | ||
| excludedXHandles?: string[]; | ||
| postFavoriteCount?: number; | ||
| postViewCount?: number; | ||
| } | ||
| interface NewsSearchSource { | ||
| type: "news"; | ||
| country?: string; | ||
| excludedWebsites?: string[]; | ||
| allowedWebsites?: string[]; | ||
| safeSearch?: boolean; | ||
| } | ||
| interface RssSearchSource { | ||
| type: "rss"; | ||
| links: string[]; | ||
| } | ||
| type SearchSource = WebSearchSource | XSearchSource | NewsSearchSource | RssSearchSource; | ||
| interface SearchParameters { | ||
| mode?: "off" | "auto" | "on"; | ||
| sources?: SearchSource[]; | ||
| returnCitations?: boolean; | ||
| fromDate?: string; | ||
| toDate?: string; | ||
| maxSearchResults?: number; | ||
| } | ||
| interface Spending { | ||
| totalUsd: number; | ||
| calls: number; | ||
| } | ||
| interface LLMClientOptions { | ||
| /** EVM wallet private key (hex string starting with 0x). Optional if BASE_CHAIN_WALLET_KEY env var is set. */ | ||
| privateKey?: `0x${string}` | string; | ||
| /** API endpoint URL (default: https://blockrun.ai/api) */ | ||
| apiUrl?: string; | ||
| /** Request timeout in milliseconds (default: 60000) */ | ||
| timeout?: number; | ||
| } | ||
| interface ChatOptions { | ||
| /** System prompt */ | ||
| system?: string; | ||
| /** Max tokens to generate */ | ||
| maxTokens?: number; | ||
| /** Sampling temperature */ | ||
| temperature?: number; | ||
| /** Nucleus sampling parameter */ | ||
| topP?: number; | ||
| /** Enable xAI Live Search (shortcut for searchParameters.mode = "on") */ | ||
| search?: boolean; | ||
| /** Full xAI Live Search configuration (for Grok models) */ | ||
| searchParameters?: SearchParameters; | ||
| } | ||
| interface ChatCompletionOptions { | ||
| /** Max tokens to generate */ | ||
| maxTokens?: number; | ||
| /** Sampling temperature */ | ||
| temperature?: number; | ||
| /** Nucleus sampling parameter */ | ||
| topP?: number; | ||
| /** Enable xAI Live Search (shortcut for searchParameters.mode = "on") */ | ||
| search?: boolean; | ||
| /** Full xAI Live Search configuration (for Grok models) */ | ||
| searchParameters?: SearchParameters; | ||
| /** Tool definitions for function calling */ | ||
| tools?: Tool[]; | ||
| /** Tool selection strategy */ | ||
| toolChoice?: ToolChoice; | ||
| } | ||
| type RoutingProfile = "free" | "eco" | "auto" | "premium"; | ||
| type RoutingTier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING"; | ||
| interface RoutingDecision { | ||
| model: string; | ||
| tier: RoutingTier; | ||
| confidence: number; | ||
| method: "rules" | "llm"; | ||
| reasoning: string; | ||
| costEstimate: number; | ||
| baselineCost: number; | ||
| savings: number; | ||
| } | ||
| interface SmartChatOptions extends ChatOptions { | ||
| /** Routing profile: free (zero cost), eco (budget), auto (balanced), premium (best quality) */ | ||
| routingProfile?: RoutingProfile; | ||
| /** Maximum output tokens (used for cost estimation) */ | ||
| maxOutputTokens?: number; | ||
| } | ||
| interface SmartChatResponse { | ||
| /** The AI response text */ | ||
| response: string; | ||
| /** Which model was selected by smart routing */ | ||
| model: string; | ||
| /** Routing decision metadata */ | ||
| routing: RoutingDecision; | ||
| } | ||
| interface SearchResult { | ||
| query: string; | ||
| summary: string; | ||
| citations?: Array<Record<string, string>>; | ||
| sources_used?: number; | ||
| model?: string; | ||
| } | ||
| interface ImageEditOptions { | ||
| /** Model ID (default: "openai/gpt-image-1") */ | ||
| model?: string; | ||
| /** Optional base64-encoded mask image */ | ||
| mask?: string; | ||
| /** Image size (default: "1024x1024") */ | ||
| size?: string; | ||
| /** Number of images to generate (default: 1) */ | ||
| n?: number; | ||
| } | ||
| interface SearchOptions { | ||
| /** Source types to search (e.g. ["web", "x", "news"]) */ | ||
| sources?: string[]; | ||
| /** Maximum number of results (default: 10) */ | ||
| maxResults?: number; | ||
| /** Start date filter (YYYY-MM-DD) */ | ||
| fromDate?: string; | ||
| /** End date filter (YYYY-MM-DD) */ | ||
| toDate?: string; | ||
| } | ||
| interface XUser { | ||
| id: string; | ||
| userName: string; | ||
| name: string; | ||
| profilePicture?: string; | ||
| description?: string; | ||
| followers?: number; | ||
| following?: number; | ||
| isBlueVerified?: boolean; | ||
| verifiedType?: string; | ||
| location?: string; | ||
| joined?: string; | ||
| } | ||
| interface XUserLookupResponse { | ||
| users: XUser[]; | ||
| not_found?: string[]; | ||
| total_requested?: number; | ||
| total_found?: number; | ||
| } | ||
| interface XFollower { | ||
| id: string; | ||
| name?: string; | ||
| screen_name?: string; | ||
| userName?: string; | ||
| location?: string; | ||
| description?: string; | ||
| protected?: boolean; | ||
| verified?: boolean; | ||
| followers_count?: number; | ||
| following_count?: number; | ||
| favourites_count?: number; | ||
| statuses_count?: number; | ||
| created_at?: string; | ||
| profile_image_url_https?: string; | ||
| can_dm?: boolean; | ||
| } | ||
| interface XFollowersResponse { | ||
| followers: XFollower[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| username?: string; | ||
| } | ||
| interface XFollowingsResponse { | ||
| followings: XFollower[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| username?: string; | ||
| } | ||
| interface XUserInfoResponse { | ||
| data: Record<string, unknown>; | ||
| username?: string; | ||
| } | ||
| interface XVerifiedFollowersResponse { | ||
| followers: XFollower[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XTweet { | ||
| id: string; | ||
| text?: string; | ||
| created_at?: string; | ||
| author?: Record<string, unknown>; | ||
| favorite_count?: number; | ||
| retweet_count?: number; | ||
| reply_count?: number; | ||
| view_count?: number; | ||
| lang?: string; | ||
| entities?: Record<string, unknown>; | ||
| media?: Array<Record<string, unknown>>; | ||
| [key: string]: unknown; | ||
| } | ||
| interface XTweetsResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XMentionsResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| username?: string; | ||
| } | ||
| interface XTweetLookupResponse { | ||
| tweets: XTweet[]; | ||
| not_found?: string[]; | ||
| total_requested?: number; | ||
| total_found?: number; | ||
| } | ||
| interface XTweetRepliesResponse { | ||
| replies: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XTweetThreadResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XSearchResponse { | ||
| tweets: XTweet[]; | ||
| has_next_page?: boolean; | ||
| next_cursor?: string; | ||
| total_returned?: number; | ||
| } | ||
| interface XTrendingResponse { | ||
| data: Record<string, unknown>; | ||
| } | ||
| interface XArticlesRisingResponse { | ||
| data: Record<string, unknown>; | ||
| } | ||
| interface XAuthorAnalyticsResponse { | ||
| data: Record<string, unknown>; | ||
| handle?: string; | ||
| } | ||
| interface XCompareAuthorsResponse { | ||
| data: Record<string, unknown>; | ||
| } | ||
| declare class BlockrunError extends Error { | ||
| constructor(message: string); | ||
| } | ||
| declare class PaymentError extends BlockrunError { | ||
| constructor(message: string); | ||
| } | ||
| declare class APIError extends BlockrunError { | ||
| statusCode: number; | ||
| response?: unknown; | ||
| constructor(message: string, statusCode: number, response?: unknown); | ||
| } | ||
| /** | ||
| * BlockRun LLM Client - Main SDK entry point. | ||
| * | ||
| * Usage: | ||
| * import { LLMClient } from '@blockrun/llm'; | ||
| * | ||
| * // Option 1: Use BASE_CHAIN_WALLET_KEY env var | ||
| * const client = new LLMClient(); | ||
| * | ||
| * // Option 2: Pass private key directly | ||
| * const client = new LLMClient({ privateKey: '0x...' }); | ||
| * | ||
| * const response = await client.chat('openai/gpt-4o', 'Hello!'); | ||
| * console.log(response); | ||
| */ | ||
| /** | ||
| * BlockRun LLM Gateway Client. | ||
| * | ||
| * Provides access to multiple LLM providers (OpenAI, Anthropic, Google, etc.) | ||
| * with automatic x402 micropayments on Base chain. | ||
| * | ||
| * Networks: | ||
| * - Mainnet: https://blockrun.ai/api (Base, Chain ID 8453) | ||
| * - Testnet: https://testnet.blockrun.ai/api (Base Sepolia, Chain ID 84532) | ||
| * | ||
| * @example Testnet usage | ||
| * ```ts | ||
| * // Use testnet convenience function | ||
| * import { testnetClient } from '@blockrun/llm'; | ||
| * const client = testnetClient({ privateKey: '0x...' }); | ||
| * const response = await client.chat('openai/gpt-oss-20b', 'Hello!'); | ||
| * | ||
| * // Or configure manually | ||
| * const client = new LLMClient({ | ||
| * privateKey: '0x...', | ||
| * apiUrl: 'https://testnet.blockrun.ai/api' | ||
| * }); | ||
| * ``` | ||
| */ | ||
| declare class LLMClient { | ||
| static readonly DEFAULT_API_URL = "https://blockrun.ai/api"; | ||
| static readonly TESTNET_API_URL = "https://testnet.blockrun.ai/api"; | ||
| private account; | ||
| private privateKey; | ||
| private apiUrl; | ||
| private timeout; | ||
| private sessionTotalUsd; | ||
| private sessionCalls; | ||
| private modelPricingCache; | ||
| private modelPricingPromise; | ||
| /** | ||
| * Initialize the BlockRun LLM client. | ||
| * | ||
| * @param options - Client configuration options (optional if BASE_CHAIN_WALLET_KEY env var is set) | ||
| */ | ||
| constructor(options?: LLMClientOptions); | ||
| /** | ||
| * Simple 1-line chat interface. | ||
| * | ||
| * @param model - Model ID (e.g., 'openai/gpt-4o', 'anthropic/claude-sonnet-4') | ||
| * @param prompt - User message | ||
| * @param options - Optional chat parameters | ||
| * @returns Assistant's response text | ||
| * | ||
| * @example | ||
| * const response = await client.chat('gpt-4o', 'What is the capital of France?'); | ||
| * console.log(response); // 'The capital of France is Paris.' | ||
| */ | ||
| chat(model: string, prompt: string, options?: ChatOptions): Promise<string>; | ||
| /** | ||
| * Smart chat with automatic model routing. | ||
| * | ||
| * Uses ClawRouter's 14-dimension rule-based scoring algorithm (<1ms, 100% local) | ||
| * to select the cheapest model that can handle your request. | ||
| * | ||
| * @param prompt - User message | ||
| * @param options - Optional chat and routing parameters | ||
| * @returns SmartChatResponse with response text, selected model, and routing metadata | ||
| * | ||
| * @example Simple usage (auto profile) | ||
| * ```ts | ||
| * const result = await client.smartChat('What is 2+2?'); | ||
| * console.log(result.response); // '4' | ||
| * console.log(result.model); // 'google/gemini-2.5-flash-lite' | ||
| * console.log(result.routing.savings); // 0.78 (78% savings) | ||
| * ``` | ||
| * | ||
| * @example With routing profile | ||
| * ```ts | ||
| * // Free tier only (zero cost) | ||
| * const result = await client.smartChat('Hello!', { routingProfile: 'free' }); | ||
| * | ||
| * // Eco mode (budget optimized) | ||
| * const result = await client.smartChat('Explain quantum computing', { routingProfile: 'eco' }); | ||
| * | ||
| * // Premium mode (best quality) | ||
| * const result = await client.smartChat('Write a business plan', { routingProfile: 'premium' }); | ||
| * ``` | ||
| */ | ||
| smartChat(prompt: string, options?: SmartChatOptions): Promise<SmartChatResponse>; | ||
| /** | ||
| * Get model pricing map (cached). | ||
| * Fetches from API on first call, then returns cached result. | ||
| */ | ||
| private getModelPricing; | ||
| /** | ||
| * Fetch model pricing from API. | ||
| */ | ||
| private fetchModelPricing; | ||
| /** | ||
| * Full chat completion interface (OpenAI-compatible). | ||
| * | ||
| * @param model - Model ID | ||
| * @param messages - Array of messages with role and content | ||
| * @param options - Optional completion parameters | ||
| * @returns ChatResponse object with choices and usage | ||
| */ | ||
| chatCompletion(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<ChatResponse>; | ||
| /** | ||
| * Make a request with automatic x402 payment handling. | ||
| */ | ||
| private requestWithPayment; | ||
| /** | ||
| * Handle 402 response: parse requirements, sign payment, retry. | ||
| */ | ||
| private handlePaymentAndRetry; | ||
| /** | ||
| * Make a request with automatic x402 payment handling, returning raw JSON. | ||
| * Used for non-ChatResponse endpoints (X/Twitter, search, image edit, etc.). | ||
| */ | ||
| private requestWithPaymentRaw; | ||
| /** | ||
| * Handle 402 response for raw endpoints: parse requirements, sign payment, retry. | ||
| */ | ||
| private handlePaymentAndRetryRaw; | ||
| /** | ||
| * GET with automatic x402 payment handling, returning raw JSON. | ||
| * Used for Predexon prediction market endpoints that use GET + query params. | ||
| */ | ||
| private getWithPaymentRaw; | ||
| /** | ||
| * Handle 402 response for GET endpoints: parse requirements, sign payment, retry with GET. | ||
| */ | ||
| private handleGetPaymentAndRetryRaw; | ||
| /** | ||
| * Fetch with timeout. | ||
| */ | ||
| private fetchWithTimeout; | ||
| /** | ||
| * List available LLM models with pricing. | ||
| */ | ||
| listModels(): Promise<Model[]>; | ||
| /** | ||
| * List available image generation models with pricing. | ||
| */ | ||
| listImageModels(): Promise<ImageModel[]>; | ||
| /** | ||
| * List all available models (both LLM and image) with pricing. | ||
| * | ||
| * @returns Array of all models with 'type' field ('llm' or 'image') | ||
| * | ||
| * @example | ||
| * const models = await client.listAllModels(); | ||
| * for (const model of models) { | ||
| * if (model.type === 'llm') { | ||
| * console.log(`LLM: ${model.id} - $${model.inputPrice}/M input`); | ||
| * } else { | ||
| * console.log(`Image: ${model.id} - $${model.pricePerImage}/image`); | ||
| * } | ||
| * } | ||
| */ | ||
| listAllModels(): Promise<(Model | ImageModel)[]>; | ||
| /** | ||
| * Edit an image using img2img. | ||
| * | ||
| * @param prompt - Text description of the desired edit | ||
| * @param image - Base64-encoded image or URL of the source image | ||
| * @param options - Optional edit parameters | ||
| * @returns ImageResponse with edited image URLs | ||
| */ | ||
| imageEdit(prompt: string, image: string, options?: ImageEditOptions): Promise<ImageResponse>; | ||
| /** | ||
| * Standalone search (web, X/Twitter, news). | ||
| * | ||
| * @param query - Search query | ||
| * @param options - Optional search parameters | ||
| * @returns SearchResult with summary and citations | ||
| */ | ||
| search(query: string, options?: SearchOptions): Promise<SearchResult>; | ||
| /** | ||
| * Get USDC balance on Base network. | ||
| * | ||
| * Automatically detects mainnet vs testnet based on API URL. | ||
| * | ||
| * @returns USDC balance as a float (6 decimal places normalized) | ||
| * | ||
| * @example | ||
| * const balance = await client.getBalance(); | ||
| * console.log(`Balance: $${balance.toFixed(2)} USDC`); | ||
| */ | ||
| getBalance(): Promise<number>; | ||
| /** | ||
| * Look up X/Twitter user profiles by username. | ||
| * | ||
| * Powered by AttentionVC. $0.002 per user (min $0.02, max $0.20). | ||
| * | ||
| * @param usernames - Single username or array of usernames (without @) | ||
| */ | ||
| xUserLookup(usernames: string | string[]): Promise<XUserLookupResponse>; | ||
| /** | ||
| * Get followers of an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.05 per page (~200 accounts). | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xFollowers(username: string, cursor?: string): Promise<XFollowersResponse>; | ||
| /** | ||
| * Get accounts an X/Twitter user is following. | ||
| * | ||
| * Powered by AttentionVC. $0.05 per page (~200 accounts). | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xFollowings(username: string, cursor?: string): Promise<XFollowingsResponse>; | ||
| /** | ||
| * Get detailed profile info for a single X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.002 per request. | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| */ | ||
| xUserInfo(username: string): Promise<XUserInfoResponse>; | ||
| /** | ||
| * Get verified (blue-check) followers of an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.048 per page. | ||
| * | ||
| * @param userId - X/Twitter user ID (not username) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xVerifiedFollowers(userId: string, cursor?: string): Promise<XVerifiedFollowersResponse>; | ||
| /** | ||
| * Get tweets posted by an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param includeReplies - Include reply tweets (default: false) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xUserTweets(username: string, includeReplies?: boolean, cursor?: string): Promise<XTweetsResponse>; | ||
| /** | ||
| * Get tweets that mention an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param username - X/Twitter username (without @) | ||
| * @param sinceTime - Start time filter (ISO8601 or Unix timestamp) | ||
| * @param untilTime - End time filter (ISO8601 or Unix timestamp) | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xUserMentions(username: string, sinceTime?: string, untilTime?: string, cursor?: string): Promise<XMentionsResponse>; | ||
| /** | ||
| * Fetch full tweet data for up to 200 tweet IDs. | ||
| * | ||
| * Powered by AttentionVC. $0.16 per batch. | ||
| * | ||
| * @param tweetIds - Single tweet ID or array of tweet IDs (max 200) | ||
| */ | ||
| xTweetLookup(tweetIds: string | string[]): Promise<XTweetLookupResponse>; | ||
| /** | ||
| * Get replies to a specific tweet. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param tweetId - The tweet ID to get replies for | ||
| * @param queryType - Sort order: 'Latest' or 'Default' | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xTweetReplies(tweetId: string, queryType?: string, cursor?: string): Promise<XTweetRepliesResponse>; | ||
| /** | ||
| * Get the full thread context for a tweet. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param tweetId - The tweet ID to get thread for | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xTweetThread(tweetId: string, cursor?: string): Promise<XTweetThreadResponse>; | ||
| /** | ||
| * Search X/Twitter with advanced query operators. | ||
| * | ||
| * Powered by AttentionVC. $0.032 per page. | ||
| * | ||
| * @param query - Search query (supports Twitter search operators) | ||
| * @param queryType - Sort order: 'Latest', 'Top', or 'Default' | ||
| * @param cursor - Pagination cursor from previous response | ||
| */ | ||
| xSearch(query: string, queryType?: string, cursor?: string): Promise<XSearchResponse>; | ||
| /** | ||
| * Get current trending topics on X/Twitter. | ||
| * | ||
| * Powered by AttentionVC. $0.002 per request. | ||
| */ | ||
| xTrending(): Promise<XTrendingResponse>; | ||
| /** | ||
| * Get rising/viral articles from X/Twitter. | ||
| * | ||
| * Powered by AttentionVC intelligence layer. $0.05 per request. | ||
| */ | ||
| xArticlesRising(): Promise<XArticlesRisingResponse>; | ||
| /** | ||
| * Get author analytics and intelligence metrics for an X/Twitter user. | ||
| * | ||
| * Powered by AttentionVC intelligence layer. $0.02 per request. | ||
| * | ||
| * @param handle - X/Twitter handle (without @) | ||
| */ | ||
| xAuthorAnalytics(handle: string): Promise<XAuthorAnalyticsResponse>; | ||
| /** | ||
| * Compare two X/Twitter authors side-by-side with intelligence metrics. | ||
| * | ||
| * Powered by AttentionVC intelligence layer. $0.05 per request. | ||
| * | ||
| * @param handle1 - First X/Twitter handle (without @) | ||
| * @param handle2 - Second X/Twitter handle (without @) | ||
| */ | ||
| xCompareAuthors(handle1: string, handle2: string): Promise<XCompareAuthorsResponse>; | ||
| /** | ||
| * Query Predexon prediction market data (GET endpoints). | ||
| * | ||
| * Access real-time data from Polymarket, Kalshi, dFlow, and Binance Futures. | ||
| * Powered by Predexon. $0.001 per request. | ||
| * | ||
| * @param path - Endpoint path, e.g. "polymarket/events", "kalshi/markets/12345" | ||
| * @param params - Query parameters passed to the endpoint | ||
| * | ||
| * @example | ||
| * const events = await client.pm("polymarket/events"); | ||
| * const market = await client.pm("kalshi/markets/KXBTC-25MAR14"); | ||
| * const results = await client.pm("polymarket/search", { q: "bitcoin" }); | ||
| */ | ||
| pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>; | ||
| /** | ||
| * Structured query for Predexon prediction market data (POST endpoints). | ||
| * | ||
| * For complex queries that require a JSON body. $0.005 per request. | ||
| * | ||
| * @param path - Endpoint path, e.g. "polymarket/query", "kalshi/query" | ||
| * @param query - JSON body for the structured query | ||
| * | ||
| * @example | ||
| * const data = await client.pmQuery("polymarket/query", { filter: "active", limit: 10 }); | ||
| */ | ||
| pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>; | ||
| /** | ||
| * Get current session spending. | ||
| * | ||
| * @returns Object with totalUsd and calls count | ||
| * | ||
| * @example | ||
| * const spending = client.getSpending(); | ||
| * console.log(`Spent $${spending.totalUsd.toFixed(4)} across ${spending.calls} calls`); | ||
| */ | ||
| getSpending(): Spending; | ||
| /** | ||
| * Get the wallet address being used for payments. | ||
| */ | ||
| getWalletAddress(): string; | ||
| /** | ||
| * Check if client is configured for testnet. | ||
| */ | ||
| isTestnet(): boolean; | ||
| } | ||
| /** | ||
| * Create a testnet LLM client for development and testing. | ||
| * | ||
| * This is a convenience function that creates an LLMClient configured | ||
| * for the BlockRun testnet (Base Sepolia). | ||
| * | ||
| * @param options - Client options (privateKey required unless BASE_CHAIN_WALLET_KEY env var is set) | ||
| * @returns LLMClient configured for testnet | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * import { testnetClient } from '@blockrun/llm'; | ||
| * | ||
| * const client = testnetClient({ privateKey: '0x...' }); | ||
| * const response = await client.chat('openai/gpt-oss-20b', 'Hello!'); | ||
| * ``` | ||
| * | ||
| * Testnet Setup: | ||
| * 1. Get testnet ETH from https://www.alchemy.com/faucets/base-sepolia | ||
| * 2. Get testnet USDC from https://faucet.circle.com/ | ||
| * 3. Use your wallet with testnet funds | ||
| * | ||
| * Available Testnet Models: | ||
| * - openai/gpt-oss-20b | ||
| * - openai/gpt-oss-120b | ||
| */ | ||
| declare function testnetClient(options?: Omit<LLMClientOptions, 'apiUrl'>): LLMClient; | ||
| /** | ||
| * BlockRun Image Client - Generate images via x402 micropayments. | ||
| * | ||
| * SECURITY NOTE - Private Key Handling: | ||
| * Your private key NEVER leaves your machine. Here's what happens: | ||
| * 1. Key stays local - only used to sign an EIP-712 typed data message | ||
| * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header | ||
| * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator | ||
| * | ||
| * Usage: | ||
| * import { ImageClient } from '@blockrun/llm'; | ||
| * | ||
| * const client = new ImageClient({ privateKey: '0x...' }); | ||
| * const result = await client.generate('A cute cat in space'); | ||
| * console.log(result.data[0].url); | ||
| */ | ||
| /** | ||
| * BlockRun Image Generation Client. | ||
| * | ||
| * Generate images using Nano Banana (Google Gemini), DALL-E 3, or GPT Image | ||
| * with automatic x402 micropayments on Base chain. | ||
| */ | ||
| declare class ImageClient { | ||
| private account; | ||
| private privateKey; | ||
| private apiUrl; | ||
| private timeout; | ||
| private sessionTotalUsd; | ||
| private sessionCalls; | ||
| /** | ||
| * Initialize the BlockRun Image client. | ||
| * | ||
| * @param options - Client configuration options | ||
| */ | ||
| constructor(options?: ImageClientOptions); | ||
| /** | ||
| * Generate an image from a text prompt. | ||
| * | ||
| * @param prompt - Text description of the image to generate | ||
| * @param options - Optional generation parameters | ||
| * @returns ImageResponse with generated image URLs | ||
| * | ||
| * @example | ||
| * const result = await client.generate('A sunset over mountains'); | ||
| * console.log(result.data[0].url); | ||
| */ | ||
| generate(prompt: string, options?: ImageGenerateOptions): Promise<ImageResponse>; | ||
| /** | ||
| * Edit an image using img2img. | ||
| * | ||
| * @param prompt - Text description of the desired edit | ||
| * @param image - Base64-encoded image or URL of the source image | ||
| * @param options - Optional edit parameters | ||
| * @returns ImageResponse with edited image URLs | ||
| * | ||
| * @example | ||
| * const result = await client.edit('Make it a painting', imageBase64); | ||
| * console.log(result.data[0].url); | ||
| */ | ||
| edit(prompt: string, image: string, options?: ImageEditOptions): Promise<ImageResponse>; | ||
| /** | ||
| * List available image generation models with pricing. | ||
| */ | ||
| listImageModels(): Promise<ImageModel[]>; | ||
| /** | ||
| * Make a request with automatic x402 payment handling. | ||
| */ | ||
| private requestWithPayment; | ||
| /** | ||
| * Handle 402 response: parse requirements, sign payment, retry. | ||
| */ | ||
| private handlePaymentAndRetry; | ||
| /** | ||
| * Fetch with timeout. | ||
| */ | ||
| private fetchWithTimeout; | ||
| /** | ||
| * Get the wallet address being used for payments. | ||
| */ | ||
| getWalletAddress(): string; | ||
| /** | ||
| * Get session spending information. | ||
| */ | ||
| getSpending(): Spending; | ||
| } | ||
| /** | ||
| * x402 Payment Protocol v2 Implementation for BlockRun. | ||
| * | ||
| * This module handles creating signed payment payloads for the x402 v2 protocol. | ||
| * The private key is used ONLY for local signing and NEVER leaves the client. | ||
| */ | ||
| declare const BASE_CHAIN_ID = 8453; | ||
| declare const USDC_BASE: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; | ||
| declare const SOLANA_NETWORK = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"; | ||
| declare const USDC_SOLANA = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; | ||
| interface CreateSolanaPaymentOptions { | ||
| resourceUrl?: string; | ||
| resourceDescription?: string; | ||
| maxTimeoutSeconds?: number; | ||
| extra?: Record<string, unknown>; | ||
| extensions?: Record<string, unknown>; | ||
| rpcUrl?: string; | ||
| } | ||
| /** | ||
| * Create a signed Solana x402 v2 payment payload. | ||
| * | ||
| * This creates an SPL TransferChecked transaction for USDC payment | ||
| * that the CDP facilitator can verify and settle. | ||
| * | ||
| * Requires @solana/web3.js and @solana/spl-token dependencies. | ||
| * | ||
| * @param secretKey - Solana secret key (Uint8Array, 64 bytes) | ||
| * @param fromAddress - Sender wallet address (base58) | ||
| * @param recipient - Payment recipient address (base58) | ||
| * @param amount - Amount in micro USDC (6 decimals) | ||
| * @param feePayer - CDP facilitator fee payer address (base58) | ||
| * @param options - Additional options | ||
| * @returns Base64-encoded signed payment payload | ||
| */ | ||
| declare function createSolanaPaymentPayload(secretKey: Uint8Array, fromAddress: string, recipient: string, amount: string, feePayer: string, options?: CreateSolanaPaymentOptions): Promise<string>; | ||
| /** | ||
| * BlockRun Wallet Management - Auto-create and manage wallets. | ||
| * | ||
| * Provides frictionless wallet setup for new users: | ||
| * - Auto-creates wallet if none exists | ||
| * - Stores key securely at ~/.blockrun/.session | ||
| * - Generates EIP-681 URIs for easy MetaMask funding | ||
| */ | ||
| declare const USDC_BASE_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; | ||
| interface WalletInfo { | ||
| privateKey: string; | ||
| address: string; | ||
| isNew: boolean; | ||
| } | ||
| interface PaymentLinks { | ||
| basescan: string; | ||
| walletLink: string; | ||
| ethereum: string; | ||
| blockrun: string; | ||
| } | ||
| /** | ||
| * Create a new Ethereum wallet. | ||
| * | ||
| * @returns Object with address and privateKey | ||
| */ | ||
| declare function createWallet(): { | ||
| address: string; | ||
| privateKey: string; | ||
| }; | ||
| /** | ||
| * Save wallet private key to ~/.blockrun/.session | ||
| * | ||
| * @param privateKey - Private key string (with 0x prefix) | ||
| * @returns Path to saved wallet file | ||
| */ | ||
| declare function saveWallet(privateKey: string): string; | ||
| /** | ||
| * Scan ~/.<dir>/wallet.json files from any provider (agentcash, etc.). | ||
| * | ||
| * Each file should contain JSON with "privateKey" and "address" fields. | ||
| * Results are sorted by modification time (most recent first). | ||
| * | ||
| * @returns Array of wallet objects with privateKey and address | ||
| */ | ||
| declare function scanWallets(): Array<{ | ||
| privateKey: string; | ||
| address: string; | ||
| }>; | ||
| /** | ||
| * Load wallet private key from file. | ||
| * | ||
| * Priority: | ||
| * 1. Scan ~/.* /wallet.json (any provider) | ||
| * 2. Legacy ~/.blockrun/.session | ||
| * 3. Legacy ~/.blockrun/wallet.key | ||
| * | ||
| * @returns Private key string or null if not found | ||
| */ | ||
| declare function loadWallet(): string | null; | ||
| /** | ||
| * Get existing wallet or create new one. | ||
| * | ||
| * Priority: | ||
| * 1. BLOCKRUN_WALLET_KEY environment variable | ||
| * 2. Scan wallet.json files from providers | ||
| * 3. ~/.blockrun/.session file | ||
| * 4. ~/.blockrun/wallet.key file - legacy | ||
| * 5. Create new wallet | ||
| * | ||
| * @returns WalletInfo with address, privateKey, and isNew flag | ||
| */ | ||
| declare function getOrCreateWallet(): WalletInfo; | ||
| /** | ||
| * Get wallet address without exposing private key. | ||
| * | ||
| * @returns Wallet address or null if no wallet configured | ||
| */ | ||
| declare function getWalletAddress(): string | null; | ||
| /** | ||
| * Generate EIP-681 URI for USDC transfer on Base. | ||
| * | ||
| * @param address - Recipient Ethereum address | ||
| * @param amountUsdc - Amount in USDC (default 1.0) | ||
| * @returns EIP-681 URI string for MetaMask/wallet scanning | ||
| */ | ||
| declare function getEip681Uri(address: string, amountUsdc?: number): string; | ||
| /** | ||
| * Generate payment links for the wallet address. | ||
| * | ||
| * @param address - Ethereum address | ||
| * @returns Object with various payment links | ||
| */ | ||
| declare function getPaymentLinks(address: string): PaymentLinks; | ||
| /** | ||
| * Format the message shown when a new wallet is created. | ||
| * | ||
| * @param address - New wallet address | ||
| * @returns Formatted message string | ||
| */ | ||
| declare function formatWalletCreatedMessage(address: string): string; | ||
| /** | ||
| * Format the message shown when wallet needs more funds. | ||
| * | ||
| * @param address - Wallet address | ||
| * @returns Formatted message string | ||
| */ | ||
| declare function formatNeedsFundingMessage(address: string): string; | ||
| /** | ||
| * Compact funding message (no QR) for repeated displays. | ||
| * | ||
| * @param address - Wallet address | ||
| * @returns Short formatted message string | ||
| */ | ||
| declare function formatFundingMessageCompact(address: string): string; | ||
| declare const WALLET_FILE_PATH: string; | ||
| declare const WALLET_DIR_PATH: string; | ||
| /** | ||
| * BlockRun Solana LLM Client. | ||
| * | ||
| * Usage: | ||
| * import { SolanaLLMClient } from '@blockrun/llm'; | ||
| * | ||
| * // SOLANA_WALLET_KEY env var (bs58-encoded Solana secret key) | ||
| * const client = new SolanaLLMClient(); | ||
| * | ||
| * // Or pass key directly | ||
| * const client = new SolanaLLMClient({ privateKey: 'your-bs58-key' }); | ||
| * | ||
| * const response = await client.chat('openai/gpt-4o', 'gm Solana'); | ||
| */ | ||
| interface SolanaLLMClientOptions { | ||
| /** bs58-encoded Solana secret key (64 bytes). Optional if SOLANA_WALLET_KEY env var is set. */ | ||
| privateKey?: string; | ||
| /** API endpoint URL (default: https://sol.blockrun.ai/api) */ | ||
| apiUrl?: string; | ||
| /** Solana RPC URL (default: https://api.mainnet-beta.solana.com) */ | ||
| rpcUrl?: string; | ||
| /** Request timeout in milliseconds (default: 60000) */ | ||
| timeout?: number; | ||
| } | ||
| declare class SolanaLLMClient { | ||
| static readonly SOLANA_API_URL = "https://sol.blockrun.ai/api"; | ||
| private privateKey; | ||
| private apiUrl; | ||
| private rpcUrl; | ||
| private timeout; | ||
| private sessionTotalUsd; | ||
| private sessionCalls; | ||
| private addressCache; | ||
| constructor(options?: SolanaLLMClientOptions); | ||
| /** Get Solana wallet address (public key in base58). */ | ||
| getWalletAddress(): Promise<string>; | ||
| /** Simple 1-line chat. */ | ||
| chat(model: string, prompt: string, options?: ChatOptions): Promise<string>; | ||
| /** Full chat completion (OpenAI-compatible). */ | ||
| chatCompletion(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<ChatResponse>; | ||
| /** List available models. */ | ||
| listModels(): Promise<Model[]>; | ||
| /** | ||
| * Get Solana USDC balance. | ||
| * | ||
| * @returns USDC balance as a float | ||
| */ | ||
| getBalance(): Promise<number>; | ||
| /** Edit an image using img2img (Solana payment). */ | ||
| imageEdit(prompt: string, image: string, options?: ImageEditOptions): Promise<ImageResponse>; | ||
| /** Standalone search (Solana payment). */ | ||
| search(query: string, options?: SearchOptions): Promise<SearchResult>; | ||
| xUserLookup(usernames: string | string[]): Promise<XUserLookupResponse>; | ||
| xFollowers(username: string, cursor?: string): Promise<XFollowersResponse>; | ||
| xFollowings(username: string, cursor?: string): Promise<XFollowingsResponse>; | ||
| xUserInfo(username: string): Promise<XUserInfoResponse>; | ||
| xVerifiedFollowers(userId: string, cursor?: string): Promise<XVerifiedFollowersResponse>; | ||
| xUserTweets(username: string, includeReplies?: boolean, cursor?: string): Promise<XTweetsResponse>; | ||
| xUserMentions(username: string, sinceTime?: string, untilTime?: string, cursor?: string): Promise<XMentionsResponse>; | ||
| xTweetLookup(tweetIds: string | string[]): Promise<XTweetLookupResponse>; | ||
| xTweetReplies(tweetId: string, queryType?: string, cursor?: string): Promise<XTweetRepliesResponse>; | ||
| xTweetThread(tweetId: string, cursor?: string): Promise<XTweetThreadResponse>; | ||
| xSearch(query: string, queryType?: string, cursor?: string): Promise<XSearchResponse>; | ||
| xTrending(): Promise<XTrendingResponse>; | ||
| xArticlesRising(): Promise<XArticlesRisingResponse>; | ||
| xAuthorAnalytics(handle: string): Promise<XAuthorAnalyticsResponse>; | ||
| xCompareAuthors(handle1: string, handle2: string): Promise<XCompareAuthorsResponse>; | ||
| pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>; | ||
| pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>; | ||
| /** Get session spending. */ | ||
| getSpending(): Spending; | ||
| /** True if using sol.blockrun.ai. */ | ||
| isSolana(): boolean; | ||
| private requestWithPayment; | ||
| private handlePaymentAndRetry; | ||
| private requestWithPaymentRaw; | ||
| private handlePaymentAndRetryRaw; | ||
| private getWithPaymentRaw; | ||
| private handleGetPaymentAndRetryRaw; | ||
| private fetchWithTimeout; | ||
| } | ||
| /** | ||
| * Convenience function: create SolanaLLMClient for sol.blockrun.ai. | ||
| */ | ||
| declare function solanaClient(options?: SolanaLLMClientOptions): SolanaLLMClient; | ||
| declare const SOLANA_WALLET_FILE: string; | ||
| interface SolanaWalletInfo { | ||
| privateKey: string; | ||
| address: string; | ||
| isNew: boolean; | ||
| } | ||
| /** | ||
| * Create a new Solana wallet. | ||
| * Requires @solana/web3.js (optional dep). | ||
| */ | ||
| declare function createSolanaWallet(): { | ||
| address: string; | ||
| privateKey: string; | ||
| }; | ||
| /** | ||
| * Convert a bs58 private key string to Uint8Array (64 bytes). | ||
| * Accepts: bs58-encoded 64-byte key (standard Solana format). | ||
| */ | ||
| declare function solanaKeyToBytes(privateKey: string): Promise<Uint8Array>; | ||
| /** | ||
| * Get Solana public key (address) from bs58 private key. | ||
| */ | ||
| declare function solanaPublicKey(privateKey: string): Promise<string>; | ||
| declare function saveSolanaWallet(privateKey: string): string; | ||
| /** | ||
| * Scan ~/.<dir>/solana-wallet.json files from any provider. | ||
| * | ||
| * Each file should contain JSON with "privateKey" and "address" fields. | ||
| * Also checks ~/.brcc/wallet.json for BRCC wallets. | ||
| * Results are sorted by modification time (most recent first). | ||
| * | ||
| * @returns Array of wallet objects with secretKey and publicKey | ||
| */ | ||
| declare function scanSolanaWallets(): Array<{ | ||
| secretKey: string; | ||
| publicKey: string; | ||
| }>; | ||
| declare function loadSolanaWallet(): string | null; | ||
| declare function getOrCreateSolanaWallet(): Promise<SolanaWalletInfo>; | ||
| declare function getCached(key: string): unknown | null; | ||
| declare function getCachedByRequest(endpoint: string, body: Record<string, unknown>): unknown | null; | ||
| declare function setCache(key: string, data: unknown, ttlMs: number): void; | ||
| declare function saveToCache(endpoint: string, body: Record<string, unknown>, response: unknown, costUsd?: number): void; | ||
| declare function clearCache(): number; | ||
| /** | ||
| * Agent wallet setup utilities. | ||
| * | ||
| * Convenience functions for agent runtimes (Claude Code skills, etc.) | ||
| * that auto-create wallets and return configured clients. | ||
| */ | ||
| declare function setupAgentWallet(options?: { | ||
| silent?: boolean; | ||
| }): LLMClient; | ||
| declare function setupAgentSolanaWallet(options?: { | ||
| silent?: boolean; | ||
| }): Promise<SolanaLLMClient>; | ||
| declare function status(): Promise<{ | ||
| address: string; | ||
| balance: number; | ||
| }>; | ||
| interface CostEntry { | ||
| timestamp: string; | ||
| model: string; | ||
| inputTokens: number; | ||
| outputTokens: number; | ||
| costUsd: number; | ||
| } | ||
| declare function logCost(entry: CostEntry): void; | ||
| declare function getCostSummary(): { | ||
| totalUsd: number; | ||
| calls: number; | ||
| byModel: Record<string, number>; | ||
| }; | ||
| /** | ||
| * OpenAI-compatible API wrapper for BlockRun LLM SDK. | ||
| * | ||
| * Drop-in replacement for OpenAI SDK - just change the import and use walletKey instead of apiKey. | ||
| * | ||
| * @example | ||
| * // Before (OpenAI) | ||
| * import OpenAI from 'openai'; | ||
| * const client = new OpenAI({ apiKey: 'sk-...' }); | ||
| * | ||
| * // After (BlockRun) | ||
| * import { OpenAI } from '@blockrun/llm'; | ||
| * const client = new OpenAI({ walletKey: '0x...' }); | ||
| * | ||
| * // Rest of your code stays exactly the same! | ||
| * const response = await client.chat.completions.create({ | ||
| * model: 'gpt-4o', | ||
| * messages: [{ role: 'user', content: 'Hello!' }] | ||
| * }); | ||
| */ | ||
| interface OpenAIClientOptions { | ||
| /** EVM wallet private key (replaces apiKey) */ | ||
| walletKey?: `0x${string}` | string; | ||
| /** Alternative: use privateKey like LLMClient */ | ||
| privateKey?: `0x${string}` | string; | ||
| /** API endpoint URL (default: https://blockrun.ai/api) */ | ||
| baseURL?: string; | ||
| /** Request timeout in milliseconds */ | ||
| timeout?: number; | ||
| } | ||
| interface OpenAIChatCompletionParams { | ||
| model: string; | ||
| messages: Array<{ | ||
| role: "system" | "user" | "assistant" | "tool"; | ||
| content?: string | null; | ||
| name?: string; | ||
| tool_call_id?: string; | ||
| tool_calls?: ToolCall[]; | ||
| }>; | ||
| max_tokens?: number; | ||
| temperature?: number; | ||
| top_p?: number; | ||
| stream?: boolean; | ||
| n?: number; | ||
| stop?: string | string[]; | ||
| presence_penalty?: number; | ||
| frequency_penalty?: number; | ||
| user?: string; | ||
| tools?: Tool[]; | ||
| tool_choice?: ToolChoice; | ||
| } | ||
| interface OpenAIChatCompletionChoice { | ||
| index: number; | ||
| message: { | ||
| role: "assistant"; | ||
| content?: string | null; | ||
| tool_calls?: ToolCall[]; | ||
| }; | ||
| finish_reason: "stop" | "length" | "content_filter" | "tool_calls" | null; | ||
| } | ||
| interface OpenAIChatCompletionResponse { | ||
| id: string; | ||
| object: "chat.completion"; | ||
| created: number; | ||
| model: string; | ||
| choices: OpenAIChatCompletionChoice[]; | ||
| usage?: { | ||
| prompt_tokens: number; | ||
| completion_tokens: number; | ||
| total_tokens: number; | ||
| }; | ||
| } | ||
| interface OpenAIChatCompletionChunk { | ||
| id: string; | ||
| object: "chat.completion.chunk"; | ||
| created: number; | ||
| model: string; | ||
| choices: Array<{ | ||
| index: number; | ||
| delta: { | ||
| role?: "assistant"; | ||
| content?: string; | ||
| }; | ||
| finish_reason: string | null; | ||
| }>; | ||
| } | ||
| /** | ||
| * Chat completions API (OpenAI-compatible) | ||
| */ | ||
| declare class ChatCompletions { | ||
| private client; | ||
| private apiUrl; | ||
| private timeout; | ||
| constructor(client: LLMClient, apiUrl: string, timeout: number); | ||
| /** | ||
| * Create a chat completion (OpenAI-compatible). | ||
| */ | ||
| create(params: OpenAIChatCompletionParams): Promise<OpenAIChatCompletionResponse>; | ||
| create(params: OpenAIChatCompletionParams & { | ||
| stream: true; | ||
| }): Promise<AsyncIterable<OpenAIChatCompletionChunk>>; | ||
| private createStream; | ||
| private transformResponse; | ||
| } | ||
| /** | ||
| * Chat API namespace | ||
| */ | ||
| declare class Chat { | ||
| completions: ChatCompletions; | ||
| constructor(client: LLMClient, apiUrl: string, timeout: number); | ||
| } | ||
| /** | ||
| * OpenAI-compatible client for BlockRun. | ||
| * | ||
| * Drop-in replacement for the OpenAI SDK. | ||
| * | ||
| * @example | ||
| * import { OpenAI } from '@blockrun/llm'; | ||
| * | ||
| * const client = new OpenAI({ walletKey: '0x...' }); | ||
| * | ||
| * const response = await client.chat.completions.create({ | ||
| * model: 'gpt-4o', | ||
| * messages: [{ role: 'user', content: 'Hello!' }] | ||
| * }); | ||
| * | ||
| * console.log(response.choices[0].message.content); | ||
| */ | ||
| declare class OpenAI { | ||
| chat: Chat; | ||
| private client; | ||
| constructor(options?: OpenAIClientOptions); | ||
| /** | ||
| * Get the wallet address being used for payments. | ||
| */ | ||
| getWalletAddress(): string; | ||
| } | ||
| interface BlockRunAnthropicOptions { | ||
| privateKey?: `0x${string}` | string; | ||
| apiUrl?: string; | ||
| timeout?: number; | ||
| } | ||
| declare class AnthropicClient { | ||
| private _client; | ||
| private _clientPromise; | ||
| private _privateKey; | ||
| private _account; | ||
| private _apiUrl; | ||
| private _timeout; | ||
| constructor(options?: BlockRunAnthropicOptions); | ||
| private _getClient; | ||
| private _x402Fetch; | ||
| get messages(): _anthropic_ai_sdk.default['messages']; | ||
| getWalletAddress(): string; | ||
| } | ||
| export { APIError, AnthropicClient, BASE_CHAIN_ID, type BlockRunAnthropicOptions, BlockrunError, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatUsage, type CostEntry, 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, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, testnetClient }; |
| import { | ||
| Account, | ||
| AddressLookupTableAccount, | ||
| AddressLookupTableInstruction, | ||
| AddressLookupTableProgram, | ||
| Authorized, | ||
| BLOCKHASH_CACHE_TIMEOUT_MS, | ||
| BPF_LOADER_DEPRECATED_PROGRAM_ID, | ||
| BPF_LOADER_PROGRAM_ID, | ||
| BpfLoader, | ||
| COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, | ||
| ComputeBudgetInstruction, | ||
| ComputeBudgetProgram, | ||
| Connection, | ||
| Ed25519Program, | ||
| Enum, | ||
| EpochSchedule, | ||
| FeeCalculatorLayout, | ||
| Keypair, | ||
| LAMPORTS_PER_SOL, | ||
| LOOKUP_TABLE_INSTRUCTION_LAYOUTS, | ||
| Loader, | ||
| Lockup, | ||
| MAX_SEED_LENGTH, | ||
| Message, | ||
| MessageAccountKeys, | ||
| MessageV0, | ||
| NONCE_ACCOUNT_LENGTH, | ||
| NonceAccount, | ||
| PACKET_DATA_SIZE, | ||
| PUBLIC_KEY_LENGTH, | ||
| PublicKey, | ||
| SIGNATURE_LENGTH_IN_BYTES, | ||
| SOLANA_SCHEMA, | ||
| STAKE_CONFIG_ID, | ||
| STAKE_INSTRUCTION_LAYOUTS, | ||
| SYSTEM_INSTRUCTION_LAYOUTS, | ||
| SYSVAR_CLOCK_PUBKEY, | ||
| SYSVAR_EPOCH_SCHEDULE_PUBKEY, | ||
| SYSVAR_INSTRUCTIONS_PUBKEY, | ||
| SYSVAR_RECENT_BLOCKHASHES_PUBKEY, | ||
| SYSVAR_RENT_PUBKEY, | ||
| SYSVAR_REWARDS_PUBKEY, | ||
| SYSVAR_SLOT_HASHES_PUBKEY, | ||
| SYSVAR_SLOT_HISTORY_PUBKEY, | ||
| SYSVAR_STAKE_HISTORY_PUBKEY, | ||
| Secp256k1Program, | ||
| SendTransactionError, | ||
| SolanaJSONRPCError, | ||
| SolanaJSONRPCErrorCode, | ||
| StakeAuthorizationLayout, | ||
| StakeInstruction, | ||
| StakeProgram, | ||
| Struct, | ||
| SystemInstruction, | ||
| SystemProgram, | ||
| Transaction, | ||
| TransactionExpiredBlockheightExceededError, | ||
| TransactionExpiredNonceInvalidError, | ||
| TransactionExpiredTimeoutError, | ||
| TransactionInstruction, | ||
| TransactionMessage, | ||
| TransactionStatus, | ||
| VALIDATOR_INFO_KEY, | ||
| VERSION_PREFIX_MASK, | ||
| VOTE_PROGRAM_ID, | ||
| ValidatorInfo, | ||
| VersionedMessage, | ||
| VersionedTransaction, | ||
| VoteAccount, | ||
| VoteAuthorizationLayout, | ||
| VoteInit, | ||
| VoteInstruction, | ||
| VoteProgram, | ||
| clusterApiUrl, | ||
| init_index_esm, | ||
| sendAndConfirmRawTransaction, | ||
| sendAndConfirmTransaction | ||
| } from "./chunk-KRDGCX7W.js"; | ||
| init_index_esm(); | ||
| export { | ||
| Account, | ||
| AddressLookupTableAccount, | ||
| AddressLookupTableInstruction, | ||
| AddressLookupTableProgram, | ||
| Authorized, | ||
| BLOCKHASH_CACHE_TIMEOUT_MS, | ||
| BPF_LOADER_DEPRECATED_PROGRAM_ID, | ||
| BPF_LOADER_PROGRAM_ID, | ||
| BpfLoader, | ||
| COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, | ||
| ComputeBudgetInstruction, | ||
| ComputeBudgetProgram, | ||
| Connection, | ||
| Ed25519Program, | ||
| Enum, | ||
| EpochSchedule, | ||
| FeeCalculatorLayout, | ||
| Keypair, | ||
| LAMPORTS_PER_SOL, | ||
| LOOKUP_TABLE_INSTRUCTION_LAYOUTS, | ||
| Loader, | ||
| Lockup, | ||
| MAX_SEED_LENGTH, | ||
| Message, | ||
| MessageAccountKeys, | ||
| MessageV0, | ||
| NONCE_ACCOUNT_LENGTH, | ||
| NonceAccount, | ||
| PACKET_DATA_SIZE, | ||
| PUBLIC_KEY_LENGTH, | ||
| PublicKey, | ||
| SIGNATURE_LENGTH_IN_BYTES, | ||
| SOLANA_SCHEMA, | ||
| STAKE_CONFIG_ID, | ||
| STAKE_INSTRUCTION_LAYOUTS, | ||
| SYSTEM_INSTRUCTION_LAYOUTS, | ||
| SYSVAR_CLOCK_PUBKEY, | ||
| SYSVAR_EPOCH_SCHEDULE_PUBKEY, | ||
| SYSVAR_INSTRUCTIONS_PUBKEY, | ||
| SYSVAR_RECENT_BLOCKHASHES_PUBKEY, | ||
| SYSVAR_RENT_PUBKEY, | ||
| SYSVAR_REWARDS_PUBKEY, | ||
| SYSVAR_SLOT_HASHES_PUBKEY, | ||
| SYSVAR_SLOT_HISTORY_PUBKEY, | ||
| SYSVAR_STAKE_HISTORY_PUBKEY, | ||
| Secp256k1Program, | ||
| SendTransactionError, | ||
| SolanaJSONRPCError, | ||
| SolanaJSONRPCErrorCode, | ||
| StakeAuthorizationLayout, | ||
| StakeInstruction, | ||
| StakeProgram, | ||
| Struct, | ||
| SystemInstruction, | ||
| SystemProgram, | ||
| Transaction, | ||
| TransactionExpiredBlockheightExceededError, | ||
| TransactionExpiredNonceInvalidError, | ||
| TransactionExpiredTimeoutError, | ||
| TransactionInstruction, | ||
| TransactionMessage, | ||
| TransactionStatus, | ||
| VALIDATOR_INFO_KEY, | ||
| VERSION_PREFIX_MASK, | ||
| VOTE_PROGRAM_ID, | ||
| ValidatorInfo, | ||
| VersionedMessage, | ||
| VersionedTransaction, | ||
| VoteAccount, | ||
| VoteAuthorizationLayout, | ||
| VoteInit, | ||
| VoteInstruction, | ||
| VoteProgram, | ||
| clusterApiUrl, | ||
| sendAndConfirmRawTransaction, | ||
| sendAndConfirmTransaction | ||
| }; |
Sorry, the diff of this file is too big to display
Empty package
Supply chain riskPackage does not contain any code. It may be removed, is name squatting, or the result of a faulty package publish.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 7 instances in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
0
-100%2
-80%30041
-99.19%3
-70%0
-100%