Skip to content

Commit ca906df

Browse files
committed
OpenAI Chat quickstart - TypeScript
1 parent 6474690 commit ca906df

File tree

1 file changed

+130
-0
lines changed

1 file changed

+130
-0
lines changed

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

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,27 @@ ms.date: 05/21/2024
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 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).
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,67 @@ 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 { AzureOpenAI } from "openai";
73+
import { type ChatCompletion, type ChatCompletionCreateParamsNonStreaming } from "openai/resources/index";
74+
import "dotenv/config";
75+
76+
// You will need to set these environment variables or edit the following values
77+
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
78+
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
79+
80+
const apiVersion = "2024-05-01-preview";
81+
const deployment = "gpt-4o"; //This must match your deployment name.
82+
83+
function getClient(): AzureOpenAI {
84+
return new AzureOpenAI({ endpoint, apiKey, apiVersion, deployment });
85+
}
86+
87+
function createMessages(): ChatCompletionCreateParamsNonStreaming {
88+
return {
89+
messages: [
90+
{ role: "system", content: "You are a helpful assistant." },
91+
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
92+
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
93+
{ role: "user", content: "Do other Azure AI services support this too?" },
94+
],
95+
model: ""
96+
}
97+
}
98+
async function getChoices(completion: ChatCompletion): Promise<void> {
99+
for (const choice of completion.choices) {
100+
console.log(choice.message);
101+
}
102+
}
103+
export async function main() {
104+
105+
const client = getClient();
106+
const messages = createMessages();
107+
const result = await client.chat.completions.create(messages);
108+
await getChoices(result);
109+
}
110+
111+
main().catch((err) => {
112+
console.error("The sample encountered an error:", err);
113+
});
114+
```
115+
116+
Build the script with the following command:
117+
118+
```cmd
119+
tsc
120+
```
121+
122+
Run the script with the following command:
123+
124+
```cmd
125+
node.exe Completion.js
126+
```
127+
128+
## [**JavaScript**](#tab/javascript)
129+
55130
```javascript
56131
const { AzureOpenAI } = require("openai");
57132

@@ -97,6 +172,8 @@ Run the script with the following command:
97172
node.exe ChatCompletion.js
98173
```
99174

175+
---
176+
100177
## Output
101178

102179
```output
@@ -112,6 +189,56 @@ node.exe ChatCompletion.js
112189
> [!IMPORTANT]
113190
> 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).
114191
192+
## [**TypeScript**](#tab/typescript)
193+
194+
```typescript
195+
import { AzureOpenAI } from "openai";
196+
import { type ChatCompletionCreateParamsNonStreaming, type ChatCompletion } from "openai/resources/index";
197+
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
198+
import "dotenv/config";
199+
200+
const apiVersion = "2024-05-01-preview";
201+
const deployment = "gpt-4o"; //This must match your deployment name.
202+
203+
function getClient(): AzureOpenAI {
204+
const scope = "https://cognitiveservices.azure.com/.default";
205+
const azureADTokenProvider = getBearerTokenProvider(new DefaultAzureCredential(), scope);
206+
return new AzureOpenAI({ azureADTokenProvider, deployment, apiVersion });
207+
208+
}
209+
210+
function createMessages(): ChatCompletionCreateParamsNonStreaming {
211+
return {
212+
messages: [
213+
{ role: "system", content: "You are a helpful assistant." },
214+
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
215+
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
216+
{ role: "user", content: "Do other Azure AI services support this too?" },
217+
],
218+
model: ""
219+
}
220+
}
221+
async function getChoices(completion: ChatCompletion): Promise<void> {
222+
for (const choice of completion.choices) {
223+
console.log(choice.message);
224+
}
225+
}
226+
export async function main() {
227+
228+
const client = getClient();
229+
const messages = createMessages();
230+
const result = await client.chat.completions.create(messages);
231+
await getChoices(result);
232+
}
233+
234+
main().catch((err) => {
235+
console.error("The sample encountered an error:", err);
236+
});
237+
```
238+
239+
240+
## [**JavaScript**](#tab/javascript)
241+
115242
```javascript
116243
const { AzureOpenAI } = require("openai");
117244
const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity");
@@ -150,6 +277,9 @@ main().catch((err) => {
150277

151278
module.exports = { main };
152279
```
280+
281+
---
282+
153283
> [!NOTE]
154284
> 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.
155285

0 commit comments

Comments
 (0)