|
| 1 | +--- |
| 2 | +title: 'Quickstart: Use Azure OpenAI Service with the JavaScript SDK' |
| 3 | +titleSuffix: Azure OpenAI |
| 4 | +description: Walkthrough on how to get started with Azure OpenAI and make your first chat completions call with the JavaScript SDK. |
| 5 | +#services: cognitive-services |
| 6 | +manager: nitinme |
| 7 | +ms.service: azure-ai-openai |
| 8 | +ms.topic: include |
| 9 | +author: mrbullwinkle |
| 10 | +ms.author: mbullwin |
| 11 | +ms.date: 10/22 |
| 12 | +--- |
| 13 | + |
| 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) |
| 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 [available in this repo](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/openai/openai/samples/v2-beta/javascript). |
| 18 | +
|
| 19 | +## Prerequisites |
| 20 | + |
| 21 | + |
| 22 | +- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true) |
| 23 | +- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) |
| 24 | +- [TypeScript](https://www.typescriptlang.org/download/) |
| 25 | +- [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. |
| 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 | +> [!div class="nextstepaction"] |
| 32 | +> [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) |
| 33 | +
|
| 34 | + |
| 35 | +## Set up |
| 36 | + |
| 37 | +[!INCLUDE [get-key-endpoint](get-key-endpoint.md)] |
| 38 | + |
| 39 | +[!INCLUDE [environment-variables](environment-variables.md)] |
| 40 | + |
| 41 | +## Create a Node application |
| 42 | + |
| 43 | +In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it. |
| 44 | + |
| 45 | +## Install the client library |
| 46 | + |
| 47 | +Install the required packages for JavaScript with npm from within the context of your new directory: |
| 48 | + |
| 49 | +```console |
| 50 | +npm install openai dotenv @azure/identity |
| 51 | +``` |
| 52 | + |
| 53 | +Your app's _package.json_ file will be updated with the dependencies. |
| 54 | + |
| 55 | +> [!div class="nextstepaction"] |
| 56 | +> [I ran into an issue with the setup.](https://microsoft.qualtrics.com/jfe/form/SV_0Cl5zkG3CnDjq6O?PLanguage=JAVASCRIPT&Pillar=AOAI&Product=Chatgpt&Page=quickstart&Section=Set-up-the-environment) |
| 57 | +
|
| 58 | +## Create a sample application |
| 59 | + |
| 60 | +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. |
| 61 | + |
| 62 | +## [Microsoft Entra ID](#tab/typescript-keyless) |
| 63 | + |
| 64 | +```typescript |
| 65 | +import { AzureOpenAI } from "openai"; |
| 66 | +import { |
| 67 | + DefaultAzureCredential, |
| 68 | + getBearerTokenProvider |
| 69 | +} from "@azure/identity"; |
| 70 | +import type { |
| 71 | + ChatCompletion, |
| 72 | + ChatCompletionCreateParamsNonStreaming, |
| 73 | +} from "openai/resources/index"; |
| 74 | + |
| 75 | +// You will need to set these environment variables or edit the following values |
| 76 | +const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>"; |
| 77 | + |
| 78 | +// Required Azure OpenAI deployment name and API version |
| 79 | +const apiVersion = "2024-08-01-preview"; |
| 80 | +const deploymentName = "gpt-4o-mini"; //This must match your deployment name. |
| 81 | + |
| 82 | +// keyless authentication |
| 83 | +const credential = new DefaultAzureCredential(); |
| 84 | +const scope = "https://cognitiveservices.azure.com/.default"; |
| 85 | +const azureADTokenProvider = getBearerTokenProvider(credential, scope); |
| 86 | + |
| 87 | +function getClient(): AzureOpenAI { |
| 88 | + return new AzureOpenAI({ |
| 89 | + endpoint, |
| 90 | + azureADTokenProvider, |
| 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 | +## [API Key](#tab/typescript-key) |
| 143 | + |
| 144 | +```typescript |
| 145 | +import { AzureOpenAI } from "openai"; |
| 146 | +import type { |
| 147 | + ChatCompletion, |
| 148 | + ChatCompletionCreateParamsNonStreaming, |
| 149 | +} from "openai/resources/index"; |
| 150 | + |
| 151 | +// You will need to set these environment variables or edit the following values |
| 152 | +const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>"; |
| 153 | +const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>"; |
| 154 | + |
| 155 | +// Required Azure OpenAI deployment name and API version |
| 156 | +const apiVersion = "2024-08-01-preview"; |
| 157 | +const deploymentName = "gpt-4o-mini"; //This must match your deployment name. |
| 158 | + |
| 159 | +function getClient(): AzureOpenAI { |
| 160 | + return new AzureOpenAI({ |
| 161 | + endpoint, |
| 162 | + apiKey, |
| 163 | + apiVersion, |
| 164 | + deployment: deploymentName, |
| 165 | + }); |
| 166 | +} |
| 167 | + |
| 168 | +function createMessages(): ChatCompletionCreateParamsNonStreaming { |
| 169 | + return { |
| 170 | + messages: [ |
| 171 | + { role: "system", content: "You are a helpful assistant." }, |
| 172 | + { |
| 173 | + role: "user", |
| 174 | + content: "Does Azure OpenAI support customer managed keys?", |
| 175 | + }, |
| 176 | + { |
| 177 | + role: "assistant", |
| 178 | + content: "Yes, customer managed keys are supported by Azure OpenAI?", |
| 179 | + }, |
| 180 | + { role: "user", content: "Do other Azure AI services support this too?" }, |
| 181 | + ], |
| 182 | + model: "", |
| 183 | + }; |
| 184 | +} |
| 185 | +async function printChoices(completion: ChatCompletion): Promise<void> { |
| 186 | + for (const choice of completion.choices) { |
| 187 | + console.log(choice.message); |
| 188 | + } |
| 189 | +} |
| 190 | +export async function main() { |
| 191 | + const client = getClient(); |
| 192 | + const messages = createMessages(); |
| 193 | + const result = await client.chat.completions.create(messages); |
| 194 | + await printChoices(result); |
| 195 | +} |
| 196 | + |
| 197 | +main().catch((err) => { |
| 198 | + console.error("The sample encountered an error:", err); |
| 199 | +}); |
| 200 | +``` |
| 201 | + |
| 202 | +Build the script with the following command: |
| 203 | + |
| 204 | +```cmd |
| 205 | +tsc |
| 206 | +``` |
| 207 | + |
| 208 | +Run the script with the following command: |
| 209 | + |
| 210 | +```cmd |
| 211 | +node.exe Completion.js |
| 212 | +``` |
| 213 | + |
| 214 | +--- |
| 215 | + |
| 216 | +## Output |
| 217 | + |
| 218 | +```output |
| 219 | +== Chat Completions Sample == |
| 220 | +{ |
| 221 | + content: 'Yes, several other Azure AI services also support customer managed keys for enhanced security and control over encryption keys.', |
| 222 | + role: 'assistant' |
| 223 | +} |
| 224 | +``` |
| 225 | + |
| 226 | +--- |
| 227 | + |
| 228 | +> [!NOTE] |
| 229 | +> 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. |
| 230 | +
|
| 231 | +> [!div class="nextstepaction"] |
| 232 | +> [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) |
| 233 | +
|
| 234 | +## Clean up resources |
| 235 | + |
| 236 | +If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models. |
| 237 | + |
| 238 | +- [Azure portal](../../multi-service-resource.md?pivots=azportal#clean-up-resources) |
| 239 | +- [Azure CLI](../../multi-service-resource.md?pivots=azcli#clean-up-resources) |
| 240 | + |
| 241 | +## Next steps |
| 242 | + |
| 243 | +* [Azure OpenAI Overview](../overview.md) |
| 244 | +* For more examples, check out the [Azure OpenAI Samples GitHub repository](https://aka.ms/AOAICodeSamples) |
0 commit comments