UNPKG

@hivetechs/hive-ai

Version:

Real-time streaming AI consensus platform with HTTP+SSE MCP integration for Claude Code, VS Code, Cursor, and Windsurf - powered by OpenRouter's unified API

142 lines (138 loc) 5.21 kB
/** * OpenRouter-Exclusive AI Provider Client * * This module provides access to 300+ AI models through OpenRouter's unified API. * All complexity of individual provider APIs is handled by OpenRouter's infrastructure. * * Architecture Decision (June 2025): * Based on extensive research showing only 30-40% of providers have stable APIs * and the impossibility of maintaining 55+ integrations with a small team, we've * partnered with OpenRouter as our exclusive infrastructure provider. * * Benefits: * - Access to ALL models through one API key * - Automatic failover and load balancing * - Zero maintenance of provider integrations * - Focus on our unique value: 4-stage consensus pipeline */ import { getOpenRouterApiKey as getUnifiedOpenRouterApiKey } from '../../storage/unified-database.js'; /** * Create a chat completion using OpenRouter's unified API * ALL models from ALL providers are accessed through this single endpoint */ export async function createChatCompletion(options) { // Get OpenRouter API key - this is now the ONLY key we need const openRouterApiKey = await getOpenRouterApiKey(); if (!openRouterApiKey) { throw new Error('No OpenRouter API key configured.\n' + 'Please run: hive-ai provider configure openrouter <your-api-key>\n' + 'Get your key at: https://openrouter.ai/keys'); } const modelId = options.model; console.log(`🌐 OpenRouter API: ${modelId}`); // OpenRouter request headers const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${openRouterApiKey}`, 'HTTP-Referer': 'https://hive.ai', // For analytics 'X-Title': 'Hive.AI Consensus' // Shows in OpenRouter dashboard }; // Request body in OpenAI-compatible format const requestBody = { model: modelId, messages: options.messages, temperature: options.temperature ?? 0.7, max_tokens: options.max_tokens ?? 2048, stream: options.stream ?? false }; try { const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers, body: JSON.stringify(requestBody) }); if (!response.ok) { const errorData = await response.text(); let errorMessage = `OpenRouter API error (${response.status})`; try { const errorJson = JSON.parse(errorData); if (errorJson.error?.message) { errorMessage = errorJson.error.message; } } catch { errorMessage = errorData || errorMessage; } // Provide helpful error messages if (response.status === 401) { throw new Error('Invalid OpenRouter API key.\n' + 'Please check your key and reconfigure:\n' + 'hive-ai provider configure openrouter <your-api-key>'); } else if (response.status === 402) { throw new Error('OpenRouter account has insufficient credits.\n' + 'Please add credits at: https://openrouter.ai/credits'); } throw new Error(errorMessage); } const result = await response.json(); if (!result.choices?.[0]?.message?.content) { throw new Error('Invalid response format from OpenRouter'); } // Extract provider info and usage stats const actualProvider = result.model || modelId.split('/')[0]; console.log(`✅ Success: ${actualProvider}`); return { content: result.choices[0].message.content, model: modelId, provider: actualProvider, usage: result.usage }; } catch (error) { console.error(`❌ OpenRouter error:`, error); throw error; } } /** * Get the configured OpenRouter API key * This is now the ONLY API key our system needs */ async function getOpenRouterApiKey() { try { // Use unified database - single source of truth return await getUnifiedOpenRouterApiKey(); } catch (error) { console.error('Error accessing OpenRouter key:', error); return null; } } /** * Check if the system is properly configured with OpenRouter */ export async function isOpenRouterConfigured() { const key = await getOpenRouterApiKey(); return !!key; } /** * Get helpful setup instructions for new users */ export function getSetupInstructions() { return ` Welcome to hive-ai! 🚀 To get started, you need an OpenRouter API key: 1. Sign up at: https://openrouter.ai/signup 2. Add credits: https://openrouter.ai/credits ($5 minimum recommended) 3. Get your API key: https://openrouter.ai/keys 4. Configure hive-ai: hive-ai provider configure openrouter <your-key> With one OpenRouter key, you get instant access to: - OpenAI (GPT-4, GPT-3.5) - Anthropic (Claude 3.5, Claude 3) - Google (Gemini Pro, PaLM) - Meta (Llama models) - 50+ more providers and 300+ models Learn more: https://hive.ai/docs/openrouter `; } //# sourceMappingURL=provider-client.js.map