Skip to content

Commit 9e96dd2

Browse files
committed
fix
1 parent 9fe15d7 commit 9e96dd2

File tree

1 file changed

+222
-2
lines changed
  • articles/ai-foundry/model-inference/includes/use-chat-multi-modal

1 file changed

+222
-2
lines changed

articles/ai-foundry/model-inference/includes/use-chat-multi-modal/javascript.md

Lines changed: 222 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,225 @@ ms.custom: references_regions, tool_generated
1414
zone_pivot_groups: azure-ai-inference-samples
1515
---
1616

17-
> [!NOTE]
18-
> Using audio inputs is only supported using Python, C#, or REST requests.
17+
[!INCLUDE [Feature preview](~/reusable-content/ce-skilling/azure/includes/ai-studio/includes/feature-preview.md)]
18+
19+
This article explains how to use chat completions API with models deployed to Azure AI model inference in Azure AI services.
20+
21+
## Prerequisites
22+
23+
To use chat completion models in your application, you need:
24+
25+
[!INCLUDE [how-to-prerequisites](../how-to-prerequisites.md)]
26+
27+
[!INCLUDE [how-to-prerequisites-javascript](../how-to-prerequisites-javascript.md)]
28+
29+
* A chat completions model deployment with support for **audio and images**. If you don't have one read [Add and configure models to Azure AI services](../../how-to/create-model-deployments.md) to add a chat completions model to your resource.
30+
31+
* This tutorial uses `Phi-4-multimodal-instruct`.
32+
33+
## Use chat completions
34+
35+
First, create the client to consume the model. The following code uses an endpoint URL and key that are stored in environment variables.
36+
37+
```javascript
38+
const client = new ModelClient(
39+
"https://<resource>.services.ai.azure.com/models",
40+
new AzureKeyCredential(process.env.AZUREAI_ENDPOINT_KEY)
41+
);
42+
```
43+
44+
If you have configured the resource to with **Microsoft Entra ID** support, you can use the following code snippet to create a client.
45+
46+
```javascript
47+
const clientOptions = { credentials: { "https://cognitiveservices.azure.com" } };
48+
49+
const client = new ModelClient(
50+
"https://<resource>.services.ai.azure.com/models",
51+
new DefaultAzureCredential(),
52+
clientOptions,
53+
);
54+
```
55+
56+
## Use chat completions with images
57+
58+
Some models can reason across text and images and generate text completions based on both kinds of input. In this section, you explore the capabilities of some models for vision in a chat fashion.
59+
60+
> [!IMPORTANT]
61+
> Some models support only one image for each turn in the chat conversation and only the last image is retained in context. If you add multiple images, it results in an error.
62+
63+
To see this capability, download an image and encode the information as `base64` string. The resulting data should be inside of a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs):
64+
65+
```javascript
66+
const image_url = "https://news.microsoft.com/source/wp-content/uploads/2024/04/The-Phi-3-small-language-models-with-big-potential-1-1900x1069.jpg";
67+
const image_format = "jpeg";
68+
69+
const response = await fetch(image_url, { headers: { "User-Agent": "Mozilla/5.0" } });
70+
const image_data = await response.arrayBuffer();
71+
const image_data_base64 = Buffer.from(image_data).toString("base64");
72+
const data_url = `data:image/${image_format};base64,${image_data_base64}`;
73+
```
74+
75+
Visualize the image:
76+
77+
78+
```javascript
79+
const img = document.createElement("img");
80+
img.src = data_url;
81+
document.body.appendChild(img);
82+
```
83+
84+
:::image type="content" source="../../../../ai-foundry/media/how-to/sdks/small-language-models-chart-example.jpg" alt-text="A chart displaying the relative capabilities between large language models and small language models." lightbox="../../../../ai-foundry/media/how-to/sdks/small-language-models-chart-example.jpg":::
85+
86+
Now, create a chat completion request with the image:
87+
88+
89+
```javascript
90+
var messages = [
91+
{ role: "system", content: "You are a helpful assistant that can generate responses based on images." },
92+
{ role: "user", content:
93+
[
94+
{ type: "text", text: "Which conclusion can be extracted from the following chart?" },
95+
{ type: "image_url", image:
96+
{
97+
url: data_url
98+
}
99+
}
100+
]
101+
}
102+
];
103+
104+
var response = await client.path("/chat/completions").post({
105+
body: {
106+
messages: messages,
107+
model: "Phi-4-multimodal-instruct",
108+
}
109+
});
110+
```
111+
112+
The response is as follows, where you can see the model's usage statistics:
113+
114+
115+
```javascript
116+
console.log(response.body.choices[0].message.role + ": " + response.body.choices[0].message.content);
117+
console.log("Model:", response.body.model);
118+
console.log("Usage:");
119+
console.log("\tPrompt tokens:", response.body.usage.prompt_tokens);
120+
console.log("\tCompletion tokens:", response.body.usage.completion_tokens);
121+
console.log("\tTotal tokens:", response.body.usage.total_tokens);
122+
```
123+
124+
```console
125+
ASSISTANT: The chart illustrates that larger models tend to perform better in quality, as indicated by their size in billions of parameters. However, there are exceptions to this trend, such as Phi-3-medium and Phi-3-small, which outperform smaller models in quality. This suggests that while larger models generally have an advantage, there might be other factors at play that influence a model's performance.
126+
Model: Phi-4-multimodal-instruct
127+
Usage:
128+
Prompt tokens: 2380
129+
Completion tokens: 126
130+
Total tokens: 2506
131+
```
132+
133+
## Use chat completions with audio
134+
135+
Some models can reason across text and audio inputs. The following example shows how you can send audio context to chat completions models that also supports audio.
136+
137+
In this example, we create a function `getAudioData` to load the content of the audio file encoded in `base64` data as the model expects it.
138+
139+
```javascript
140+
/**
141+
* Get the Base 64 data of an audio file.
142+
* @param {string} audioFile - The path to the image file.
143+
* @returns {string} Base64 data of the audio.
144+
*/
145+
function getAudioData(audioFile: string): string {
146+
try {
147+
const audioBuffer = fs.readFileSync(audioFile);
148+
return audioBuffer.toString("base64");
149+
} catch (error) {
150+
console.error(`Could not read '${audioFile}'.`);
151+
console.error("Set the correct path to the audio file before running this sample.");
152+
process.exit(1);
153+
}
154+
}
155+
```
156+
157+
Let's now use this function to load the content of an audio file stored on disk. We send the content of the audio file in a user message. Notice that in the request we also indicate the format of the audio content:
158+
159+
```javascript
160+
const audioFilePath = "hello_how_are_you.mp3"
161+
const audioFormat = "mp3"
162+
const audioData = getAudioData(audioFilePath);
163+
164+
const systemMessage = { role: "system", content: "You are an AI assistant for translating and transcribing audio clips." };
165+
const audioMessage = {
166+
role: "user",
167+
content: [
168+
{ type: "text", text: "Translate this audio snippet to spanish."},
169+
{ type: "input_audio",
170+
input_audio: {
171+
audioData,
172+
audioFormat,
173+
},
174+
},
175+
]
176+
};
177+
178+
const response = await client.path("/chat/completions").post({
179+
body: {
180+
messages: [
181+
systemMessage,
182+
audioMessage
183+
],
184+
model: "Phi-4-multimodal-instruct",
185+
},
186+
});
187+
```
188+
189+
The response is as follows, where you can see the model's usage statistics:
190+
191+
```javascript
192+
if (isUnexpected(response)) {
193+
throw response.body.error;
194+
}
195+
196+
console.log("Response: ", response.body.choices[0].message.content);
197+
console.log("Model: ", response.body.model);
198+
console.log("Usage:");
199+
console.log("\tPrompt tokens:", response.body.usage.prompt_tokens);
200+
console.log("\tTotal tokens:", response.body.usage.total_tokens);
201+
console.log("\tCompletion tokens:", response.body.usage.completion_tokens);
202+
```
203+
204+
```console
205+
ASSISTANT: Hola. ¿Cómo estás?
206+
Model: speech
207+
Usage:
208+
Prompt tokens: 77
209+
Completion tokens: 7
210+
Total tokens: 84
211+
```
212+
213+
The model can read the content from an **accessible cloud location** by passing the URL as an input. The Python SDK doesn't provide a direct way to do it, but you can indicate the payload as follows:
214+
215+
```javascript
216+
const systemMessage = { role: "system", content: "You are a helpful assistant." };
217+
const audioMessage = {
218+
role: "user",
219+
content: [
220+
{ type: "text", text: "Transcribe this audio."},
221+
{ type: "audio_url",
222+
audio_url: {
223+
url: "https://example.com/audio.mp3",
224+
},
225+
},
226+
]
227+
};
228+
229+
const response = await client.path("/chat/completions").post({
230+
body: {
231+
messages: [
232+
systemMessage,
233+
audioMessage
234+
],
235+
model: "Phi-4-multimodal-instruct",
236+
},
237+
});
238+
```

0 commit comments

Comments
 (0)