DEV Community

Cover image for A Practical Guide for Beginners: Azure OpenAI with JavaScript and TypeScript (Part 03)
Glaucia Lemos for Microsoft Azure

Posted on • Updated on

A Practical Guide for Beginners: Azure OpenAI with JavaScript and TypeScript (Part 03)

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. 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. If you want to test the application, you can use the Codespaces from your forked repository.

  • Step 01: Create a folder for the project, and inside the folder, enter the following command:
npm init -y
Enter fullscreen mode Exit fullscreen mode

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.

{
  "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"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Step 02: Install the Azure OpenAI Service package:
npm install @azure/openai
Enter fullscreen mode Exit fullscreen mode
  • Step 03: Let's also install the packages dotenv and nodemon:
npm install dotenv --save
Enter fullscreen mode Exit fullscreen mode
npm install nodemon --save-dev
Enter fullscreen mode Exit fullscreen mode
  • Step 04: Go to the package.json file and add the following script:
"scripts": {
  "start": "nodemon src/index.js"
}
Enter fullscreen mode Exit fullscreen mode
  • Step 05: Create a file named .env and inside the file, enter the following code:
AZURE_OPENAI_ENDPOINT="https://<resource name>.openai.azure.com"
AZURE_OPENAI_KEY="<azure api key>"
Enter fullscreen mode Exit fullscreen mode

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

  • 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:
/**
 * 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);
});
Enter fullscreen mode Exit fullscreen mode

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.

  • Step 07: Now, simply run the following command to run the application:
npm start
Enter fullscreen mode Exit fullscreen mode

And see the result:

gif-azureopenai-js.gif

📚 Important Resources & Free Courses

Here are some important resources about Azure OpenAI Service:

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 logo glaucia86 / azureopenai-js-samples

A repository for studies proporses how to use A.I + TypeScript + Langchain + Azure Open A.I

Learn Live Code Sessions: Azure OpenAI + LangChain with JavaScript/TypeScript

This repository is responsible for studies, code samples and learnings about how to use the Microsoft Azure OpenAI + LangChain with JavaScript/TypeScript.

🚀 Resources Used

📺 Video Series

(... to be include)

A Practical Guide for Beginners blog posts

There's a blog post teaching test by step how to use Azure OpenAI with JavaScript. It's divided in 3 parts. If you want to read it:

💻 Code samples Developed

Here you will find some code samples developed using Azure OpenAI with JavaScript/TypeScript.

📕 Important Resources






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 logo microsoft / generative-ai-for-beginners

21 Lessons, Get Started Building with Generative AI 🔗 https://microsoft.github.io/generative-ai-for-beginners/

Generative AI For Beginners

21 Lessons teaching everything you need to know to start building Generative AI applications

GitHub license GitHub contributors GitHub issues GitHub pull-requests PRs Welcome

GitHub watchers GitHub forks GitHub stars

Generative AI for Beginners (Version 3) - A Course

Learn the fundamentals of building Generative AI applications with our 21-lesson comprehensive course by Microsoft Cloud Advocates.

🌱 Getting Started

This course has 21 lessons. Each lesson covers its own topic so start wherever you like!

Lessons are labeled either "Learn" lessons explaining a Generative AI concept or "Build" lessons that explain a concept and code examples in both Python and TypeScript when possible.

Each lesson also includes a "Keep Learning" section with additional learning tools.

What You Need

To run this code of this course, you can use either:

Oh! I almost forgot to mention! Don't forget to subscribe to my YouTube Channel! 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

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

See you soon! Until next time ❤️❤️

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