I’m having trouble switching from regular OpenAI to Azure OpenAI in my Node.js project. Everything worked fine before but now I keep getting authentication errors.
My original working code:
const { Configuration, OpenAIApi } = require('openai');
const myApiKey = process.env.OPENAI_SECRET;
const config = new Configuration({
apiKey: myApiKey,
});
const client = new OpenAIApi(config);
async function generateResponse(systemPrompt, userInput, modelName) {
try {
const result = await client.createChatCompletion({
model: modelName,
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: userInput
}
]
});
const answer = result.data.choices[0].message.content;
return answer;
}
}
Updated Azure version that fails:
const { Configuration, OpenAIApi } = require('openai');
const config = new Configuration({
apiKey: process.env.AZURE_OPENAI_KEY,
api_type: "azure",
api_base: "my_azure_endpoint",
api_version: "my_api_version",
});
const client = new OpenAIApi(config);
async function generateResponse(systemPrompt, userInput, modelName) {
try {
const result = await client.ChatCompletion.create({
engine: "myDeployment",
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: userInput
}
],
});
console.log(result);
const answer = result.data.choices[0].message;
console.log(answer);
return answer;
}
}
I keep getting 401 unauthorized errors even though my credentials work perfectly in Python. Has anyone successfully configured Azure OpenAI with Node.js? What am I missing in the setup?