-
Notifications
You must be signed in to change notification settings - Fork 55
feat: add Vercel AI Gateway as a provider #745
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
zhaog100
wants to merge
1
commit into
Merit-Systems:master
Choose a base branch
from
zhaog100:feat/vercel-ai-gateway
base: master
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 all commits
Commits
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
117 changes: 117 additions & 0 deletions
117
packages/app/server/src/providers/VercelGatewayProvider.ts
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,117 @@ | ||
| import { LlmTransactionMetadata, Transaction } from '../types'; | ||
| import { getCostPerToken } from '../services/AccountingService'; | ||
| import { BaseProvider } from './BaseProvider'; | ||
| import { ProviderType } from './ProviderType'; | ||
| import logger from '../logger'; | ||
| import { env } from '../env'; | ||
|
|
||
| interface CompletionStateBody { | ||
| id: string; | ||
| usage: { | ||
| prompt_tokens: number; | ||
| completion_tokens: number; | ||
| total_tokens: number; | ||
| }; | ||
| } | ||
|
|
||
| interface StreamingChunkBody { | ||
| id: string; | ||
| choices: { | ||
| index: number; | ||
| delta: { | ||
| content?: string; | ||
| }; | ||
| finish_reason: string | null; | ||
| }[]; | ||
| usage: { | ||
| prompt_tokens: number; | ||
| completion_tokens: number; | ||
| total_tokens: number; | ||
| } | null; | ||
| } | ||
|
|
||
| const parseSSEGPTFormat = (data: string): StreamingChunkBody[] => { | ||
| const events = data.split('\n\n'); | ||
| const chunks: StreamingChunkBody[] = []; | ||
|
|
||
| for (const event of events) { | ||
| if (!event.trim()) continue; | ||
| if (event.startsWith('data: ')) { | ||
| const jsonStr = event.slice(6); | ||
| if (jsonStr.trim() === '[DONE]') continue; | ||
| try { | ||
| const parsed = JSON.parse(jsonStr); | ||
| chunks.push(parsed); | ||
| } catch (error) { | ||
| logger.error(`Error parsing SSE chunk: ${error}`); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return chunks; | ||
| }; | ||
|
|
||
| export class VercelGatewayProvider extends BaseProvider { | ||
| getType(): ProviderType { | ||
| return ProviderType.VERCEL_GATEWAY; | ||
| } | ||
|
|
||
| getBaseUrl(): string { | ||
| return env.VERCEL_GATEWAY_BASE_URL || 'https://ai-gateway.vercel.sh/v1/ai'; | ||
| } | ||
|
|
||
| getApiKey(): string | undefined { | ||
| return env.VERCEL_GATEWAY_API_KEY; | ||
| } | ||
|
|
||
| async handleBody(data: string): Promise<Transaction> { | ||
| try { | ||
| let prompt_tokens = 0; | ||
| let completion_tokens = 0; | ||
| let total_tokens = 0; | ||
| let providerId = 'null'; | ||
|
|
||
| if (this.getIsStream()) { | ||
| const chunks = parseSSEGPTFormat(data); | ||
| for (const chunk of chunks) { | ||
| if (chunk.usage !== null) { | ||
| prompt_tokens += chunk.usage.prompt_tokens; | ||
| completion_tokens += chunk.usage.completion_tokens; | ||
| total_tokens += chunk.usage.total_tokens; | ||
| } | ||
| providerId = chunk.id || 'null'; | ||
| } | ||
| } else { | ||
| const parsed = JSON.parse(data) as CompletionStateBody; | ||
| prompt_tokens += parsed.usage.prompt_tokens; | ||
| completion_tokens += parsed.usage.completion_tokens; | ||
| total_tokens += parsed.usage.total_tokens; | ||
| providerId = parsed.id || 'null'; | ||
| } | ||
|
|
||
| const cost = getCostPerToken( | ||
| this.getModel(), | ||
| prompt_tokens, | ||
| completion_tokens | ||
| ); | ||
|
|
||
| const metadata: LlmTransactionMetadata = { | ||
| providerId: providerId, | ||
| provider: this.getType(), | ||
| model: this.getModel(), | ||
| inputTokens: prompt_tokens, | ||
| outputTokens: completion_tokens, | ||
| totalTokens: total_tokens, | ||
| }; | ||
|
|
||
| return { | ||
| rawTransactionCost: cost, | ||
| metadata: metadata, | ||
| status: 'success', | ||
| }; | ||
| } catch (error) { | ||
| logger.error(`Error processing data: ${error}`); | ||
| throw error; | ||
| } | ||
| } | ||
| } |
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,10 @@ | ||
| import { getEchoToken } from '../auth/token-manager'; | ||
| import { | ||
| createEchoVercelGateway as createEchoVercelGatewayBase, | ||
| EchoConfig, | ||
| GatewayProvider, | ||
| } from '@merit-systems/echo-typescript-sdk'; | ||
|
|
||
| export function createEchoVercelGateway(config: EchoConfig): GatewayProvider { | ||
| return createEchoVercelGatewayBase(config, async () => getEchoToken(config)); | ||
| } |
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
45 changes: 45 additions & 0 deletions
45
packages/sdk/ts/src/__tests__/vercel-gateway-models.test.ts
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,45 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { VercelGatewayModels } from '../src/supported-models/chat/vercel-gateway'; | ||
|
|
||
| describe('VercelGatewayModels', () => { | ||
| it('should export a non-empty array of models', () => { | ||
| expect(VercelGatewayModels.length).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| it('should have all models with VercelGateway provider', () => { | ||
| for (const model of VercelGatewayModels) { | ||
| expect(model.provider).toBe('VercelGateway'); | ||
| } | ||
| }); | ||
|
|
||
| it('should have valid pricing for all models', () => { | ||
| for (const model of VercelGatewayModels) { | ||
| expect(model.input_cost_per_token).toBeGreaterThan(0); | ||
| expect(model.output_cost_per_token).toBeGreaterThan(0); | ||
| } | ||
| }); | ||
|
|
||
| it('should have prefixed model IDs (provider/model-name)', () => { | ||
| for (const model of VercelGatewayModels) { | ||
| expect(model.model_id).toMatch(/^[a-z]+\/[a-z0-9._-]+$/); | ||
| } | ||
| }); | ||
|
|
||
| it('should include key OpenAI models', () => { | ||
| const ids = VercelGatewayModels.map(m => m.model_id); | ||
| expect(ids).toContain('openai/gpt-4o'); | ||
| expect(ids).toContain('openai/gpt-4o-mini'); | ||
| }); | ||
|
|
||
| it('should include key Anthropic models', () => { | ||
| const ids = VercelGatewayModels.map(m => m.model_id); | ||
| expect(ids).toContain('anthropic/claude-sonnet-4'); | ||
| expect(ids).toContain('anthropic/claude-3.5-sonnet'); | ||
| }); | ||
|
|
||
| it('should include key Google models', () => { | ||
| const ids = VercelGatewayModels.map(m => m.model_id); | ||
| expect(ids).toContain('google/gemini-2.5-flash'); | ||
| expect(ids).toContain('google/gemini-2.5-pro'); | ||
| }); | ||
| }); |
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,66 @@ | ||
| import { describe, it, expect, vi } from 'vitest'; | ||
| import { createEchoVercelGateway } from '../src/providers/vercel'; | ||
| import { echoFetch } from '../src/providers/index'; | ||
|
|
||
| // Mock @ai-sdk/gateway | ||
| vi.mock('@ai-sdk/gateway', () => ({ | ||
| createGatewayProvider: vi.fn((options) => ({ | ||
| _type: 'gateway', | ||
| _options: options, | ||
| languageModel: vi.fn(), | ||
| getAvailableModels: vi.fn(), | ||
| getCredits: vi.fn(), | ||
| textEmbeddingModel: vi.fn(), | ||
| })), | ||
| })); | ||
|
|
||
| describe('createEchoVercelGateway', () => { | ||
| const mockGetTokenFn = vi.fn(); | ||
| const mockOnInsufficientFunds = vi.fn(); | ||
|
|
||
| it('should create a gateway provider with echo fetch wrapper', () => { | ||
| const provider = createEchoVercelGateway( | ||
| { appId: '60601628-cdb7-481e-8f7e-921981220348' }, | ||
| mockGetTokenFn, | ||
| mockOnInsufficientFunds | ||
| ); | ||
|
|
||
| expect(provider._type).toBe('gateway'); | ||
| expect(provider._options.apiKey).toBe('placeholder_replaced_by_echoFetch'); | ||
| expect(provider._options.baseURL).toBe('https://echo.router.merit.systems'); | ||
| expect(provider._options.fetch).toBeDefined(); | ||
| }); | ||
|
|
||
| it('should use custom baseRouterUrl when provided', () => { | ||
| const provider = createEchoVercelGateway( | ||
| { | ||
| appId: '60601628-cdb7-481e-8f7e-921981220348', | ||
| baseRouterUrl: 'https://custom-gateway.example.com', | ||
| }, | ||
| mockGetTokenFn, | ||
| mockOnInsufficientFunds | ||
| ); | ||
|
|
||
| expect(provider._options.baseURL).toBe('https://custom-gateway.example.com'); | ||
| }); | ||
|
|
||
| it('should throw on invalid appId', () => { | ||
| expect(() => | ||
| createEchoVercelGateway( | ||
| { appId: 'invalid' }, | ||
| mockGetTokenFn, | ||
| mockOnInsufficientFunds | ||
| ) | ||
| ).toThrow('Invalid Echo App ID'); | ||
| }); | ||
|
|
||
| it('should throw on empty appId', () => { | ||
| expect(() => | ||
| createEchoVercelGateway( | ||
| { appId: '' }, | ||
| mockGetTokenFn, | ||
| mockOnInsufficientFunds | ||
| ) | ||
| ).toThrow('Invalid Echo App ID'); | ||
| }); | ||
| }); | ||
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,26 @@ | ||
| import { | ||
| createGatewayProvider, | ||
| GatewayProvider, | ||
| } from '@ai-sdk/gateway'; | ||
| import { ROUTER_BASE_URL } from 'config'; | ||
| import { EchoConfig } from '../types'; | ||
| import { validateAppId } from '../utils/validation'; | ||
| import { echoFetch } from './index'; | ||
|
|
||
| export function createEchoVercelGateway( | ||
| { appId, baseRouterUrl = ROUTER_BASE_URL }: EchoConfig, | ||
| getTokenFn: (appId: string) => Promise<string | null>, | ||
| onInsufficientFunds?: () => void | ||
| ): GatewayProvider { | ||
| validateAppId(appId, 'createEchoVercelGateway'); | ||
|
|
||
| return createGatewayProvider({ | ||
| baseURL: baseRouterUrl, | ||
| apiKey: 'placeholder_replaced_by_echoFetch', | ||
| fetch: echoFetch( | ||
| fetch, | ||
| async () => await getTokenFn(appId), | ||
| onInsufficientFunds | ||
| ), | ||
| }); | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Test files have incorrect import paths with extra
srcprefix that would cause module resolution failures.