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.

fix(providers): send anthropic-version on model-list fetch (#8433)

Akarshan Biswasab1ac765f593
diff --git a/web-app/src/lib/__tests__/remoteModelCatalog.test.ts b/web-app/src/lib/__tests__/remoteModelCatalog.test.ts
index 43f3f32e0..07ae3b970 100644
--- a/web-app/src/lib/__tests__/remoteModelCatalog.test.ts
+++ b/web-app/src/lib/__tests__/remoteModelCatalog.test.ts
@@ -46,6 +46,13 @@ describe('supportsRemoteCatalog', () => {
expect(supportsRemoteCatalog('groq')).toBe(false)
expect(supportsRemoteCatalog('mistral')).toBe(false)
})
+
+ it('supports custom-named providers with api_type anthropic', () => {
+ expect(
+ supportsRemoteCatalog({ provider: 'my-gateway', api_type: 'anthropic' })
+ ).toBe(true)
+ expect(supportsRemoteCatalog({ provider: 'my-gateway' })).toBe(false)
+ })
})
describe('fetchTopRemoteModels gemini', () => {
@@ -194,4 +201,44 @@ describe('fetchTopRemoteModels anthropic', () => {
const c2 = result.find((m) => m.id === 'claude-2.1')!
expect(c2.capabilities).toEqual(['completion', 'tools'])
})
+
+ it('infers claude capabilities for custom-named anthropic providers', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(
+ mkResponse({
+ data: [{ id: 'claude-3-5-sonnet-20240620', created_at: '2024-06-20T00:00:00Z' }],
+ })
+ )
+ const provider = mkAnthropicProvider({
+ provider: 'my-gateway',
+ base_url: 'https://gateway.corp.com/v1',
+ api_type: 'anthropic',
+ })
+ const result = await fetchTopRemoteModels(provider, fetchImpl)
+ expect(result[0].id).toBe('claude-3-5-sonnet-20240620')
+ expect(result[0].capabilities).toEqual(['completion', 'tools', 'vision'])
+ })
+
+ it('sends default anthropic-version and browser-access headers', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(mkResponse({ data: [] }))
+ await fetchTopRemoteModels(mkAnthropicProvider(), fetchImpl)
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://api.anthropic.com/v1/models',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ 'anthropic-version': '2023-06-01',
+ 'anthropic-dangerous-direct-browser-access': 'true',
+ }),
+ })
+ )
+ })
+
+ it('does not send anthropic headers for openai', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(mkResponse({ data: [] }))
+ await fetchTopRemoteModels(mkOpenAIProvider(), fetchImpl)
+ const headers = fetchImpl.mock.calls[0][1].headers as Record<string, string>
+ expect(headers).not.toHaveProperty('anthropic-version')
+ expect(headers).not.toHaveProperty(
+ 'anthropic-dangerous-direct-browser-access'
+ )
+ })
})
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 8b6c03bda..0d6219e84 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -75,6 +75,7 @@ import {
getProviderApiType,
} from '@/lib/providerCaps'
import { useAppState } from '@/hooks/useAppState'
+import { ensureAnthropicHeaders } from '@/lib/remoteModelCatalog'
/**
* Llama.cpp timings structure from the response
@@ -1057,12 +1058,14 @@ export class ModelFactory {
): LanguageModel {
const headers: Record<string, string> = {}
- // Add custom headers if specified (e.g., anthropic-version)
if (provider.custom_header) {
provider.custom_header.forEach((customHeader) => {
headers[customHeader.header] = customHeader.value
})
}
+ // Custom Anthropic providers may ship no custom_header; Anthropic rejects
+ // browser-context requests (webview Origin) without the opt-in header.
+ ensureAnthropicHeaders(provider, headers)
const keyChain = providerRemoteApiKeyChain(provider)
const fetchImpl =
diff --git a/web-app/src/lib/remoteModelCatalog.ts b/web-app/src/lib/remoteModelCatalog.ts
index d6ceda4f2..632d64e60 100644
--- a/web-app/src/lib/remoteModelCatalog.ts
+++ b/web-app/src/lib/remoteModelCatalog.ts
@@ -11,6 +11,7 @@ type ProviderLike = {
base_url?: string
api_key?: string
api_key_fallbacks?: string[]
+ api_type?: string
custom_header?: { header: string; value: string }[] | null
}
@@ -18,12 +19,72 @@ type FetchImpl = typeof fetch
const TOP_N = 10
-export function supportsRemoteCatalog(providerName: string): boolean {
+const ANTHROPIC_VERSION_HEADER = 'anthropic-version'
+const ANTHROPIC_VERSION = '2023-06-01'
+const ANTHROPIC_BROWSER_ACCESS_HEADER =
+ 'anthropic-dangerous-direct-browser-access'
+
+/// Whether a provider fronts Anthropic's API. The `api_type` discriminant is
+/// authoritative (matches the inference dispatch in model-factory); provider
+/// name and host are fallbacks for configs predating that field.
+function isAnthropicProvider(provider: {
+ provider?: string
+ base_url?: string
+ api_type?: string
+}): boolean {
return (
- providerName === 'openai' ||
- providerName === 'anthropic' ||
- providerName === 'gemini'
+ provider.api_type === 'anthropic' ||
+ (provider.provider ?? '').toLowerCase().includes('anthropic') ||
+ (provider.base_url ?? '').toLowerCase().includes('anthropic')
+ )
+}
+
+function setDefaultHeader(
+ headers: Record<string, string>,
+ name: string,
+ value: string
+): void {
+ const present = Object.keys(headers).some(
+ (h) => h.toLowerCase() === name.toLowerCase()
)
+ if (!present) headers[name] = value
+}
+
+/// Anthropic rejects `/v1/models` (and any Anthropic-shaped proxy) without
+/// `anthropic-version`, and rejects requests carrying an `Origin` (Jan's
+/// webview is a browser context) without the browser-access opt-in header.
+/// Add both defaults for Anthropic providers when the caller hasn't set them;
+/// other providers are left untouched.
+export function ensureAnthropicHeaders(
+ provider: { provider?: string; base_url?: string; api_type?: string },
+ headers: Record<string, string>
+): void {
+ if (!isAnthropicProvider(provider)) return
+ setDefaultHeader(headers, ANTHROPIC_VERSION_HEADER, ANTHROPIC_VERSION)
+ setDefaultHeader(headers, ANTHROPIC_BROWSER_ACCESS_HEADER, 'true')
+}
+
+type CatalogKind = 'openai' | 'anthropic' | 'gemini'
+
+/// Resolve which catalog shape a provider speaks. `api_type` is authoritative
+/// (a custom-named Anthropic gateway still lists Claude models), falling back
+/// to the built-in provider name.
+function resolveCatalogKind(
+ provider: string | { provider: string; api_type?: string }
+): CatalogKind | null {
+ const name = typeof provider === 'string' ? provider : provider.provider
+ const apiType = typeof provider === 'string' ? undefined : provider.api_type
+ if (apiType === 'anthropic') return 'anthropic'
+ if (name === 'openai' || name === 'anthropic' || name === 'gemini') {
+ return name
+ }
+ return null
+}
+
+export function supportsRemoteCatalog(
+ provider: string | { provider: string; api_type?: string }
+): boolean {
+ return resolveCatalogKind(provider) !== null
}
function inferOpenAICapabilities(id: string): string[] | null {
@@ -108,6 +169,7 @@ function buildHeaders(p: ProviderLike, key: string | undefined): Record<string,
if (p.custom_header) {
for (const h of p.custom_header) headers[h.header] = h.value
}
+ ensureAnthropicHeaders(p, headers)
return headers
}
@@ -135,7 +197,8 @@ export async function fetchTopRemoteModels(
provider: ProviderLike,
fetchImpl: FetchImpl
): Promise<RemoteCatalogModel[]> {
- if (!supportsRemoteCatalog(provider.provider)) {
+ const kind = resolveCatalogKind(provider)
+ if (!kind) {
throw new Error(`Catalog not supported for ${provider.provider}`)
}
if (!provider.base_url) {
@@ -162,17 +225,17 @@ export async function fetchTopRemoteModels(
const body = result.body as { data?: unknown }
const rows = Array.isArray(body?.data) ? (body.data as unknown[]) : []
- return normalizeCatalog(provider.provider, rows)
+ return normalizeCatalog(kind, rows)
}
throw new Error(`Failed to fetch models from ${provider.provider}: ${lastStatus} ${lastStatusText}`)
}
-function normalizeCatalog(providerName: string, rows: unknown[]): RemoteCatalogModel[] {
+function normalizeCatalog(kind: CatalogKind, rows: unknown[]): RemoteCatalogModel[] {
const inferCaps =
- providerName === 'openai'
+ kind === 'openai'
? inferOpenAICapabilities
- : providerName === 'gemini'
+ : kind === 'gemini'
? inferGeminiCapabilities
: inferAnthropicCapabilities
@@ -188,7 +251,7 @@ function normalizeCatalog(providerName: string, rows: unknown[]): RemoteCatalogM
parsed.push({ id, capabilities: caps, createdMs })
}
- if (providerName === 'gemini') {
+ if (kind === 'gemini') {
parsed.sort((a, b) => {
const va = geminiVersionScore(a.id)
const vb = geminiVersionScore(b.id)
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index 73288f982..25668e44d 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -280,7 +280,7 @@ function ProviderDetail() {
const autoCatalogAttempted = useRef<Set<string>>(new Set())
useEffect(() => {
if (!provider) return
- if (!supportsRemoteCatalog(provider.provider)) return
+ if (!supportsRemoteCatalog(provider)) return
if (provider.models.length > 0) return
if (!providerHasRemoteApiKeys(provider)) return
if (autoCatalogAttempted.current.has(provider.provider)) return
@@ -530,7 +530,7 @@ function ProviderDetail() {
setRefreshingModels(true)
try {
let newModels: Model[]
- if (supportsRemoteCatalog(provider.provider)) {
+ if (supportsRemoteCatalog(provider)) {
const catalog = await fetchTopRemoteModels(provider, serviceHub.providers().fetch())
newModels = catalog.map((m) => ({
id: m.id,
@@ -552,7 +552,7 @@ function ProviderDetail() {
}))
}
- if (supportsRemoteCatalog(provider.provider)) {
+ if (supportsRemoteCatalog(provider)) {
const importedModels = provider.models.filter((m) => m.imported)
const importedIds = new Set(importedModels.map((m) => m.id))
const fresh = newModels.filter((m) => !importedIds.has(m.id))
@@ -789,7 +789,7 @@ function ProviderDetail() {
{provider &&
!isLocalProvider(provider.provider) &&
- !supportsRemoteCatalog(provider.provider) && (
+ !supportsRemoteCatalog(provider) && (
<div className="flex items-start gap-2 rounded-md border border-main-view-fg/10 bg-main-view-fg/5 px-3 py-2 text-xs text-muted-foreground">
<IconInfoCircle size={16} className="mt-0.5 shrink-0" />
<span>
diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.ts
index 93482b72b..e9496bbb2 100644
--- a/web-app/src/services/providers/__tests__/tauri.test.ts
+++ b/web-app/src/services/providers/__tests__/tauri.test.ts
@@ -358,6 +358,91 @@ describe('TauriProvidersService', () => {
)
})
+ it('adds default anthropic-version header for anthropic-shaped custom providers', async () => {
+ const provider = {
+ ...baseProvider,
+ provider: 'anthropic_proxy',
+ base_url: 'https://anthropic.example.com/v1',
+ }
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(provider)
+ expect(fetchTauri).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ 'anthropic-version': '2023-06-01' }),
+ })
+ )
+ })
+
+ it('adds default anthropic-version header when api_type is anthropic despite non-anthropic name/host', async () => {
+ const provider = {
+ ...baseProvider,
+ provider: 'my-gateway',
+ base_url: 'https://gateway.corp.com/v1',
+ api_type: 'anthropic',
+ }
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(provider)
+ expect(fetchTauri).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ 'anthropic-version': '2023-06-01',
+ 'anthropic-dangerous-direct-browser-access': 'true',
+ }),
+ })
+ )
+ })
+
+ it('does not add anthropic-version for non-anthropic providers', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(baseProvider)
+ const headers = vi.mocked(fetchTauri).mock.calls[0][1]?.headers as Record<
+ string,
+ string
+ >
+ expect(headers).not.toHaveProperty('anthropic-version')
+ expect(headers).not.toHaveProperty(
+ 'anthropic-dangerous-direct-browser-access'
+ )
+ })
+
+ it('does not override a caller-supplied anthropic-version', async () => {
+ const provider = {
+ ...baseProvider,
+ provider: 'anthropic_proxy',
+ custom_header: [{ header: 'anthropic-version', value: '2099-01-01' }],
+ }
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(provider)
+ expect(fetchTauri).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ 'anthropic-version': '2099-01-01' }),
+ })
+ )
+ })
+
it('retries with next key on 401 and succeeds', async () => {
vi.mocked(providerRemoteApiKeyChain).mockReturnValue(['bad-key', 'good-key'])
vi.mocked(fetchTauri)
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index 15f315858..f449d6d86 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -16,6 +16,7 @@ import {
API_KEY_FALLBACKS_SETTING_KEY,
providerRemoteApiKeyChain,
} from '@/lib/provider-api-keys'
+import { ensureAnthropicHeaders } from '@/lib/remoteModelCatalog'
export class TauriProvidersService extends DefaultProvidersService {
fetch(): typeof fetch {
@@ -178,6 +179,8 @@ export class TauriProvidersService extends DefaultProvidersService {
})
}
+ ensureAnthropicHeaders(provider, headers)
+
const response = await fetchTauri(`${provider.base_url}/models`, {
method: 'GET',
headers,