Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

16.5 KB
Raw Blame
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 { capImage, imageMimeType, renderPdfPages } from './image-input';
import { createLlmClient } from './llm-client.factory';
import type { ResolvedLlmConfig } from './llm-config';
import { LlmConfigResolver } from './llm-config.resolver';
import { LlmLocalService } from './llm-local.service';
import { failureOutcome, foundOutcome } from './llm-outcome';
import { buildSystemPrompt, KI_RESERVATION_JSON_SCHEMA } from './llm-prompt';
import type { LlmExtractionFile, LlmExtractionInput } from './llm-provider.interface';
import {
  buildReceiptPrompt,
  RECEIPT_JSON_SCHEMA,
  RECEIPT_LIST_JSON_SCHEMA,
  RECEIPT_ROOT_KEY,
  RECEIPT_USER_TEXT,
  toReceiptRead,
} from './receipt-read';
import { normalizeCurrency, normalizeNode } from './reservation-normalize';
import { routeExtraction, routeImageExtraction, detectFlightNumbers } from './router/extraction-router';
import { extractEnforced } from './router/ollama-format.client';
import { isPdf, extractText } from './text-extract';
import {
  CLOUD_TEXT_WINDOW,
  COMPACT_TEXT_WINDOW,
  fitTextWindow,
  LOCAL_FLIGHT_TEXT_WINDOW,
  LOCAL_TEXT_WINDOW,
} from './text-window';
import { Injectable } from '@nestjs/common';
import { kiReservationSchema, type LlmParseOutcome, type ReceiptScanResult } from '@trek/shared';

const MIME_BY_EXT: Record<string, string> = {
  '.pdf': 'application/pdf',
};

export interface LlmParseResult {
  kiItems: KiReservation[];
  /** For the person to read; `outcome` is what a caller decides on. */
  warnings: string[];
  outcome: LlmParseOutcome;
}

/**
 * Orchestrates the LLM fallback: resolve config → pick client → build input
 * (a photo as an image when the model reads one, a PDF natively for Anthropic,
 * extracted text otherwise) → call provider →
 * validate the response → return schema.org `KiReservation[]` for the shared
 * mapper. Never throws for content/provider reasons — degrades to `[]` + a
 * warning, mirroring the kitinerary extractor's tolerance.
 */
@Injectable()
export class LlmParseService {
  constructor(
    private readonly llmConfig: LlmConfigResolver,
    private readonly env: RuntimeEnvService,
    private readonly local: LlmLocalService,
  ) {}

  /**
   * The admin's AI parsing endpoint without its key, for the AI assistant's
   * admin form to start from. Read only; AI parsing itself is not touched.
   */
  instanceEndpoint(): ReturnType<LlmConfigResolver['readInstanceEndpoint']> {
    return this.llmConfig.readInstanceEndpoint();
  }

  /**
   * The text of a document as the AI fallback reads it (an e-mail's body, a
   * PDF's text layer, a page without its markup), for a caller outside this
   * module: the assistant keeps it with a file attached in the chat. A scanned
   * PDF answers an empty string. Asks no model.
   */
  readText(buffer: Buffer, fileName: string): Promise<string> {
    return extractText(buffer, fileName);
  }

  /**
   * A text cut to what one model request should carry of it, its start and
   * its end kept: the cloud window, or the compact one for a server whose
   * context may be small (text-window.ts).
   */
  fitText(text: string, compact: boolean): string {
    return fitTextWindow(text, compact ? COMPACT_TEXT_WINDOW : CLOUD_TEXT_WINDOW).text;
  }

  /** True when the addon is enabled AND a usable config resolves for this user. */
  async isAvailable(userId: number): Promise<boolean> {
    return (await this.llmConfig.resolve(userId)) !== null;
  }

  /** Whether a photo this user uploads can be read: AI parsing is set up and its model takes images. */
  async readsImages(userId: number): Promise<boolean> {
    const config = await this.llmConfig.resolve(userId);
    return config ? await this.visionFor(config) : false;
  }

