diff --git a/server/src/nest/ai-connections/ai-chat-client.interface.ts b/server/src/nest/ai-connections/ai-chat-client.interface.ts index c3fde730b..a5ec1d7f3 100644 --- a/server/src/nest/ai-connections/ai-chat-client.interface.ts +++ b/server/src/nest/ai-connections/ai-chat-client.interface.ts @@ -57,9 +57,12 @@ export interface AiChatRequest { /** * `none` asks for text only: the tools are still sent, so the tool calls * already in the history stay valid, but the model may not call one. - * Absent means the model chooses (#3016). + * Absent means the model chooses (#3016). `required` makes it call one: the + * parsing read on a ChatGPT plan asks for that, through the Responses API; + * the Anthropic adapter, whose extended thinking refuses a forced tool, + * treats it as absent. */ - toolChoice?: 'auto' | 'none'; + toolChoice?: 'auto' | 'none' | 'required'; } /** A page the model's answer draws on, from its web search. */ 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 3a9db9a90..d5f325895 100644 --- a/server/src/nest/ai-connections/ai-chat-client.service.ts +++ b/server/src/nest/ai-connections/ai-chat-client.service.ts @@ -45,17 +45,7 @@ export class AiChatClientService { create(connection: ResolvedAiConnection): AiChatClient { const { credential, kind, model } = connection; - if (credential.type === 'chatgpt') { - let current = credential.accessToken; - return new OpenAiResponsesClient( - model, - async (rejected) => { - if (rejected) current = await this.chatgpt.refresh(connection.id, rejected); - return current; - }, - cloudFetch, - ); - } + if (credential.type === 'chatgpt') return this.chatgptPlan(connection.id, model, credential.accessToken); if (kind === 'openai' && openAiWantsResponses(model)) { const apiKey = credential.apiKey ?? ''; return new OpenAiResponsesClient(model, () => Promise.resolve(apiKey), cloudFetch, 'openai'); @@ -75,4 +65,21 @@ export class AiChatClientService { return new OpenAiChatClient(kind, model, AI_BASE_URLS[kind], credential.apiKey, cloudFetch); } } + + /** + * The Responses client on a ChatGPT plan: a token the provider refuses is + * refreshed once for this connection, and the fresh one is kept for the + * client's following calls. + */ + chatgptPlan(connectionId: number, model: string, accessToken: string): AiChatClient { + let current = accessToken; + return new OpenAiResponsesClient( + model, + async (rejected) => { + if (rejected) current = await this.chatgpt.refresh(connectionId, rejected); + return current; + }, + cloudFetch, + ); + } } diff --git a/server/src/nest/ai-connections/ai-connections.module.ts b/server/src/nest/ai-connections/ai-connections.module.ts index 9302f82a3..54cfaf5a7 100644 --- a/server/src/nest/ai-connections/ai-connections.module.ts +++ b/server/src/nest/ai-connections/ai-connections.module.ts @@ -16,6 +16,7 @@ import { AiRefreshLock, InMemoryAiRefreshLock } from './ai-refresh-lock'; import { AiSettingsService } from './ai-settings.service'; import { AiUsageService } from './ai-usage.service'; import { ChatgptAuthService } from './chatgpt-auth.service'; +import { ChatgptParsingReader } from './chatgpt-parsing.reader'; import { ModelCatalogService } from './model-catalog.service'; import { OpenrouterAuthService } from './openrouter-auth.service'; import { MikroOrmModule } from '@mikro-orm/nestjs'; @@ -47,6 +48,7 @@ import { Module } from '@nestjs/common'; AiUsageService, AiChatClientService, ChatgptAuthService, + ChatgptParsingReader, OpenrouterAuthService, ModelCatalogService, { provide: AiAuthFlowStore, useClass: InMemoryAiAuthFlowStore }, diff --git a/server/src/nest/ai-connections/ai-connections.service.ts b/server/src/nest/ai-connections/ai-connections.service.ts index 0209e4ca4..74f9e31cb 100644 --- a/server/src/nest/ai-connections/ai-connections.service.ts +++ b/server/src/nest/ai-connections/ai-connections.service.ts @@ -23,6 +23,7 @@ import { maskHint, openSecrets, sealSecrets } from './ai-secrets'; import { AiSettingsService } from './ai-settings.service'; import { AiUsageService } from './ai-usage.service'; import { ChatgptAuthService } from './chatgpt-auth.service'; +import { ChatgptParsingReader } from './chatgpt-parsing.reader'; import { ModelCatalogService, modelReadsImages, pickDefaultModel, type CatalogTarget } from './model-catalog.service'; import { AiProviderError } from './providers/provider-errors'; import { InjectRepository } from '@mikro-orm/nestjs'; @@ -87,6 +88,7 @@ export class AiConnectionsService implements SharedAiConnectionPort { private readonly rateLimit: RateLimitService, private readonly llmParse: LlmParseService, private readonly audit: AuditService, + private readonly chatgptParsing: ChatgptParsingReader, ) {} /** `kind:model` of the models a provider refused an image for, while this process runs. */ @@ -411,10 +413,10 @@ export class AiConnectionsService implements SharedAiConnectionPort { /** * The connection a user's assistant would run on, as AI parsing reads it, so * an instance sets up one provider for both. The admin's policy decides it - * the same way. A ChatGPT plan is left out: its sign-in only reaches the chat - * models, not the completions endpoint parsing calls. Gemini and OpenRouter - * go through their OpenAI-compatible endpoints; a custom server is the - * admin's own address, read like parsing's local provider (#1772). + * the same way. A ChatGPT plan has no key for parsing's clients, so it is + * lent as a reader that holds the sign-in (chatgpt-parsing.reader.ts). Gemini + * and OpenRouter go through their OpenAI-compatible endpoints; a custom server + * is the admin's own address, read like parsing's local provider (#1772). */ async forParsing(userId: number): Promise { if (readEnv().managed.enabled) return null; @@ -438,6 +440,8 @@ export class AiConnectionsService implements SharedAiConnectionPort { return apiKey ? { provider: 'openai', model: row.model, apiKey, baseUrl: AI_BASE_URLS[kind] } : null; case 'custom': return row.base_url ? { provider: 'local', model: row.model, apiKey, baseUrl: row.base_url } : null; + case 'chatgpt': + return { provider: 'chatgpt', model: row.model, read: this.chatgptParsing.readerFor(row, row.model) }; default: return null; } diff --git a/server/src/nest/ai-connections/chatgpt-parsing.reader.ts b/server/src/nest/ai-connections/chatgpt-parsing.reader.ts new file mode 100644 index 000000000..87e23b71f --- /dev/null +++ b/server/src/nest/ai-connections/chatgpt-parsing.reader.ts @@ -0,0 +1,60 @@ +import type { AiConnectionRow } from '../../db/repositories/AiConnections.repository'; +import type { + StructuredReadAnswer, + StructuredReader, + StructuredReadRequest, +} from '../llm-parse/llm-provider.interface'; +import { AiChatClientService } from './ai-chat-client.service'; +import { ChatgptAuthService } from './chatgpt-auth.service'; +import { Injectable } from '@nestjs/common'; + +/** + * Lends a ChatGPT plan to AI parsing. Parsing's own clients call an endpoint + * with a key; a plan signs in instead, and only the Responses client here + * holds its token. So parsing gets a reader: one document per call, the shape + * to fill offered as the single tool the model has to call. The token is read + * per call, refreshed when it is about to expire or refused; a sign-in that + * cannot be renewed is marked by ChatgptAuthService and the next resolve lends + * nothing. + */ +@Injectable() +export class ChatgptParsingReader { + constructor( + private readonly chatgpt: ChatgptAuthService, + private readonly clients: AiChatClientService, + ) {} + + /** The reader for one ChatGPT connection, with the model it is saved with. */ + readerFor(row: AiConnectionRow, model: string): StructuredReader { + return (request) => this.read(row, model, request); + } + + /** + * @txIndependent writes nothing itself: a token refresh is stored by ChatgptAuthService under its own + * lock, complete on its own, with the model call (network I/O) after it. + */ + private async read( + row: AiConnectionRow, + model: string, + request: StructuredReadRequest, + ): Promise { + const client = this.clients.chatgptPlan(row.id, model, await this.chatgpt.accessToken(row)); + let filled: Record | null = null; + let text = ''; + const turn = client.stream( + { + system: request.system, + messages: [{ role: 'user', text: request.text, images: request.images }], + tools: [request.shape], + toolChoice: 'required', + }, + request.signal, + ); + for await (const event of turn) { + // The one tool offered is the shape; its first call is the answer. + if (event.type === 'tool-call' && filled === null) filled = event.call.args; + else if (event.type === 'text-delta') text += event.delta; + } + return filled ? { filled } : { text }; + } +} diff --git a/server/src/nest/llm-parse/clients/connection-read.client.ts b/server/src/nest/llm-parse/clients/connection-read.client.ts new file mode 100644 index 000000000..662f7504f --- /dev/null +++ b/server/src/nest/llm-parse/clients/connection-read.client.ts @@ -0,0 +1,57 @@ +import { readEnv } from '../../../app-config'; +import { parseLenientJson, toReservationList } from '../lenient-json'; +import type { + LlmExtractionClient, + LlmExtractionInput, + StructuredReader, + StructuredReadImage, +} from '../llm-provider.interface'; +import { UnreadableLlmResponse, USER_TEXT } from './openai-compatible.client'; + +/** The image types a structured read carries; anything else reaches the model as text or not at all. */ +const IMAGE_TYPES: ReadonlySet = new Set(['image/jpeg', 'image/png', 'image/webp']); + +/** + * Extraction on a connection the AI connections module lends as a reader (a + * ChatGPT plan). The document goes as text plus its images, the schema as the + * one tool the model has to call; what it fills is the answer. A native PDF + * never arrives here: llm-parse.service.ts sends it as text, or a scan as its + * pages drawn as images. Bounded by LLM_TIMEOUT_MS like the other clients. + */ +export class ConnectionReadClient implements LlmExtractionClient { + constructor(private readonly read: StructuredReader) {} + + async extract(input: LlmExtractionInput): Promise[]> { + const rootKey = input.rootKey ?? 'reservations'; + const userText = input.userText ?? USER_TEXT; + const answer = await this.read({ + system: input.prompt, + text: input.text ? `${userText}\n\n${input.text}` : userText, + images: imagesOf(input), + shape: { + name: `record_${rootKey}`, + description: `Record the ${rootKey} found in the document, as an empty list when there are none.`, + parameters: input.jsonSchema as Record, + }, + signal: AbortSignal.timeout(readEnv().integrations.llmTimeoutMs), + }); + if ('filled' in answer) return toReservationList(answer.filled, rootKey); + // A model that wrote the shape as text instead of calling the tool; prose is no answer. + const written = parseLenientJson(answer.text); + if (!written || typeof written !== 'object') { + throw new UnreadableLlmResponse('The model answered without filling the requested shape'); + } + return toReservationList(written, rootKey); + } +} + +/** The document's photo or scanned pages, in order, those of a type the read carries. */ +function imagesOf(input: LlmExtractionInput): StructuredReadImage[] { + const files = input.file ? [input.file, ...(input.pageImages ?? [])] : []; + return files + .filter((file) => IMAGE_TYPES.has(file.mimeType)) + .map((file) => ({ + mimeType: file.mimeType as StructuredReadImage['mimeType'], + data: file.data.toString('base64'), + })); +} diff --git a/server/src/nest/llm-parse/clients/openai-compatible.client.ts b/server/src/nest/llm-parse/clients/openai-compatible.client.ts index 741979629..2014230b1 100644 --- a/server/src/nest/llm-parse/clients/openai-compatible.client.ts +++ b/server/src/nest/llm-parse/clients/openai-compatible.client.ts @@ -236,7 +236,8 @@ function parseNuExtract(content: string | undefined | null): Record[] { diff --git a/server/src/nest/llm-parse/llm-client.factory.ts b/server/src/nest/llm-parse/llm-client.factory.ts index 462946020..31941dc4e 100644 --- a/server/src/nest/llm-parse/llm-client.factory.ts +++ b/server/src/nest/llm-parse/llm-client.factory.ts @@ -1,4 +1,5 @@ import { AnthropicClient } from './clients/anthropic.client'; +import { ConnectionReadClient } from './clients/connection-read.client'; import { OpenAiCompatibleClient } from './clients/openai-compatible.client'; import type { ResolvedLlmConfig } from './llm-config'; import type { LlmExtractionClient } from './llm-provider.interface'; @@ -7,11 +8,14 @@ import type { LlmExtractionClient } from './llm-provider.interface'; * Pick the provider client for a resolved config. * - 'anthropic' → Anthropic Messages API client * - 'openai' | 'local' → OpenAI-compatible client (cloud or local base URL) + * - 'chatgpt' → the plan the AI connection lends, read through it */ export function createLlmClient(config: ResolvedLlmConfig): LlmExtractionClient { switch (config.provider) { case 'anthropic': return new AnthropicClient(); + case 'chatgpt': + return new ConnectionReadClient(config.read); case 'openai': case 'local': return new OpenAiCompatibleClient(); diff --git a/server/src/nest/llm-parse/llm-config.resolver.ts b/server/src/nest/llm-parse/llm-config.resolver.ts index 7461c0140..23e60f590 100644 --- a/server/src/nest/llm-parse/llm-config.resolver.ts +++ b/server/src/nest/llm-parse/llm-config.resolver.ts @@ -3,7 +3,13 @@ import { Addons } from '../../db/entities/Addons.entity'; import type { AddonsRepository } from '../../db/repositories/Addons.repository'; import { AddonsService } from '../addons/addons.service'; import { SettingsService } from '../settings/settings.service'; -import { decryptLlmApiKey, LLM_PROVIDERS, type LlmProvider, type ResolvedLlmConfig } from './llm-config'; +import { + decryptLlmApiKey, + LLM_PROVIDERS, + type ApiLlmConfig, + type LlmProvider, + type ResolvedLlmConfig, +} from './llm-config'; import { SHARED_AI_CONNECTION, type SharedAiConnectionPort } from './shared-ai-connection.interface'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; @@ -69,7 +75,7 @@ export class LlmConfigResolver { return { ...shared, vision: asLlmVision(row?.config?.vision) }; } - private async readInstanceConfig(): Promise { + private async readInstanceConfig(): Promise { const row = await this.addonsRepo.findById(ADDON_IDS.LLM_PARSING); const cfg = row?.config; if (!cfg) return null; @@ -90,7 +96,7 @@ export class LlmConfigResolver { * address, for the AI assistant's admin form to start from while it has no * connection of its own. Read only; nothing here changes AI parsing. */ - async readInstanceEndpoint(): Promise | null> { + async readInstanceEndpoint(): Promise | null> { const config = await this.readInstanceConfig(); return config ? { provider: config.provider, model: config.model, baseUrl: config.baseUrl } : null; } diff --git a/server/src/nest/llm-parse/llm-config.ts b/server/src/nest/llm-parse/llm-config.ts index 9d8b27648..e98f11a2d 100644 --- a/server/src/nest/llm-parse/llm-config.ts +++ b/server/src/nest/llm-parse/llm-config.ts @@ -1,4 +1,5 @@ import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto'; +import type { StructuredReader } from './llm-provider.interface'; import { asLlmVision, type LlmVision } from '@trek/shared'; /** @@ -16,8 +17,8 @@ import { asLlmVision, type LlmVision } from '@trek/shared'; export type LlmProvider = 'local' | 'openai' | 'anthropic'; -/** Fully-resolved config the clients consume. */ -export interface ResolvedLlmConfig { +/** A provider called with a key (or none, on a local server) at an address: what an admin can configure. */ +export interface ApiLlmConfig { provider: LlmProvider; model: string; baseUrl?: string; @@ -25,6 +26,23 @@ export interface ResolvedLlmConfig { vision: LlmVision; } +/** + * A ChatGPT plan the AI connection lends: it signs in instead of holding a key, + * so it has no address or key here and is read through `read`. Never stored in + * the addon config, only resolved from the shared connection. + */ +export interface PlanLlmConfig { + provider: 'chatgpt'; + model: string; + read: StructuredReader; + vision: LlmVision; + baseUrl?: undefined; + apiKey?: undefined; +} + +/** Fully-resolved config the clients consume. */ +export type ResolvedLlmConfig = ApiLlmConfig | PlanLlmConfig; + /** Shape of the admin instance config stored in `addons.config` (apiKey encrypted). */ export interface LlmAddonConfig { provider?: LlmProvider; diff --git a/server/src/nest/llm-parse/llm-provider.interface.ts b/server/src/nest/llm-parse/llm-provider.interface.ts index f74096a59..06b593261 100644 --- a/server/src/nest/llm-parse/llm-provider.interface.ts +++ b/server/src/nest/llm-parse/llm-provider.interface.ts @@ -37,3 +37,32 @@ export interface LlmExtractionInput { export interface LlmExtractionClient { extract(input: LlmExtractionInput): Promise[]>; } + +/** An image a structured read sends, base64 without line breaks. */ +export interface StructuredReadImage { + mimeType: 'image/jpeg' | 'image/png' | 'image/webp'; + data: string; +} + +/** + * One document read into a given shape on a connection the extraction clients + * do not call themselves: the instructions, the document as text and images, + * and the shape the model is made to fill, as a tool it has to call. + */ +export interface StructuredReadRequest { + system: string; + text: string; + images: StructuredReadImage[]; + shape: { name: string; description: string; parameters: Record }; + signal: AbortSignal; +} + +/** What the model gave back: the shape it filled, or, when it called no tool, the text it wrote. */ +export type StructuredReadAnswer = { filled: Record } | { text: string }; + +/** + * Reads one document on a ChatGPT plan, which signs in instead of holding a + * key: the AI connections module owns its token and its client and lends this + * function (see shared-ai-connection.interface.ts). A provider failure is thrown. + */ +export type StructuredReader = (request: StructuredReadRequest) => Promise; diff --git a/server/src/nest/llm-parse/shared-ai-connection.interface.ts b/server/src/nest/llm-parse/shared-ai-connection.interface.ts index 01f35371a..18b601b29 100644 --- a/server/src/nest/llm-parse/shared-ai-connection.interface.ts +++ b/server/src/nest/llm-parse/shared-ai-connection.interface.ts @@ -11,7 +11,10 @@ import type { ResolvedLlmConfig } from './llm-config'; export const SHARED_AI_CONNECTION = Symbol('SHARED_AI_CONNECTION'); /** A shared connection as parsing reads it; the vision setting stays parsing's own. */ -export type SharedParsingConnection = Omit; +export type SharedParsingConnection = WithoutVision; + +/** Each variant of the config without its vision setting (an Omit over the union would merge them). */ +type WithoutVision = C extends unknown ? Omit : never; export interface SharedAiConnectionPort { /** The connection a user's booking import may read with; null when there is none it can use. */ diff --git a/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts b/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts index 6be56b8f6..258b619b1 100644 --- a/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts +++ b/server/tests/unit/nest/ai-connections/ai-connections.service.test.ts @@ -4,11 +4,13 @@ * decides whose connection a user's assistant runs on, and the instance's * connection keeps a stored key only for the target it was saved for. * - * Replaced: the model catalog (no provider is asked), the ChatGPT sign-in, the - * addon switch, the demo check, the audit writer and AI parsing's config. + * Replaced: the model catalog (no provider is asked), the ChatGPT sign-in and + * its chat client, the addon switch, the demo check, the audit writer and AI parsing's config. */ import { AiConnections } from '../../../../src/db/entities/AiConnections.entity'; import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import type { AiChatEvent, AiChatRequest } from '../../../../src/nest/ai-connections/ai-chat-client.interface'; +import { AiChatClientService } from '../../../../src/nest/ai-connections/ai-chat-client.service'; import { AiConnectionsModule } from '../../../../src/nest/ai-connections/ai-connections.module'; import { AiConnectionsService } from '../../../../src/nest/ai-connections/ai-connections.service'; import { ChatgptAuthService } from '../../../../src/nest/ai-connections/chatgpt-auth.service'; @@ -42,6 +44,20 @@ const MODELS: AiModelInfo[] = [ const catalog = { list: vi.fn(async (): Promise => MODELS) }; const chatgpt = { accessToken: vi.fn(async () => 'chatgpt-access') }; +/** What the plan's model answers a parsing read with, and what it was asked. */ +let planAnswer: AiChatEvent[] = []; +const planAsked: AiChatRequest[] = []; +const chatClients = { + chatgptPlan: vi.fn((_id: number, model: string, _token: string) => ({ + kind: 'chatgpt' as const, + model, + webSearch: true, + async *stream(request: AiChatRequest) { + planAsked.push(request); + yield* planAnswer; + }, + })), +}; const addons = { isAddonEnabled: vi.fn(async () => true) }; const demo = { isDemoUserId: vi.fn(async () => false) }; const audit = { writeAudit: vi.fn(async () => undefined) }; @@ -56,6 +72,7 @@ beforeAll(async () => { overrides: [ { provide: ModelCatalogService, useValue: catalog }, { provide: ChatgptAuthService, useValue: chatgpt }, + { provide: AiChatClientService, useValue: chatClients }, { provide: AddonsService, useValue: addons }, { provide: DemoService, useValue: demo }, { provide: AuditService, useValue: audit }, @@ -449,21 +466,85 @@ describe('the connection AI parsing shares', () => { }); }); - it('AICS-031: a ChatGPT plan or a connection with a problem is not lent to parsing', async () => { + it('AICS-031: a connection with a problem is not lent to parsing', async () => { const id = await user(); const { em } = orm(); - await em.fork().insert(AiConnections, { - scope: 'user', - user: id, - kind: 'chatgpt', - model: 'gpt-6.1-sol', - status: 'ok', - }); - expect(await service().forParsing(id)).toBeNull(); - await em.fork().nativeDelete(AiConnections, { user: id }); await service().saveOwnKey(id, { kind: 'openai', apiKey: 'sk-proj-own-parse' }); expect(await service().forParsing(id)).toMatchObject({ provider: 'openai', apiKey: 'sk-proj-own-parse' }); await em.fork().nativeUpdate(AiConnections, { user: id }, { status: 'error' }); expect(await service().forParsing(id)).toBeNull(); }); }); + +describe('a ChatGPT plan lent to AI parsing', () => { + const READ = { + system: 'Read bookings.', + text: 'LH 1166 FRA-LIS', + images: [{ mimeType: 'image/png' as const, data: 'cGFnZQ==' }], + shape: { name: 'record_reservations', description: 'Record them.', parameters: { type: 'object' } }, + }; + + async function planUser(status = 'ok'): Promise { + const id = await user(); + await orm() + .em.fork() + .insert(AiConnections, { scope: 'user', user: id, kind: 'chatgpt', model: 'gpt-6.1-sol', status }); + return id; + } + + async function lent(id: number) { + const connection = await service().forParsing(id); + if (connection?.provider !== 'chatgpt') throw new Error('no ChatGPT plan was lent'); + return connection; + } + + beforeEach(() => { + planAnswer = []; + planAsked.length = 0; + }); + + it('AICS-032: the plan is lent as a reader that makes the model fill the shape as its one tool', async () => { + const id = await planUser(); + const connection = await lent(id); + expect(connection).toMatchObject({ provider: 'chatgpt', model: 'gpt-6.1-sol' }); + expect(chatgpt.accessToken).not.toHaveBeenCalled(); + + planAnswer = [ + { type: 'tool-call', call: { id: 'c1', name: 'record_reservations', args: { reservations: [{ n: 1 }] } } }, + { type: 'tool-call', call: { id: 'c2', name: 'record_reservations', args: { reservations: [{ n: 2 }] } } }, + { type: 'finish', reason: 'tool-calls' }, + ]; + expect(await connection.read({ ...READ, signal: new AbortController().signal })).toEqual({ + filled: { reservations: [{ n: 1 }] }, + }); + expect(chatgpt.accessToken).toHaveBeenCalledTimes(1); + expect(chatClients.chatgptPlan).toHaveBeenCalledWith(expect.any(Number), 'gpt-6.1-sol', 'chatgpt-access'); + expect(planAsked[0]).toEqual({ + system: 'Read bookings.', + messages: [{ role: 'user', text: 'LH 1166 FRA-LIS', images: READ.images }], + tools: [READ.shape], + toolChoice: 'required', + }); + }); + + it('AICS-033: a model that called no tool answers with the text it wrote, whole', async () => { + const connection = await lent(await planUser()); + planAnswer = [ + { type: 'text-delta', delta: '{"reservations": ' }, + { type: 'text-delta', delta: '[]}' }, + { type: 'finish', reason: 'stop' }, + ]; + expect(await connection.read({ ...READ, signal: new AbortController().signal })).toEqual({ + text: '{"reservations": []}', + }); + }); + + it('AICS-034: a sign-in to renew lends nothing, and a refused token reaches the caller', async () => { + expect(await service().forParsing(await planUser('needs_reauth'))).toBeNull(); + const connection = await lent(await planUser()); + chatgpt.accessToken.mockRejectedValueOnce(new AiProviderError('needs_reauth', 401, false)); + await expect(connection.read({ ...READ, signal: new AbortController().signal })).rejects.toBeInstanceOf( + AiProviderError, + ); + }); +}); diff --git a/server/tests/unit/nest/llm-parse/connection-read.client.test.ts b/server/tests/unit/nest/llm-parse/connection-read.client.test.ts new file mode 100644 index 000000000..90c14a11e --- /dev/null +++ b/server/tests/unit/nest/llm-parse/connection-read.client.test.ts @@ -0,0 +1,76 @@ +/** + * ConnectionReadClient: extraction on a connection lent as a reader (a ChatGPT + * plan). What the reader is handed, which images go along, and what comes back. + */ +import { ConnectionReadClient } from '../../../../src/nest/llm-parse/clients/connection-read.client'; +import { UnreadableLlmResponse, USER_TEXT } from '../../../../src/nest/llm-parse/clients/openai-compatible.client'; +import type { + LlmExtractionInput, + StructuredReadAnswer, + StructuredReadRequest, +} from '../../../../src/nest/llm-parse/llm-provider.interface'; + +import { describe, expect, it, vi } from 'vitest'; + +const SCHEMA = { type: 'object', properties: { reservations: { type: 'array' } } }; +const base: LlmExtractionInput = { prompt: 'Read bookings.', jsonSchema: SCHEMA, model: 'gpt-x' }; + +function reader(answer: StructuredReadAnswer) { + return vi.fn(async (_request: StructuredReadRequest) => answer); +} + +describe('ConnectionReadClient', () => { + it('CONNREAD-001: sends the prompt, the document text and the schema as the shape to fill', async () => { + const read = reader({ filled: { reservations: [{ '@type': 'FlightReservation' }] } }); + const list = await new ConnectionReadClient(read).extract({ ...base, text: 'LH 1166 FRA-LIS' }); + expect(list).toEqual([{ '@type': 'FlightReservation' }]); + const request = read.mock.calls[0][0]; + expect(request.system).toBe('Read bookings.'); + expect(request.text).toBe(`${USER_TEXT}\n\nLH 1166 FRA-LIS`); + expect(request.shape).toMatchObject({ name: 'record_reservations', parameters: SCHEMA }); + expect(request.images).toEqual([]); + expect(request.signal).toBeInstanceOf(AbortSignal); + }); + + it('CONNREAD-002: a photo and the scanned pages go as images, other files do not', async () => { + const read = reader({ filled: { receipts: [{ total: 12 }] } }); + const list = await new ConnectionReadClient(read).extract({ + ...base, + rootKey: 'receipts', + userText: 'Read the receipt.', + file: { mimeType: 'image/png', data: Buffer.from('page-1') }, + pageImages: [ + { mimeType: 'image/jpeg', data: Buffer.from('page-2') }, + { mimeType: 'image/heic', data: Buffer.from('no') }, + { mimeType: 'application/pdf', data: Buffer.from('no') }, + ], + }); + expect(list).toEqual([{ total: 12 }]); + const request = read.mock.calls[0][0]; + expect(request.text).toBe('Read the receipt.'); + expect(request.shape.name).toBe('record_receipts'); + expect(request.images).toEqual([ + { mimeType: 'image/png', data: Buffer.from('page-1').toString('base64') }, + { mimeType: 'image/jpeg', data: Buffer.from('page-2').toString('base64') }, + ]); + }); + + it('CONNREAD-003: a shape written as text is read, prose is an unreadable answer, an empty list is none found', async () => { + const written = reader({ text: '```json\n{"reservations": [{"n": 3}]}\n```' }); + expect(await new ConnectionReadClient(written).extract(base)).toEqual([{ n: 3 }]); + await expect(new ConnectionReadClient(reader({ text: 'No booking here.' })).extract(base)).rejects.toBeInstanceOf( + UnreadableLlmResponse, + ); + await expect(new ConnectionReadClient(reader({ text: '' })).extract(base)).rejects.toBeInstanceOf( + UnreadableLlmResponse, + ); + expect(await new ConnectionReadClient(reader({ filled: { reservations: [] } })).extract(base)).toEqual([]); + }); + + it('CONNREAD-004: a provider failure reaches the caller as it came', async () => { + const failing = vi.fn(async () => { + throw new Error('needs_reauth'); + }); + await expect(new ConnectionReadClient(failing).extract(base)).rejects.toThrow('needs_reauth'); + }); +}); diff --git a/server/tests/unit/nest/llm-parse/llm-client.factory.test.ts b/server/tests/unit/nest/llm-parse/llm-client.factory.test.ts index f29af7659..82062d73f 100644 --- a/server/tests/unit/nest/llm-parse/llm-client.factory.test.ts +++ b/server/tests/unit/nest/llm-parse/llm-client.factory.test.ts @@ -1,4 +1,5 @@ import { AnthropicClient } from '../../../../src/nest/llm-parse/clients/anthropic.client'; +import { ConnectionReadClient } from '../../../../src/nest/llm-parse/clients/connection-read.client'; import { OpenAiCompatibleClient } from '../../../../src/nest/llm-parse/clients/openai-compatible.client'; import { createLlmClient } from '../../../../src/nest/llm-parse/llm-client.factory'; import type { ResolvedLlmConfig } from '../../../../src/nest/llm-parse/llm-config'; @@ -18,6 +19,16 @@ describe('createLlmClient', () => { expect(createLlmClient(cfg('local'))).toBeInstanceOf(OpenAiCompatibleClient); }); + it('reads a ChatGPT plan through the reader its connection lends', () => { + const plan: ResolvedLlmConfig = { + provider: 'chatgpt', + model: 'gpt-x', + vision: 'auto', + read: async () => ({ text: '' }), + }; + expect(createLlmClient(plan)).toBeInstanceOf(ConnectionReadClient); + }); + it('falls back to the OpenAI-compatible client for an unknown provider', () => { expect(createLlmClient(cfg('something-else'))).toBeInstanceOf(OpenAiCompatibleClient); }); diff --git a/server/tests/unit/nest/llm-parse/llm-config.resolver.test.ts b/server/tests/unit/nest/llm-parse/llm-config.resolver.test.ts index b19f933de..90dda209a 100644 --- a/server/tests/unit/nest/llm-parse/llm-config.resolver.test.ts +++ b/server/tests/unit/nest/llm-parse/llm-config.resolver.test.ts @@ -222,6 +222,14 @@ describe('the shared AI connection', () => { expect(await resolver.resolve(1)).toMatchObject({ model: 'gemini-3-flash', vision: 'auto' }); }); + it('LLMRES-SHARED-004: a lent ChatGPT plan comes through with its reader and the vision setting of parsing', async () => { + portRegistered = true; + const read = async () => ({ text: '' }); + forParsing.mockResolvedValue({ provider: 'chatgpt', model: 'gpt-6.1-sol', read }); + setInstanceConfig({ vision: 'on' }); + expect(await resolver.resolve(3)).toEqual({ provider: 'chatgpt', model: 'gpt-6.1-sol', read, vision: 'on' }); + }); + it('LLMRES-SHARED-003: without the port or a usable connection, the personal config answers', async () => { getUserSettings.mockReturnValue({ llm_provider: 'openai', llm_model: 'gpt-4o' }); expect(await resolver.resolve(1)).toMatchObject({ provider: 'openai', model: 'gpt-4o' }); diff --git a/wiki/AI-Booking-Import.md b/wiki/AI-Booking-Import.md index 6867825e5..79de9a73a 100644 --- a/wiki/AI-Booking-Import.md +++ b/wiki/AI-Booking-Import.md @@ -30,7 +30,7 @@ If none of them exists, the import fails with an error shown in the widget. Two details of the shared connection: -- A **ChatGPT** sign-in is not used for parsing. It only reaches ChatGPT's chat models, not the endpoint that parsing calls. Connect an API key (or another provider) for parsing instead. +- A **ChatGPT** sign-in reads bookings too, on the plan it is signed in with. Each file or forwarded mail is one request on that plan and counts toward its usage limits. If the sign-in has expired, parsing stops until someone signs in again under **AI connection**. - **Model reads images** is a setting of AI parsing itself and stays there, whichever connection reads. See [Photos](#photos). ## Choosing a provider @@ -43,7 +43,7 @@ The shared connection of the AI assistant supports these providers: | **Anthropic** | Anthropic's API | Needs an API key. **Reads PDFs natively, scans included.** | | **Gemini** | Google's OpenAI-compatible endpoint | Needs an API key. | | **OpenRouter** | OpenRouter's API | **Connect OpenRouter** signs you in, so there is no key to copy. | -| **Sign in with ChatGPT** | ChatGPT | Uses a ChatGPT plan, no key. Chat only, not used for parsing. | +| **Sign in with ChatGPT** | ChatGPT | Uses a ChatGPT plan, no key. Reads bookings on the same plan. | | **Own server** | Your own hardware, or any OpenAI-compatible service | Ollama, LM Studio, vLLM, llama.cpp, a LiteLLM proxy or a hosted endpoint such as Groq, at a **Server address** you enter: the one that `/chat/completions` follows, usually ending in `/v1` (`http://localhost:11434/v1`, `https://api.groq.com/openai/v1`). Ollama is read through its own API, every other server through `/chat/completions`. The API key is optional. | To connect, pick **Sign in with ChatGPT**, **Paste an API key** or **Own server**. When you paste a key, TREK shows *Detected: {provider}*; if it cannot tell, it asks *Which provider is this key from?*. **Connect OpenRouter** is offered as its own button.