-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(ai): support for openrouter models #126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PhantomInTheWire
wants to merge
2
commits into
pickle-com:main
Choose a base branch
from
PhantomInTheWire:feat/openrouter-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+214
−4
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| const OpenAI = require('openai'); | ||
|
|
||
| const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1'; | ||
|
|
||
| class OpenRouterProvider { | ||
| static async validateApiKey(key) { | ||
| if (!key || typeof key !== 'string' || !key.startsWith('sk-or-')) { | ||
| return { success: false, error: 'Invalid OpenRouter API key format.' }; | ||
| } | ||
|
|
||
| try { | ||
| const response = await fetch(`${OPENROUTER_BASE_URL}/models`, { | ||
| headers: { 'Authorization': `Bearer ${key}` } | ||
| }); | ||
|
|
||
| if (response.ok) { | ||
| return { success: true }; | ||
| } else { | ||
| const errorData = await response.json().catch(() => ({})); | ||
| const message = errorData.error?.message || `Validation failed with status: ${response.status}`; | ||
| return { success: false, error: message }; | ||
| } | ||
| } catch (error) { | ||
| console.error(`[OpenRouterProvider] Network error during key validation:`, error); | ||
| return { success: false, error: 'A network error occurred during validation.' }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates an OpenRouter STT session | ||
| * Note: OpenRouter doesn't have native real-time STT, so this is a placeholder | ||
| * @param {object} opts - Configuration options | ||
| * @param {string} opts.apiKey - OpenRouter API key | ||
| * @param {string} [opts.language='en'] - Language code | ||
| * @param {object} [opts.callbacks] - Event callbacks | ||
| * @returns {Promise<object>} STT session placeholder | ||
| */ | ||
| async function createSTT({ apiKey, language = "en", callbacks = {}, ...config }) { | ||
| console.warn("[OpenRouter] STT not natively supported. Consider using OpenAI or Gemini for STT.") | ||
|
|
||
| // Return a mock STT session that doesn't actually do anything | ||
| return { | ||
| sendRealtimeInput: async (audioData) => { | ||
| console.warn("[OpenRouter] STT sendRealtimeInput called but not implemented") | ||
| }, | ||
| close: async () => { | ||
| console.log("[OpenRouter] STT session closed") | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates an OpenRouter LLM instance | ||
| * @param {object} opts - Configuration options | ||
| * @param {string} opts.apiKey - OpenRouter API key | ||
| * @param {string} [opts.model='x-ai/grok-4'] - Model name | ||
| * @param {number} [opts.temperature=0.7] - Temperature | ||
| * @param {number} [opts.maxTokens=2048] - Max tokens | ||
| * @returns {object} LLM instance | ||
| */ | ||
| function createLLM({ apiKey, model = 'x-ai/grok-4', temperature = 0.7, maxTokens = 2048, ...config }) { | ||
| const client = new OpenAI({ apiKey, baseURL: OPENROUTER_BASE_URL }); | ||
|
|
||
| const callApi = async (messages) => { | ||
| try { | ||
| const response = await client.chat.completions.create({ | ||
| model: model, | ||
| messages: messages, | ||
| temperature: temperature, | ||
| max_tokens: maxTokens | ||
| }); | ||
|
|
||
| if (!response.choices || response.choices.length === 0) { | ||
| throw new Error('No response choices returned from OpenRouter API'); | ||
| } | ||
|
|
||
| return { | ||
| content: response.choices[0].message.content?.trim() || '', | ||
| raw: response | ||
| }; | ||
| } catch (error) { | ||
| console.error('[OpenRouter] API call failed:', error); | ||
| throw new Error(`OpenRouter API error: ${error.message}`); | ||
| } | ||
| }; | ||
|
|
||
| return { | ||
| generateContent: async (parts) => { | ||
| const messages = []; | ||
| let systemPrompt = ''; | ||
| let userContent = []; | ||
|
|
||
| for (const part of parts) { | ||
| if (typeof part === 'string') { | ||
| if ( | ||
| systemPrompt === '' && | ||
| ( | ||
| part.toLowerCase().startsWith('you are') || | ||
| part.toLowerCase().includes('system:') | ||
| ) | ||
| ) { | ||
| systemPrompt = part; | ||
| } else { | ||
| userContent.push({ type: 'text', text: part }); | ||
| } | ||
| } else if (part.inlineData) { | ||
| userContent.push({ | ||
| type: 'image_url', | ||
| image_url: { url: `data:${part.inlineData.mimeType};base64,${part.inlineData.data}` } | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| if (systemPrompt) messages.push({ role: 'system', content: systemPrompt }); | ||
| if (userContent.length > 0) messages.push({ role: 'user', content: userContent }); | ||
|
|
||
| const result = await callApi(messages); | ||
|
|
||
| return { | ||
| response: { | ||
| text: () => result.content | ||
| }, | ||
| raw: result.raw | ||
| }; | ||
| }, | ||
|
|
||
| // For compatibility with chat-style interfaces | ||
| chat: async (messages) => { | ||
| return await callApi(messages); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Creates an OpenRouter streaming LLM instance | ||
| * @param {object} opts - Configuration options | ||
| * @param {string} opts.apiKey - OpenRouter API key | ||
| * @param {string} [opts.model='x-ai/grok-4'] - Model name | ||
| * @param {number} [opts.temperature=0.7] - Temperature | ||
| * @param {number} [opts.maxTokens=2048] - Max tokens | ||
| * @returns {object} Streaming LLM instance | ||
| */ | ||
| function createStreamingLLM({ apiKey, model = 'x-ai/grok-4', temperature = 0.7, maxTokens = 2048, ...config }) { | ||
| return { | ||
| streamChat: async (messages) => { | ||
| console.log("[OpenRouter Provider] Starting Streaming request") | ||
|
|
||
| if (!messages || !Array.isArray(messages) || messages.length === 0) { | ||
| throw new Error('Messages array is required and cannot be empty') | ||
| } | ||
|
|
||
| const fetchUrl = `${OPENROUTER_BASE_URL}/chat/completions`; | ||
| const headers = { | ||
| Authorization: `Bearer ${apiKey}`, | ||
| 'Content-Type': 'application/json', | ||
| }; | ||
|
|
||
| try { | ||
| const response = await fetch(fetchUrl, { | ||
| method: 'POST', | ||
| headers, | ||
| body: JSON.stringify({ | ||
| model, | ||
| messages, | ||
| temperature, | ||
| max_tokens: maxTokens, | ||
| stream: true, | ||
| }), | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| const errorText = await response.text().catch(() => 'Unknown error'); | ||
| throw new Error(`OpenRouter API error: ${response.status} ${response.statusText}. ${errorText}`); | ||
| } | ||
|
|
||
| return response; | ||
| } catch (error) { | ||
| console.error('[OpenRouter] Streaming request failed:', error); | ||
| throw error; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| module.exports = { | ||
| OpenRouterProvider, | ||
| createSTT, | ||
| createLLM, | ||
| createStreamingLLM | ||
| }; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.