TPTruPDF

@trupdf/ai

Provider-abstracted LLM engine for Document Summary, Explain Selection, Explain Page, Intelligent Document Extraction (IDE), and Intelligent Document Parsing (IDP). Streaming chat + vision.

Configure via DocViewer

import type { AIConfig } from '@trupdf/viewer';
 
const aiConfig: AIConfig = {
  provider: 'anthropic',
  // Recommended for browser deployments: route through your own proxy
  // that injects the API key server-side — the key never reaches the
  // browser. Alternatively pass apiKey + optInDirectBrowserAccess.
  proxyUrl: '/api/ai-proxy',
};
 
<DocViewer source="…" licenseManager={license} aiConfig={aiConfig} />;

AIConfig

OptionPurpose
provider'anthropic' | 'gemini' | 'openai-compatible'
model?Model override; sensible per-provider defaults (DEFAULT_MODELS)
apiKey?Cloud-provider key; ignored when proxyUrl is set
baseUrl?Required for openai-compatible (any gateway — OpenRouter-style, self-hosted, etc.)
proxyUrl?Send all LLM requests through your server-side proxy (key never leaves the server)
optInDirectBrowserAccess?Explicit opt-in required to use apiKey directly from the browser
onPromptCheck?Hook invoked with the assembled prompt before sending — scrub PII, rewrite, or reject (allow: false aborts with AIError('ABORTED'))
fieldTemplates?Extra IDE field-schema templates
includeBuiltInTemplates?Merge the built-in Invoice / Receipt / Contract / Resume templates (default true)
parsingConcurrency?Parallel LLM calls during IDP (default 4)
maxRetries?Retries for 429 / 5xx (default 2)
requestTimeoutMs?Per-request timeout (default 120 000)
disableCache?Disable the IndexedDB result cache

AIEngine

For programmatic use (no panel):

import { AnthropicProvider } from '@trupdf/ai';
import { AIEngine } from '@trupdf/viewer'; // providers import from @trupdf/ai
 
const ai = new AIEngine({
  config: { provider: 'anthropic', proxyUrl: '/api/ai-proxy' },
  provider: new AnthropicProvider({ proxyUrl: '/api/ai-proxy', model: 'claude-sonnet-4-6' }),
  auditLogger: audit, // optional — ai.* events join your audit timeline
});
ai.setPageProvider(pageProvider); // wires page text / images from the viewer
 
const card = ai.summarize({ docHash, pageCount, mode: 'short' });          // StreamingCard
const sel = ai.explainSelection({ docHash, page, rects, selectedText, action: 'explain' });
const pg  = ai.explainPage({ page, action: 'simplify' });                  // StreamingCard
const res = await ai.extractFields({ schema });                            // ExtractionResult
const doc = await ai.parseDocument({ onProgress });                        // ParsedDocument
ai.destroy();
MethodReturns
setPageProvider(p) / getPageProvider()Wire the viewer's page-content source
summarize(req)StreamingCard (streams chunks as they arrive)
explainSelection(req) / explainPage(req)StreamingCard
extractFields({ schema, signal? })Promise<ExtractionResult> (IDE, one-shot)
parseDocument({ onProgress?, signal? })Promise<ParsedDocument> (IDP)
recordExtractionAudit / recordParsingAudit / recordCacheHitAudit-log helpers
destroy()Aborts all in-flight calls

IDP results export via the emitters toJsonString(doc) / toPlainText(doc).

Providers

import {
  AnthropicProvider,
  GeminiProvider,
  OpenAICompatibleProvider,
  createMcpProvider,
} from '@trupdf/ai';
ProviderNotes
AnthropicProviderClaude models
GeminiProviderGemini models
OpenAICompatibleProviderAny OpenAI-compatible gateway — OpenRouter-style endpoints, self-hosted runtimes
createMcpProvider(opts)On-prem MCP server

Extractors

import {
  TextExtractor, // reads the document's text layer
  OcrExtractor, // the OCR engine — auto-loaded for scanned PDFs
  PageImageExtractor, // rasterises pages to vision-ready PNGs
  ExtractionRouter,
} from '@trupdf/ai';

The router picks the right extractor based on input + secure mode.

FieldSchema

type FieldSchema = Record<string, FieldDef>;
 
type FieldDef =
  | { type: 'string'; required?: boolean; pattern?: string; enum?: string[] }
  | { type: 'number'; required?: boolean; unit?: string; min?: number; max?: number }
  | { type: 'date'; required?: boolean; format?: string }
  | { type: 'boolean'; required?: boolean }
  | { type: 'table'; columns: string[]; required?: boolean }
  | { type: 'object'; fields: FieldSchema };

BUILT_IN_TEMPLATES ships Invoice, Receipt, Contract, and Resume schemas; merge your own via aiConfig.fieldTemplates.

ExtractionResult

interface ExtractedField<T> {
  value: T | null;
  confidence: number; // 0..1
  citations: Citation[];
}
 
interface Citation {
  page: number; // 1-indexed
  rect: PdfRect;
}

UI components

import { AiPanel, IdePanel, IdpPanel, ResultCard, CitationChip } from '@trupdf/ai';

Mountable React components if you want to host the AI surface outside the default right-side panel.

Audit & prompt check

Every provider call passes through the audit chokepoint (ai.* events on the shared AuditLogger). Scrub PII or veto calls before the request hits the network via onPromptCheck:

const aiConfig: AIConfig = {
  provider: 'anthropic',
  proxyUrl: '/api/ai-proxy',
  onPromptCheck: ({ feature, user }) => ({
    allow: true,
    rewrittenUser: user.replace(/\b[\w.-]+@[\w.-]+\.\w+\b/g, '[email]'),
  }),
};

Cache

IndexedDB result cache keyed by SHA-256 of the request content. Disable via aiConfig.disableCache = true.

License gate

new AIEngine(...) requires the ai feature. Trial cannot use AI.