import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
import { generateText } from 'ai';
try {
const { API_BASE_URL, API_KEY, API_MODEL } = process.env;
const base = new URL(API_BASE_URL || 'invalid:');
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password
|| base.search || base.hash || !API_KEY?.trim() || !API_MODEL?.trim()) {
throw new Error('Invalid configuration.');
}
const provider = createOpenAICompatible({
name: 'api-gateway', baseURL: base.href.replace(/\/+$/, ''), apiKey: API_KEY,
fetch: (input, init) => fetch(input, { ...init, redirect: 'error' }),
});
const result = await generateText({
model: provider.chatModel(API_MODEL),
prompt: 'Say hello in one short sentence.',
maxRetries: 0,
abortSignal: AbortSignal.timeout(60_000),
include: { responseBody: true },
});
// Check the raw Chat response as well: adapters can normalize away refusal fields.
const raw = result.response.body as {
error?: unknown;
choices?: Array<{ index?: number; finish_reason?: string; message?: {
role?: string; content?: unknown; refusal?: unknown; tool_calls?: unknown;
function_call?: unknown;
} }>;
} | undefined;
const choice = raw?.choices?.[0];
const message = choice?.message;
if (raw?.error || raw?.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' || !message.content.trim()
|| result.finishReason !== 'stop' || result.toolCalls.length !== 0
|| result.text !== message.content) {
throw new Error('Expected one completed text response.');
}
console.log(result.text);
} catch {
console.error('AI SDK request failed or returned incomplete text. Check configuration and request logs. No automatic retry.');
process.exitCode = 1;
}