Skip to content

Commit e30f31c

Browse files
authored
Merge pull request #275763 from mrbullwinkle/mrb_05_20_2024_js_completions
[Azure OpenAI} Completions JS Update
2 parents 0f3f90d + 40aa0a6 commit e30f31c

File tree

1 file changed

+64
-20
lines changed

1 file changed

+64
-20
lines changed

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

Lines changed: 64 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@ 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/20/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-js/tree/main/sdk/openai/openai/samples)
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

@@ -30,19 +33,14 @@ ms.date: 07/26/2023
3033

3134
[!INCLUDE [environment-variables](environment-variables.md)]
3235

33-
34-
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.
35-
36-
```console
37-
npm init
38-
```
36+
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
3937

4038
## Install the client library
4139

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

4442
```console
45-
npm install @azure/openai
43+
npm install openai dotenv @azure/identity
4644
```
4745

4846
Your app's _package.json_ file will be updated with the dependencies.
@@ -55,34 +53,39 @@ Your app's _package.json_ file will be updated with the dependencies.
5553
Open a command prompt where you created the new project, and create a new file named Completion.js. Copy the following code into the Completion.js file.
5654

5755
```javascript
58-
const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
59-
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] ;
60-
const azureApiKey = process.env["AZURE_OPENAI_API_KEY"] ;
56+
const { AzureOpenAI } = require("openai");
57+
58+
// Load the .env file if it exists
59+
const dotenv = require("dotenv");
60+
dotenv.config();
61+
62+
// 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>";
65+
const apiVersion = "2024-04-01-preview";
66+
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.
6167

6268
const prompt = ["When was Microsoft founded?"];
6369

6470
async function main() {
6571
console.log("== Get completions Sample ==");
6672

67-
const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
68-
const deploymentId = "gpt-35-turbo-instruct";
69-
const result = await client.getCompletions(deploymentId, prompt);
73+
const client = new AzureOpenAI({ endpoint, apiKey, apiVersion, deployment });
74+
75+
const result = await client.completions.create({ prompt, model: deployment, max_tokens: 128 });
7076

7177
for (const choice of result.choices) {
7278
console.log(choice.text);
7379
}
7480
}
7581

7682
main().catch((err) => {
77-
console.error("The sample encountered an error:", err);
83+
console.error("Error occurred:", err);
7884
});
7985

8086
module.exports = { main };
8187
```
8288

83-
> [!IMPORTANT]
84-
> 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.
85-
8689
Run the script with the following command:
8790

8891
```cmd
@@ -97,6 +100,47 @@ node.exe Completion.js
97100
Microsoft was founded on April 4, 1975.
98101
```
99102

103+
## Microsoft Entra ID
104+
105+
> [!IMPORTANT]
106+
> 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).
107+
108+
```javascript
109+
const { AzureOpenAI } = require("openai");
110+
const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity");
111+
112+
// Set AZURE_OPENAI_ENDPOINT to the endpoint of your
113+
// OpenAI resource. You can find this in the Azure portal.
114+
// Load the .env file if it exists
115+
require("dotenv/config");
116+
117+
const prompt = ["When was Microsoft founded?"];
118+
119+
async function main() {
120+
console.log("== Get completions Sample ==");
121+
122+
const scope = "https://cognitiveservices.azure.com/.default";
123+
const azureADTokenProvider = getBearerTokenProvider(new DefaultAzureCredential(), scope);
124+
const deployment = "gpt-35-turbo-instruct";
125+
const apiVersion = "2024-04-01-preview";
126+
const client = new AzureOpenAI({ azureADTokenProvider, deployment, apiVersion });
127+
const result = await client.completions.create({ prompt, model: deployment, max_tokens: 128 });
128+
129+
for (const choice of result.choices) {
130+
console.log(choice.text);
131+
}
132+
}
133+
134+
main().catch((err) => {
135+
console.error("Error occurred:", err);
136+
});
137+
138+
module.exports = { main };
139+
```
140+
141+
> [!NOTE]
142+
> 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.
143+
100144
> [!div class="nextstepaction"]
101145
> [I ran into an issue when running the code sample.](https://microsoft.qualtrics.com/jfe/form/SV_0Cl5zkG3CnDjq6O?PLanguage=JAVASCRIPT&Pillar=AOAI&&Product=gpt&Page=quickstart&Section=Create-application)
102146

0 commit comments

Comments
 (0)