38 lines
1.2 KiB
JavaScript
38 lines
1.2 KiB
JavaScript
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
|
|
const DEFAULT_MODEL = process.env.OPENROUTER_DEFAULT_MODEL || "openai/gpt-4o-mini";
|
|
|
|
export async function askOpenRouter(model, prompt) {
|
|
if (!OPENROUTER_API_KEY) {
|
|
throw new Error("OPENROUTER_API_KEY is not set");
|
|
}
|
|
|
|
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Bearer ${OPENROUTER_API_KEY}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
model: model || DEFAULT_MODEL,
|
|
messages: [{ role: "user", content: prompt }],
|
|
// Some models default max_tokens to their full context window (e.g. 65536),
|
|
// which can exceed available credit balance before a single token is generated.
|
|
// This is a quick chat reply, not a long-form task — cap it.
|
|
max_tokens: 1024,
|
|
}),
|
|
});
|
|
|
|
if (!res.ok) {
|
|
throw new Error(`OpenRouter request failed: ${res.status} ${await res.text()}`);
|
|
}
|
|
|
|
const data = await res.json();
|
|
const content = data.choices?.[0]?.message?.content;
|
|
if (!content) {
|
|
throw new Error(`OpenRouter returned no content: ${JSON.stringify(data)}`);
|
|
}
|
|
return content;
|
|
}
|
|
|
|
export { DEFAULT_MODEL };
|