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(chat): restore Anthropic and OpenAI providers broken by SSE filter and thinking options

Akarshan Biswas53dc64e05b1c
diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.ts
index f2003945d..75ae27864 100644
--- a/web-app/src/lib/__tests__/model-factory.test.ts
+++ b/web-app/src/lib/__tests__/model-factory.test.ts
@@ -282,6 +282,57 @@ describe('createCustomFetch — transport error wrapping', () => {
})
})
+describe('ModelFactory — missing API key guard', () => {
+ it('throws an actionable error instead of sending an empty credential', async () => {
+ const provider = {
+ provider: 'anthropic',
+ base_url: 'https://api.anthropic.com/v1',
+ api_key: '',
+ models: [],
+ } as unknown as ProviderObject
+ await expect(
+ ModelFactory.createModel('claude-opus-4-8', provider)
+ ).rejects.toThrow(/No API key configured for anthropic/)
+ })
+})
+
+describe('createCustomFetch — named SSE event filtering scope', () => {
+ const NAMED_EVENT_STREAM = [
+ 'event: message_start',
+ 'data: {"type":"message_start"}',
+ '',
+ 'event: content_block_delta',
+ 'data: {"type":"content_block_delta"}',
+ '',
+ ].join('\n')
+
+ function sseFetch(): typeof globalThis.fetch {
+ return (async () =>
+ new Response(NAMED_EVENT_STREAM, {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ })) as typeof globalThis.fetch
+ }
+
+ it('passes named SSE events through untouched by default (native protocols)', async () => {
+ const wrapped = createCustomFetch(sseFetch(), {})
+ const res = await wrapped('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ body: '{}',
+ })
+ expect(await res.text()).toBe(NAMED_EVENT_STREAM)
+ })
+
+ it('strips named SSE events when filterNamedSseEvents is enabled', async () => {
+ const wrapped = createCustomFetch(sseFetch(), {}, false, undefined, true)
+ const res = await wrapped('http://localhost:1337/v1/chat/completions', {
+ method: 'POST',
+ body: '{}',
+ })
+ expect(await res.text()).not.toContain('message_start')
+ })
+})
+
describe('createCustomFetch — max_tokens coercion', () => {
async function captureSentBody(
parameters: Record<string, unknown>,
diff --git a/web-app/src/lib/__tests__/reasoningProviderOptions.test.ts b/web-app/src/lib/__tests__/reasoningProviderOptions.test.ts
index 821ac34b9..41b34412b 100644
--- a/web-app/src/lib/__tests__/reasoningProviderOptions.test.ts
+++ b/web-app/src/lib/__tests__/reasoningProviderOptions.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest'
import { buildReasoningProviderOptions } from '../reasoningProviderOptions'
-const modelWith = (settings: Record<string, unknown>) =>
- ({ settings }) as unknown as Model
+const modelWith = (settings: Record<string, unknown>, id?: string) =>
+ ({ id, settings }) as unknown as Model
const reasoning = (value: string) => ({
reasoning: { controller_props: { value } },
@@ -77,6 +77,45 @@ describe('buildReasoningProviderOptions', () => {
buildReasoningProviderOptions('anthropic', modelWith({}))
).toBeUndefined()
})
+
+ it('sends adaptive thinking with summarized display on 4.7+ models', () => {
+ expect(
+ buildReasoningProviderOptions(
+ 'anthropic',
+ modelWith(reasoning('on'), 'claude-opus-4-8')
+ )
+ ).toEqual({
+ anthropic: { thinking: { type: 'adaptive', display: 'summarized' } },
+ })
+ })
+
+ it('omits display on 4.6 models (display shipped with 4.7)', () => {
+ expect(
+ buildReasoningProviderOptions(
+ 'anthropic',
+ modelWith(reasoning('on'), 'claude-sonnet-4-6')
+ )
+ ).toEqual({ anthropic: { thinking: { type: 'adaptive' } } })
+ })
+
+ it('uses enabled + budget_tokens on pre-4.6 models (adaptive 400s there)', () => {
+ expect(
+ buildReasoningProviderOptions(
+ 'anthropic',
+ modelWith(reasoning('on'), 'claude-sonnet-4-5')
+ )
+ ).toEqual({
+ anthropic: { thinking: { type: 'enabled', budgetTokens: 8192 } },
+ })
+ expect(
+ buildReasoningProviderOptions(
+ 'anthropic',
+ modelWith({ ...budget('high') }, 'claude-haiku-4-5-20251001')
+ )
+ ).toEqual({
+ anthropic: { thinking: { type: 'enabled', budgetTokens: 16384 } },
+ })
+ })
})
describe('openai', () => {
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 4e3732f82..8b6c03bda 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -363,7 +363,8 @@ export function createCustomFetch(
baseFetch: typeof globalThis.fetch,
parameters: Record<string, unknown>,
keepLlamacppOnly = false,
- onLlamacppServerError?: () => void
+ onLlamacppServerError?: () => void,
+ filterNamedSseEvents = false
): typeof globalThis.fetch {
// Params entered via a text input arrive as strings (see InputControl).
// Providers reject a string where a number is required, so coerce back to a
@@ -460,12 +461,17 @@ export function createCustomFetch(
throw new Error(`${friendly} (${requestUrlOf(input)})`)
}
if (res.ok) {
- // Servers may interleave custom named SSE events (e.g. tool-progress)
- // with chat.completion.chunk data. The AI SDK validates every data line
- // against the chunk schema regardless of event type, so strip non-default
- // events before the stream reaches it.
+ // OpenAI-compatible servers may interleave custom named SSE events (e.g.
+ // tool-progress) with chat.completion.chunk data; the AI SDK validates
+ // every data line against the chunk schema, so strip non-default events.
+ // Opt-in only: Anthropic and the OpenAI Responses API use named SSE
+ // events as their protocol, so filtering there blanks the whole stream.
const contentType = res.headers.get('content-type') || ''
- if (res.body && contentType.includes('text/event-stream')) {
+ if (
+ filterNamedSseEvents &&
+ res.body &&
+ contentType.includes('text/event-stream')
+ ) {
return new Response(filterDefaultSseEvents(res.body), {
status: res.status,
statusText: res.statusText,
@@ -709,9 +715,16 @@ function createApiKeyRotatingFetch(
baseFetch: typeof globalThis.fetch,
apiKeys: string[],
parameters: Record<string, unknown>,
- headerMode: ApiKeyHeaderMode
+ headerMode: ApiKeyHeaderMode,
+ filterNamedSseEvents = false
): typeof globalThis.fetch {
- const inner = createCustomFetch(baseFetch, parameters)
+ const inner = createCustomFetch(
+ baseFetch,
+ parameters,
+ false,
+ undefined,
+ filterNamedSseEvents
+ )
if (apiKeys.length <= 1) {
return inner
}
@@ -740,6 +753,22 @@ function createApiKeyRotatingFetch(
}
}
+// An empty apiKey still puts an empty auth header on the wire, which upstreams
+// answer with misleading 401s (e.g. Anthropic's "x-api-key header is
+// required"). Fail here with an actionable message instead.
+function requireRemoteApiKey(
+ provider: ProviderObject,
+ keyChain: string[]
+): string {
+ const key = keyChain[0] ?? provider.api_key?.trim()
+ if (!key) {
+ throw new Error(
+ `No API key configured for ${provider.provider}. Add one in Settings > Model Providers.`
+ )
+ }
+ return key
+}
+
function getRuntimeFetch(): typeof globalThis.fetch {
const maybeWindow = globalThis as typeof globalThis & {
__TAURI__?: unknown
@@ -897,7 +926,8 @@ export class ModelFactory {
httpFetch,
parameters,
true,
- onLlamacppServerError
+ onLlamacppServerError,
+ true
)
if (shouldStripReasoningFromContext(provider)) {
customFetch = withAssistantReasoningStripped(customFetch)
@@ -966,7 +996,13 @@ export class ModelFactory {
// rebuilds upstream errors from buffered text rather than re-decoding the
// raw stream) with every other provider, then layer MLX's /cancel-on-abort
// on top.
- let baseCustomFetch = createCustomFetch(httpFetch, parameters)
+ let baseCustomFetch = createCustomFetch(
+ httpFetch,
+ parameters,
+ false,
+ undefined,
+ true
+ )
if (shouldStripReasoningFromContext(provider)) {
baseCustomFetch = withAssistantReasoningStripped(baseCustomFetch)
}
@@ -1040,7 +1076,7 @@ export class ModelFactory {
: createCustomFetch(getRuntimeFetch(), parameters)
const anthropic = createAnthropic({
- apiKey: keyChain[0] ?? provider.api_key ?? '',
+ apiKey: requireRemoteApiKey(provider, keyChain),
baseURL: provider.base_url,
headers: Object.keys(headers).length > 0 ? headers : undefined,
fetch: fetchImpl,
@@ -1079,7 +1115,7 @@ export class ModelFactory {
: createCustomFetch(getRuntimeFetch(), parameters)
const openai = createOpenAI({
- apiKey: keyChain[0] ?? provider.api_key ?? '',
+ apiKey: requireRemoteApiKey(provider, keyChain),
baseURL: provider.base_url,
headers: Object.keys(headers).length > 0 ? headers : undefined,
fetch: fetchImpl,
@@ -1123,7 +1159,7 @@ export class ModelFactory {
: createCustomFetch(getRuntimeFetch(), parameters)
const mistral = createMistral({
- apiKey: keyChain[0] ?? provider.api_key ?? '',
+ apiKey: requireRemoteApiKey(provider, keyChain),
baseURL: provider.base_url,
headers: Object.keys(headers).length > 0 ? headers : undefined,
fetch: fetchImpl,
@@ -1161,7 +1197,7 @@ export class ModelFactory {
: createCustomFetch(getRuntimeFetch(), parameters)
const xai = createXai({
- apiKey: keyChain[0] ?? provider.api_key ?? '',
+ apiKey: requireRemoteApiKey(provider, keyChain),
baseURL: provider.base_url,
headers: Object.keys(headers).length > 0 ? headers : undefined,
fetch: fetchImpl,
@@ -1207,7 +1243,7 @@ export class ModelFactory {
: 'https://generativelanguage.googleapis.com/v1beta'
const google = createGoogleGenerativeAI({
- apiKey: keyChain[0] ?? provider.api_key ?? '',
+ apiKey: requireRemoteApiKey(provider, keyChain),
baseURL,
headers: Object.keys(headers).length > 0 ? headers : undefined,
fetch: fetchImpl,
@@ -1244,9 +1280,10 @@ export class ModelFactory {
getRuntimeFetch(),
keyChain,
parameters,
- 'authorization-bearer'
+ 'authorization-bearer',
+ true
)
- : createCustomFetch(getRuntimeFetch(), parameters)
+ : createCustomFetch(getRuntimeFetch(), parameters, false, undefined, true)
if (provider.provider === 'groq') {
fetchImpl = withAssistantReasoningStripped(fetchImpl)
diff --git a/web-app/src/lib/reasoningProviderOptions.ts b/web-app/src/lib/reasoningProviderOptions.ts
index 476628586..cd9a3c6ce 100644
--- a/web-app/src/lib/reasoningProviderOptions.ts
+++ b/web-app/src/lib/reasoningProviderOptions.ts
@@ -16,6 +16,19 @@ const LEVEL_TO_OPENAI_EFFORT: Partial<Record<ThinkingBudgetLevelKey, string>> =
xhigh: 'xhigh',
}
+// The AI SDK adds budget_tokens on top of max_tokens, so these are safe caps
+// regardless of the request's output limit (Anthropic minimum is 1024).
+const ANTHROPIC_LEVEL_BUDGET_TOKENS: Record<
+ Exclude<ThinkingBudgetLevelKey, 'unlimited'>,
+ number
+> = {
+ low: 4096,
+ medium: 8192,
+ high: 16384,
+ xhigh: 32768,
+}
+const DEFAULT_ANTHROPIC_BUDGET_TOKENS = 8192
+
function readReasoning(model: Model | null | undefined): ReasoningChoice {
const v = model?.settings?.reasoning?.controller_props?.value
return v === 'on' || v === 'off' || v === 'auto' ? v : undefined
@@ -66,10 +79,26 @@ export function buildReasoningProviderOptions(
return { anthropic: { thinking: { type: 'disabled' } } }
}
if (reasoning === 'on' || level) {
- // Adaptive lets Claude size its own thinking budget; 'summarized' streams
- // the thought summary we render in the reasoning trace.
+ const id = (model?.id ?? '').toLowerCase()
+ // Adaptive thinking exists on Claude 4.6+ only; pre-4.6 models reject it
+ // with a 400 and require enabled + budget_tokens. `display` shipped with
+ // 4.7, so it is omitted on the 4.6 family. Unknown ids get the
+ // current-generation default (adaptive + summarized).
+ const isPre46 = /(opus|sonnet|haiku)-([0-3]|4-[0-5])\b/.test(id)
+ if (isPre46) {
+ const budgetTokens =
+ level && level !== 'unlimited'
+ ? ANTHROPIC_LEVEL_BUDGET_TOKENS[level]
+ : DEFAULT_ANTHROPIC_BUDGET_TOKENS
+ return { anthropic: { thinking: { type: 'enabled', budgetTokens } } }
+ }
+ const supportsDisplay = !/(opus|sonnet)-4-6\b/.test(id)
return {
- anthropic: { thinking: { type: 'adaptive', display: 'summarized' } },
+ anthropic: {
+ thinking: supportsDisplay
+ ? { type: 'adaptive', display: 'summarized' }
+ : { type: 'adaptive' },
+ },
}
}
return undefined