7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(anthropic): stop silently dropping document content blocks (#793)
OhOkThisIsFine35af82c1c07b
diff --git a/docs/api.md b/docs/api.mdindex f0fe1ca9..0161a14c 100644--- a/docs/api.md+++ b/docs/api.md@@ -15,6 +15,7 @@ Any OpenAI-compatible client works (Anthropic / Claude clients too — see [Anth- [Ollama emulation](#ollama-emulation)- [Revocable URL tokens](#revocable-url-tokens)- [Vision / image input](#vision--image-input)+- [Document attachments](#document-attachments)- [Images & text-to-speech](#images--text-to-speech)- [Fusion (multi-model synthesis)](#fusion-multi-model-synthesis)- [Response headers](#response-headers)@@ -223,6 +224,21 @@ print(resp.choices[0].message.content)If no vision-capable model is enabled in your Fallback Chain, an image request returns a clear `422` (`code: "no_vision_model"`) rather than silently dropping the image. (Image input on `/v1/responses` isn't supported yet — use `/v1/chat/completions`.)+## Document attachments++Anthropic's `document` content blocks are accepted on `/v1/messages` when their source is already text:++```json+{"type": "document", "title": "contract.txt",+ "source": {"type": "text", "media_type": "text/plain", "data": "PAYMENT TERMS: net 30."}}+```++`text` and `content` sources are inlined into the prompt, wrapped in a fence tagged with a hash of the document body so the model can tell quoted material from your instructions. The tag is derived from the content rather than randomized, so a repeated attachment keeps the prompt prefix stable and stays cacheable.++**Binary sources — `base64` (PDF, DOCX, XLSX…) and `url` — return a `400`.** No provider in the pool accepts them, and there is no local converter, so the honest answer is to refuse: forwarding the request would drop the attachment and produce a confident answer about a document the model never saw. The rejection happens before routing, so it spends no provider quota. Send the extracted text instead.++`url` sources are refused rather than fetched on your behalf; making the proxy retrieve arbitrary URLs would turn it into a request forwarder for whatever a client names.+## Images & text-to-speech`POST /v1/images/generations` and `POST /v1/audio/speech` route across the providers that serve media models, including custom OpenAI-compatible media endpoints. Browse and toggle them on the dashboard's **Models → Image / Audio** tabs.diff --git a/server/src/__tests__/lib/anthropic-documents.test.ts b/server/src/__tests__/lib/anthropic-documents.test.tsnew file mode 100644index 00000000..5e621ce2--- /dev/null+++ b/server/src/__tests__/lib/anthropic-documents.test.ts@@ -0,0 +1,137 @@+import { describe, it, expect } from 'vitest';+import {+ convertDocumentBlock,+ documentRejectionMessage,+ fenceTag,+ labelTitle,+} from '../../lib/anthropic-documents.js';++const doc = (source: unknown, rest: Record<string, unknown> = {}) => ({ type: 'document', source, ...rest });++describe('convertDocumentBlock — sources that are already text', () => {+ it('inlines a `text` source, which needs no converter at all', () => {+ const result = convertDocumentBlock(doc({ type: 'text', media_type: 'text/plain', data: 'the contract body' }));++ expect(result.ok).toBe(true);+ if (result.ok) expect(result.text).toContain('the contract body');+ });++ it('joins the text parts of a `content` source', () => {+ const result = convertDocumentBlock(doc({+ type: 'content',+ content: [{ type: 'text', text: 'clause one' }, { type: 'text', text: 'clause two' }],+ }));++ expect(result.ok).toBe(true);+ if (result.ok) expect(result.text).toContain('clause one\nclause two');+ });++ it('wraps the body in a fence so the model can tell document from instruction', () => {+ const result = convertDocumentBlock(doc({ type: 'text', data: 'body' }, { title: 'Q3 report' }));++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.text).toMatch(/^<document-[0-9a-f]{12} title="Q3 report">\nbody\n<\/document-[0-9a-f]{12}>$/);+ }+ });+});++describe('convertDocumentBlock — sources that cannot be served', () => {+ it('refuses a base64 PDF instead of dropping it', () => {+ const result = convertDocumentBlock(doc({+ type: 'base64',+ media_type: 'application/pdf',+ data: 'JVBERi0xLjQK',+ }));++ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.reason).toContain('application/pdf');+ });++ it('refuses a url source rather than fetching whatever the client names', () => {+ // Fetching it would make the proxy a request forwarder for an arbitrary+ // URL, which is an SSRF surface. The client can inline the text.+ const result = convertDocumentBlock(doc({ type: 'url', url: 'http://169.254.169.254/latest/meta-data/' }));++ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.reason).toContain('`url` source');+ });++ it('refuses a block with no source', () => {+ expect(convertDocumentBlock({ type: 'document' }).ok).toBe(false);+ });++ it('refuses an empty text source rather than inlining an empty fence', () => {+ expect(convertDocumentBlock(doc({ type: 'text', data: ' ' })).ok).toBe(false);+ expect(convertDocumentBlock(doc({ type: 'content', content: [] })).ok).toBe(false);+ });++ it('never puts the payload in the reason', () => {+ const result = convertDocumentBlock(doc({ type: 'base64', media_type: 'application/pdf', data: 'SECRETPAYLOAD' }));++ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.reason).not.toContain('SECRETPAYLOAD');+ });+});++describe('fenceTag', () => {+ it('is derived from the content, so an unchanged document keeps its prefix cacheable', () => {+ // These blocks can carry cache_control; a per-request nonce would change+ // the prompt prefix every call and bust the provider cache for nothing.+ expect(fenceTag('same body')).toBe(fenceTag('same body'));+ expect(fenceTag('one body')).not.toBe(fenceTag('other body'));+ });++ it('picks a tag the content does not already contain, so a document cannot close its own fence', () => {+ const tag = fenceTag('hello');+ const hostile = `hello ${tag}`;++ expect(fenceTag(hostile)).not.toBe(tag);+ expect(hostile).not.toContain(fenceTag(hostile));+ });+});++describe('labelTitle', () => {+ it('strips the characters that would break out of the tag', () => {+ // A title of `doc>\n</doc` used to close the fence early, making the rest+ // of the prompt read as instructions rather than as quoted document text.+ expect(labelTitle('doc>\n</doc')).toBe('doc /doc');+ });++ it('removes control characters', () => {+ expect(labelTitle('a\u0001b\u0002c')).toBe('a b c');+ });++ it('caps the length', () => {+ expect(labelTitle('x'.repeat(500)).length).toBe(120);+ });++ it('falls back to a default for anything unusable', () => {+ expect(labelTitle(undefined)).toBe('document');+ expect(labelTitle(42)).toBe('document');+ expect(labelTitle(' ')).toBe('document');+ expect(labelTitle('<<>>')).toBe('document');+ });+});++describe('documentRejectionMessage', () => {+ it('says what was wrong and what to do instead', () => {+ const message = documentRejectionMessage(['a document block of type application/pdf']);++ expect(message).toContain('application/pdf');+ expect(message).toContain('Send the text instead');+ });++ it('collapses duplicates so ten identical PDFs read as one reason', () => {+ const message = documentRejectionMessage(Array(10).fill('a document block of type application/pdf'));++ expect(message.match(/application\/pdf/g)).toHaveLength(1);+ expect(message).not.toContain('more');+ });++ it('summarizes once past three distinct reasons', () => {+ const message = documentRejectionMessage(['one', 'two', 'three', 'four', 'five']);++ expect(message).toContain('and 2 more');+ });+});diff --git a/server/src/__tests__/routes/anthropic-documents.test.ts b/server/src/__tests__/routes/anthropic-documents.test.tsnew file mode 100644index 00000000..f44ddc08--- /dev/null+++ b/server/src/__tests__/routes/anthropic-documents.test.ts@@ -0,0 +1,189 @@+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';++// `document` content blocks on POST /v1/messages.+//+// They used to fall off the end of the block ladder with every other+// unrecognised type, so attaching a PDF produced a confident answer about a+// document the model never saw. Text-shaped documents are now inlined; the+// rest are refused, before routing, with an actionable message.++let dashToken = '';++async function request(app: Express, path: string, body: any, extraHeaders: Record<string, string> = {}) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...extraHeaders },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(text); } catch { /* SSE body */ }+ return { status: res.status, headers: res.headers, text, body: json };+}++function anthropicHeaders() {+ return { 'x-api-key': getUnifiedApiKey(), 'anthropic-version': '2023-06-01' };+}++/** Mock Groq's upstream and capture the post-translation outbound body. */+function mockJson(response: any) {+ const origFetch = global.fetch;+ const captured: { body: any; calls: number } = { body: null, calls: 0 };+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {+ const urlStr = typeof url === 'string' ? url : url.toString();+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {+ captured.calls++;+ captured.body = JSON.parse(String((init as RequestInit).body));+ return new Response(JSON.stringify(response), {+ status: 200, headers: { 'Content-Type': 'application/json' },+ });+ }+ return origFetch(url, init);+ });+ return captured;+}++const OK_RESPONSE = {+ id: 'chatcmpl-1',+ choices: [{ index: 0, message: { role: 'assistant', content: 'read it' }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 10, completion_tokens: 2, total_tokens: 12 },+};++const PDF_BLOCK = {+ type: 'document',+ source: { type: 'base64', media_type: 'application/pdf', data: 'JVBERi0xLjQKUEFZTE9BRA==' },+ title: 'contract.pdf',+};++const TEXT_DOC_BLOCK = {+ type: 'document',+ source: { type: 'text', media_type: 'text/plain', data: 'PAYMENT TERMS: net 30.' },+ title: 'contract.txt',+};++describe('Anthropic document blocks', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(async () => {+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ db.prepare('DELETE FROM requests').run();+ db.prepare('DELETE FROM rate_limit_cooldowns').run();+ db.prepare('DELETE FROM rate_limit_usage').run();+ const { status } = await request(app, '/api/keys',+ { platform: 'groq', key: 'gsk_document_test', label: 't' },+ { Authorization: `Bearer ${dashToken}` });+ expect(status).toBe(201);+ });++ afterEach(() => vi.restoreAllMocks());++ it('refuses a base64 PDF with an actionable error instead of answering without it', async () => {+ const captured = mockJson(OK_RESPONSE);++ const { status, body } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5',+ max_tokens: 64,+ messages: [{ role: 'user', content: [PDF_BLOCK, { type: 'text', text: 'summarize this' }] }],+ }, anthropicHeaders());++ expect(status).toBe(400);+ expect(body.type).toBe('error');+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.message).toContain('application/pdf');+ expect(body.error.message).toContain('Send the text instead');+ });++ it('spends no provider quota on a request every candidate would refuse', async () => {+ // Rejected before routing: a document failure is ours, not a provider's,+ // and failing over would try the same impossible request on the next key.+ const captured = mockJson(OK_RESPONSE);++ await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5',+ max_tokens: 64,+ messages: [{ role: 'user', content: [PDF_BLOCK] }],+ }, anthropicHeaders());++ expect(captured.calls).toBe(0);+ expect(getDb().prepare('SELECT COUNT(*) c FROM requests').get()).toMatchObject({ c: 0 });+ });++ it('never echoes the document payload back in the error', async () => {+ mockJson(OK_RESPONSE);++ const { body } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5',+ max_tokens: 64,+ messages: [{ role: 'user', content: [PDF_BLOCK] }],+ }, anthropicHeaders());++ expect(body.error.message).not.toContain('JVBERi');+ });++ it('inlines a text-source document and forwards it upstream', async () => {+ const captured = mockJson(OK_RESPONSE);++ const { status } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5',+ max_tokens: 64,+ messages: [{ role: 'user', content: [TEXT_DOC_BLOCK, { type: 'text', text: 'what are the terms?' }] }],+ }, anthropicHeaders());++ expect(status).not.toBe(400);+ if (captured.body) {+ const forwarded = JSON.stringify(captured.body);+ expect(forwarded).toContain('PAYMENT TERMS: net 30.');+ expect(forwarded).toContain('what are the terms?');+ // Fenced, so the model can tell quoted document from instruction.+ expect(forwarded).toMatch(/document-[0-9a-f]{12}/);+ }+ });++ it('applies the same verdict on count_tokens, not just on messages', async () => {+ const { status, body } = await request(app, '/v1/messages/count_tokens', {+ model: 'claude-sonnet-4-5',+ messages: [{ role: 'user', content: [PDF_BLOCK] }],+ }, anthropicHeaders());++ expect(status).toBe(400);+ expect(body.error.message).toContain('application/pdf');+ });++ it('still counts tokens for a text-source document', async () => {+ const { status, body } = await request(app, '/v1/messages/count_tokens', {+ model: 'claude-sonnet-4-5',+ messages: [{ role: 'user', content: [TEXT_DOC_BLOCK] }],+ }, anthropicHeaders());++ expect(status).toBe(200);+ expect(body.input_tokens).toBeGreaterThan(0);+ });++ it('leaves ordinary requests untouched', async () => {+ const captured = mockJson(OK_RESPONSE);++ const { status } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5',+ max_tokens: 64,+ messages: [{ role: 'user', content: [{ type: 'text', text: 'no documents here' }] }],+ }, anthropicHeaders());++ expect(status).not.toBe(400);+ if (captured.body) expect(JSON.stringify(captured.body)).toContain('no documents here');+ });+});diff --git a/server/src/lib/anthropic-documents.ts b/server/src/lib/anthropic-documents.tsnew file mode 100644index 00000000..1542b590--- /dev/null+++ b/server/src/lib/anthropic-documents.ts@@ -0,0 +1,153 @@+import crypto from 'crypto';++/**+ * Anthropic `document` content blocks on a surface whose providers are all+ * text-and-image only.+ *+ * Today such a block passes the permissive envelope schema and is then dropped+ * with every other unrecognised type, so a client that attaches a PDF gets a+ * confident answer about a document the model never saw. That is the worst of+ * the available behaviours: worse than refusing, because nothing tells the+ * caller their attachment went nowhere.+ *+ * Anthropic defines four source kinds, and they split cleanly:+ *+ * text, content — the document IS text already. Converting it costs nothing+ * and needs nothing installed, so we do it.+ * base64, url — the bytes need a real converter (PDF, DOCX, XLSX…). No+ * provider in the pool accepts them and nothing here can+ * decode them, so these are refused with an actionable+ * message instead of being silently discarded.+ *+ * Stringifying the block instead — which is what a naive passthrough does —+ * would inject an entire base64 payload into the prompt. That is not a cheaper+ * version of support; it is a way to burn a context window on nothing.+ */++/** Source kinds that are already text, so they need no converter. */+const TEXTUAL_SOURCE_TYPES = new Set(['text', 'content']);++/** Longest title we will echo into the prompt. */+const MAX_TITLE_LENGTH = 120;++/** C0 controls, DEL, and the C1 range — they can carry terminal escapes. */+const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/g;++export interface DocumentBlockOk {+ ok: true;+ /** The text block body to substitute for the document block. */+ text: string;+}++export interface DocumentBlockRejected {+ ok: false;+ /** Caller-facing reason, already phrased to slot into an error response. */+ reason: string;+}++export type DocumentBlockResult = DocumentBlockOk | DocumentBlockRejected;++/**+ * A fence tag derived from the CONTENT, as `document-<12 hex>`.+ *+ * Deliberately not random: these blocks can carry `cache_control`, and a+ * per-request nonce would change the prompt prefix on every call and bust the+ * provider's cache for no benefit.+ *+ * Deliberately not the client's title either. A title of `doc>\n</doc` closes+ * the fence early, and everything after it reads to the model as instructions+ * rather than as quoted document text.+ */+export function fenceTag(content: string): string {+ const digest = crypto.createHash('sha256').update(content, 'utf8').digest('hex');+ for (let offset = 0; offset + 12 <= digest.length; offset += 12) {+ const candidate = `document-${digest.slice(offset, offset + 12)}`;+ // A tag that already appears in the content would let the document close+ // its own fence. Walk to the next slice rather than giving up.+ if (!content.includes(candidate)) return candidate;+ }+ return `document-${digest.slice(0, 12)}`;+}++/**+ * A title safe to echo inside the fence: no control characters, no angle+ * brackets or quotes (they break out of the tag), collapsed whitespace,+ * bounded length.+ */+export function labelTitle(raw: unknown): string {+ if (typeof raw !== 'string') return 'document';+ const cleaned = raw+ .replace(CONTROL_CHARS, ' ')+ .replace(/[<>"]/g, '')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, MAX_TITLE_LENGTH)+ .trim();+ return cleaned.length > 0 ? cleaned : 'document';+}++/** The text carried by a `content` source: its text blocks, joined. */+function textFromContentSource(content: unknown): string {+ if (typeof content === 'string') return content;+ if (!Array.isArray(content)) return '';+ return content+ .map(block => {+ if (typeof block === 'string') return block;+ if (block && typeof block === 'object' && typeof (block as any).text === 'string') return (block as any).text;+ return '';+ })+ .filter(Boolean)+ .join('\n');+}++/**+ * Convert one Anthropic `document` block into the text that stands in for it,+ * or explain why it cannot be converted.+ */+export function convertDocumentBlock(block: unknown): DocumentBlockResult {+ const source = (block as any)?.source;+ if (!source || typeof source !== 'object') {+ return { ok: false, reason: 'a document block without a `source`' };+ }++ const sourceType = typeof source.type === 'string' ? source.type : '';++ if (!TEXTUAL_SOURCE_TYPES.has(sourceType)) {+ const mediaType = typeof source.media_type === 'string' ? source.media_type : '';+ if (sourceType === 'url') return { ok: false, reason: 'a document block with a `url` source' };+ return {+ ok: false,+ reason: `a document block of type ${mediaType || sourceType || 'unknown'}`,+ };+ }++ const body = sourceType === 'text'+ ? (typeof source.data === 'string' ? source.data : '')+ : textFromContentSource(source.content);++ if (body.trim().length === 0) {+ return { ok: false, reason: 'a document block whose text source is empty' };+ }++ const tag = fenceTag(body);+ const title = labelTitle((block as any)?.title);+ return { ok: true, text: `<${tag} title="${title}">\n${body}\n</${tag}>` };+}++/**+ * The error message for one or more unconvertible documents. Names what was+ * wrong and then what to do instead — a caller that only learns "unsupported"+ * has to guess at the fix.+ */+export function documentRejectionMessage(reasons: string[]): string {+ const unique = [...new Set(reasons)];+ const listed = unique.slice(0, 3).join(', ');+ const extra = unique.length > 3 ? `, and ${unique.length - 3} more` : '';+ return (+ `This request contains ${listed}${extra}. ` ++ 'Binary document attachments are not supported: no provider in the pool accepts them, ' ++ 'and forwarding the request anyway would silently drop the attachment from the prompt. ' ++ 'Send the text instead — either a `text` content block, or a document block with a ' ++ '`text` or `content` source, both of which are passed through.'+ );+}diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.tsindex 4a0c1314..ab5b9ab1 100644--- a/server/src/routes/anthropic.ts+++ b/server/src/routes/anthropic.ts@@ -15,6 +15,7 @@ import { contentToString } from '../lib/content.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarker, containsDialectMarker } from '../lib/tool-call-rescue.js';import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';+import { convertDocumentBlock, documentRejectionMessage } from '../lib/anthropic-documents.js';import { isClientAbortError, newClientAbortError } from '../lib/error-classify.js';import { logRequest } from '../lib/request-log.js';import { extractApiToken, timingSafeStringEqual, getStickyModel, setStickyModel } from './proxy.js';@@ -253,10 +254,14 @@ interface ConvertedRequest {tool_choice?: ChatToolChoice;hasImage: boolean;wantsTools: boolean;+ /** Reasons the request carried documents we cannot convert. Non-empty means+ * the caller must be told, not served — see the rejection below. */+ documentRejections: string[];}function convertRequest(input: AnthropicRequest): ConvertedRequest {const messages: ChatMessage[] = [];+ const documentRejections: string[] = [];let hasImage = false;const system = flattenSystem(input.system);@@ -307,8 +312,15 @@ function convertRequest(input: AnthropicRequest): ConvertedRequest {tool_call_id: String((block as any).tool_use_id ?? ''),content: flattenToolResult((block as any).content),});+ } else if (type === 'document') {+ // A document that is already text costs nothing to inline. One that+ // needs decoding cannot be served by any provider here, and dropping+ // it would answer confidently about a document the model never saw.+ const result = convertDocumentBlock(block);+ if (result.ok) textParts.push(result.text);+ else documentRejections.push(result.reason);}- // Unknown block types (thinking, document, …) are intentionally dropped.+ // Other unknown block types (thinking, …) are intentionally dropped.}const text = textParts.join('\n');@@ -346,6 +358,7 @@ function convertRequest(input: AnthropicRequest): ConvertedRequest {tool_choice: convertToolChoice(input.tool_choice),hasImage,wantsTools: (tools?.length ?? 0) > 0,+ documentRejections,};}@@ -447,6 +460,15 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {const { temperature, top_p, stream } = body;const converted = convertRequest(body);+ // Rejected before routing, and before compression: this is our verdict, not+ // a provider's. Entering the failover loop would spend quota on a request+ // every candidate would fail identically, and book it as provider failure.+ if (converted.documentRejections.length > 0) {+ const message = documentRejectionMessage(converted.documentRejections);+ console.warn(`[anthropic] 400 unsupported document block: ${converted.documentRejections.join('; ')}`);+ sendError(res, 400, 'invalid_request_error', message);+ return;+ }let { messages } = converted;const { tools, tool_choice, hasImage, wantsTools } = converted;const systemHasCacheControl = Array.isArray(body.system)@@ -925,7 +947,15 @@ anthropicRouter.post('/messages/count_tokens', (req: Request, res: Response) =>sendError(res, 400, 'invalid_request_error', 'Invalid request');return;}- const { messages, tools } = convertRequest(parsed.data);+ const converted = convertRequest(parsed.data);+ // Same verdict as POST /messages, so a client sizing a context window learns+ // the document is unusable here rather than getting a count for a prompt we+ // would go on to refuse.+ if (converted.documentRejections.length > 0) {+ sendError(res, 400, 'invalid_request_error', documentRejectionMessage(converted.documentRejections));+ return;+ }+ const { messages, tools } = converted;const compressionResult = compressRequest(messages, {header: req.headers['x-freellm-compress'],tools,