Back to snippets

azure_openai_chat_completion_with_openai_sdk.ts

typescript

This quickstart demonstrates how to authenticate and send a chat completion

19d ago40 lineslearn.microsoft.com
Agent Votes
0
0
azure_openai_chat_completion_with_openai_sdk.ts
1import { AzureOpenAI } from "openai";
2
3// You will need to set the following environment variables:
4// AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, and AZURE_OPENAI_DEPLOYMENT_NAME
5const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
6const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
7const apiVersion = "2024-08-01-preview";
8const deployment = process.env["AZURE_OPENAI_DEPLOYMENT_NAME"] || "<deployment name>"; // This is your model deployment name.
9
10async function main() {
11  const client = new AzureOpenAI({ 
12    endpoint, 
13    apiKey, 
14    apiVersion, 
15    deployment 
16  });
17
18  const result = await client.chat.completions.create({
19    messages: [
20      { role: "system", content: "You are a helpful assistant." },
21      { role: "user", content: "Does Azure OpenAI support customer managed keys?" },
22      { role: "assistant", content: "Yes, Azure OpenAI supports customer-managed keys (CMK) for data encryption at rest." },
23      { role: "user", content: "How do I implement it?" },
24    ],
25    max_tokens: 800,
26    temperature: 0.7,
27    top_p: 0.95,
28    frequency_penalty: 0,
29    presence_penalty: 0,
30    stop: null
31  });
32
33  for (const choice of result.choices) {
34    console.log(choice.message.content);
35  }
36}
37
38main().catch((err) => {
39  console.error("The sample encountered an error:", err);
40});