Hey there, fellow dev! Ready to supercharge your JS app with some AI goodness? Let's dive into integrating Azure OpenAI Service using the @azure/openai
package. It's easier than you might think, and I'll walk you through it step by step.
Before we jump in, make sure you've got:
Got all that? Great! Let's get coding.
First things first, let's get that package installed:
npm install @azure/openai
Easy peasy, right?
Now, let's set up authentication. You'll need Azure AD credentials:
Once that's done, set up these environment variables:
AZURE_OPENAI_KEY=your_api_key AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com/
Time to get that client up and running:
import { OpenAIClient, AzureKeyCredential } from "@azure/openai"; const client = new OpenAIClient( process.env.AZURE_OPENAI_ENDPOINT, new AzureKeyCredential(process.env.AZURE_OPENAI_KEY) );
Now for the fun part! Let's make some API calls:
const result = await client.getCompletions("your-deployment-name", ["Hello, I am"]); console.log(result.choices[0].text);
const result = await client.getChatCompletions("your-deployment-name", [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "What's the weather like today?" } ]); console.log(result.choices[0].message.content);
const result = await client.getEmbeddings("your-deployment-name", ["Hello world"]); console.log(result.data[0].embedding);
Always remember to handle those responses and errors:
try { const result = await client.getChatCompletions(/*...*/); // Handle successful response } catch (error) { console.error("An error occurred:", error); }
A couple of quick tips:
Want to level up? Try streaming responses:
const events = await client.listChatCompletions(/*...*/); for await (const event of events) { console.log(event.choices[0]?.delta?.content || ''); }
And there you have it! You're now ready to integrate Azure OpenAI into your JS projects like a pro. Remember, the key to mastering this is practice and experimentation. So go forth and create some AI magic!
Need more info? Check out the Azure OpenAI Service docs and the @azure/openai package docs.
Happy coding!