Back

Step by Step Guide to Building an Azure OpenAI Service API Integration in JS

Aug 7, 20244 minute read

Introduction

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.

Prerequisites

Before we jump in, make sure you've got:

  • An Azure account with an active subscription
  • Node.js installed on your machine
  • An Azure OpenAI Service resource set up

Got all that? Great! Let's get coding.

Installation

First things first, let's get that package installed:

npm install @azure/openai

Easy peasy, right?

Authentication

Now, let's set up authentication. You'll need Azure AD credentials:

  1. Create an Azure AD app registration
  2. Grant it access to your Azure OpenAI resource

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/

Initializing the OpenAIClient

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) );

Making API Calls

Now for the fun part! Let's make some API calls:

Completions

const result = await client.getCompletions("your-deployment-name", ["Hello, I am"]); console.log(result.choices[0].text);

Chat Completions

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);

Embeddings

const result = await client.getEmbeddings("your-deployment-name", ["Hello world"]); console.log(result.data[0].embedding);

Handling Responses

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); }

Best Practices

A couple of quick tips:

  • Implement rate limiting to avoid hitting API limits
  • Craft your prompts carefully for best results

Advanced Usage

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 || ''); }

Conclusion

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!