A Practical Guide for Beginners: Azure OpenAI with JavaScript and TypeScript (Part 03)
Tags: javascript, azureopenai, webdev, beginners
Published: 2023-10-28 00:00:44

---
title: A Practical Guide for Beginners: Azure OpenAI with JavaScript and TypeScript (Part 03) 
published: true
description: In this series of three articles, you will learn how to take the first steps in using Azure OpenAI Service with JavaScript and TypeScript!
tags: #javascript #azureopenai #webdev #beginners
series: A Practical Guide for Beginners - Azure OpenAI with JavaScript and TypeScript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rir2q7qvxijv5hri4p9.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-10-27 23:34 +0000
---

## Introduction

In the third part of _A Practical Guide for Beginners: Azure OpenAI with JavaScript and TypeScript_, we continue to explore the exciting world of Azure OpenAI with JavaScript and TypeScript. In this article, you will learn how to create a Node.js application that consumes Azure OpenAI Service. We will start from scratch, from setting up the development environment in Visual Studio Code to creating and running an application ready to interact with the AI service. You will discover how to configure environment variables, set parameters to control the generation of conclusions, and get impressive results. Additionally, we provide additional resources for you to deepen your knowledge in artificial intelligence. Get ready to bring your ideas to life with Azure OpenAI and JavaScript/TypeScript.

## Creating the Node.js Application to Consume Azure OpenAI Service

