Skip to content

Commit 281e44d

Browse files
authored
Merge pull request #275988 from mrbullwinkle/mrb_05_20_2024_js_update
[Azure OpenAI] Chat completions
2 parents 7cf9fe5 + dd8f817 commit 281e44d

File tree

2 files changed

+81
-31
lines changed

2 files changed

+81
-31
lines changed

articles/ai-services/openai/includes/chatgpt-javascript.md

Lines changed: 78 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,21 @@ ms.service: azure-ai-openai
88
ms.topic: include
99
author: mrbullwinkle
1010
ms.author: mbullwin
11-
ms.date: 07/26/2023
11+
ms.date: 05/21/2024
1212
---
1313

14-
[Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/openai/openai) | [Package (npm)](https://www.npmjs.com/package/@azure/openai) | [Samples](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/openai/Azure.AI.OpenAI/tests/Samples) | [Retrieval Augmented Generation (RAG) enterprise chat template](/azure/developer/javascript/get-started-app-chat-template)|
14+
[Source code](https://github.com/openai/openai-node) | [Package (npm)](https://www.npmjs.com/package/openai) | [Samples](https://github.com/Azure/azure-sdk-for-js/tree/openai-azure-samples/sdk/openai/openai/samples/v1-beta/javascript)
15+
16+
> [!NOTE]
17+
> This article has been updated to use the [latest OpenAI npm package](https://www.npmjs.com/package/openai) which now fully supports Azure OpenAI. If you are looking for code examples for the legacy Azure OpenAI JavaScript SDK they are currently still [1available in this repo](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/openai/openai/samples/v1-beta/javascript).
1518
1619
## Prerequisites
1720

1821
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
1922
- Access granted to the Azure OpenAI service in the desired Azure subscription.
2023
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI Service by completing the form at [https://aka.ms/oai/access](https://aka.ms/oai/access?azure-portal=true).
2124
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
22-
- An Azure OpenAI Service resource with either the `gpt-35-turbo` or the `gpt-4` models deployed. For more information about model deployment, see the [resource deployment guide](../how-to/create-resource.md).
25+
- An Azure OpenAI Service resource with either a `gpt-35-turbo` or `gpt-4` series models deployed. For more information about model deployment, see the [resource deployment guide](../how-to/create-resource.md).
2326

2427
> [!div class="nextstepaction"]
2528
> [I ran into an issue with the prerequisites.](https://microsoft.qualtrics.com/jfe/form/SV_0Cl5zkG3CnDjq6O?PLanguage=JAVASCRIPT&Pillar=AOAI&Product=Chatgpt&Page=quickstart&Section=Prerequisites)
@@ -32,18 +35,14 @@ ms.date: 07/26/2023
3235

3336
## Create a Node application
3437

35-
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it. Then run the `npm init` command to create a node application with a _package.json_ file.
36-
37-
```console
38-
npm init
39-
```
38+
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
4039

4140
## Install the client library
4241

43-
Install the Azure OpenAI client library for JavaScript with npm:
42+
Install the required packages for JavaScript with npm from within the context of your new directory:
4443

4544
```console
46-
npm install @azure/openai
45+
npm install openai dotenv @azure/identity
4746
```
4847

4948
Your app's _package.json_ file will be updated with the dependencies.
@@ -56,23 +55,31 @@ Your app's _package.json_ file will be updated with the dependencies.
5655
Open a command prompt where you want the new project, and create a new file named ChatCompletion.js. Copy the following code into the ChatCompletion.js file.
5756

5857
```javascript
59-
const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
60-
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] ;
61-
const azureApiKey = process.env["AZURE_OPENAI_API_KEY"] ;
58+
const { AzureOpenAI } = require("openai");
6259

63-
const messages = [
64-
{ role: "system", content: "You are a helpful assistant." },
65-
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
66-
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI" },
67-
{ role: "user", content: "Do other Azure AI services support this too" },
68-
];
60+
// Load the .env file if it exists
61+
const dotenv = require("dotenv");
62+
dotenv.config();
63+
64+
// You will need to set these environment variables or edit the following values
65+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
66+
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
67+
const apiVersion = "2024-05-01-preview";
68+
const deployment = "gpt-4o"; //This must match your deployment name.
69+
require("dotenv/config");
6970

7071
async function main() {
71-
console.log("== Chat Completions Sample ==");
7272

73-
const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
74-
const deploymentId = "gpt-35-turbo";
75-
const result = await client.getChatCompletions(deploymentId, messages);
73+
const client = new AzureOpenAI({ endpoint, apiKey, apiVersion, deployment });
74+
const result = await client.chat.completions.create({
75+
messages: [
76+
{ role: "system", content: "You are a helpful assistant." },
77+
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
78+
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
79+
{ role: "user", content: "Do other Azure AI services support this too?" },
80+
],
81+
model: "",
82+
});
7683

7784
for (const choice of result.choices) {
7885
console.log(choice.message);
@@ -86,9 +93,6 @@ main().catch((err) => {
8693
module.exports = { main };
8794
```
8895

89-
> [!IMPORTANT]
90-
> For production, use a secure way of storing and accessing your credentials like [Azure Key Vault](../../../key-vault/general/overview.md). For more information about credential security, see the Azure AI services [security](../../security-features.md) article.
91-
9296
Run the script with the following command:
9397

9498
```cmd
@@ -100,10 +104,56 @@ node.exe ChatCompletion.js
100104
```output
101105
== Chat Completions Sample ==
102106
{
103-
role: 'assistant',
104-
content: 'Yes, most Azure AI services support customer managed keys. It is always best to check the specific service documentation to confirm this.'
107+
content: 'Yes, several other Azure AI services also support customer managed keys for enhanced security and control over encryption keys.',
108+
role: 'assistant'
109+
}
110+
```
111+
112+
## Microsoft Entra ID
113+
114+
> [!IMPORTANT]
115+
> In the previous example we are demonstrating key-based authentication. Once you have tested with key-based authentication successfully, we recommend using the more secure [Microsoft Entra ID](/entra/fundamentals/whatis) for authentication which is demonstrated in the next code sample. Getting started with [Microsoft Entra ID] will require some additional [prerequisites](https://www.npmjs.com/package/@azure/identity).
116+
117+
```javascript
118+
const { AzureOpenAI } = require("openai");
119+
const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity");
120+
121+
// Set AZURE_OPENAI_ENDPOINT to the endpoint of your
122+
// OpenAI resource. You can find this in the Azure portal.
123+
// Load the .env file if it exists
124+
require("dotenv/config");
125+
126+
async function main() {
127+
console.log("== Chat Completions Sample ==");
128+
129+
const scope = "https://cognitiveservices.azure.com/.default";
130+
const azureADTokenProvider = getBearerTokenProvider(new DefaultAzureCredential(), scope);
131+
const deployment = "gpt-35-turbo";
132+
const apiVersion = "2024-04-01-preview";
133+
const client = new AzureOpenAI({ azureADTokenProvider, deployment, apiVersion });
134+
const result = await client.chat.completions.create({
135+
messages: [
136+
{ role: "system", content: "You are a helpful assistant." },
137+
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
138+
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
139+
{ role: "user", content: "Do other Azure AI services support this too?" },
140+
],
141+
model: "",
142+
});
143+
144+
for (const choice of result.choices) {
145+
console.log(choice.message);
146+
}
105147
}
148+
149+
main().catch((err) => {
150+
console.error("The sample encountered an error:", err);
151+
});
152+
153+
module.exports = { main };
106154
```
155+
> [!NOTE]
156+
> If your receive the error: *Error occurred: OpenAIError: The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.* You may need to remove a pre-existing environment variable for the API key from your system. Even though the Microsoft Entra ID code sample is not explicitly referencing the API key environment variable, if one is present on the system executing this sample, this error will still be generated.
107157
108158
> [!div class="nextstepaction"]
109159
> [I ran into an issue when running the code sample.](https://microsoft.qualtrics.com/jfe/form/SV_0Cl5zkG3CnDjq6O?PLanguage=JAVASCRIPT&Pillar=AOAI&Product=Chatgpt&Page=quickstart&Section=Create-application)

articles/ai-services/openai/includes/javascript.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ ms.date: 05/20/2024
1414
[Source code](https://github.com/openai/openai-node) | [Package (npm)](https://www.npmjs.com/package/openai) | [Samples](https://github.com/Azure/azure-sdk-for-js/tree/openai-azure-samples/sdk/openai/openai/samples/v1-beta/javascript)
1515

1616
> [!NOTE]
17-
> This article has been updated to use the [latest OpenAI npm package](https://www.npmjs.com/package/openai) which now fully supports Azure OpenAI.If you are looking for code examples for the legacy Azure OpenAI JavaScript SDK they are currently still [1available in this repo](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/openai/openai/samples/v1-beta/javascript).
17+
> This article has been updated to use the [latest OpenAI npm package](https://www.npmjs.com/package/openai) which now fully supports Azure OpenAI. If you are looking for code examples for the legacy Azure OpenAI JavaScript SDK they are currently still [1available in this repo](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/openai/openai/samples/v1-beta/javascript).
1818
1919
## Prerequisites
2020

@@ -60,8 +60,8 @@ const dotenv = require("dotenv");
6060
dotenv.config();
6161

6262
// You will need to set these environment variables or edit the following values
63-
const endpoint = process.env["ENDPOINT"] || "<endpoint>";
64-
const apiKey = process.env["AZURE_API_KEY"] || "<api key>";
63+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
64+
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
6565
const apiVersion = "2024-04-01-preview";
6666
const deployment = "gpt-35-turbo-instruct"; //The deployment name for your completions API model. The instruct model is the only new model that supports the legacy API.
6767

0 commit comments

Comments
 (0)