-
Notifications
You must be signed in to change notification settings - Fork 3
Add OpenRouter provider support for unified LLM API access #2
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
Copilot
wants to merge
4
commits into
main
Choose a base branch
from
copilot/fix-1
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.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a2c331e
Initial plan
Copilot 9dad692
Initial commit: Add OpenRouter provider support - planning phase
Copilot d6e1fcc
Implement OpenRouter provider support with complete functionality
Copilot 43a237f
refactor: extract LLM provider list to constant to eliminate duplication
malaksedarous 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
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,62 @@ | ||
/** | ||
* OpenRouter provider implementation | ||
*/ | ||
|
||
import { BaseLLMProvider, LLMResponse } from './base'; | ||
|
||
export class OpenRouterProvider extends BaseLLMProvider { | ||
readonly name = 'OpenRouter'; | ||
readonly defaultModel = 'openai/gpt-4o-mini'; | ||
readonly apiKeyUrl = 'https://openrouter.ai/'; | ||
readonly apiKeyPrefix = undefined; // Not standardized | ||
|
||
async processRequest(prompt: string, model?: string, apiKey?: string): Promise<LLMResponse> { | ||
if (!apiKey) { | ||
return this.createErrorResponse('OpenRouter API key not configured'); | ||
} | ||
|
||
try { | ||
const body = this.createStandardRequest(prompt, model || this.defaultModel); | ||
const headers: Record<string, string> = { | ||
'Authorization': `Bearer ${apiKey}`, | ||
'Content-Type': 'application/json' | ||
}; | ||
|
||
// Add optional branding headers if environment variables are present | ||
if (process.env.CONTEXT_OPT_APP_URL) { | ||
headers['HTTP-Referer'] = process.env.CONTEXT_OPT_APP_URL; | ||
} | ||
if (process.env.CONTEXT_OPT_APP_NAME) { | ||
headers['X-Title'] = process.env.CONTEXT_OPT_APP_NAME; | ||
} | ||
|
||
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { | ||
method: 'POST', | ||
headers, | ||
body: JSON.stringify(body) | ||
}); | ||
|
||
if (!response.ok) { | ||
let errorMsg = `HTTP ${response.status}`; | ||
try { | ||
const errorJson: any = await response.json(); | ||
errorMsg = errorJson?.error?.message || errorMsg; | ||
} catch { | ||
// Ignore JSON parsing errors, use HTTP status | ||
} | ||
return this.createErrorResponse(`OpenRouter request failed: ${errorMsg}`); | ||
} | ||
|
||
const json: any = await response.json(); | ||
const content = json?.choices?.[0]?.message?.content; | ||
if (!content) { | ||
return this.createErrorResponse('No response from OpenRouter'); | ||
} | ||
|
||
return this.createSuccessResponse(content); | ||
} catch (error: unknown) { | ||
const errorMessage = error instanceof Error ? error.message : 'Unknown error'; | ||
return this.createErrorResponse(`OpenRouter processing failed: ${errorMessage}`); | ||
} | ||
} | ||
} |
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,224 @@ | ||
/** | ||
* Tests for OpenRouter provider | ||
*/ | ||
|
||
import { OpenRouterProvider } from '../src/providers/openrouter'; | ||
|
||
// Mock global fetch | ||
const mockFetch = jest.fn(); | ||
(global as any).fetch = mockFetch; | ||
|
||
describe('OpenRouterProvider', () => { | ||
let provider: OpenRouterProvider; | ||
|
||
beforeEach(() => { | ||
provider = new OpenRouterProvider(); | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.restoreAllMocks(); | ||
}); | ||
|
||
describe('Provider properties', () => { | ||
it('should have correct provider properties', () => { | ||
expect(provider.name).toBe('OpenRouter'); | ||
expect(provider.defaultModel).toBe('openai/gpt-4o-mini'); | ||
expect(provider.apiKeyUrl).toBe('https://openrouter.ai/'); | ||
expect(provider.apiKeyPrefix).toBeUndefined(); | ||
}); | ||
}); | ||
|
||
describe('processRequest', () => { | ||
it('should return error when API key is not provided', async () => { | ||
const result = await provider.processRequest('test prompt'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('OpenRouter API key not configured'); | ||
expect(result.content).toBe(''); | ||
}); | ||
|
||
it('should make successful request and return content', async () => { | ||
const mockResponse = { | ||
ok: true, | ||
json: jest.fn().mockResolvedValue({ | ||
choices: [ | ||
{ | ||
message: { | ||
content: 'Test response from OpenRouter' | ||
} | ||
} | ||
] | ||
}) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
const result = await provider.processRequest('test prompt', 'test-model', 'test-api-key'); | ||
|
||
expect(result.success).toBe(true); | ||
expect(result.content).toBe('Test response from OpenRouter'); | ||
expect(result.error).toBeUndefined(); | ||
|
||
expect(mockFetch).toHaveBeenCalledWith( | ||
'https://openrouter.ai/api/v1/chat/completions', | ||
{ | ||
method: 'POST', | ||
headers: { | ||
'Authorization': 'Bearer test-api-key', | ||
'Content-Type': 'application/json' | ||
}, | ||
body: JSON.stringify({ | ||
model: 'test-model', | ||
temperature: 0.1, | ||
max_tokens: 4000, | ||
messages: [{ role: 'user', content: 'test prompt' }] | ||
}) | ||
} | ||
); | ||
}); | ||
|
||
it('should use default model when model is not specified', async () => { | ||
const mockResponse = { | ||
ok: true, | ||
json: jest.fn().mockResolvedValue({ | ||
choices: [ | ||
{ | ||
message: { | ||
content: 'Response with default model' | ||
} | ||
} | ||
] | ||
}) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(true); | ||
expect(mockFetch).toHaveBeenCalledWith( | ||
expect.any(String), | ||
expect.objectContaining({ | ||
body: expect.stringContaining('"model":"openai/gpt-4o-mini"') | ||
}) | ||
); | ||
}); | ||
|
||
it('should include optional branding headers when environment variables are set', async () => { | ||
// Set environment variables | ||
process.env.CONTEXT_OPT_APP_URL = 'https://example.com'; | ||
process.env.CONTEXT_OPT_APP_NAME = 'Test App'; | ||
|
||
const mockResponse = { | ||
ok: true, | ||
json: jest.fn().mockResolvedValue({ | ||
choices: [{ message: { content: 'Test response' } }] | ||
}) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(mockFetch).toHaveBeenCalledWith( | ||
expect.any(String), | ||
expect.objectContaining({ | ||
headers: expect.objectContaining({ | ||
'Authorization': 'Bearer test-api-key', | ||
'Content-Type': 'application/json', | ||
'HTTP-Referer': 'https://example.com', | ||
'X-Title': 'Test App' | ||
}) | ||
}) | ||
); | ||
|
||
// Clean up environment variables | ||
delete process.env.CONTEXT_OPT_APP_URL; | ||
delete process.env.CONTEXT_OPT_APP_NAME; | ||
}); | ||
|
||
it('should handle HTTP error responses', async () => { | ||
const mockResponse = { | ||
ok: false, | ||
status: 400, | ||
json: jest.fn().mockResolvedValue({ | ||
error: { | ||
message: 'Bad Request - Invalid model' | ||
} | ||
}) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('OpenRouter request failed: Bad Request - Invalid model'); | ||
expect(result.content).toBe(''); | ||
}); | ||
|
||
it('should handle HTTP error without error JSON', async () => { | ||
const mockResponse = { | ||
ok: false, | ||
status: 500, | ||
json: jest.fn().mockRejectedValue(new Error('Invalid JSON')) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('OpenRouter request failed: HTTP 500'); | ||
expect(result.content).toBe(''); | ||
}); | ||
|
||
it('should handle malformed response (no choices)', async () => { | ||
const mockResponse = { | ||
ok: true, | ||
json: jest.fn().mockResolvedValue({ | ||
// Missing choices array | ||
}) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('No response from OpenRouter'); | ||
expect(result.content).toBe(''); | ||
}); | ||
|
||
it('should handle malformed response (empty choices)', async () => { | ||
const mockResponse = { | ||
ok: true, | ||
json: jest.fn().mockResolvedValue({ | ||
choices: [] | ||
}) | ||
}; | ||
mockFetch.mockResolvedValue(mockResponse); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('No response from OpenRouter'); | ||
expect(result.content).toBe(''); | ||
}); | ||
|
||
it('should handle fetch network errors', async () => { | ||
mockFetch.mockRejectedValue(new Error('Network error')); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('OpenRouter processing failed: Network error'); | ||
expect(result.content).toBe(''); | ||
}); | ||
|
||
it('should handle unknown errors', async () => { | ||
mockFetch.mockRejectedValue('Unknown error type'); | ||
|
||
const result = await provider.processRequest('test prompt', undefined, 'test-api-key'); | ||
|
||
expect(result.success).toBe(false); | ||
expect(result.error).toBe('OpenRouter processing failed: Unknown error'); | ||
expect(result.content).toBe(''); | ||
}); | ||
}); | ||
}); |
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
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.