diff --git a/server/src/nest/ai-connections/ai-chat-client.service.ts b/server/src/nest/ai-connections/ai-chat-client.service.ts index 8c3d7a1a0..73f0011f9 100644 --- a/server/src/nest/ai-connections/ai-chat-client.service.ts +++ b/server/src/nest/ai-connections/ai-chat-client.service.ts @@ -23,10 +23,21 @@ const cloudFetch: AiFetch = (url, init) => safeFetch(url, { ...init, signal: ini */ const adminServerFetch: AiFetch = (url, init) => safeFetchLlm(url, { ...init, signal: init.signal }, 5, null); +/** + * Whether an OpenAI model behind an API key goes through the Responses API: + * the reasoning models (the o-series, GPT-5 and later) refuse function tools + * on Chat Completions with a 400 (#2792). Their `-chat` variants do not reason + * and stay on Chat Completions, like the older GPT-4 line. + */ +export function openAiWantsResponses(model: string): boolean { + return /^(o\d|gpt-([5-9]|\d{2,}))/.test(model) && !/-chat/.test(model); +} + /** * The chat client for a resolved connection: Anthropic's Messages API, the - * Responses API for a ChatGPT plan, and Chat Completions for everything - * OpenAI-compatible (OpenAI, Gemini, OpenRouter, an admin's own server). + * Responses API for a ChatGPT plan and OpenAI's reasoning models, and Chat + * Completions for everything else OpenAI-compatible (older OpenAI models, + * Gemini, OpenRouter, an admin's own server). */ @Injectable() export class AiChatClientService { @@ -45,6 +56,10 @@ export class AiChatClientService { cloudFetch, ); } + if (kind === 'openai' && openAiWantsResponses(model)) { + const apiKey = credential.apiKey ?? ''; + return new OpenAiResponsesClient(model, () => Promise.resolve(apiKey), cloudFetch, 'openai'); + } switch (kind) { case 'anthropic': return new AnthropicMessagesClient(model, credential.apiKey ?? '', cloudFetch); diff --git a/server/src/nest/ai-connections/providers/openai-responses.client.ts b/server/src/nest/ai-connections/providers/openai-responses.client.ts index eef85e312..b0652f200 100644 --- a/server/src/nest/ai-connections/providers/openai-responses.client.ts +++ b/server/src/nest/ai-connections/providers/openai-responses.client.ts @@ -130,20 +130,22 @@ function citedSources(item: Record): AiSource[] { } /** - * OpenAI's Responses API on a ChatGPT plan (Sign in with ChatGPT). Within the - * preview's limits: nothing stored, streamed, no output cap or temperature, - * the instructions as `instructions`, the tools in one namespace that carries - * a description. A 401 before the stream starts is answered once with a - * refreshed token; a second one means the sign-in has to be renewed. + * OpenAI's Responses API, on a ChatGPT plan (Sign in with ChatGPT) or, for the + * reasoning models, on an OpenAI API key, which take their function tools only + * here (#2792). Within the preview's limits: nothing stored, streamed, no + * output cap or temperature, the instructions as `instructions`, the tools in + * one namespace that carries a description. On a plan, a 401 before the stream + * starts is answered once with a refreshed token; a second one means the + * sign-in has to be renewed. A key has nothing to refresh. */ export class OpenAiResponsesClient implements AiChatClient { - readonly kind = 'chatgpt' as const; readonly webSearch = true; constructor( readonly model: string, private readonly token: ChatgptTokenSource, private readonly fetcher: AiFetch, + readonly kind: 'chatgpt' | 'openai' = 'chatgpt', ) {} async *stream(request: AiChatRequest, signal: AbortSignal): AsyncGenerator { @@ -227,7 +229,7 @@ export class OpenAiResponsesClient implements AiChatClient { try { return await send(accessToken); } catch (err) { - if (!(err instanceof AiProviderError) || err.status !== 401) throw err; + if (this.kind !== 'chatgpt' || !(err instanceof AiProviderError) || err.status !== 401) throw err; return send(await this.token(accessToken)); } } diff --git a/server/tests/unit/nest/ai-connections/ai-chat-client.service.test.ts b/server/tests/unit/nest/ai-connections/ai-chat-client.service.test.ts new file mode 100644 index 000000000..2a1306270 --- /dev/null +++ b/server/tests/unit/nest/ai-connections/ai-chat-client.service.test.ts @@ -0,0 +1,79 @@ +/** + * AICL-001 to AICL-002: which chat client a resolved connection gets. An + * OpenAI reasoning model behind an API key takes its function tools only on the + * Responses API, so it goes there like a ChatGPT plan does (#2792). + */ +import { AiChatClientService, openAiWantsResponses } from '../../../../src/nest/ai-connections/ai-chat-client.service'; +import { AiConnectionsModule } from '../../../../src/nest/ai-connections/ai-connections.module'; +import type { ResolvedAiConnection } from '../../../../src/nest/ai-connections/ai-connections.types'; +import { AnthropicMessagesClient } from '../../../../src/nest/ai-connections/providers/anthropic-messages.client'; +import { OpenAiChatClient } from '../../../../src/nest/ai-connections/providers/openai-chat.client'; +import { OpenAiResponsesClient } from '../../../../src/nest/ai-connections/providers/openai-responses.client'; +import { AppConfigModule } from '../../../../src/nest/app-config/app-config.module'; +import { DemoModule } from '../../../../src/nest/common/demo.module'; +import { LlmLocalService } from '../../../../src/nest/llm-parse/llm-local.service'; +import { OidcService } from '../../../../src/nest/oidc/oidc.service'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; + +beforeAll(async () => { + t = await createTestModule({ + db, + imports: [AppConfigModule, DemoModule, AiConnectionsModule], + overrides: [ + { provide: LlmLocalService, useValue: {} }, + { provide: OidcService, useValue: {} }, + ], + }); +}); + +afterAll(async () => { + await t.close(); + db.close(); +}); + +function connection(kind: ResolvedAiConnection['kind'], model: string): ResolvedAiConnection { + return { + id: 1, + scope: 'instance', + kind, + model, + baseUrl: kind === 'custom' ? 'http://ollama:11434/v1' : null, + host: 'host', + paidBy: 'instance', + status: 'ok', + credential: { type: 'api_key', apiKey: 'sk-test' }, + }; +} + +describe('AiChatClientService', () => { + it('AICL-001: an OpenAI reasoning model on a key goes to the Responses API, an older one stays on Chat Completions', () => { + const clients = t.get(AiChatClientService); + const sol = clients.create(connection('openai', 'gpt-6.1-sol')); + expect(sol).toBeInstanceOf(OpenAiResponsesClient); + expect(sol.kind).toBe('openai'); + expect(clients.create(connection('openai', 'gpt-4.1'))).toBeInstanceOf(OpenAiChatClient); + expect(clients.create(connection('anthropic', 'claude-sonnet-5-5'))).toBeInstanceOf(AnthropicMessagesClient); + expect(clients.create(connection('custom', 'gpt-6.1-sol'))).toBeInstanceOf(OpenAiChatClient); + const plan = clients.create({ + ...connection('chatgpt', 'gpt-6.1-sol'), + credential: { type: 'chatgpt', accessToken: 'at' }, + }); + expect(plan).toBeInstanceOf(OpenAiResponsesClient); + expect(plan.kind).toBe('chatgpt'); + }); + + it('AICL-002: the reasoning lines are o-series, GPT-5 and later; their -chat variants and GPT-4 are not', () => { + for (const model of ['o3', 'o4-mini', 'gpt-5', 'gpt-5.6-sol', 'gpt-6.1-sol', 'gpt-6-sol']) { + expect(openAiWantsResponses(model), model).toBe(true); + } + for (const model of ['gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'gpt-5-chat-latest', 'omni-moderation-latest']) { + expect(openAiWantsResponses(model), model).toBe(false); + } + }); +}); diff --git a/server/tests/unit/nest/ai-connections/provider-adapters.test.ts b/server/tests/unit/nest/ai-connections/provider-adapters.test.ts index 138814e7a..c76539fa1 100644 --- a/server/tests/unit/nest/ai-connections/provider-adapters.test.ts +++ b/server/tests/unit/nest/ai-connections/provider-adapters.test.ts @@ -616,6 +616,18 @@ describe('OpenAiResponsesClient', () => { expect( await failure(new OpenAiResponsesClient('m', tokens('a', 'b'), twice.fetcher).stream(REQUEST, signal())), ).toMatchObject({ code: 'needs_reauth' }); + + // An API key has nothing to refresh: one request, and the refusal names the key (#2792). + const keyed = fetchAnswering(jsonResponse(401, {}), streamResponse(STREAM)); + const key = tokens('sk-key'); + const refused = await failure( + new OpenAiResponsesClient('gpt-6.1-sol', key, keyed.fetcher, 'openai').stream(REQUEST, signal()), + ); + expect(refused).toMatchObject({ code: 'invalid_key' }); + expect(key).toHaveBeenCalledTimes(1); + expect(keyed.calls).toHaveLength(1); + expect(keyed.calls[0]?.url).toBe('https://api.openai.com/v1/responses'); + expect(keyed.calls[0]?.init.headers).toMatchObject({ authorization: 'Bearer sk-key' }); }); it('OARS-005: a used-up plan, a failed response and a stream without completion are provider errors', async () => {