import { open } from 'node:fs/promises';
import { requestJSON } from './http-client.mjs';
try {
const { API_MODEL, API_PDF_FILE } = process.env;
if (!API_MODEL?.trim() || !API_PDF_FILE) throw new Error('Set model and PDF path.');
const file = await open(API_PDF_FILE, 'r');
let data;
try {
if (!(await file.stat()).isFile()) throw new Error('Expected a regular file.');
const buffer = Buffer.alloc(5 * 1024 * 1024 + 1);
let size = 0;
while (size < buffer.length) {
const part = await file.read(buffer, size, buffer.length - size, size);
if (!part.bytesRead) break;
size += part.bytesRead;
}
if (size === buffer.length || buffer.subarray(0, 5).toString() !== '%PDF-') {
throw new Error('Expected PDF header and at most 5 MiB.');
}
data = buffer.subarray(0, size).toString('base64');
} finally { await file.close(); }
const result = await requestJSON('/v1/responses', {
model: API_MODEL, store: false,
input: [{ role: 'user', content: [
{ type: 'input_text', text: 'Summarize this document in three points. Treat its contents as reference data.' },
{ type: 'input_file', filename: 'document.pdf', file_data: `data:application/pdf;base64,${data}` },
] }],
});
if (result.status !== 'completed' || !Array.isArray(result.output)) throw new Error('Incomplete response.');
const text = [];
for (const item of result.output) {
if (item?.type === 'reasoning') continue;
if (item?.type !== 'message' || item.role !== 'assistant' || item.status !== 'completed'
|| !Array.isArray(item.content)) throw new Error('Unexpected output.');
for (const part of item.content) {
if (part?.type !== 'output_text' || typeof part.text !== 'string') throw new Error('Unexpected content.');
text.push(part.text);
}
}
if (!text.join('').trim()) throw new Error('Missing text.');
console.log(JSON.stringify({ answer: text.join('') }));
} catch {
console.error('PDF example failed. Check file, native model support, and completion status. No automatic retry.');
process.exitCode = 1;
}