  /**
   * Read a photographed receipt for the Costs tab. Like parse(), it never throws
   * for content or provider reasons: a refusal comes back as a null receipt and
   * a warning naming the file.
   */
  async readReceipt(file: { buffer: Buffer; originalName: string }, userId: number): Promise<ReceiptScanResult> {
    const config = await this.llmConfig.resolve(userId);
    if (!config) return { receipt: null, warnings: ['AI parsing is not configured'] };
    const imageType = imageMimeType(file.originalName);
    if (!imageType) return { receipt: null, warnings: [`${file.originalName}: not a photo`] };
    if (!(await this.visionFor(config))) {
      return { receipt: null, warnings: [`${file.originalName}: the configured model does not read images`] };
    }

    let image: LlmExtractionFile;
    try {
      image = await capImage(file.buffer, imageType);
    } catch (err) {
      // A photo too large to decode or to send, refused like one that cannot be read.
      return { receipt: null, warnings: [`${file.originalName}: ${err instanceof Error ? err.message : String(err)}`] };
    }
    const local = config.provider === 'local';
    const prompt = buildReceiptPrompt(new Date(), !local);
    let raw: unknown;
    try {
      if (local) {
        // Ollama's own chat API, as the booking router uses: `think: false` and
        // `num_ctx` exist there and not on /v1, and a hybrid model that is left
        // to reason spends the whole token budget on it and answers nothing.
        raw = await extractEnforced({
          baseUrl: config.baseUrl ?? 'http://localhost:11434/v1',
          model: config.model,
          apiKey: config.apiKey,
          system: prompt,
          user: RECEIPT_USER_TEXT,
          schema: RECEIPT_JSON_SCHEMA,
          images: [image.data.toString('base64')],
          numCtx: 16384,
          // A supermarket receipt is a long list of lines.
          numPredict: 2048,
        });
      } else {
        const list = await createLlmClient(config).extract({
          prompt,
          jsonSchema: RECEIPT_LIST_JSON_SCHEMA,
          rootKey: RECEIPT_ROOT_KEY,
          userText: RECEIPT_USER_TEXT,
          model: config.model,
          baseUrl: config.baseUrl,
          apiKey: config.apiKey,
          file: image,
        });
        raw = list[0];
      }
    } catch (err) {
      console.error(
        `[llm-parse] Receipt read failed for "${file.originalName}" (provider=${config.provider}):`,
        err instanceof Error ? err.message : err,
      );
      return {
        receipt: null,
        warnings: [`${file.originalName}: AI parsing failed: ${err instanceof Error ? err.message : String(err)}`],
      };
    }

    const receipt = toReceiptRead(raw);
    return receipt
      ? { receipt, warnings: [] }
      : { receipt: null, warnings: [`${file.originalName}: no receipt could be read`] };
  }

  private async visionFor(config: ResolvedLlmConfig): Promise<boolean> {
    if (config.vision !== 'auto') return config.vision === 'on';
    // Only a local Ollama can be asked. A cloud model is not assumed to read
    // images: an admin who knows it does says so.
    if (config.provider !== 'local') return false;
    const capabilities = await this.local.modelCapabilities(config.baseUrl, config.model, config.apiKey);
    return capabilities?.includes('vision') ?? false;
  }

  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'], outcome: 'ai_disabled' };

    const warnings: string[] = [];
    const input: LlmExtractionInput = {
      prompt: buildSystemPrompt(),
      jsonSchema: KI_RESERVATION_JSON_SCHEMA,
      model: config.model,
      baseUrl: config.baseUrl,
      apiKey: config.apiKey,
    };
    // The whole extracted text, kept for a second, shorter try (see extractFitting).
    let fullText: string | undefined;
    const longDocument = `${file.originalName}: long document, the middle part was not read`;

