c7a75d069d
* 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>
227 lines
7.7 KiB
TypeScript
227 lines
7.7 KiB
TypeScript
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
|
import { getAiStatus, readAiConfig, resolveTierModel } from '../config'
|
|
import { createAiClient, AiProviderUnsupportedError, hasAiCredentials, resolveAiProvider, toProviderModelId } from '../provider'
|
|
|
|
const KEYS = [
|
|
'AI_PROVIDER',
|
|
'AI_BASE_URL',
|
|
'AI_API_KEY',
|
|
'AI_MODEL',
|
|
'AI_ASSISTANT_MODEL',
|
|
'AI_HEAVY_MODEL',
|
|
'AI_EXTRACTION_MODEL',
|
|
'AI_EXTRACTION_MAX_TOKENS',
|
|
'AI_VISION',
|
|
'AI_STRICT_JSON',
|
|
'AI_PDF_MODE',
|
|
'AI_PDF_MAX_PAGES',
|
|
'ANTHROPIC_API_KEY',
|
|
'AWS_ACCESS_KEY_ID',
|
|
'AWS_SECRET_ACCESS_KEY',
|
|
'AWS_REGION',
|
|
'BEDROCK_MODEL_ID',
|
|
'BEDROCK_SONNET_MODEL_ID',
|
|
'BEDROCK_OPUS_MODEL_ID',
|
|
'BEDROCK_MAX_TOKENS',
|
|
] as const
|
|
|
|
let saved: Partial<Record<(typeof KEYS)[number], string | undefined>> = {}
|
|
beforeEach(() => {
|
|
saved = {}
|
|
for (const k of KEYS) {
|
|
saved[k] = process.env[k]
|
|
delete process.env[k]
|
|
}
|
|
})
|
|
afterEach(() => {
|
|
for (const k of KEYS) {
|
|
if (saved[k] === undefined) delete process.env[k]
|
|
else process.env[k] = saved[k]
|
|
}
|
|
})
|
|
|
|
function hosted() {
|
|
process.env.AWS_ACCESS_KEY_ID = 'AKIAEXAMPLE'
|
|
process.env.AWS_SECRET_ACCESS_KEY = 'secret'
|
|
}
|
|
function byo(model = 'google/gemma-4-31B-it') {
|
|
process.env.AI_BASE_URL = 'https://api.berget.ai/v1'
|
|
process.env.AI_API_KEY = 'sk-berget-example'
|
|
if (model) process.env.AI_MODEL = model
|
|
}
|
|
|
|
describe('provider resolution with an OpenAI-compatible endpoint', () => {
|
|
it('auto-detects AI_BASE_URL + AI_API_KEY when no Anthropic-family credentials exist', () => {
|
|
byo()
|
|
expect(resolveAiProvider()).toBe('openai-compatible')
|
|
expect(hasAiCredentials()).toBe(true)
|
|
})
|
|
|
|
// Hosted stays hosted: a stray BYO pair must never move inference.
|
|
it('keeps Bedrock ahead of a BYO endpoint when static AWS keys are present', () => {
|
|
hosted()
|
|
byo()
|
|
expect(resolveAiProvider()).toBe('bedrock')
|
|
})
|
|
|
|
it('keeps the direct Anthropic API ahead of a BYO endpoint', () => {
|
|
process.env.ANTHROPIC_API_KEY = 'sk-ant-api03-example'
|
|
byo()
|
|
expect(resolveAiProvider()).toBe('anthropic')
|
|
})
|
|
|
|
it('honours AI_PROVIDER=openai-compatible as the explicit escape hatch', () => {
|
|
hosted()
|
|
byo()
|
|
process.env.AI_PROVIDER = 'openai-compatible'
|
|
expect(resolveAiProvider()).toBe('openai-compatible')
|
|
})
|
|
|
|
// AI_API_KEY is optional: a local OpenAI-compatible server usually has no
|
|
// auth, so a base URL alone counts as configured. A key is added only when
|
|
// the endpoint requires one.
|
|
it('counts a base URL alone as credentials (keyless local server)', () => {
|
|
process.env.AI_PROVIDER = 'openai-compatible'
|
|
process.env.AI_BASE_URL = 'http://localhost:11434/v1'
|
|
expect(hasAiCredentials()).toBe(true)
|
|
})
|
|
|
|
it('is not configured with no base URL at all', () => {
|
|
process.env.AI_PROVIDER = 'openai-compatible'
|
|
expect(hasAiCredentials()).toBe(false)
|
|
})
|
|
|
|
it('passes bare model ids through untouched', () => {
|
|
expect(toProviderModelId('google/gemma-4-31B-it', 'openai-compatible')).toBe('google/gemma-4-31B-it')
|
|
})
|
|
|
|
// The chat loop and the other direct SDK callers cannot run here: fail
|
|
// loudly at construction rather than with an opaque error at call time.
|
|
it('refuses to build an Anthropic client for it', () => {
|
|
byo()
|
|
expect(() => createAiClient()).toThrow(AiProviderUnsupportedError)
|
|
})
|
|
})
|
|
|
|
describe('resolveTierModel precedence', () => {
|
|
it('defaults every tier to Claude on the Anthropic family', () => {
|
|
hosted()
|
|
expect(resolveTierModel('assistant')).toBe('claude-sonnet-5')
|
|
expect(resolveTierModel('heavy')).toBe('claude-sonnet-5')
|
|
expect(resolveTierModel('extraction')).toBe('claude-sonnet-5')
|
|
})
|
|
|
|
// Hosted operators set BEDROCK_* today; those must keep winning over the
|
|
// new generic AI_MODEL so a migration to the new names is a no-op until
|
|
// someone deliberately moves.
|
|
it('lets the legacy Bedrock tier variables beat AI_MODEL, and AI_<TIER>_MODEL beat both', () => {
|
|
hosted()
|
|
process.env.AI_MODEL = 'generic'
|
|
process.env.BEDROCK_MODEL_ID = 'legacy-extraction'
|
|
process.env.BEDROCK_SONNET_MODEL_ID = 'legacy-assistant'
|
|
process.env.BEDROCK_OPUS_MODEL_ID = 'legacy-heavy'
|
|
expect(resolveTierModel('extraction')).toBe('legacy-extraction')
|
|
expect(resolveTierModel('assistant')).toBe('legacy-assistant')
|
|
expect(resolveTierModel('heavy')).toBe('legacy-heavy')
|
|
|
|
process.env.AI_EXTRACTION_MODEL = 'specific-extraction'
|
|
expect(resolveTierModel('extraction')).toBe('specific-extraction')
|
|
})
|
|
|
|
it('has no default on an OpenAI-compatible endpoint', () => {
|
|
byo('')
|
|
expect(resolveTierModel('extraction')).toBeNull()
|
|
process.env.AI_MODEL = 'x'
|
|
expect(resolveTierModel('extraction')).toBe('x')
|
|
process.env.AI_EXTRACTION_MODEL = 'y'
|
|
expect(resolveTierModel('extraction')).toBe('y')
|
|
expect(resolveTierModel('assistant')).toBe('x')
|
|
})
|
|
})
|
|
|
|
describe('readAiConfig', () => {
|
|
it('reads the extraction output cap from the new name, then the legacy name, then 8192', () => {
|
|
hosted()
|
|
expect(readAiConfig().extractionMaxTokens).toBe(8192)
|
|
process.env.BEDROCK_MAX_TOKENS = '4000'
|
|
expect(readAiConfig().extractionMaxTokens).toBe(4000)
|
|
process.env.AI_EXTRACTION_MAX_TOKENS = '12000'
|
|
expect(readAiConfig().extractionMaxTokens).toBe(12000)
|
|
})
|
|
|
|
// A deliberate `0` is an invalid configuration, not "disable": fall back.
|
|
it('ignores non-positive or garbage token caps', () => {
|
|
hosted()
|
|
process.env.AI_EXTRACTION_MAX_TOKENS = '0'
|
|
expect(readAiConfig().extractionMaxTokens).toBe(8192)
|
|
process.env.AI_EXTRACTION_MAX_TOKENS = 'lots'
|
|
expect(readAiConfig().extractionMaxTokens).toBe(8192)
|
|
})
|
|
|
|
it('rasterizes PDFs by default on OpenAI-compatible endpoints and reads them natively on Claude', () => {
|
|
byo()
|
|
expect(readAiConfig().pdfMode).toBe('rasterize')
|
|
process.env.AI_PDF_MODE = 'native'
|
|
expect(readAiConfig().pdfMode).toBe('native')
|
|
})
|
|
|
|
it('reads PDFs natively on the Anthropic family regardless', () => {
|
|
hosted()
|
|
expect(readAiConfig().pdfMode).toBe('native')
|
|
})
|
|
|
|
it('parses the boolean flags with sane defaults', () => {
|
|
byo()
|
|
expect(readAiConfig().vision).toBe(true)
|
|
expect(readAiConfig().strictJson).toBe(false)
|
|
process.env.AI_VISION = 'false'
|
|
process.env.AI_STRICT_JSON = '1'
|
|
expect(readAiConfig().vision).toBe(false)
|
|
expect(readAiConfig().strictJson).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('getAiStatus', () => {
|
|
it('is unconfigured with a reason when nothing is set', () => {
|
|
const s = getAiStatus()
|
|
expect(s.configured).toBe(false)
|
|
expect(s.reason).toBe('no_credentials')
|
|
expect(s.assistantAvailable).toBe(false)
|
|
})
|
|
|
|
it('is configured and assistant-capable on hosted', () => {
|
|
hosted()
|
|
const s = getAiStatus()
|
|
expect(s.provider).toBe('bedrock')
|
|
expect(s.configured).toBe(true)
|
|
expect(s.assistantAvailable).toBe(true)
|
|
expect(s.capabilities.pdfNative).toBe(true)
|
|
expect(s.models.extraction).toBe('eu.anthropic.claude-sonnet-5')
|
|
})
|
|
|
|
it('needs a model id on an OpenAI-compatible endpoint before it counts as configured', () => {
|
|
byo('')
|
|
const s = getAiStatus()
|
|
expect(s.configured).toBe(false)
|
|
expect(s.reason).toBe('no_model')
|
|
})
|
|
|
|
// Extraction and single-call jobs run; the chat loop does not (yet).
|
|
it('is configured but not assistant-capable on an OpenAI-compatible endpoint', () => {
|
|
byo()
|
|
const s = getAiStatus()
|
|
expect(s.provider).toBe('openai-compatible')
|
|
expect(s.configured).toBe(true)
|
|
expect(s.assistantAvailable).toBe(false)
|
|
expect(s.capabilities.pdfNative).toBe(false)
|
|
expect(s.capabilities.imageInput).toBe(true)
|
|
expect(s.models.extraction).toBe('google/gemma-4-31B-it')
|
|
})
|
|
|
|
it('reports AI_VISION=false as no image input', () => {
|
|
byo()
|
|
process.env.AI_VISION = 'false'
|
|
expect(getAiStatus().capabilities.imageInput).toBe(false)
|
|
})
|
|
})
|