Repository navigation
Use the standalone AI gateway in production, staging, and development #7173
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
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bfb0c40
feat(ai-gateway): rewrite web routes to the standalone gateway
chrarnoldus 4900696
fix(ai-gateway): route staging traffic to the staging gateway
chrarnoldus c8487c2
fix(ai-gateway): start the gateway for Playwright E2E tests
chrarnoldus 69c9061
fix(ai-gateway): start the gateway with standalone web dev
chrarnoldus 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,45 @@ | ||
| export function getAiGatewayRewrites(env = process.env) { | ||
| const origin = | ||
| env.NODE_ENV === 'development' | ||
| ? `http://localhost:${env.AI_GATEWAY_PORT || 3010 + Number(env.KILO_PORT_OFFSET || 0)}` | ||
| : env.VERCEL_TARGET_ENV === 'staging' | ||
| ? 'https://staging-ai-gateway.kilo.ai' | ||
| : env.VERCEL_ENV === 'production' | ||
| ? 'https://ai-gateway.kilo.ai' | ||
| : undefined; | ||
|
|
||
| if (!origin) return []; | ||
|
|
||
| return [ | ||
| { | ||
| source: '/api/gateway/typesafe/v1/systemone', | ||
| destination: `${origin}/api/v1/systemone`, | ||
| }, | ||
| ...['gateway', 'openrouter'].flatMap(prefix => [ | ||
| { | ||
| source: `/api/${prefix}/v1/:path*`, | ||
| destination: `${origin}/api/v1/:path*`, | ||
| }, | ||
| { | ||
| source: `/api/${prefix}/:path*`, | ||
| destination: `${origin}/api/v1/:path*`, | ||
| }, | ||
| ]), | ||
| { | ||
| source: '/api/fim/completions', | ||
| destination: `${origin}/api/v1/fim/completions`, | ||
| }, | ||
| { | ||
| source: '/api/edit/completions', | ||
| destination: `${origin}/api/v1/edit/completions`, | ||
| }, | ||
| { | ||
| source: '/api/organizations/:id/models', | ||
| destination: `${origin}/api/v1/organizations/:id/models`, | ||
| }, | ||
| { | ||
| source: '/api/organizations/:id/models/validate', | ||
| destination: `${origin}/api/v1/organizations/:id/models/validate`, | ||
| }, | ||
| ]; | ||
| } | ||
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,44 @@ | ||
| import { expect, test } from '@playwright/test'; | ||
|
|
||
| test.use({ storageState: { cookies: [], origins: [] } }); | ||
|
|
||
| test('starts the standalone gateway with the Playwright servers', async ({ request, baseURL }) => { | ||
| if (!baseURL) throw new Error('Playwright baseURL is required'); | ||
| const gatewayPort = process.env.AI_GATEWAY_PORT || Number(new URL(baseURL).port) + 10; | ||
| const response = await request.post(`http://localhost:${gatewayPort}/api/v1/fim/completions`, { | ||
| data: {}, | ||
| }); | ||
|
|
||
| expect(response.status()).toBe(401); | ||
| expect(response.headers()['content-type']).toContain('application/json'); | ||
| }); | ||
|
|
||
| for (const path of ['/api/fim/completions', '/api/edit/completions']) { | ||
| test(`proxies ${path} to the gateway`, async ({ request }) => { | ||
| const response = await request.post(path, { data: {} }); | ||
|
|
||
| expect(response.status()).toBe(401); | ||
| expect(response.headers()['content-type']).toContain('application/json'); | ||
| }); | ||
| } | ||
|
|
||
| test('proxies organization model requests without changing authentication', async ({ request }) => { | ||
| const response = await request.get('/api/organizations/playwright/models'); | ||
|
|
||
| expect(response.status()).toBe(401); | ||
| expect(response.headers()['content-type']).toContain('application/json'); | ||
| }); | ||
|
|
||
| test('serves a gateway response to browser requests through the web app', async ({ page }) => { | ||
| await page.goto('/users/sign_in'); | ||
| const status = await page.evaluate(async () => { | ||
| const response = await fetch('/api/fim/completions', { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: '{}', | ||
| }); | ||
| return response.status; | ||
| }); | ||
|
|
||
| expect(status).toBe(401); | ||
| }); |
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,144 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { createRequire } from 'node:module'; | ||
| import test from 'node:test'; | ||
|
|
||
| import { getAiGatewayRewrites } from '../../apps/web/ai-gateway-rewrites.mjs'; | ||
|
|
||
| const require = createRequire(new URL('../../apps/web/next.config.mjs', import.meta.url)); | ||
| const { getPathMatch } = require('next/dist/shared/lib/router/utils/path-match'); | ||
| const { prepareDestination } = require('next/dist/shared/lib/router/utils/prepare-destination'); | ||
|
|
||
| function rewrite(url: string, env: NodeJS.ProcessEnv) { | ||
| const request = new URL(url, 'http://localhost'); | ||
| for (const rule of getAiGatewayRewrites(env)) { | ||
| const params = getPathMatch(rule.source)(request.pathname); | ||
| if (params) { | ||
| return prepareDestination({ | ||
| destination: rule.destination, | ||
| params, | ||
| query: Object.fromEntries(request.searchParams), | ||
| appendParamsToQuery: true, | ||
| }).parsedDestination; | ||
| } | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| const routes = [ | ||
| ...['gateway', 'openrouter'].flatMap(prefix => [ | ||
| ...['chat/completions', 'responses', 'messages', 'audio/transcriptions', 'transcription-models'] | ||
| .flatMap(endpoint => [endpoint, `v1/${endpoint}`]) | ||
| .map(endpoint => [`/api/${prefix}/${endpoint}`, `/api/v1/${endpoint.replace(/^v1\//, '')}`]), | ||
| ...['models-by-provider', 'providers', 'embeddings'].map(endpoint => [ | ||
| `/api/${prefix}/${endpoint}`, | ||
| `/api/v1/${endpoint}`, | ||
| ]), | ||
| ...['models', 'v1/models'].map(endpoint => [ | ||
| `/api/${prefix}/${endpoint}/anthropic/claude-sonnet-4/endpoints`, | ||
| '/api/v1/models/anthropic/claude-sonnet-4/endpoints', | ||
| ]), | ||
| [`/api/${prefix}/models`, '/api/v1/models'], | ||
| ]), | ||
| ['/api/gateway/v1/models', '/api/v1/models'], | ||
| ['/api/gateway/embedding-models', '/api/v1/embedding-models'], | ||
| ['/api/openrouter/models/validate', '/api/v1/models/validate'], | ||
| ['/api/gateway/typesafe/v1/systemone', '/api/v1/systemone'], | ||
| ['/api/fim/completions', '/api/v1/fim/completions'], | ||
| ['/api/edit/completions', '/api/v1/edit/completions'], | ||
| ['/api/organizations/org-123/models', '/api/v1/organizations/org-123/models'], | ||
| ['/api/organizations/org-123/models/validate', '/api/v1/organizations/org-123/models/validate'], | ||
| ]; | ||
|
|
||
| for (const globalBackend of ['true', 'false']) { | ||
| void test(`rewrites every legacy gateway route in production with GLOBAL_KILO_BACKEND=${globalBackend}`, () => { | ||
| const env = { | ||
| NODE_ENV: 'production', | ||
| VERCEL_ENV: 'production', | ||
| VERCEL_TARGET_ENV: 'production', | ||
| GLOBAL_KILO_BACKEND: globalBackend, | ||
| AI_GATEWAY_PORT: '9999', | ||
| KILO_PORT_OFFSET: '2500', | ||
| }; | ||
| for (const [source, destination] of routes) { | ||
| const result = rewrite(`${source}?source=extension&stream=true`, env); | ||
| assert.equal(result?.protocol, 'https:', source); | ||
| assert.equal(result?.hostname, 'ai-gateway.kilo.ai', source); | ||
| assert.equal(result?.pathname, destination, source); | ||
| assert.deepEqual(result?.query, { source: 'extension', stream: 'true' }, source); | ||
| } | ||
| }); | ||
|
|
||
| void test(`rewrites every legacy gateway route in staging with GLOBAL_KILO_BACKEND=${globalBackend}`, () => { | ||
| for (const vercelEnv of ['preview', 'production']) { | ||
| const env = { | ||
| NODE_ENV: 'production', | ||
| VERCEL_ENV: vercelEnv, | ||
| VERCEL_TARGET_ENV: 'staging', | ||
| GLOBAL_KILO_BACKEND: globalBackend, | ||
| }; | ||
| for (const [source, destination] of routes) { | ||
| const result = rewrite(`${source}?source=extension&stream=true`, env); | ||
| assert.equal(result?.protocol, 'https:', source); | ||
| assert.equal(result?.hostname, 'staging-ai-gateway.kilo.ai', source); | ||
| assert.equal(result?.pathname, destination, source); | ||
| assert.deepEqual(result?.query, { source: 'extension', stream: 'true' }, source); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| void test('rewrites to the local gateway with default, offset, and explicit ports', () => { | ||
| for (const [env, port] of [ | ||
| [{}, '3010'], | ||
| [{ KILO_PORT_OFFSET: '2500' }, '5510'], | ||
| [{ KILO_PORT_OFFSET: '2500', AI_GATEWAY_PORT: '6000' }, '6000'], | ||
| ] as const) { | ||
| for (const [source, destination] of routes) { | ||
| const result = rewrite(source, { | ||
| ...env, | ||
| NODE_ENV: 'development', | ||
| VERCEL_ENV: 'production', | ||
| VERCEL_TARGET_ENV: 'staging', | ||
| }); | ||
| assert.equal(result?.protocol, 'http:', source); | ||
| assert.equal(result?.hostname, 'localhost', source); | ||
| assert.equal(result?.port, port, source); | ||
| assert.equal(result?.pathname, destination, source); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| void test('leaves preview, test, and non-Vercel production handlers on the web app', () => { | ||
| for (const env of [ | ||
| { NODE_ENV: 'production', VERCEL_ENV: 'preview' }, | ||
| { NODE_ENV: 'production', VERCEL_ENV: 'preview', VERCEL_TARGET_ENV: 'preview' }, | ||
| { NODE_ENV: 'production', VERCEL_ENV: 'development' }, | ||
| { NODE_ENV: 'production' }, | ||
| { NODE_ENV: 'test' }, | ||
| ]) { | ||
| assert.deepEqual(getAiGatewayRewrites(env), []); | ||
| } | ||
| }); | ||
|
|
||
| void test('does not move unrelated organization, Exa, marketplace, or cron routes to the gateway', () => { | ||
| for (const source of [ | ||
| '/api/organizations', | ||
| '/api/organizations/org-123', | ||
| '/api/organizations/org-123/defaults', | ||
| '/api/organizations/org-123/modes', | ||
| '/api/organizations/org-123/tokens', | ||
| '/api/exa/search', | ||
| '/api/marketplace/mcps', | ||
| '/api/cron/sync-model-stats', | ||
| ]) { | ||
| assert.equal(rewrite(source, { NODE_ENV: 'production', VERCEL_ENV: 'production' }), undefined); | ||
| } | ||
| }); | ||
|
|
||
| void test('preserves encoded model paths and trailing slashes', () => { | ||
| const result = rewrite('/api/gateway/v1/models/provider/model%2Fvariant/endpoints/', { | ||
| NODE_ENV: 'production', | ||
| VERCEL_ENV: 'production', | ||
| }); | ||
| assert.equal(result?.pathname, '/api/v1/models/provider/model%2Fvariant/endpoints'); | ||
| }); |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.