Skip to content

Commit e06abf7

Browse files
Merge pull request #102 from diberry/diberry/0903-completions-typescript
TS - Completions & Chat quickstart
2 parents 6bf11c6 + bf9c1d2 commit e06abf7

File tree

3 files changed

+337
-3
lines changed

3 files changed

+337
-3
lines changed

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

Lines changed: 167 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,34 @@ ms.author: mbullwin
1111
ms.date: 05/21/2024
1212
---
1313

14-
[Source code](https://github.com/openai/openai-node) | [Package (npm)](https://www.npmjs.com/package/openai)
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/main/sdk/openai/openai/samples)
1515

1616
> [!NOTE]
1717
> 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 [available in this repo](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/openai/openai/samples/v2-beta/javascript).
1818
1919
## Prerequisites
2020

21+
## [**TypeScript**](#tab/typescript)
22+
23+
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
24+
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
25+
- [TypeScript](https://www.typescriptlang.org/download/)
26+
- 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).
27+
28+
> [!div class="nextstepaction"]
29+
> [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)
30+
31+
## [**JavaScript**](#tab/javascript)
32+
2133
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
2234
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
2335
- 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).
2436

2537
> [!div class="nextstepaction"]
2638
> [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)
2739
40+
---
41+
2842
## Set up
2943

3044
[!INCLUDE [get-key-endpoint](get-key-endpoint.md)]
@@ -52,6 +66,81 @@ Your app's _package.json_ file will be updated with the dependencies.
5266

5367
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.
5468

69+
## [**TypeScript**](#tab/typescript)
70+
71+
```typescript
72+
import "dotenv/config";
73+
import { AzureOpenAI } from "openai";
74+
import type {
75+
ChatCompletion,
76+
ChatCompletionCreateParamsNonStreaming,
77+
} from "openai/resources/index";
78+
79+
// You will need to set these environment variables or edit the following values
80+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
81+
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
82+
83+
// Required Azure OpenAI deployment name and API version
84+
const apiVersion = "2024-08-01-preview";
85+
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.
86+
87+
function getClient(): AzureOpenAI {
88+
return new AzureOpenAI({
89+
endpoint,
90+
apiKey,
91+
apiVersion,
92+
deployment: deploymentName,
93+
});
94+
}
95+
96+
function createMessages(): ChatCompletionCreateParamsNonStreaming {
97+
return {
98+
messages: [
99+
{ role: "system", content: "You are a helpful assistant." },
100+
{
101+
role: "user",
102+
content: "Does Azure OpenAI support customer managed keys?",
103+
},
104+
{
105+
role: "assistant",
106+
content: "Yes, customer managed keys are supported by Azure OpenAI?",
107+
},
108+
{ role: "user", content: "Do other Azure AI services support this too?" },
109+
],
110+
model: "",
111+
};
112+
}
113+
async function printChoices(completion: ChatCompletion): Promise<void> {
114+
for (const choice of completion.choices) {
115+
console.log(choice.message);
116+
}
117+
}
118+
export async function main() {
119+
const client = getClient();
120+
const messages = createMessages();
121+
const result = await client.chat.completions.create(messages);
122+
await printChoices(result);
123+
}
124+
125+
main().catch((err) => {
126+
console.error("The sample encountered an error:", err);
127+
});
128+
```
129+
130+
Build the script with the following command:
131+
132+
```cmd
133+
tsc
134+
```
135+
136+
Run the script with the following command:
137+
138+
```cmd
139+
node.exe Completion.js
140+
```
141+
142+
## [**JavaScript**](#tab/javascript)
143+
55144
```javascript
56145
const { AzureOpenAI } = require("openai");
57146

@@ -97,6 +186,8 @@ Run the script with the following command:
97186
node.exe ChatCompletion.js
98187
```
99188

189+
---
190+
100191
## Output
101192

102193
```output
@@ -112,6 +203,78 @@ node.exe ChatCompletion.js
112203
> [!IMPORTANT]
113204
> 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).
114205
206+
## [**TypeScript**](#tab/typescript)
207+
208+
```typescript
209+
import {
210+
DefaultAzureCredential,
211+
getBearerTokenProvider,
212+
} from "@azure/identity";
213+
import "dotenv/config";
214+
import { AzureOpenAI } from "openai";
215+
import type {
216+
ChatCompletion,
217+
ChatCompletionCreateParamsNonStreaming,
218+
} from "openai/resources/index";
219+
220+
// You will need to set these environment variables or edit the following values
221+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
222+
223+
// Required Azure OpenAI deployment name and API version
224+
const apiVersion = "2024-08-01-preview";
225+
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.
226+
227+
function getClient(): AzureOpenAI {
228+
const scope = "https://cognitiveservices.azure.com/.default";
229+
const azureADTokenProvider = getBearerTokenProvider(
230+
new DefaultAzureCredential(),
231+
scope
232+
);
233+
return new AzureOpenAI({
234+
endpoint,
235+
azureADTokenProvider,
236+
deployment: deploymentName,
237+
apiVersion,
238+
});
239+
}
240+
241+
function createMessages(): ChatCompletionCreateParamsNonStreaming {
242+
return {
243+
messages: [
244+
{ role: "system", content: "You are a helpful assistant." },
245+
{
246+
role: "user",
247+
content: "Does Azure OpenAI support customer managed keys?",
248+
},
249+
{
250+
role: "assistant",
251+
content: "Yes, customer managed keys are supported by Azure OpenAI?",
252+
},
253+
{ role: "user", content: "Do other Azure AI services support this too?" },
254+
],
255+
model: "",
256+
};
257+
}
258+
async function printChoices(completion: ChatCompletion): Promise<void> {
259+
for (const choice of completion.choices) {
260+
console.log(choice.message);
261+
}
262+
}
263+
export async function main() {
264+
const client = getClient();
265+
const messages = createMessages();
266+
const result = await client.chat.completions.create(messages);
267+
await printChoices(result);
268+
}
269+
270+
main().catch((err) => {
271+
console.error("The sample encountered an error:", err);
272+
});
273+
```
274+
275+
276+
## [**JavaScript**](#tab/javascript)
277+
115278
```javascript
116279
const { AzureOpenAI } = require("openai");
117280
const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity");
@@ -150,6 +313,9 @@ main().catch((err) => {
150313

151314
module.exports = { main };
152315
```
316+
317+
---
318+
153319
> [!NOTE]
154320
> 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.
155321

0 commit comments

Comments
 (0)