|
| 1 | +/** |
| 2 | + * Direct SDK/HTTP calls for providers that support native PDF document input. |
| 3 | + * This bypasses pi-ai's content type system which does not have a "document" type. |
| 4 | + */ |
| 5 | + |
| 6 | +import { isRecord } from "../../utils.js"; |
| 7 | +import { normalizeSecretInput } from "../../utils/normalize-secret-input.js"; |
| 8 | + |
| 9 | +type PdfInput = { |
| 10 | + base64: string; |
| 11 | + filename?: string; |
| 12 | +}; |
| 13 | + |
| 14 | +// --------------------------------------------------------------------------- |
| 15 | +// Anthropic – native PDF via Messages API |
| 16 | +// --------------------------------------------------------------------------- |
| 17 | + |
| 18 | +type AnthropicDocBlock = { |
| 19 | + type: "document"; |
| 20 | + source: { |
| 21 | + type: "base64"; |
| 22 | + media_type: "application/pdf"; |
| 23 | + data: string; |
| 24 | + }; |
| 25 | +}; |
| 26 | + |
| 27 | +type AnthropicTextBlock = { |
| 28 | + type: "text"; |
| 29 | + text: string; |
| 30 | +}; |
| 31 | + |
| 32 | +type AnthropicContentBlock = AnthropicDocBlock | AnthropicTextBlock; |
| 33 | + |
| 34 | +type AnthropicResponseContent = Array<{ type: string; text?: string }>; |
| 35 | + |
| 36 | +export async function anthropicAnalyzePdf(params: { |
| 37 | + apiKey: string; |
| 38 | + modelId: string; |
| 39 | + prompt: string; |
| 40 | + pdfs: PdfInput[]; |
| 41 | + maxTokens?: number; |
| 42 | + baseUrl?: string; |
| 43 | +}): Promise<string> { |
| 44 | + const apiKey = normalizeSecretInput(params.apiKey); |
| 45 | + if (!apiKey) { |
| 46 | + throw new Error("Anthropic PDF: apiKey required"); |
| 47 | + } |
| 48 | + |
| 49 | + const content: AnthropicContentBlock[] = []; |
| 50 | + for (const pdf of params.pdfs) { |
| 51 | + content.push({ |
| 52 | + type: "document", |
| 53 | + source: { |
| 54 | + type: "base64", |
| 55 | + media_type: "application/pdf", |
| 56 | + data: pdf.base64, |
| 57 | + }, |
| 58 | + }); |
| 59 | + } |
| 60 | + content.push({ type: "text", text: params.prompt }); |
| 61 | + |
| 62 | + const baseUrl = (params.baseUrl ?? "https://api.anthropic.com").replace(/\/+$/, ""); |
| 63 | + const res = await fetch(`${baseUrl}/v1/messages`, { |
| 64 | + method: "POST", |
| 65 | + headers: { |
| 66 | + "Content-Type": "application/json", |
| 67 | + "x-api-key": apiKey, |
| 68 | + "anthropic-version": "2023-06-01", |
| 69 | + "anthropic-beta": "pdfs-2024-09-25", |
| 70 | + }, |
| 71 | + body: JSON.stringify({ |
| 72 | + model: params.modelId, |
| 73 | + max_tokens: params.maxTokens ?? 4096, |
| 74 | + messages: [{ role: "user", content }], |
| 75 | + }), |
| 76 | + }); |
| 77 | + |
| 78 | + if (!res.ok) { |
| 79 | + const body = await res.text().catch(() => ""); |
| 80 | + throw new Error( |
| 81 | + `Anthropic PDF request failed (${res.status} ${res.statusText})${body ? `: ${body.slice(0, 400)}` : ""}`, |
| 82 | + ); |
| 83 | + } |
| 84 | + |
| 85 | + const json = (await res.json().catch(() => null)) as unknown; |
| 86 | + if (!isRecord(json)) { |
| 87 | + throw new Error("Anthropic PDF response was not JSON."); |
| 88 | + } |
| 89 | + |
| 90 | + const responseContent = json.content as AnthropicResponseContent | undefined; |
| 91 | + if (!Array.isArray(responseContent)) { |
| 92 | + throw new Error("Anthropic PDF response missing content array."); |
| 93 | + } |
| 94 | + |
| 95 | + const text = responseContent |
| 96 | + .filter((block) => block.type === "text" && typeof block.text === "string") |
| 97 | + .map((block) => block.text!) |
| 98 | + .join(""); |
| 99 | + |
| 100 | + if (!text.trim()) { |
| 101 | + throw new Error("Anthropic PDF returned no text."); |
| 102 | + } |
| 103 | + |
| 104 | + return text.trim(); |
| 105 | +} |
| 106 | + |
| 107 | +// --------------------------------------------------------------------------- |
| 108 | +// Google Gemini – native PDF via generateContent API |
| 109 | +// --------------------------------------------------------------------------- |
| 110 | + |
| 111 | +type GeminiPart = { inline_data: { mime_type: string; data: string } } | { text: string }; |
| 112 | + |
| 113 | +type GeminiCandidate = { |
| 114 | + content?: { parts?: Array<{ text?: string }> }; |
| 115 | +}; |
| 116 | + |
| 117 | +export async function geminiAnalyzePdf(params: { |
| 118 | + apiKey: string; |
| 119 | + modelId: string; |
| 120 | + prompt: string; |
| 121 | + pdfs: PdfInput[]; |
| 122 | + baseUrl?: string; |
| 123 | +}): Promise<string> { |
| 124 | + const apiKey = normalizeSecretInput(params.apiKey); |
| 125 | + if (!apiKey) { |
| 126 | + throw new Error("Gemini PDF: apiKey required"); |
| 127 | + } |
| 128 | + |
| 129 | + const parts: GeminiPart[] = []; |
| 130 | + for (const pdf of params.pdfs) { |
| 131 | + parts.push({ |
| 132 | + inline_data: { |
| 133 | + mime_type: "application/pdf", |
| 134 | + data: pdf.base64, |
| 135 | + }, |
| 136 | + }); |
| 137 | + } |
| 138 | + parts.push({ text: params.prompt }); |
| 139 | + |
| 140 | + const baseUrl = (params.baseUrl ?? "https://generativelanguage.googleapis.com").replace( |
| 141 | + /\/+$/, |
| 142 | + "", |
| 143 | + ); |
| 144 | + const url = `${baseUrl}/v1beta/models/${encodeURIComponent(params.modelId)}:generateContent?key=${encodeURIComponent(apiKey)}`; |
| 145 | + |
| 146 | + const res = await fetch(url, { |
| 147 | + method: "POST", |
| 148 | + headers: { "Content-Type": "application/json" }, |
| 149 | + body: JSON.stringify({ |
| 150 | + contents: [{ role: "user", parts }], |
| 151 | + }), |
| 152 | + }); |
| 153 | + |
| 154 | + if (!res.ok) { |
| 155 | + const body = await res.text().catch(() => ""); |
| 156 | + throw new Error( |
| 157 | + `Gemini PDF request failed (${res.status} ${res.statusText})${body ? `: ${body.slice(0, 400)}` : ""}`, |
| 158 | + ); |
| 159 | + } |
| 160 | + |
| 161 | + const json = (await res.json().catch(() => null)) as unknown; |
| 162 | + if (!isRecord(json)) { |
| 163 | + throw new Error("Gemini PDF response was not JSON."); |
| 164 | + } |
| 165 | + |
| 166 | + const candidates = json.candidates as GeminiCandidate[] | undefined; |
| 167 | + if (!Array.isArray(candidates) || candidates.length === 0) { |
| 168 | + throw new Error("Gemini PDF returned no candidates."); |
| 169 | + } |
| 170 | + |
| 171 | + const textParts = candidates[0].content?.parts?.filter((p) => typeof p.text === "string") ?? []; |
| 172 | + const text = textParts.map((p) => p.text!).join(""); |
| 173 | + |
| 174 | + if (!text.trim()) { |
| 175 | + throw new Error("Gemini PDF returned no text."); |
| 176 | + } |
| 177 | + |
| 178 | + return text.trim(); |
| 179 | +} |
0 commit comments