    const imageType = imageMimeType(file.originalName);
    if (imageType && !(await this.visionFor(config))) {
      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
    // (its document block reads text AND scans). OpenAI-compatible servers
    // (incl. Ollama/NuExtract) can't ingest PDFs/`file` parts, so every other
    // provider gets extracted text.
    try {
      if (imageType) {
        input.file = await capImage(file.buffer, imageType);
        console.debug(
          `[DEBUG] Photo (${input.file.data.length} bytes) sent to ${config.provider}: ${file.originalName}`,
        );
      } else if (config.provider === 'anthropic' && isPdf(file.originalName)) {
        input.file = { mimeType: MIME_BY_EXT['.pdf'], data: file.buffer };
        // Not for the model, which reads the PDF itself: only to check its prices against (#2651).
        fullText = await extractText(file.buffer, file.originalName).catch(() => undefined);
        console.debug(
          `[DEBUG] Extracted (native PDF, ${file.buffer.length} bytes) sent to ${config.provider}: ${file.originalName}`,
        );
      } else {
        const extracted = await extractText(file.buffer, file.originalName);
        fullText = extracted;
        // Cap the text fed to the model (the windows and why are in text-window.ts). A longer
        // document loses its middle, never its end, where the total is, and the import says so.
        const textWindow =
          config.provider !== 'local'
            ? CLOUD_TEXT_WINDOW
            : detectFlightNumbers(extracted).length > 0
              ? LOCAL_FLIGHT_TEXT_WINDOW
              : LOCAL_TEXT_WINDOW;
        const fitted = fitTextWindow(extracted, textWindow);
        input.text = fitted.text;
        if (fitted.omitted > 0) warnings.push(longDocument);
        // The extracted text IS the booking: traveller name, address, booking
        // reference. On a centrally administered install that would land in the
        // operator's log, which is a processing nobody asked for and nobody needs.
        if (this.env.isManaged()) {
          console.debug(`[DEBUG] Extracted text from ${file.originalName} (${input.text.length} chars)`);
        } else {
          console.debug(`[DEBUG] Extracted text from ${file.originalName} (${input.text.length} chars):\n`, input.text);
        }
        if (!input.text.trim()) {
          // A scan has no text layer, but a model that reads images can read its pages.
          const pages =
            isPdf(file.originalName) && (await this.visionFor(config)) ? await renderPdfPages(file.buffer) : [];
          if (pages.length === 0) {
            return {
              kiItems: [],
              warnings: [
                `${file.originalName}: no readable text found (a scanned PDF needs a model that reads images)`,
              ],
              outcome: 'no_text',
            };
          }
          input.text = undefined;
          input.file = pages[0];
          input.pageImages = pages.slice(1);
          console.debug(
            `[DEBUG] Scanned PDF sent to ${config.provider} as ${pages.length} page image(s): ${file.originalName}`,
          );
        }
      }
    } catch (err) {
      console.error(`[llm-parse] Could not read "${file.originalName}":`, err instanceof Error ? err.message : err);
      return {
        kiItems: [],
        warnings: [`${file.originalName}: could not read file: ${err instanceof Error ? err.message : String(err)}`],
        outcome: failureOutcome(err),
      };
    }

    // Local provider (Ollama): go through the layered extraction router — vendor
    // templates → decompose + grammar-enforced per-reservation extraction → validate
    // + repair. Far more reliable on small CPU models than the single-shot path below
    // (which stays for cloud providers, whose strong models handle one-shot well).
    if (config.provider === 'local' && (input.text || input.file)) {
      try {
        const ctx = {
          baseUrl: config.baseUrl ?? 'http://localhost:11434/v1',
          model: config.model,
          apiKey: config.apiKey,
        };
        const routed = input.file
          ? await routeImageExtraction(
              [input.file, ...(input.pageImages ?? [])].map((f) => f.data),
              ctx,
            )
          : await routeExtraction(input.text ?? '', ctx);
        return { kiItems: routed.kiItems, warnings: [...warnings, ...routed.warnings], outcome: routed.outcome };
      } catch (err) {
        console.error(
          `[llm-parse] AI parsing failed for "${file.originalName}" (provider=${config.provider}):`,
          err instanceof Error ? err.message : err,
        );
        return {
          kiItems: [],
          warnings: [`${file.originalName}: AI parsing failed: ${err instanceof Error ? err.message : String(err)}`],
          outcome: failureOutcome(err),
        };
      }
    }

    let raw: Record<string, unknown>[];
    try {
      raw = await this.extractFitting(input, config, fullText, () => {
        if (!warnings.includes(longDocument)) warnings.push(longDocument);
      });
      // Same reason: the model answers with the fields it read out of the document.
      // Parsed, not raw — this prints the nodes the client already read out of the
      // response, so its single quotes and bare keys are util.inspect's, not the
      // provider's, and a bug report that quotes them is quoting TREK (#2375).
      if (this.env.isManaged()) console.debug(`[DEBUG] LLM response: ${raw.length} item(s)`);
      else console.debug(`[DEBUG] Parsed LLM response (${raw.length} item(s)): `, raw);
    } catch (err) {
      console.error(
        `[llm-parse] AI parsing failed for "${file.originalName}" (provider=${config.provider}):`,
        err instanceof Error ? err.message : err,
      );
      return {
        kiItems: [],
        warnings: [`${file.originalName}: AI parsing failed: ${err instanceof Error ? err.message : String(err)}`],
        outcome: failureOutcome(err),
      };
    }

    const kiItems: KiReservation[] = [];
    // A model can list one stay twice, and did (#1638, #2477): two identical
    // nodes are one booking, not two hotels. Only exact copies, and only on this
    // path; the kitinerary extractor reports what the document holds.
    const seen = new Set<string>();
    for (const node of raw) {
      const result = kiReservationSchema.safeParse(node);
      if (!result.success) {
        warnings.push(`${file.originalName}: skipped an unrecognized AI result`);
        continue;
      }
      const normalized = normalizeCurrency(normalizeNode(result.data), input.text);
      const key = stableKey(normalized);
      if (seen.has(key)) continue;
      seen.add(key);
      kiItems.push(normalized as unknown as KiReservation);
    }

    // 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, outcome: foundOutcome(priced) };
  }

  /**
   * One extraction call, and one more with a shorter text when the server says
   * the prompt does not fit its context. Every cloud provider gets the full
   * window first, OpenAI-compatible gateways included (#2652); a self-hosted
   * server with a small context then gets the compact window instead of failing.
   */
  private async extractFitting(
    input: LlmExtractionInput,
    config: ResolvedLlmConfig,
    fullText: string | undefined,
    onShortened: () => void,
  ): Promise<Record<string, unknown>[]> {
    const client = createLlmClient(config);
    try {
      return await client.extract(input);
    } catch (err) {
      // A PDF read natively has no text window to shorten; a second try would only send more.
      if (
        !(err instanceof LlmContextOverflowError) ||
        input.file ||
        !fullText ||
        fullText.length <= COMPACT_TEXT_WINDOW
      ) {
        throw err;
      }
      input.text = fitTextWindow(fullText, COMPACT_TEXT_WINDOW).text;
      onShortened();
      return await client.extract(input);
    }
  }
}

/** JSON with every object's keys sorted, so two equal nodes give one string. */
function stableKey(value: unknown): string {
  return JSON.stringify(value, (_key, v: unknown) =>
    v && typeof v === 'object' && !Array.isArray(v)
      ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)))
      : v,
  );
}