import { requestJSON } from './http-client.mjs';
try {
const model = process.env.API_MODEL;
const protocol = process.env.API_JSON_PROTOCOL || 'chat';
if (!model?.trim() || !['chat', 'responses'].includes(protocol)) throw new Error('Invalid configuration.');
const instruction = 'Return only a JSON object with exactly sku, quantity, notes. sku must be NOTEBOOK, quantity an integer from 0 to 100, and notes a string or null. Extract: three notebooks, no notes.';
const result = await requestJSON(protocol === 'chat' ? '/v1/chat/completions' : '/v1/responses',
protocol === 'chat' ? { model, messages: [{ role: 'user', content: instruction }], response_format: { type: 'json_object' } }
: { model, input: instruction, text: { format: { type: 'json_object' } }, store: false });
let text;
if (protocol === 'chat') {
const choice = result.choices?.[0];
const message = choice?.message;
if (!Array.isArray(result.choices) || result.choices.length !== 1 || choice?.index !== 0
|| choice.finish_reason !== 'stop' || message?.role !== 'assistant'
|| message.refusal != null || message.tool_calls != null || message.function_call != null
|| typeof message.content !== 'string') throw new Error('Incomplete text.');
text = message.content;
} else {
if (result.status !== 'completed' || !Array.isArray(result.output)) throw new Error('Incomplete response.');
const parts = [];
let messages = 0;
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) || ++messages > 1) 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.');
parts.push(part.text);
}
}
text = parts.join('');
}
// Parse only complete JSON; do not strip fences, repair truncation, or coerce field types.
const value = JSON.parse(text);
if (!value || Array.isArray(value) || Object.keys(value).length !== 3 || value.sku !== 'NOTEBOOK'
|| !Number.isSafeInteger(value.quantity) || value.quantity < 0 || value.quantity > 100
|| !(value.notes === null || typeof value.notes === 'string')) throw new Error('Invalid business object.');
console.log(JSON.stringify({ sku: value.sku, quantity: value.quantity, notes: value.notes }));
} catch {
console.error('JSON mode example failed. Check protocol, completion, and business fields. No automatic repair or retry.');
process.exitCode = 1;
}