Files
accounted/lib/ai/services/openai-compatible.ts
T
c7a75d069d feat(ai): job-shaped AI service with OpenAI-compatible backend, extraction-first; stop extracting every inbox document twice (#1740)
* feat(ai): job-shaped AI service with OpenAI-compatible backend, extraction-first; stop extracting every inbox document twice

Sovereign plan WS1 PR1 (#1406 Tier 2, extraction-first, aligned with the
AI surface audit).

lib/ai grows a job-shaped service (generateText / generateStructured /
extractFromDocument; no streaming members yet, see plan rule R3):
- services/anthropic-family delegates to the existing createAiClient()
  and sends the exact request literals the inbox extractor sent before
  (request-shape tests deep-equal them), so hosted Bedrock stays
  byte-identical.
- services/openai-compatible talks to any chat-completions endpoint
  (BYO Swedish provider) via Vercel AI SDK 6.x, exact-pinned and
  guarded: images as parts, PDFs rasterized with poppler (AI_PDF_MODE)
  or sent natively, AI_VISION / AI_STRICT_JSON declared, honest skips
  (ai_no_vision, pdf_rasterizer_missing) instead of fake failures.
- config.ts: AI_PROVIDER/AI_BASE_URL/AI_API_KEY/AI_MODEL and per-tier
  AI_*_MODEL with the legacy BEDROCK_* names kept as the same overrides;
  getAiStatus() is the single source of truth for "is AI wired up".
- provider.ts: openai-compatible in the auto-detect chain (after Bedrock
  and the direct API); createAiClient() refuses it loudly.

Document extraction moves onto the service and gets the audit's fixes:
- Inbox documents were extracted TWICE (pipeline A ran inside
  uploadDocument() before the inbox row existed, so its dedupe branch
  never fired; 3 707 + 1 666 calls / 30 d). The inbox now declares
  extractionOwner on the upload, the extension yields, and the inbox
  mirrors its single outcome onto document_attachments from every
  writer (sync, deferred, attach, retry, MCP).
- Every "no extraction will ever happen" outcome is stamped
  (skipped:no_ai_entitlement / ai_unconfigured / system_generated /
  ...); the status route maps the quiet ones to 'disabled' on the first
  poll instead of a 30 s client timeout. Prod showed 309 of the 327
  never-extracted uploads were the paywall working silently.
- Self-generated documents (our own invoice PDFs, payout files) are no
  longer OCR'd.
- Agent invoke answers 503 ai_unconfigured when the deployment has no
  assistant backend, distinct from the paywall.

Guard: new direct-ai-client antipattern check (shrink-only allowlist of
the pre-abstraction SDK callers) plus exact pins for @anthropic-ai/sdk,
ai and @ai-sdk/openai-compatible.

Verified: 15 958 unit tests green, guards, lint ratchet, typecheck, and a
live smoke against hosted Bedrock through the new service (ping, streamed
tool turn, thinking+cache, PDF extraction).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(ai): make AI_API_KEY optional for OpenAI-compatible endpoints (keyless local model servers)

A local model server (llama.cpp's server, Ollama /v1, LM Studio, vLLM)
usually has no auth. Before, the OpenAI-compatible backend required both
AI_BASE_URL and AI_API_KEY to count as configured, so running Accounted on a
local model meant setting a meaningless placeholder key.

- resolveAiProvider / hasAiCredentials: a base URL alone is now enough.
- services/openai-compatible: only send Authorization: Bearer when AI_API_KEY
  is set, so a keyless server is never handed an empty bearer; a hosted
  provider that needs a key still sets it.
- Docs (SELF-HOSTING Option 3: local-model example, key marked optional),
  DECISIONS.

Verified: with no AI_API_KEY, just AI_BASE_URL + AI_MODEL, getAiStatus()
reports configured=true / provider=openai-compatible (live). lib/ai suite
71 green; tsc, guards, lint clean. Bedrock/Anthropic logic unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 19:39:08 +02:00

199 lines
7.5 KiB
TypeScript

import { createOpenAICompatible } from '@ai-sdk/openai-compatible'
import { generateText, jsonSchema, Output, type ModelMessage, type UserContent } from 'ai'
import { capabilitiesFor, type ResolvedAiConfig } from '../config'
import { extractJsonObject } from '../json'
import { rasterizePdf } from '../rasterize-pdf'
import type {
AiDocumentInput,
AiService,
AiTier,
AiUsage,
ExtractFromDocumentRequest,
ExtractFromDocumentResult,
ExtractionSkipReason,
GenerateStructuredRequest,
GenerateStructuredResult,
GenerateTextRequest,
GenerateTextResult,
} from '../types'
/**
* Any endpoint speaking the OpenAI chat-completions API, through the Vercel
* AI SDK's openai-compatible provider. This is the sovereign self-host path:
* the operator points AI_BASE_URL + AI_API_KEY at a Swedish inference
* provider (Berget AI, evroc, ...) and names the models per tier.
*
* Scope discipline: the AI SDK is used ONLY here. The hosted Bedrock /
* direct-API path stays on the Anthropic SDK (services/anthropic-family.ts)
* and no call site imports `ai` directly (antipattern guard direct-ai-client).
*
* Provider quirks this has to absorb, by design choice:
* - PDFs: most such endpoints have no PDF part; the default is to rasterize
* the first pages with poppler (AI_PDF_MODE=rasterize). Operators whose
* provider accepts the OpenAI `file` part can set AI_PDF_MODE=native.
* - Vision: AI_VISION=false declares a text-only model; images and PDFs are
* then skipped honestly (`ai_no_vision`) instead of failing with a 400.
* HTML mail invoices arrive as text and extract on every model.
* - JSON: the default is JSON-in-prose plus the caller's extraction + Zod,
* which works everywhere; AI_STRICT_JSON=true opts into response_format
* json_schema for providers that enforce it.
*/
export function createOpenAICompatibleService(cfg: ResolvedAiConfig): AiService {
const provider = createOpenAICompatible({
name: 'accounted-byo',
baseURL: cfg.baseUrl ?? '',
// Only send a key when one is configured: a keyless local server would
// reject or ignore an empty Bearer, and omitting it means no auth header.
...(cfg.apiKey ? { apiKey: cfg.apiKey } : {}),
supportsStructuredOutputs: cfg.strictJson,
})
const capabilities = capabilitiesFor(cfg)
const modelFor = (tier: AiTier): string => {
const id = cfg.models[tier]
if (!id) throw new Error(`No AI model configured for tier "${tier}" (set AI_MODEL or AI_${tier.toUpperCase()}_MODEL)`)
return id
}
function usageOf(result: { usage: { inputTokens?: number; outputTokens?: number; inputTokenDetails?: { cacheReadTokens?: number; cacheWriteTokens?: number } } }): AiUsage {
const u = result.usage
return {
inputTokens: u.inputTokens ?? null,
outputTokens: u.outputTokens ?? null,
cacheCreationInputTokens: u.inputTokenDetails?.cacheWriteTokens ?? null,
cacheReadInputTokens: u.inputTokenDetails?.cacheReadTokens ?? null,
}
}
async function buildUserContent(
document: AiDocumentInput,
instruction: string
): Promise<
| { ok: true; content: UserContent; pagesRasterized?: number }
| { ok: false; skipped: ExtractionSkipReason }
> {
const tail = { type: 'text' as const, text: instruction }
if (document.kind === 'text') {
return { ok: true, content: [{ type: 'text', text: document.text }, tail] }
}
if (!capabilities.imageInput) return { ok: false, skipped: 'ai_no_vision' }
if (document.kind === 'image') {
return {
ok: true,
content: [{ type: 'image', image: document.data, mediaType: document.mediaType }, tail],
}
}
// PDF
if (capabilities.pdfNative) {
return {
ok: true,
content: [
{
type: 'file',
data: document.data,
mediaType: 'application/pdf',
...(document.fileName ? { filename: document.fileName } : {}),
},
tail,
],
}
}
const raster = await rasterizePdf(document.data, { maxPages: cfg.pdfMaxPages })
if (!raster.ok) {
return {
ok: false,
skipped: raster.reason === 'rasterizer_missing' ? 'pdf_rasterizer_missing' : 'pdf_rasterize_failed',
}
}
return {
ok: true,
pagesRasterized: raster.pageCount,
content: [
...raster.pages.map((page) => ({ type: 'image' as const, image: page, mediaType: raster.mediaType })),
tail,
],
}
}
return {
provider: cfg.provider,
capabilities,
modelFor,
async generateText(req: GenerateTextRequest): Promise<GenerateTextResult> {
const model = modelFor(req.tier)
const result = await generateText({
model: provider(model),
...(req.system ? { system: req.system } : {}),
prompt: req.prompt,
maxOutputTokens: req.maxTokens,
})
return { text: result.text.trim(), model, usage: usageOf(result) }
},
async generateStructured(req: GenerateStructuredRequest): Promise<GenerateStructuredResult> {
const model = modelFor(req.tier)
if (cfg.strictJson) {
const result = await generateText({
model: provider(model),
...(req.system ? { system: req.system } : {}),
prompt: req.prompt,
maxOutputTokens: req.maxTokens,
output: Output.object({ schema: jsonSchema<Record<string, unknown>>(req.schema.jsonSchema) }),
})
return { value: result.output, model, usage: usageOf(result) }
}
// Prose JSON: ask for the shape in the prompt, then pull the first
// parseable object out of whatever the model wrapped it in.
const schemaHint =
`Answer with ONLY a single JSON object${req.schema.description ? ` (${req.schema.description})` : ''}` +
` matching this JSON Schema, no prose, no markdown fences:\n${JSON.stringify(req.schema.jsonSchema)}`
const result = await generateText({
model: provider(model),
system: req.system ? `${req.system}\n\n${schemaHint}` : schemaHint,
prompt: req.prompt,
maxOutputTokens: req.maxTokens,
})
const value: unknown = JSON.parse(extractJsonObject(result.text))
return { value, model, usage: usageOf(result) }
},
async extractFromDocument(req: ExtractFromDocumentRequest): Promise<ExtractFromDocumentResult> {
if (!cfg.configured) return { ok: false, skipped: 'ai_unconfigured' }
const model = modelFor('extraction')
const built = await buildUserContent(req.document, req.instruction)
if (!built.ok) return { ok: false, skipped: built.skipped }
const messages: ModelMessage[] = [{ role: 'user', content: built.content }]
if (cfg.strictJson && req.jsonSchema) {
const result = await generateText({
model: provider(model),
system: req.system,
messages,
maxOutputTokens: req.maxTokens,
output: Output.object({ schema: jsonSchema<Record<string, unknown>>(req.jsonSchema) }),
})
return {
ok: true,
text: JSON.stringify(result.output),
model,
usage: usageOf(result),
...(built.pagesRasterized ? { pagesRasterized: built.pagesRasterized } : {}),
}
}
const result = await generateText({
model: provider(model),
system: req.system,
messages,
maxOutputTokens: req.maxTokens,
})
return {
ok: true,
text: result.text.trim(),
model,
usage: usageOf(result),
...(built.pagesRasterized ? { pagesRasterized: built.pagesRasterized } : {}),
}
},
}
}