feat(llm-parse): read bookings on a ChatGPT plan

A ChatGPT sign-in only ever ran the assistant: parsing's clients call an
endpoint with a key, and a plan has none. AI connections now lends the plan
as a reader. Each document is one Responses call with the schema as the one
tool the model has to call (tool_choice required). The token is read and
refreshed per call by ChatgptAuthService, and a sign-in that has to be
renewed lends nothing.

- ResolvedLlmConfig is a union: ApiLlmConfig (what an admin configures) or
  PlanLlmConfig (provider chatgpt, a read function, never stored).
- ConnectionReadClient sends the text plus photo or scanned pages, and reads
  the filled shape, or the shape written as text; prose is unreadable.
- AiChatClientService.chatgptPlan is the one place that builds the plan's
  client, for the assistant and for parsing.
- Wiki: a ChatGPT sign-in reads bookings on its plan.
This commit is contained in:
Maurice
2026-11-13 20:49:08 +01:00
parent 29816f81a9
commit 7a40225852
17 changed files with 408 additions and 38 deletions
@@ -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. */
@@ -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,
);
}
}
@@ -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 },
@@ -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<SharedParsingConnection | null> {
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;
}
@@ -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<StructuredReadAnswer> {
const client = this.clients.chatgptPlan(row.id, model, await this.chatgpt.accessToken(row));
let filled: Record<string, unknown> | 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 };
}
}
@@ -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<string> = 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<Record<string, unknown>[]> {
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<string, unknown>,
},
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'),
}));
}
@@ -236,7 +236,8 @@ function parseNuExtract(content: string | undefined | null): Record<string, unkn
return nuExtractToKiReservations(readAnswer(content));
}
const USER_TEXT = 'Extract every travel reservation from the following document as schema.org JSON-LD.';
/** The user-turn instruction when the caller names none: the booking import's. */
export const USER_TEXT = 'Extract every travel reservation from the following document as schema.org JSON-LD.';
/** Tolerant parse: strip code fences, JSON(5).parse, pull the `rootKey` array. */
function parseReservations(content: string | undefined | null, rootKey: string): Record<string, unknown>[] {
@@ -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();
@@ -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<ResolvedLlmConfig | null> {
private async readInstanceConfig(): Promise<ApiLlmConfig | null> {
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<Pick<ResolvedLlmConfig, 'provider' | 'model' | 'baseUrl'> | null> {
async readInstanceEndpoint(): Promise<Pick<ApiLlmConfig, 'provider' | 'model' | 'baseUrl'> | null> {
const config = await this.readInstanceConfig();
return config ? { provider: config.provider, model: config.model, baseUrl: config.baseUrl } : null;
}
+20 -2
View File
@@ -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;
@@ -37,3 +37,32 @@ export interface LlmExtractionInput {
export interface LlmExtractionClient {
extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]>;
}
/** 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<string, unknown> };
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<string, unknown> } | { 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<StructuredReadAnswer>;
@@ -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<ResolvedLlmConfig, 'vision'>;
export type SharedParsingConnection = WithoutVision<ResolvedLlmConfig>;
/** Each variant of the config without its vision setting (an Omit over the union would merge them). */
type WithoutVision<C> = C extends unknown ? Omit<C, 'vision'> : never;
export interface SharedAiConnectionPort {
/** The connection a user's booking import may read with; null when there is none it can use. */