To create the Node.js application, we will use [Visual Studio Code](https://code.visualstudio.com/). If you haven't already installed it, you can access the link and download it.

After installing Visual Studio Code, let's create the Node.js application. Follow the steps below:

> The example below is related to the [Completion Code Sample](https://github.com/glaucia86/azureopenai-js-samples/tree/main/01-azure-openai-samples/javascript/01-completion-code-sample). If you want to test the application, you can use the **[Codespaces](https://github.com/features/codespaces)** from your forked repository.

- ✅ **Step 01:** Create a folder for the project, and inside the folder, enter the following command:

```bash
npm init -y
```

The `package.json` file will be created.

> Note: I set it to use `esm` (ECMAScript Modules) in the project. To do this, just add the `type` field with the value `module` to the `package.json` file.


```json
{
  "name": "javascript",
  "version": "1.0.0",
  "description": "a simple code sample on how to use Azure OpenAI Service with JavaScript",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon src/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "javascript",
    "ai",
    "artificial intelligence",
    "azure-openai"
  ],
  "author": "Glaucia Lemos <Twitter: @glaucia_lemos86>",
  "license": "MIT",
  "dependencies": {
    "@azure/openai": "^1.0.0-beta.6",
    "dotenv": "^16.3.1"
  },
  "devDependencies": {
    "nodemon": "^3.0.1"
  }
}
```

- ✅ **Step 02:** Install the Azure OpenAI Service package:

```bash
npm install @azure/openai
```

- ✅ **Step 03:** Let's also install the packages dotenv and nodemon:

```bash
npm install dotenv --save
```

```bash
npm install nodemon --save-dev
```

- ✅ **Step 04:** Go to the `package.json` file and add the following script:

```json
"scripts": {
  "start": "nodemon src/index.js"
}
```

- ✅ **Step 05:** Create a file named `.env` and inside the file, enter the following code:

```bash
AZURE_OPENAI_ENDPOINT="https://<resource name>.openai.azure.com"
AZURE_OPENAI_KEY="<azure api key>"
```

To obtain the `endpoint` and the `key`, simply access the Azure OpenAI Service resource created in the Azure Portal and then click on **Keys and Endpoint**.

[![azure-openai-11.png](https://i.postimg.cc/ZKMSdf0p/azure-openai-11.png)](https://postimg.cc/nCBg8G4h)

- ✅ **Step 06:** Create a folder called `src`, and inside the folder, create a file named `index.js`. In the `index.js` file, enter the following code:

```javascript
/**
 * file: src/index.js
 * description: file responsible for running the code sample completion
 * date: 10/20/2023
 * author: Glaucia Lemos <Twitter: @glaucia_lemos86>
 */

import { OpenAIClient, AzureKeyCredential } from '@azure/openai';
import dotenv from 'dotenv';

dotenv.config();

const endpoint = process.env.AZURE_OPENAI_ENDPOINT || '';
const azureApiKey = process.env.AZURE_OPENAI_KEY || '';

const prompt = ['What is Azure OpenAI?'];

async function main() {
  console.log('=== Get completions Sample ===');

  const client = new OpenAIClient(
    endpoint,
    new AzureKeyCredential(azureApiKey)
  );
  const deploymentName = 'deployment-name-completion';
  const result = await client.getCompletions(deploymentName, prompt, {
    maxTokens: 200,
    temperature: 0.25
  });

  for (const choice of result.choices) {
    console.log(choice.text);
  }
}

main().catch((err) => {
  console.error('The sample encountered an error:', err);
});
```

Note that in the code, we have included the `deploymentName` that we created in Azure AI Studio!

Another point to mention is that in the `result`, we set the number of tokens we want the model to return. In this case, we set it to return `200` tokens. However, you can set the quantity as desired.

The `temperature` controls the generated conclusions. A higher value makes the conclusions more creative, while lower values return more focused and deterministic conclusions.

If you want to understand what classes like `OpenAIClient` and `AzureKeyCredential` do, you can visit the link **[Azure OpenAI Service Node.js API Reference](https://learn.microsoft.com/en-us/javascript/api/%40azure/openai/?view=azure-node-preview)**.

- ✅ **Step 07:** Now, simply run the following command to run the application:

```bash
npm start
```

And see the result:

[![gif-azureopenai-js.gif](https://i.postimg.cc/XvJ8R8nN/gif-azureopenai-js.gif)](https://postimg.cc/TKzgmnyB)

## 📚 Important Resources & Free Courses

Here are some important resources about Azure OpenAI Service:

- ✅ **[Free Course - Introduction to Generative AI](https://learn.microsoft.com/training/paths/introduction-generative-ai/?WT.mc_id=javascript-110690-gllemos)**

- ✅ **[Free Course - Microsoft Azure Basics of AI: Introduction to Artificial Intelligence](https://learn.microsoft.com/training/paths/get-started-with-artificial-intelligence-on-azure/?WT.mc_id=javascript-110690-gllemos)**

- ✅ **[Azure OpenAI Service Documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/)

- **[Azure OpenAI Service Node.js API Reference](https://learn.microsoft.com/en-us/javascript/api/%40azure/openai/?view=azure-node-preview)**

- ✅ **[Azure OpenAI Service Pricing](https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/?WT.mc_id=javascript-110690-gllemos)**

- ✅ **[QuickStarts for JavaScript](https://learn.microsoft.com/azure/ai-services/openai/chatgpt-quickstart?source=recommendations&tabs=command-line&pivots=programming-language-javascript&WT.mc_id=javascript-110690-gllemos)** 

## Final Words

In this article, you learned how to create a Node.js application that consumes Azure OpenAI Service. We started from scratch, from setting up the development environment in Visual Studio Code to creating and running an application ready to interact with the AI service. You discovered how to configure environment variables, set parameters to control the generation of conclusions, and get impressive results. Additionally, we provided additional resources for you to deepen your knowledge in artificial intelligence. Now, you are ready to bring your ideas to life with Azure OpenAI and JavaScript/TypeScript. The complete source code repository is available on **GitHub**:

{% github  glaucia86/azureopenai-js-samples %} 

There's also an amazing repository where you can learn more about Generative AI with many other examples in Python to further explore the world of AI with Azure!

{% github  microsoft/generative-ai-for-beginners %} 

Oh! I almost forgot to mention! Don't forget to subscribe to my [YouTube Channel](https://www.youtube.com/@GlauciaLemos)! And during 2023, many cool things will come to the channel!

Here are some of the exciting updates:

- 😃 Microsoft Learn Live Sessions
- 😃 Weekly Tutorials on Node.js, TypeScript & JavaScript
- 😃 And much more!

If you enjoy this type of content, be sure to subscribe and hit the notification bell to stay informed about new videos! We already have an amazing new series coming up on the YouTube Channel this week.

[![Screen-Shot-12-31-20-at-01-06-AM.png](https://i.postimg.cc/pr3TL4Pd/Screen-Shot-12-31-20-at-01-06-AM.png)](https://bit.ly/youtube-canal-glaucialemos)

To stay updated on various other news and updates, don't forget to follow me on Twitter!

[![Screen-Shot-12-31-20-at-01-06-AM.png](https://i.postimg.cc/sXPk87Td/Screen-Shot-05-24-23-at-08-32-PM.png)](https://twitter.com/glaucia_lemos86)

See you soon! Until next time ❤️❤️