Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

google-apikey-rotation

jjchen013c23ea396fee
diff --git a/web-app/src/lib/__tests__/model-factory.deep.test.ts b/web-app/src/lib/__tests__/model-factory.deep.test.ts
index 718f6a168..478d8d27f 100644
--- a/web-app/src/lib/__tests__/model-factory.deep.test.ts
+++ b/web-app/src/lib/__tests__/model-factory.deep.test.ts
@@ -257,6 +257,53 @@ describe('model-factory deep coverage', () => {
})
})
+ /* google api-key rotation */
+ describe('google api-key rotation', () => {
+ it('rotates to the next key via x-goog-api-key on 429', async () => {
+ const realFetch = globalThis.fetch
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(new Response('{}', { status: 429 }))
+ .mockResolvedValueOnce(new Response('{}', { status: 200 }))
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
+ try {
+ await ModelFactory.createModel(
+ 'gemini-pro',
+ mkProvider('google', { api_key: 'key1', api_key_fallbacks: ['key2'] }),
+ {}
+ )
+ // The native @ai-sdk/google client always sends the primary key in
+ // this header; the rotating fetch must OVERRIDE it, not append.
+ const { fetch: rotatingFetch } = (globalThis as any).__capturedGoogleCfg
+ await rotatingFetch('https://g/v1beta/models', {
+ method: 'POST',
+ headers: { 'x-goog-api-key': 'key1' },
+ body: JSON.stringify({ messages: [] }),
+ })
+
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ const firstHeaders = new Headers(fetchMock.mock.calls[0][1].headers)
+ const secondHeaders = new Headers(fetchMock.mock.calls[1][1].headers)
+ expect(firstHeaders.get('x-goog-api-key')).toBe('key1')
+ expect(secondHeaders.get('x-goog-api-key')).toBe('key2')
+ // single header, not a duplicated/appended value
+ expect(secondHeaders.get('x-goog-api-key')).not.toContain('key1')
+ } finally {
+ globalThis.fetch = realFetch
+ }
+ })
+
+ it('uses a plain custom fetch (no rotation) with a single key', async () => {
+ await ModelFactory.createModel(
+ 'gemini-pro',
+ mkProvider('google', { api_key: 'only', api_key_fallbacks: [] }),
+ {}
+ )
+ const { apiKey } = (globalThis as any).__capturedGoogleCfg
+ expect(apiKey).toBe('only')
+ })
+ })
+
/* openai-compatible empty base_url */
describe('openai-compatible', () => {
it('uses default base_url when none provided', async () => {
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 4368606e0..c9e49677e 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -628,7 +628,10 @@ export function decodeVideoSentinelsInBody(body: Record<string, unknown>): void
}
}
-type ApiKeyHeaderMode = 'authorization-bearer' | 'x-api-key'
+type ApiKeyHeaderMode =
+ | 'authorization-bearer'
+ | 'x-api-key'
+ | 'x-goog-api-key'
/** Retries with the next key when the upstream returns 401, 403, or 429. */
function createApiKeyRotatingFetch(
@@ -650,6 +653,8 @@ function createApiKeyRotatingFetch(
const nextHeaders = new Headers(init?.headers as HeadersInit | undefined)
if (headerMode === 'authorization-bearer') {
nextHeaders.set('Authorization', `Bearer ${key}`)
+ } else if (headerMode === 'x-goog-api-key') {
+ nextHeaders.set('x-goog-api-key', key)
} else {
nextHeaders.set('x-api-key', key)
}
@@ -1097,7 +1102,18 @@ export class ModelFactory {
}
const keyChain = providerRemoteApiKeyChain(provider)
- const fetchImpl = createCustomFetch(getRuntimeFetch(), parameters)
+ // Rotate over configured keys on 401/403/429 (e.g. exhausted free-tier
+ // quota). The native Google client authenticates via `x-goog-api-key`, so
+ // the rotating fetch must override that header — not Authorization.
+ const fetchImpl =
+ keyChain.length > 1
+ ? createApiKeyRotatingFetch(
+ getRuntimeFetch(),
+ keyChain,
+ parameters,
+ 'x-goog-api-key'
+ )
+ : createCustomFetch(getRuntimeFetch(), parameters)
const rawBase = provider.base_url?.trim()
const baseURL = rawBase