Skip to content

Commit bbe66aa

Browse files
committed
Quickstart - JS Chat & Completions - add entra for JS & TS
1 parent b2a8256 commit bbe66aa

File tree

1 file changed

+150
-5
lines changed

1 file changed

+150
-5
lines changed

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

Lines changed: 150 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ ms.service: azure-ai-openai
88
ms.topic: include
99
author: mrbullwinkle
1010
ms.author: mbullwin
11-
ms.date: 05/21/2024
11+
ms.date: 10/22
1212
---
1313

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/main/sdk/openai/openai/samples)
@@ -23,6 +23,7 @@ ms.date: 05/21/2024
2323
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
2424
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
2525
- [TypeScript](https://www.typescriptlang.org/download/)
26+
- [Azure CLI](/cli/azure/install-azure-cli) used for passwordless authentication in a local development environment, create the necessary context by signing in with the Azure CLI.
2627
- An Azure OpenAI Service resource with 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).
2728

2829
> [!div class="nextstepaction"]
@@ -32,6 +33,7 @@ ms.date: 05/21/2024
3233

3334
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
3435
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
36+
- [Azure CLI](/cli/azure/install-azure-cli) used for passwordless authentication in a local development environment, create the necessary context by signing in with the Azure CLI.
3537
- 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).
3638

3739
> [!div class="nextstepaction"]
@@ -66,16 +68,160 @@ Your app's _package.json_ file will be updated with the dependencies.
6668

6769
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.
6870

69-
## [**TypeScript**](#tab/typescript)
71+
## [**TypeScript (Entra ID)**](#tab/typescript-keyless)
72+
73+
```typescript
74+
import { AzureOpenAI } from "openai";
75+
import {
76+
DefaultAzureCredential,
77+
getBearerTokenProvider
78+
} from "@azure/identity";
79+
import type {
80+
ChatCompletion,
81+
ChatCompletionCreateParamsNonStreaming,
82+
} from "openai/resources/index";
83+
84+
// Load the .env file if it exists
85+
const dotenv = require("dotenv");
86+
dotenv.config();
87+
88+
// You will need to set these environment variables or edit the following values
89+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
90+
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
91+
92+
// Required Azure OpenAI deployment name and API version
93+
const apiVersion = "2024-08-01-preview";
94+
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.
95+
96+
// keyless authentication
97+
const credential = new DefaultAzureCredential();
98+
const scope = "https://cognitiveservices.azure.com/.default";
99+
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
100+
101+
function getClient(): AzureOpenAI {
102+
return new AzureOpenAI({
103+
endpoint,
104+
azureADTokenProvider,
105+
apiVersion,
106+
deployment: deploymentName,
107+
});
108+
}
109+
110+
function createMessages(): ChatCompletionCreateParamsNonStreaming {
111+
return {
112+
messages: [
113+
{ role: "system", content: "You are a helpful assistant." },
114+
{
115+
role: "user",
116+
content: "Does Azure OpenAI support customer managed keys?",
117+
},
118+
{
119+
role: "assistant",
120+
content: "Yes, customer managed keys are supported by Azure OpenAI?",
121+
},
122+
{ role: "user", content: "Do other Azure AI services support this too?" },
123+
],
124+
model: "",
125+
};
126+
}
127+
async function printChoices(completion: ChatCompletion): Promise<void> {
128+
for (const choice of completion.choices) {
129+
console.log(choice.message);
130+
}
131+
}
132+
export async function main() {
133+
const client = getClient();
134+
const messages = createMessages();
135+
const result = await client.chat.completions.create(messages);
136+
await printChoices(result);
137+
}
138+
139+
main().catch((err) => {
140+
console.error("The sample encountered an error:", err);
141+
});
142+
```
143+
144+
Build the script with the following command:
145+
146+
```cmd
147+
tsc
148+
```
149+
150+
Run the script with the following command:
151+
152+
```cmd
153+
node.exe Completion.js
154+
```
155+
156+
## [**JavaScript (Entra id)**](#tab/javascript-keyless)
157+
158+
```javascript
159+
const { AzureOpenAI } = require("openai");
160+
import {
161+
DefaultAzureCredential,
162+
getBearerTokenProvider
163+
} from "@azure/identity";
164+
165+
// Load the .env file if it exists
166+
const dotenv = require("dotenv");
167+
dotenv.config();
168+
169+
// You will need to set these environment variables or edit the following values
170+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
171+
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
172+
const apiVersion = "2024-05-01-preview";
173+
const deployment = "gpt-4o"; //This must match your deployment name.
174+
175+
176+
// keyless authentication
177+
const credential = new DefaultAzureCredential();
178+
const scope = "https://cognitiveservices.azure.com/.default";
179+
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
180+
181+
async function main() {
182+
183+
const client = new AzureOpenAI({ endpoint, apiKey, azureADTokenProvider, deployment });
184+
const result = await client.chat.completions.create({
185+
messages: [
186+
{ role: "system", content: "You are a helpful assistant." },
187+
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
188+
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
189+
{ role: "user", content: "Do other Azure AI services support this too?" },
190+
],
191+
model: "",
192+
});
193+
194+
for (const choice of result.choices) {
195+
console.log(choice.message);
196+
}
197+
}
198+
199+
main().catch((err) => {
200+
console.error("The sample encountered an error:", err);
201+
});
202+
203+
module.exports = { main };
204+
```
205+
206+
Run the script with the following command:
207+
208+
```cmd
209+
node.exe ChatCompletion.js
210+
```
211+
212+
## [**TypeScript (API Key)**](#tab/typescript-key)
70213

71214
```typescript
72-
import "dotenv/config";
73215
import { AzureOpenAI } from "openai";
74216
import type {
75217
ChatCompletion,
76218
ChatCompletionCreateParamsNonStreaming,
77219
} from "openai/resources/index";
78220

221+
// Load the .env file if it exists
222+
const dotenv = require("dotenv");
223+
dotenv.config();
224+
79225
// You will need to set these environment variables or edit the following values
80226
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
81227
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
@@ -139,7 +285,7 @@ Run the script with the following command:
139285
node.exe Completion.js
140286
```
141287

142-
## [**JavaScript**](#tab/javascript)
288+
## [**JavaScript (API key)**](#tab/javascript-key)
143289

144290
```javascript
145291
const { AzureOpenAI } = require("openai");
@@ -153,7 +299,6 @@ const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
153299
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
154300
const apiVersion = "2024-05-01-preview";
155301
const deployment = "gpt-4o"; //This must match your deployment name.
156-
require("dotenv/config");
157302

158303
async function main() {
159304

0 commit comments

Comments
 (0)