The following code (on node v22.2.0) uses fetch
to call the OpenAI-compatible Gemini API
async function main() {
const resp = await fetch(
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
{
method: "POST",
headers: {
Authorization: "Bearer $API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gemini-1.5-flash",
messages: [{ role: "user", content: "Explain to me how AI works" }],
}),
},
);
const data = await resp.json();
console.log(data);
}
main().catch(console.error);
but it gives
[
{
error: {
code: 400,
message: 'Request contains an invalid argument.',
status: 'INVALID_ARGUMENT'
}
}
]
However, sending a raw request:
printf "POST /v1beta/openai/chat/completions HTTP/1.1\r\nHost: generativelanguage.googleapis.com\r\nAuthorization: Bearer $API_KEY\r\nContent-Type: application/json\r\nContent-Length: 96\r\n\r\n{\"model\":\"gemini-1.5-flash\",\"messages\":[{\"role\":\"user\",\"content\":\"Explain to me how AI works\"}]}\r\n" | openssl s_client -quiet -connect generativelanguage.googleapis.com:443
works.
What is going wrong when using node’s fetch and how can I address the problem? Due to some restrictions, I can’t use an external library (such as axios or node-fetch, which do work).