mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
feat(llm-parse): a typed outcome for every AI reading instead of warning text
LlmParseService.parse() now says how a reading ended (ok, empty, no_text, quota_exhausted, ai_disabled, user_cap, provider_error, too_large). The clients throw LlmRequestError with status and body code, so the TREK Cloud gate's 429 QUOTA_SPENT and HARD_CAP read as a spent allowance. The preview reports the outcome per file and the assistant reads its empty reason from it rather than matching warning strings.
This commit is contained in:
@@ -38,20 +38,17 @@ interface BookingRead {
|
||||
reason: BookingReadReason | null;
|
||||
}
|
||||
|
||||
/** The warnings of the AI fallback that say it could not read the file (llm-parse.service.ts words them). */
|
||||
const AI_FAILED = [/AI parsing failed/, /could not read file/, /does not read images/];
|
||||
const NO_TEXT = /no readable text found/;
|
||||
|
||||
/**
|
||||
* Why a preview of one file came back empty, from its warnings and its file
|
||||
* report. The import dialog shows those warnings as text; the chat names the
|
||||
* reason in its answer instead, so it reads them here once.
|
||||
* Why a preview of one file came back empty, from the outcome its file report
|
||||
* carries where the AI read it. The import dialog shows the warnings as text;
|
||||
* the chat names the reason in its answer instead. Every way the AI reading can
|
||||
* fail is one reason to the chat: the AI reader could not read it.
|
||||
*/
|
||||
export function emptyReason(preview: BookingImportPreviewResponse, aiAvailable: boolean): BookingReadReason {
|
||||
if (!aiAvailable) return 'ai_not_configured';
|
||||
if (preview.warnings.some((warning) => NO_TEXT.test(warning))) return 'no_text';
|
||||
if (preview.warnings.some((warning) => AI_FAILED.some((pattern) => pattern.test(warning)))) return 'ai_failed';
|
||||
return 'nothing_found';
|
||||
const outcome = preview.files?.[0]?.outcome;
|
||||
if (outcome === undefined || outcome === 'ok' || outcome === 'empty') return 'nothing_found';
|
||||
return outcome === 'no_text' ? 'no_text' : 'ai_failed';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
BookingImportFailureReason,
|
||||
BookingImportMode,
|
||||
BookingImportFileReport,
|
||||
LlmParseOutcome,
|
||||
Reservation,
|
||||
} from '@trek/shared';
|
||||
|
||||
@@ -209,6 +210,7 @@ export class BookingImportService {
|
||||
for (const file of files) {
|
||||
let kiItems: KiReservation[] = [];
|
||||
let aiUsed = false;
|
||||
let outcome: LlmParseOutcome | undefined;
|
||||
|
||||
// Stage 1: kitinerary (skipped entirely when forcing AI, and for a photo,
|
||||
// which only a model can read).
|
||||
@@ -229,10 +231,11 @@ export class BookingImportService {
|
||||
aiUsed = true;
|
||||
const llm = await this.llmParse.parse({ buffer: file.buffer, originalName: file.originalname }, userId);
|
||||
kiItems = llm.kiItems;
|
||||
outcome = llm.outcome;
|
||||
allWarnings.push(...llm.warnings);
|
||||
}
|
||||
|
||||
fileReports.push({ fileName: file.originalname, aiAvailable, aiUsed });
|
||||
fileReports.push({ fileName: file.originalname, aiAvailable, aiUsed, ...(outcome && { outcome }) });
|
||||
|
||||
if (kiItems.length === 0) {
|
||||
allWarnings.push(`${file.originalname}: no reservations found`);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { safeFetchLlm } from '../../../utils/ssrfGuard';
|
||||
import { toReservationList } from '../lenient-json';
|
||||
import type { LlmExtractionClient, LlmExtractionInput } from '../llm-provider.interface';
|
||||
import { isContextOverflow, LlmContextOverflowError } from './context-overflow';
|
||||
import { llmRequestError } from './llm-request-error';
|
||||
import { UnreadableLlmResponse } from './openai-compatible.client';
|
||||
|
||||
/** The answer cap when LLM_MAX_OUTPUT_TOKENS is unset. */
|
||||
@@ -86,10 +87,10 @@ export class AnthropicClient implements LlmExtractionClient {
|
||||
|
||||
if (!res.ok) {
|
||||
const detail = await res.text().catch(() => '');
|
||||
const message = `Anthropic request failed (${res.status}): ${detail.slice(0, 300)}`;
|
||||
const refused = llmRequestError('Anthropic request failed', res.status, detail);
|
||||
// A gateway in front of a smaller model can run out of context (#2652, #2655).
|
||||
if (res.status === 400 && isContextOverflow(detail)) throw new LlmContextOverflowError(message);
|
||||
throw new Error(message);
|
||||
if (res.status === 400 && isContextOverflow(detail)) throw new LlmContextOverflowError(refused.message);
|
||||
throw refused;
|
||||
}
|
||||
|
||||
const data = (await res.json()) as {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* A provider answered a parsing request with an error status. The message
|
||||
* stays the one the import has always logged and shown; `status` and `code`
|
||||
* let the caller tell a spent allowance from a broken request without
|
||||
* reading that message.
|
||||
*/
|
||||
export class LlmRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
/** The error code the body named (`QUOTA_SPENT` from the TREK Cloud gate), when it named one. */
|
||||
readonly code: string | undefined,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'LlmRequestError';
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of an error body is read for its code: the gate's and the providers' are a few hundred bytes. */
|
||||
const MAX_CODE_BODY = 4096;
|
||||
|
||||
/**
|
||||
* The `code` of a JSON error body, at the top (the TREK Cloud gate's
|
||||
* `{ error, code }`) or inside `error` (OpenAI's and Anthropic's shape).
|
||||
* Undefined for a body that is not JSON or names none.
|
||||
*/
|
||||
export function errorBodyCode(detail: string): string | undefined {
|
||||
if (!detail || detail.length > MAX_CODE_BODY) return undefined;
|
||||
let body: unknown;
|
||||
try {
|
||||
body = JSON.parse(detail);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!body || typeof body !== 'object') return undefined;
|
||||
const record = body as { code?: unknown; error?: unknown };
|
||||
if (typeof record.code === 'string') return record.code;
|
||||
const inner = record.error;
|
||||
if (inner && typeof inner === 'object' && typeof (inner as { code?: unknown }).code === 'string') {
|
||||
return (inner as { code: string }).code;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The error a client throws for a refused request, its message as the import has always worded it. */
|
||||
export function llmRequestError(label: string, status: number, detail: string): LlmRequestError {
|
||||
return new LlmRequestError(`${label} (${status}): ${detail.slice(0, 300)}`, status, errorBodyCode(detail));
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { safeFetchLlm } from '../../../utils/ssrfGuard';
|
||||
import { parseLenientJson, toReservationList } from '../lenient-json';
|
||||
import type { LlmExtractionClient, LlmExtractionInput } from '../llm-provider.interface';
|
||||
import { isContextOverflow, LlmContextOverflowError } from './context-overflow';
|
||||
import { llmRequestError } from './llm-request-error';
|
||||
import { isNuExtractModel, buildNuExtractUserText, nuExtractToKiReservations } from './nuextract';
|
||||
|
||||
/** The answer cap when LLM_MAX_OUTPUT_TOKENS is unset. */
|
||||
@@ -187,7 +188,7 @@ export class OpenAiCompatibleClient implements LlmExtractionClient {
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`LLM request failed (${res.status}): ${detail.slice(0, 300)}`);
|
||||
throw llmRequestError('LLM request failed', res.status, detail);
|
||||
}
|
||||
// Which rung answered. A report could not tell whether the schema reached the
|
||||
// model at all or the ladder had fallen back to the prompt alone (#2477).
|
||||
|
||||
@@ -2,8 +2,9 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import type { KiReservation } from '../booking-import/kitinerary.types';
|
||||
import { collapseRepeatedBookingTotal } from './booking-total';
|
||||
import { LlmContextOverflowError } from './clients/context-overflow';
|
||||
import { LlmRequestError } from './clients/llm-request-error';
|
||||
import { toIsoCurrency } from './currency-code';
|
||||
import { capImage, imageMimeType, renderPdfPages } from './image-input';
|
||||
import { capImage, ImageTooLargeError, imageMimeType, renderPdfPages } from './image-input';
|
||||
import { createLlmClient } from './llm-client.factory';
|
||||
import type { ResolvedLlmConfig } from './llm-config';
|
||||
import { LlmConfigResolver } from './llm-config.resolver';
|
||||
@@ -34,7 +35,7 @@ import {
|
||||
LOCAL_TEXT_WINDOW,
|
||||
} from './text-window';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { kiReservationSchema, type ReceiptScanResult } from '@trek/shared';
|
||||
import { kiReservationSchema, type LlmParseOutcome, type ReceiptScanResult } from '@trek/shared';
|
||||
|
||||
const MIME_BY_EXT: Record<string, string> = {
|
||||
'.pdf': 'application/pdf',
|
||||
@@ -42,7 +43,30 @@ const MIME_BY_EXT: Record<string, string> = {
|
||||
|
||||
export interface LlmParseResult {
|
||||
kiItems: KiReservation[];
|
||||
/** For the person to read; `outcome` is what a caller decides on. */
|
||||
warnings: string[];
|
||||
outcome: LlmParseOutcome;
|
||||
}
|
||||
|
||||
/** The codes the TREK Cloud gate answers a spent allowance with, on a 429. */
|
||||
const QUOTA_CODES = new Set(['QUOTA_SPENT', 'HARD_CAP']);
|
||||
|
||||
/**
|
||||
* How a failed reading ended, from the error alone: a spent Cloud allowance,
|
||||
* a document too large for the model or the gate, or a provider that failed.
|
||||
*/
|
||||
export function failureOutcome(err: unknown): LlmParseOutcome {
|
||||
if (err instanceof LlmRequestError) {
|
||||
if (err.status === 429 && err.code !== undefined && QUOTA_CODES.has(err.code)) return 'quota_exhausted';
|
||||
if (err.status === 413) return 'too_large';
|
||||
}
|
||||
if (err instanceof LlmContextOverflowError || err instanceof ImageTooLargeError) return 'too_large';
|
||||
return 'provider_error';
|
||||
}
|
||||
|
||||
/** A reading that found bookings or did not. */
|
||||
function foundOutcome(items: readonly unknown[]): LlmParseOutcome {
|
||||
return items.length > 0 ? 'ok' : 'empty';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,7 +205,7 @@ export class LlmParseService {
|
||||
|
||||
async parse(file: { buffer: Buffer; originalName: string }, userId: number): Promise<LlmParseResult> {
|
||||
const config = await this.llmConfig.resolve(userId);
|
||||
if (!config) return { kiItems: [], warnings: ['AI parsing is not configured'] };
|
||||
if (!config) return { kiItems: [], warnings: ['AI parsing is not configured'], outcome: 'ai_disabled' };
|
||||
|
||||
const warnings: string[] = [];
|
||||
const input: LlmExtractionInput = {
|
||||
@@ -197,7 +221,11 @@ export class LlmParseService {
|
||||
|
||||
const imageType = imageMimeType(file.originalName);
|
||||
if (imageType && !(await this.visionFor(config))) {
|
||||
return { kiItems: [], warnings: [`${file.originalName}: the configured model does not read images`] };
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: the configured model does not read images`],
|
||||
outcome: 'provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
// A photo goes as an image to every provider. Native PDF only for Anthropic
|
||||
@@ -249,6 +277,7 @@ export class LlmParseService {
|
||||
warnings: [
|
||||
`${file.originalName}: no readable text found (a scanned PDF needs a model that reads images)`,
|
||||
],
|
||||
outcome: 'no_text',
|
||||
};
|
||||
}
|
||||
input.text = undefined;
|
||||
@@ -264,6 +293,7 @@ export class LlmParseService {
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: could not read file — ${err instanceof Error ? err.message : String(err)}`],
|
||||
outcome: err instanceof ImageTooLargeError ? 'too_large' : 'provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -284,7 +314,11 @@ export class LlmParseService {
|
||||
ctx,
|
||||
)
|
||||
: await routeExtraction(input.text ?? '', ctx);
|
||||
return { kiItems: routed.kiItems, warnings: [...warnings, ...routed.warnings] };
|
||||
return {
|
||||
kiItems: routed.kiItems,
|
||||
warnings: [...warnings, ...routed.warnings],
|
||||
outcome: foundOutcome(routed.kiItems),
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[llm-parse] AI parsing failed for "${file.originalName}" (provider=${config.provider}):`,
|
||||
@@ -293,6 +327,7 @@ export class LlmParseService {
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: AI parsing failed — ${err instanceof Error ? err.message : String(err)}`],
|
||||
outcome: failureOutcome(err),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -316,6 +351,7 @@ export class LlmParseService {
|
||||
return {
|
||||
kiItems: [],
|
||||
warnings: [`${file.originalName}: AI parsing failed — ${err instanceof Error ? err.message : String(err)}`],
|
||||
outcome: failureOutcome(err),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -339,7 +375,7 @@ export class LlmParseService {
|
||||
|
||||
// The whole document, not the window the model read: a total sits at its end.
|
||||
const priced = collapseRepeatedBookingTotal(kiItems as unknown as Record<string, unknown>[], fullText);
|
||||
return { kiItems: priced as unknown as KiReservation[], warnings };
|
||||
return { kiItems: priced as unknown as KiReservation[], warnings, outcome: foundOutcome(priced) };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user