如何使用 Azure AI 模型推斷產生聊天完成
重要
本文中標示為 (預覽) 的項目目前處於公開預覽狀態。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款。
本文說明如何使用聊天完成 API 搭配部署至 Azure AI 模型推斷的 Azure AI 服務中的模型。
必要條件
若要在應用程式中使用聊天完成模型,您需要:
Azure 訂用帳戶。 如果您使用 GitHub Models,您可以升級您的體驗,並在程式中建立 Azure 訂用帳戶。 如果您的情況,請閱讀 從 GitHub 模型升級至 Azure AI 模型推斷 。
Azure AI 服務資源。 如需詳細資訊,請參閱 建立 Azure AI 服務資源。
端點 URL 和金鑰。
聊天完成模型部署。 如果您沒有一個閱讀將 模型新增並設定至 Azure AI 服務 ,以將聊天完成模型新增至您的資源。
使用下列命令安裝 Azure AI 推斷套件:
pip install -U azure-ai-inference
使用聊天完成
首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 URL 和金鑰。
import os
from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential
client = ChatCompletionsClient(
endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_INFERENCE_CREDENTIAL"]),
model="mistral-large-2407"
)
如果您已將資源設定為 Microsoft Entra ID 支援,您可以使用下列代碼段來建立用戶端。
import os
from azure.ai.inference import ChatCompletionsClient
from azure.identity import DefaultAzureCredential
client = ChatCompletionsClient(
endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
credential=DefaultAzureCredential(),
model="mistral-large-2407"
)
建立聊天完成要求
下列範例示範如何針對模型建立基本聊天完成要求。
from azure.ai.inference.models import SystemMessage, UserMessage
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
)
注意
某些模型不支援系統訊息 (role="system"
)。 當您使用 Azure AI 模型推斷 API 時,系統訊息會轉譯為使用者訊息,這是可用功能中最為相似的功能。 此轉譯功能是為了方便起見而提供,但請務必確認模型遵循系統訊息中的指示,且具有正確的信賴度等級。
回應如下,您可以在其中查看模型的使用量統計資料:
print("Response:", response.choices[0].message.content)
print("Model:", response.model)
print("Usage:")
print("\tPrompt tokens:", response.usage.prompt_tokens)
print("\tTotal tokens:", response.usage.total_tokens)
print("\tCompletion tokens:", response.usage.completion_tokens)
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: mistral-large-2407
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
檢查回應中的 usage
區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。
串流內容
根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。
您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。
若要串流完成,請在呼叫模型時設定 stream=True
。
result = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
temperature=0,
top_p=1,
max_tokens=2048,
stream=True,
)
若要將輸出視覺化,請定義協助程式函式來列印串流。
def print_stream(result):
"""
Prints the chat completion with streaming.
"""
import time
for update in result:
if update.choices:
print(update.choices[0].delta.content, end="")
您可以將串流產生內容的方式視覺化:
print_stream(result)
探索推斷用戶端支援的更多參數
探索您可以在推斷用戶端中指定的其他參數。 如需所有支援參數及其對應文件的完整清單,請參閱 [Azure AI 模型推斷 API 參考]。
from azure.ai.inference.models import ChatCompletionsResponseFormatText
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
presence_penalty=0.1,
frequency_penalty=0.8,
max_tokens=2048,
stop=["<|endoftext|>"],
temperature=0,
top_p=1,
response_format={ "type": ChatCompletionsResponseFormatText() },
)
某些模型不支援 JSON 輸出格式設定。 您隨時都可以提示模型產生 JSON 輸出。 不過,這類輸出不保證為有效的 JSON。
如果您想要傳遞不在所支援參數清單中的參數,您可以使用 [額外的參數] 將其傳遞至基礎模型。 請參閱將額外的參數傳遞至模型。
建立 JSON 輸出
某些模型可以建立 JSON 輸出。 將 response_format
設定為 json_object
以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length"
,則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens
或交談超過了最大內容長度。
from azure.ai.inference.models import ChatCompletionsResponseFormatJSON
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant that always generate responses in JSON format, using."
" the following format: { ""answer"": ""response"" }."),
UserMessage(content="How many languages are in the world?"),
],
response_format={ "type": ChatCompletionsResponseFormatJSON() }
)
將額外的參數傳遞至模型
Azure AI 模型推斷 API 可讓您將額外的參數傳遞至模型。 下列程式碼範例示範如何將額外的參數 logprobs
傳遞至模型。
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
model_extras={
"logprobs": True
}
)
將額外的參數傳遞至 Azure AI 模型推斷 API 之前,請確定您的模型支援那些額外的參數。 對基礎模型提出要求時,會將標頭 extra-parameters
傳遞至具有 pass-through
值的模型。 這個值會告訴端點將額外的參數傳遞至模型。 搭配模型使用額外的參數,不保證模型實際上可以處理這些參數。 請參閱模型的文件,以了解支援哪些額外的參數。
使用工具
有些模型支援使用工具,當您需要從語言模型卸除特定工作時,這可以是非同尋常的資源,而是依賴更具決定性的系統,甚至是不同的語言模型。 Azure AI 模型推斷 API 可讓您以下列方式定義工具。
下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。
from azure.ai.inference.models import FunctionDefinition, ChatCompletionsFunctionToolDefinition
flight_info = ChatCompletionsFunctionToolDefinition(
function=FunctionDefinition(
name="get_flight_info",
description="Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
parameters={
"type": "object",
"properties": {
"origin_city": {
"type": "string",
"description": "The name of the city where the flight originates",
},
"destination_city": {
"type": "string",
"description": "The flight destination city",
},
},
"required": ["origin_city", "destination_city"],
},
)
)
tools = [flight_info]
在此範例中,函式的輸出是所選路線沒有適合的航班,但使用者應考慮進行訓練。
def get_flight_info(loc_origin: str, loc_destination: str):
return {
"info": f"There are no flights available from {loc_origin} to {loc_destination}. You should take a train, specially if it helps to reduce CO2 emissions."
}
注意
Cohere 模型需要工具的回應,才能成為格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 JSON 字串。
使用此函式的說明,提示模型來預訂航班:
messages = [
SystemMessage(
content="You are a helpful assistant that help users to find information about traveling, how to get"
" to places and the different transportations options. You care about the environment and you"
" always have that in mind when answering inqueries.",
),
UserMessage(
content="When is the next flight from Miami to Seattle?",
),
]
response = client.complete(
messages=messages, tools=tools, tool_choice="auto"
)
您可以檢查回應,以找出是否需要呼叫工具。 檢查完成原因,以判斷是否應該呼叫工具。 請記住,可以指定多個工具類型。 此範例示範 function
類型的工具。
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
print("Finish reason:", response.choices[0].finish_reason)
print("Tool call:", tool_calls)
若要繼續,將此訊息附加至聊天記錄:
messages.append(
response_message
)
現在,是時候呼叫適當函式來處理工具呼叫。 下列程式碼片段會逐一查看回應中指定的所有工具呼叫,並使用適當的參數來呼叫對應的函式。 回應也會附加至聊天記錄。
import json
from azure.ai.inference.models import ToolMessage
for tool_call in tool_calls:
# Get the tool details:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments.replace("\'", "\""))
tool_call_id = tool_call.id
print(f"Calling function `{function_name}` with arguments {function_args}")
# Call the function defined above using `locals()`, which returns the list of all functions
# available in the scope as a dictionary. Notice that this is just done as a simple way to get
# the function callable from its string name. Then we can call it with the corresponding
# arguments.
callable_func = locals()[function_name]
function_response = callable_func(**function_args)
print("->", function_response)
# Once we have a response from the function and its arguments, we can append a new message to the chat
# history. Notice how we are telling to the model that this chat message came from a tool:
messages.append(
ToolMessage(
tool_call_id=tool_call_id,
content=json.dumps(function_response)
)
)
檢視來自模型的回應:
response = client.complete(
messages=messages,
tools=tools,
)
套用內容安全
Azure AI 模型推斷 API 支援 Azure AI 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。
下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。
from azure.ai.inference.models import AssistantMessage, UserMessage, SystemMessage
try:
response = client.complete(
messages=[
SystemMessage(content="You are an AI assistant that helps people find information."),
UserMessage(content="Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."),
]
)
print(response.choices[0].message.content)
except HttpResponseError as ex:
if ex.status_code == 400:
response = ex.response.json()
if isinstance(response, dict) and "error" in response:
print(f"Your request triggered an {response['error']['code']} error:\n\t {response['error']['message']}")
else:
raise
raise
提示
若要深入了解如何設定及控制 Azure AI 內容安全設定,請參閱 Azure AI 內容安全文件。
搭配影像使用聊天完成
某些模型可能會根據這兩種輸入來推斷文字和影像,併產生文字完成。 在本節中,您會探索一些模型以聊天方式視覺的功能:
重要
有些模型在聊天交談中只支援每個回合的一個影像,而且只有最後一個影像會保留在內容中。 如果您新增多個影像,則會產生錯誤。
若要查看此功能,請下載影像,並將資訊編碼為 base64
字串。 產生的資料應該位於資料 URL 內:
from urllib.request import urlopen, Request
import base64
image_url = "https://news.microsoft.com/source/wp-content/uploads/2024/04/The-Phi-3-small-language-models-with-big-potential-1-1900x1069.jpg"
image_format = "jpeg"
request = Request(image_url, headers={"User-Agent": "Mozilla/5.0"})
image_data = base64.b64encode(urlopen(request).read()).decode("utf-8")
data_url = f"data:image/{image_format};base64,{image_data}"
將影像視覺化:
import requests
import IPython.display as Disp
Disp.Image(requests.get(image_url).content)
現在,請使用影像建立聊天完成要求:
from azure.ai.inference.models import TextContentItem, ImageContentItem, ImageUrl
response = client.complete(
messages=[
SystemMessage("You are a helpful assistant that can generate responses based on images."),
UserMessage(content=[
TextContentItem(text="Which conclusion can be extracted from the following chart?"),
ImageContentItem(image=ImageUrl(url=data_url))
]),
],
temperature=0,
top_p=1,
max_tokens=2048,
)
回應如下所示,其中您可以查看模型的使用量統計資料:
print(f"{response.choices[0].message.role}:\n\t{response.choices[0].message.content}\n")
print("Model:", response.model)
print("Usage:")
print("\tPrompt tokens:", response.usage.prompt_tokens)
print("\tCompletion tokens:", response.usage.completion_tokens)
print("\tTotal tokens:", response.usage.total_tokens)
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.
Model: mistral-large-2407
Usage:
Prompt tokens: 2380
Completion tokens: 126
Total tokens: 2506
重要
本文中標示為 (預覽) 的項目目前處於公開預覽狀態。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款。
本文說明如何使用聊天完成 API 搭配部署至 Azure AI 模型推斷的 Azure AI 服務中的模型。
必要條件
若要在應用程式中使用聊天完成模型,您需要:
Azure 訂用帳戶。 如果您使用 GitHub Models,您可以升級您的體驗,並在程式中建立 Azure 訂用帳戶。 如果您的情況,請閱讀 從 GitHub 模型升級至 Azure AI 模型推斷 。
Azure AI 服務資源。 如需詳細資訊,請參閱 建立 Azure AI 服務資源。
端點 URL 和金鑰。
聊天完成模型部署。 如果您沒有一個閱讀將 模型新增並設定至 Azure AI 服務 ,以將聊天完成模型新增至您的資源。
使用下列命令安裝適用於 JavaScript 的 Azure 推斷連結庫:
npm install @azure-rest/ai-inference
使用聊天完成
首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 URL 和金鑰。
import ModelClient from "@azure-rest/ai-inference";
import { isUnexpected } from "@azure-rest/ai-inference";
import { AzureKeyCredential } from "@azure/core-auth";
const client = new ModelClient(
process.env.AZURE_INFERENCE_ENDPOINT,
new AzureKeyCredential(process.env.AZURE_INFERENCE_CREDENTIAL)
);
如果您已將資源設定為 Microsoft Entra ID 支援,您可以使用下列代碼段來建立用戶端。
import ModelClient from "@azure-rest/ai-inference";
import { isUnexpected } from "@azure-rest/ai-inference";
import { DefaultAzureCredential } from "@azure/identity";
const client = new ModelClient(
process.env.AZURE_INFERENCE_ENDPOINT,
new DefaultAzureCredential()
);
建立聊天完成要求
下列範例示範如何針對模型建立基本聊天完成要求。
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
}
});
注意
某些模型不支援系統訊息 (role="system"
)。 當您使用 Azure AI 模型推斷 API 時,系統訊息會轉譯為使用者訊息,這是可用功能中最為相似的功能。 此轉譯功能是為了方便起見而提供,但請務必確認模型遵循系統訊息中的指示,且具有正確的信賴度等級。
回應如下,您可以在其中查看模型的使用量統計資料:
if (isUnexpected(response)) {
throw response.body.error;
}
console.log("Response: ", response.body.choices[0].message.content);
console.log("Model: ", response.body.model);
console.log("Usage:");
console.log("\tPrompt tokens:", response.body.usage.prompt_tokens);
console.log("\tTotal tokens:", response.body.usage.total_tokens);
console.log("\tCompletion tokens:", response.body.usage.completion_tokens);
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: mistral-large-2407
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
檢查回應中的 usage
區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。
串流內容
根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。
您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。
若要串流完成,在呼叫模型時使用 .asNodeStream()
。
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
}
}).asNodeStream();
您可以將串流產生內容的方式視覺化:
var stream = response.body;
if (!stream) {
stream.destroy();
throw new Error(`Failed to get chat completions with status: ${response.status}`);
}
if (response.status !== "200") {
throw new Error(`Failed to get chat completions: ${response.body.error}`);
}
var sses = createSseStream(stream);
for await (const event of sses) {
if (event.data === "[DONE]") {
return;
}
for (const choice of (JSON.parse(event.data)).choices) {
console.log(choice.delta?.content ?? "");
}
}
探索推斷用戶端支援的更多參數
探索您可以在推斷用戶端中指定的其他參數。 如需所有支援參數及其對應文件的完整清單,請參閱 [Azure AI 模型推斷 API 參考]。
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
presence_penalty: "0.1",
frequency_penalty: "0.8",
max_tokens: 2048,
stop: ["<|endoftext|>"],
temperature: 0,
top_p: 1,
response_format: { type: "text" },
}
});
某些模型不支援 JSON 輸出格式設定。 您隨時都可以提示模型產生 JSON 輸出。 不過,這類輸出不保證為有效的 JSON。
如果您想要傳遞不在所支援參數清單中的參數,您可以使用 [額外的參數] 將其傳遞至基礎模型。 請參閱將額外的參數傳遞至模型。
建立 JSON 輸出
某些模型可以建立 JSON 輸出。 將 response_format
設定為 json_object
以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length"
,則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens
或交談超過了最大內容長度。
var messages = [
{ role: "system", content: "You are a helpful assistant that always generate responses in JSON format, using."
+ " the following format: { \"answer\": \"response\" }." },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
response_format: { type: "json_object" }
}
});
將額外的參數傳遞至模型
Azure AI 模型推斷 API 可讓您將額外的參數傳遞至模型。 下列程式碼範例示範如何將額外的參數 logprobs
傳遞至模型。
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
headers: {
"extra-params": "pass-through"
},
body: {
messages: messages,
logprobs: true
}
});
將額外的參數傳遞至 Azure AI 模型推斷 API 之前,請確定您的模型支援那些額外的參數。 對基礎模型提出要求時,會將標頭 extra-parameters
傳遞至具有 pass-through
值的模型。 這個值會告訴端點將額外的參數傳遞至模型。 搭配模型使用額外的參數,不保證模型實際上可以處理這些參數。 請參閱模型的文件,以了解支援哪些額外的參數。
使用工具
有些模型支援使用工具,當您需要從語言模型卸除特定工作時,這可以是非同尋常的資源,而是依賴更具決定性的系統,甚至是不同的語言模型。 Azure AI 模型推斷 API 可讓您以下列方式定義工具。
下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。
const flight_info = {
name: "get_flight_info",
description: "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
parameters: {
type: "object",
properties: {
origin_city: {
type: "string",
description: "The name of the city where the flight originates",
},
destination_city: {
type: "string",
description: "The flight destination city",
},
},
required: ["origin_city", "destination_city"],
},
}
const tools = [
{
type: "function",
function: flight_info,
},
];
在此範例中,函式的輸出是所選路線沒有適合的航班,但使用者應考慮進行訓練。
function get_flight_info(loc_origin, loc_destination) {
return {
info: "There are no flights available from " + loc_origin + " to " + loc_destination + ". You should take a train, specially if it helps to reduce CO2 emissions."
}
}
注意
Cohere 模型需要工具的回應,才能成為格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 JSON 字串。
使用此函式的說明,提示模型來預訂航班:
var result = await client.path("/chat/completions").post({
body: {
messages: messages,
tools: tools,
tool_choice: "auto"
}
});
您可以檢查回應,以找出是否需要呼叫工具。 檢查完成原因,以判斷是否應該呼叫工具。 請記住,可以指定多個工具類型。 此範例示範 function
類型的工具。
const response_message = response.body.choices[0].message;
const tool_calls = response_message.tool_calls;
console.log("Finish reason: " + response.body.choices[0].finish_reason);
console.log("Tool call: " + tool_calls);
若要繼續,將此訊息附加至聊天記錄:
messages.push(response_message);
現在,是時候呼叫適當函式來處理工具呼叫。 下列程式碼片段會逐一查看回應中指定的所有工具呼叫,並使用適當的參數來呼叫對應的函式。 回應也會附加至聊天記錄。
function applyToolCall({ function: call, id }) {
// Get the tool details:
const tool_params = JSON.parse(call.arguments);
console.log("Calling function " + call.name + " with arguments " + tool_params);
// Call the function defined above using `window`, which returns the list of all functions
// available in the scope as a dictionary. Notice that this is just done as a simple way to get
// the function callable from its string name. Then we can call it with the corresponding
// arguments.
const function_response = tool_params.map(window[call.name]);
console.log("-> " + function_response);
return function_response
}
for (const tool_call of tool_calls) {
var tool_response = tool_call.apply(applyToolCall);
messages.push(
{
role: "tool",
tool_call_id: tool_call.id,
content: tool_response
}
);
}
檢視來自模型的回應:
var result = await client.path("/chat/completions").post({
body: {
messages: messages,
tools: tools,
}
});
套用內容安全
Azure AI 模型推斷 API 支援 Azure AI 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。
下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。
try {
var messages = [
{ role: "system", content: "You are an AI assistant that helps people find information." },
{ role: "user", content: "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills." },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
}
});
console.log(response.body.choices[0].message.content);
}
catch (error) {
if (error.status_code == 400) {
var response = JSON.parse(error.response._content);
if (response.error) {
console.log(`Your request triggered an ${response.error.code} error:\n\t ${response.error.message}`);
}
else
{
throw error;
}
}
}
提示
若要深入了解如何設定及控制 Azure AI 內容安全設定,請參閱 Azure AI 內容安全文件。
搭配影像使用聊天完成
某些模型可能會根據這兩種輸入來推斷文字和影像,併產生文字完成。 在本節中,您會探索一些模型以聊天方式視覺的功能:
重要
有些模型在聊天交談中只支援每個回合的一個影像,而且只有最後一個影像會保留在內容中。 如果您新增多個影像,則會產生錯誤。
若要查看此功能,請下載影像,並將資訊編碼為 base64
字串。 產生的資料應該位於資料 URL 內:
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";
const image_format = "jpeg";
const response = await fetch(image_url, { headers: { "User-Agent": "Mozilla/5.0" } });
const image_data = await response.arrayBuffer();
const image_data_base64 = Buffer.from(image_data).toString("base64");
const data_url = `data:image/${image_format};base64,${image_data_base64}`;
將影像視覺化:
const img = document.createElement("img");
img.src = data_url;
document.body.appendChild(img);
現在,請使用影像建立聊天完成要求:
var messages = [
{ role: "system", content: "You are a helpful assistant that can generate responses based on images." },
{ role: "user", content:
[
{ type: "text", text: "Which conclusion can be extracted from the following chart?" },
{ type: "image_url", image:
{
url: data_url
}
}
]
}
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
temperature: 0,
top_p: 1,
max_tokens: 2048,
}
});
回應如下所示,其中您可以查看模型的使用量統計資料:
console.log(response.body.choices[0].message.role + ": " + response.body.choices[0].message.content);
console.log("Model:", response.body.model);
console.log("Usage:");
console.log("\tPrompt tokens:", response.body.usage.prompt_tokens);
console.log("\tCompletion tokens:", response.body.usage.completion_tokens);
console.log("\tTotal tokens:", response.body.usage.total_tokens);
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.
Model: mistral-large-2407
Usage:
Prompt tokens: 2380
Completion tokens: 126
Total tokens: 2506
重要
本文中標示為 (預覽) 的項目目前處於公開預覽狀態。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款。
本文說明如何使用聊天完成 API 搭配部署至 Azure AI 模型推斷的 Azure AI 服務中的模型。
必要條件
若要在應用程式中使用聊天完成模型,您需要:
Azure 訂用帳戶。 如果您使用 GitHub Models,您可以升級您的體驗,並在程式中建立 Azure 訂用帳戶。 如果您的情況,請閱讀 從 GitHub 模型升級至 Azure AI 模型推斷 。
Azure AI 服務資源。 如需詳細資訊,請參閱 建立 Azure AI 服務資源。
端點 URL 和金鑰。
聊天完成模型部署。 如果您沒有一個閱讀將 模型新增並設定至 Azure AI 服務 ,以將聊天完成模型新增至您的資源。
將 Azure AI 推斷套件新增至您的專案:
<dependency> <groupId>com.azure</groupId> <artifactId>azure-ai-inference</artifactId> <version>1.0.0-beta.1</version> </dependency>
如果您使用 Entra ID,則也需要下列套件:
<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.13.3</version> </dependency>
匯入下列命名空間:
package com.azure.ai.inference.usage; import com.azure.ai.inference.EmbeddingsClient; import com.azure.ai.inference.EmbeddingsClientBuilder; import com.azure.ai.inference.models.EmbeddingsResult; import com.azure.ai.inference.models.EmbeddingItem; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; import java.util.ArrayList; import java.util.List;
使用聊天完成
首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 URL 和金鑰。
如果您已將資源設定為 Microsoft Entra ID 支援,您可以使用下列代碼段來建立用戶端。
建立聊天完成要求
下列範例示範如何針對模型建立基本聊天完成要求。
注意
某些模型不支援系統訊息 (role="system"
)。 當您使用 Azure AI 模型推斷 API 時,系統訊息會轉譯為使用者訊息,這是可用功能中最為相似的功能。 此轉譯功能是為了方便起見而提供,但請務必確認模型遵循系統訊息中的指示,且具有正確的信賴度等級。
回應如下,您可以在其中查看模型的使用量統計資料:
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: mistral-large-2407
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
檢查回應中的 usage
區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。
串流內容
根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。
您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。
您可以將串流產生內容的方式視覺化:
探索推斷用戶端支援的更多參數
探索您可以在推斷用戶端中指定的其他參數。 如需所有支援參數及其對應文件的完整清單,請參閱 [Azure AI 模型推斷 API 參考]。 某些模型不支援 JSON 輸出格式設定。 您隨時都可以提示模型產生 JSON 輸出。 不過,這類輸出不保證為有效的 JSON。
如果您想要傳遞不在所支援參數清單中的參數,您可以使用 [額外的參數] 將其傳遞至基礎模型。 請參閱將額外的參數傳遞至模型。
建立 JSON 輸出
某些模型可以建立 JSON 輸出。 將 response_format
設定為 json_object
以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length"
,則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens
或交談超過了最大內容長度。
將額外的參數傳遞至模型
Azure AI 模型推斷 API 可讓您將額外的參數傳遞至模型。 下列程式碼範例示範如何將額外的參數 logprobs
傳遞至模型。
將額外的參數傳遞至 Azure AI 模型推斷 API 之前,請確定您的模型支援那些額外的參數。 對基礎模型提出要求時,會將標頭 extra-parameters
傳遞至具有 pass-through
值的模型。 這個值會告訴端點將額外的參數傳遞至模型。 搭配模型使用額外的參數,不保證模型實際上可以處理這些參數。 請參閱模型的文件,以了解支援哪些額外的參數。
使用工具
有些模型支援使用工具,當您需要從語言模型卸除特定工作時,這可以是非同尋常的資源,而是依賴更具決定性的系統,甚至是不同的語言模型。 Azure AI 模型推斷 API 可讓您以下列方式定義工具。
下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。
在此範例中,函式的輸出是所選路線沒有適合的航班,但使用者應考慮進行訓練。
注意
Cohere 模型需要工具的回應,才能成為格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 JSON 字串。
使用此函式的說明,提示模型來預訂航班:
您可以檢查回應,以找出是否需要呼叫工具。 檢查完成原因,以判斷是否應該呼叫工具。 請記住,可以指定多個工具類型。 此範例示範 function
類型的工具。
若要繼續,將此訊息附加至聊天記錄:
現在,是時候呼叫適當函式來處理工具呼叫。 下列程式碼片段會逐一查看回應中指定的所有工具呼叫,並使用適當的參數來呼叫對應的函式。 回應也會附加至聊天記錄。
檢視來自模型的回應:
套用內容安全
Azure AI 模型推斷 API 支援 Azure AI 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。
下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。
提示
若要深入了解如何設定及控制 Azure AI 內容安全設定,請參閱 Azure AI 內容安全文件。
搭配影像使用聊天完成
某些模型可能會根據這兩種輸入來推斷文字和影像,併產生文字完成。 在本節中,您會探索一些模型以聊天方式視覺的功能:
重要
有些模型在聊天交談中只支援每個回合的一個影像,而且只有最後一個影像會保留在內容中。 如果您新增多個影像,則會產生錯誤。
若要查看此功能,請下載影像,並將資訊編碼為 base64
字串。 產生的資料應該位於資料 URL 內:
將影像視覺化:
現在,請使用影像建立聊天完成要求:
回應如下所示,其中您可以查看模型的使用量統計資料:
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.
Model: mistral-large-2407
Usage:
Prompt tokens: 2380
Completion tokens: 126
Total tokens: 2506
重要
本文中標示為 (預覽) 的項目目前處於公開預覽狀態。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款。
本文說明如何使用聊天完成 API 搭配部署至 Azure AI 模型推斷的 Azure AI 服務中的模型。
必要條件
若要在應用程式中使用聊天完成模型,您需要:
Azure 訂用帳戶。 如果您使用 GitHub Models,您可以升級您的體驗,並在程式中建立 Azure 訂用帳戶。 如果您的情況,請閱讀 從 GitHub 模型升級至 Azure AI 模型推斷 。
Azure AI 服務資源。 如需詳細資訊,請參閱 建立 Azure AI 服務資源。
端點 URL 和金鑰。
聊天完成模型部署。 如果您沒有一個閱讀將 模型新增並設定至 Azure AI 服務 ,以將聊天完成模型新增至您的資源。
使用下列命令安裝 Azure AI 推斷套件:
dotnet add package Azure.AI.Inference --prerelease
如果您使用 Entra ID,則也需要下列套件:
dotnet add package Azure.Identity
使用聊天完成
首先,建立用戶端以取用模型。 下列程式碼會使用儲存在環境變數中的端點 URL 和金鑰。
ChatCompletionsClient client = new ChatCompletionsClient(
new Uri(Environment.GetEnvironmentVariable("AZURE_INFERENCE_ENDPOINT")),
new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_INFERENCE_CREDENTIAL")),
"mistral-large-2407"
);
如果您已將資源設定為 Microsoft Entra ID 支援,您可以使用下列代碼段來建立用戶端。
client = new ChatCompletionsClient(
new Uri(Environment.GetEnvironmentVariable("AZURE_INFERENCE_ENDPOINT")),
new DefaultAzureCredential(includeInteractiveCredentials: true),
"mistral-large-2407"
);
建立聊天完成要求
下列範例示範如何針對模型建立基本聊天完成要求。
ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world?")
},
};
Response<ChatCompletions> response = client.Complete(requestOptions);
注意
某些模型不支援系統訊息 (role="system"
)。 當您使用 Azure AI 模型推斷 API 時,系統訊息會轉譯為使用者訊息,這是可用功能中最為相似的功能。 此轉譯功能是為了方便起見而提供,但請務必確認模型遵循系統訊息中的指示,且具有正確的信賴度等級。
回應如下,您可以在其中查看模型的使用量統計資料:
Console.WriteLine($"Response: {response.Value.Content}");
Console.WriteLine($"Model: {response.Value.Model}");
Console.WriteLine("Usage:");
Console.WriteLine($"\tPrompt tokens: {response.Value.Usage.PromptTokens}");
Console.WriteLine($"\tTotal tokens: {response.Value.Usage.TotalTokens}");
Console.WriteLine($"\tCompletion tokens: {response.Value.Usage.CompletionTokens}");
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: mistral-large-2407
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
檢查回應中的 usage
區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。
串流內容
根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。
您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。
若要串流完成,在呼叫模型時使用 CompleteStreamingAsync
方法。 請注意,在此範例中,呼叫會包裝在非同步方法中。
static async Task StreamMessageAsync(ChatCompletionsClient client)
{
ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world? Write an essay about it.")
},
MaxTokens=4096
};
StreamingResponse<StreamingChatCompletionsUpdate> streamResponse = await client.CompleteStreamingAsync(requestOptions);
await PrintStream(streamResponse);
}
若要將輸出視覺化,請定義非同步方法,以在主控台中列印串流。
static async Task PrintStream(StreamingResponse<StreamingChatCompletionsUpdate> response)
{
await foreach (StreamingChatCompletionsUpdate chatUpdate in response)
{
if (chatUpdate.Role.HasValue)
{
Console.Write($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
}
if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
{
Console.Write(chatUpdate.ContentUpdate);
}
}
}
您可以將串流產生內容的方式視覺化:
StreamMessageAsync(client).GetAwaiter().GetResult();
探索推斷用戶端支援的更多參數
探索您可以在推斷用戶端中指定的其他參數。 如需所有支援參數及其對應文件的完整清單,請參閱 [Azure AI 模型推斷 API 參考]。
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world?")
},
PresencePenalty = 0.1f,
FrequencyPenalty = 0.8f,
MaxTokens = 2048,
StopSequences = { "<|endoftext|>" },
Temperature = 0,
NucleusSamplingFactor = 1,
ResponseFormat = new ChatCompletionsResponseFormatText()
};
response = client.Complete(requestOptions);
Console.WriteLine($"Response: {response.Value.Content}");
某些模型不支援 JSON 輸出格式設定。 您隨時都可以提示模型產生 JSON 輸出。 不過,這類輸出不保證為有效的 JSON。
如果您想要傳遞不在所支援參數清單中的參數,您可以使用 [額外的參數] 將其傳遞至基礎模型。 請參閱將額外的參數傳遞至模型。
建立 JSON 輸出
某些模型可以建立 JSON 輸出。 將 response_format
設定為 json_object
以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length"
,則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens
或交談超過了最大內容長度。
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage(
"You are a helpful assistant that always generate responses in JSON format, " +
"using. the following format: { \"answer\": \"response\" }."
),
new ChatRequestUserMessage(
"How many languages are in the world?"
)
},
ResponseFormat = new ChatCompletionsResponseFormatJSON()
};
response = client.Complete(requestOptions);
Console.WriteLine($"Response: {response.Value.Content}");
將額外的參數傳遞至模型
Azure AI 模型推斷 API 可讓您將額外的參數傳遞至模型。 下列程式碼範例示範如何將額外的參數 logprobs
傳遞至模型。
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world?")
},
AdditionalProperties = { { "logprobs", BinaryData.FromString("true") } },
};
response = client.Complete(requestOptions, extraParams: ExtraParameters.PassThrough);
Console.WriteLine($"Response: {response.Value.Content}");
將額外的參數傳遞至 Azure AI 模型推斷 API 之前,請確定您的模型支援那些額外的參數。 對基礎模型提出要求時,會將標頭 extra-parameters
傳遞至具有 pass-through
值的模型。 這個值會告訴端點將額外的參數傳遞至模型。 搭配模型使用額外的參數,不保證模型實際上可以處理這些參數。 請參閱模型的文件,以了解支援哪些額外的參數。
使用工具
有些模型支援使用工具,當您需要從語言模型卸除特定工作時,這可以是非同尋常的資源,而是依賴更具決定性的系統,甚至是不同的語言模型。 Azure AI 模型推斷 API 可讓您以下列方式定義工具。
下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。
FunctionDefinition flightInfoFunction = new FunctionDefinition("getFlightInfo")
{
Description = "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
Parameters = BinaryData.FromObjectAsJson(new
{
Type = "object",
Properties = new
{
origin_city = new
{
Type = "string",
Description = "The name of the city where the flight originates"
},
destination_city = new
{
Type = "string",
Description = "The flight destination city"
}
}
},
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
)
};
ChatCompletionsFunctionToolDefinition getFlightTool = new ChatCompletionsFunctionToolDefinition(flightInfoFunction);
在此範例中,函式的輸出是所選路線沒有適合的航班,但使用者應考慮進行訓練。
static string getFlightInfo(string loc_origin, string loc_destination)
{
return JsonSerializer.Serialize(new
{
info = $"There are no flights available from {loc_origin} to {loc_destination}. You " +
"should take a train, specially if it helps to reduce CO2 emissions."
});
}
注意
Cohere 模型需要工具的回應,才能成為格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 JSON 字串。
使用此函式的說明,提示模型來預訂航班:
var chatHistory = new List<ChatRequestMessage>(){
new ChatRequestSystemMessage(
"You are a helpful assistant that help users to find information about traveling, " +
"how to get to places and the different transportations options. You care about the" +
"environment and you always have that in mind when answering inqueries."
),
new ChatRequestUserMessage("When is the next flight from Miami to Seattle?")
};
requestOptions = new ChatCompletionsOptions(chatHistory);
requestOptions.Tools.Add(getFlightTool);
requestOptions.ToolChoice = ChatCompletionsToolChoice.Auto;
response = client.Complete(requestOptions);
您可以檢查回應,以找出是否需要呼叫工具。 檢查完成原因,以判斷是否應該呼叫工具。 請記住,可以指定多個工具類型。 此範例示範 function
類型的工具。
var responseMessage = response.Value;
var toolsCall = responseMessage.ToolCalls;
Console.WriteLine($"Finish reason: {response.Value.Choices[0].FinishReason}");
Console.WriteLine($"Tool call: {toolsCall[0].Id}");
若要繼續,將此訊息附加至聊天記錄:
requestOptions.Messages.Add(new ChatRequestAssistantMessage(response.Value));
現在,是時候呼叫適當函式來處理工具呼叫。 下列程式碼片段會逐一查看回應中指定的所有工具呼叫,並使用適當的參數來呼叫對應的函式。 回應也會附加至聊天記錄。
foreach (ChatCompletionsToolCall tool in toolsCall)
{
if (tool is ChatCompletionsFunctionToolCall functionTool)
{
// Get the tool details:
string callId = functionTool.Id;
string toolName = functionTool.Name;
string toolArgumentsString = functionTool.Arguments;
Dictionary<string, object> toolArguments = JsonSerializer.Deserialize<Dictionary<string, object>>(toolArgumentsString);
// Here you have to call the function defined. In this particular example we use
// reflection to find the method we definied before in an static class called
// `ChatCompletionsExamples`. Using reflection allows us to call a function
// by string name. Notice that this is just done for demonstration purposes as a
// simple way to get the function callable from its string name. Then we can call
// it with the corresponding arguments.
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
string toolResponse = (string)typeof(ChatCompletionsExamples).GetMethod(toolName, flags).Invoke(null, toolArguments.Values.Cast<object>().ToArray());
Console.WriteLine("->", toolResponse);
requestOptions.Messages.Add(new ChatRequestToolMessage(toolResponse, callId));
}
else
throw new Exception("Unsupported tool type");
}
檢視來自模型的回應:
response = client.Complete(requestOptions);
套用內容安全
Azure AI 模型推斷 API 支援 Azure AI 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。
下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。
try
{
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are an AI assistant that helps people find information."),
new ChatRequestUserMessage(
"Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."
),
},
};
response = client.Complete(requestOptions);
Console.WriteLine(response.Value.Content);
}
catch (RequestFailedException ex)
{
if (ex.ErrorCode == "content_filter")
{
Console.WriteLine($"Your query has trigger Azure Content Safety: {ex.Message}");
}
else
{
throw;
}
}
提示
若要深入了解如何設定及控制 Azure AI 內容安全設定,請參閱 Azure AI 內容安全文件。
搭配影像使用聊天完成
某些模型可能會根據這兩種輸入來推斷文字和影像,併產生文字完成。 在本節中,您會探索一些模型以聊天方式視覺的功能:
重要
有些模型在聊天交談中只支援每個回合的一個影像,而且只有最後一個影像會保留在內容中。 如果您新增多個影像,則會產生錯誤。
若要查看此功能,請下載影像,並將資訊編碼為 base64
字串。 產生的資料應該位於資料 URL 內:
string imageUrl = "https://news.microsoft.com/source/wp-content/uploads/2024/04/The-Phi-3-small-language-models-with-big-potential-1-1900x1069.jpg";
string imageFormat = "jpeg";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
byte[] imageBytes = httpClient.GetByteArrayAsync(imageUrl).Result;
string imageBase64 = Convert.ToBase64String(imageBytes);
string dataUrl = $"data:image/{imageFormat};base64,{imageBase64}";
將影像視覺化:
現在,請使用影像建立聊天完成要求:
ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are an AI assistant that helps people find information."),
new ChatRequestUserMessage([
new ChatMessageTextContentItem("Which conclusion can be extracted from the following chart?"),
new ChatMessageImageContentItem(new Uri(dataUrl))
]),
},
MaxTokens=2048,
};
var response = client.Complete(requestOptions);
Console.WriteLine(response.Value.Content);
回應如下所示,其中您可以查看模型的使用量統計資料:
Console.WriteLine($"{response.Value.Role}: {response.Value.Content}");
Console.WriteLine($"Model: {response.Value.Model}");
Console.WriteLine("Usage:");
Console.WriteLine($"\tPrompt tokens: {response.Value.Usage.PromptTokens}");
Console.WriteLine($"\tTotal tokens: {response.Value.Usage.TotalTokens}");
Console.WriteLine($"\tCompletion tokens: {response.Value.Usage.CompletionTokens}");
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.
Model: mistral-large-2407
Usage:
Prompt tokens: 2380
Completion tokens: 126
Total tokens: 2506
重要
本文中標示為 (預覽) 的項目目前處於公開預覽狀態。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款。
本文說明如何使用聊天完成 API 搭配部署至 Azure AI 模型推斷的 Azure AI 服務中的模型。
必要條件
若要在應用程式中使用聊天完成模型,您需要:
Azure 訂用帳戶。 如果您使用 GitHub Models,您可以升級您的體驗,並在程式中建立 Azure 訂用帳戶。 如果您的情況,請閱讀 從 GitHub 模型升級至 Azure AI 模型推斷 。
Azure AI 服務資源。 如需詳細資訊,請參閱 建立 Azure AI 服務資源。
端點 URL 和金鑰。
- 聊天完成模型部署。 如果您沒有一個閱讀將 模型新增並設定至 Azure AI 服務 ,以將聊天完成模型新增至您的資源。
使用聊天完成
若要使用文字內嵌,請使用附加至基底 URL 的路由 /chat/completions
,以及 中 api-key
指示的認證。
Authorization
格式也支持 Bearer <key>
標頭。
POST https://<resource>.services.ai.azure.com/models/chat/completions?api-version=2024-05-01-preview
Content-Type: application/json
api-key: <key>
如果您已使用 Microsoft Entra ID 支援來設定資源,請在標頭中 Authorization
傳遞令牌:
POST https://<resource>.services.ai.azure.com/models/chat/completions?api-version=2024-05-01-preview
Content-Type: application/json
Authorization: Bearer <token>
建立聊天完成要求
下列範例示範如何針對模型建立基本聊天完成要求。
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
]
}
注意
某些模型不支援系統訊息 (role="system"
)。 當您使用 Azure AI 模型推斷 API 時,系統訊息會轉譯為使用者訊息,這是可用功能中最為相似的功能。 此轉譯功能是為了方便起見而提供,但請務必確認模型遵循系統訊息中的指示,且具有正確的信賴度等級。
回應如下,您可以在其中查看模型的使用量統計資料:
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718726686,
"model": "mistral-large-2407",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.",
"tool_calls": null
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 19,
"total_tokens": 91,
"completion_tokens": 72
}
}
檢查回應中的 usage
區段,以查看提示所使用的權杖數目、產生的權杖總數,以及用於完成文字的權杖數目。
串流內容
根據預設,完成 API 會在單一回應中傳回整個產生的內容。 如果您正在產生的完成很長,則等候回應可能需要數秒鐘的時間。
您可以 [串流] 內容,以在內容產生期間取得它。 串流內容可讓您在內容變成可用時立即開始處理完成。 此模式會傳回以 [僅限資料的伺服器傳送事件] 形式將回應串流回來的物件。 從差異欄位擷取區塊,而不是訊息欄位。
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"stream": true,
"temperature": 0,
"top_p": 1,
"max_tokens": 2048
}
您可以將串流產生內容的方式視覺化:
{
"id": "23b54589eba14564ad8a2e6978775a39",
"object": "chat.completion.chunk",
"created": 1718726371,
"model": "mistral-large-2407",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": ""
},
"finish_reason": null,
"logprobs": null
}
]
}
串流中的最後一則訊息已設定 finish_reason
,其會指出產生流程停止的原因。
{
"id": "23b54589eba14564ad8a2e6978775a39",
"object": "chat.completion.chunk",
"created": 1718726371,
"model": "mistral-large-2407",
"choices": [
{
"index": 0,
"delta": {
"content": ""
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 19,
"total_tokens": 91,
"completion_tokens": 72
}
}
探索推斷用戶端支援的更多參數
探索您可以在推斷用戶端中指定的其他參數。 如需所有支援參數及其對應文件的完整清單,請參閱 [Azure AI 模型推斷 API 參考]。
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"presence_penalty": 0.1,
"frequency_penalty": 0.8,
"max_tokens": 2048,
"stop": ["<|endoftext|>"],
"temperature" :0,
"top_p": 1,
"response_format": { "type": "text" }
}
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718726686,
"model": "mistral-large-2407",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.",
"tool_calls": null
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 19,
"total_tokens": 91,
"completion_tokens": 72
}
}
某些模型不支援 JSON 輸出格式設定。 您隨時都可以提示模型產生 JSON 輸出。 不過,這類輸出不保證為有效的 JSON。
如果您想要傳遞不在所支援參數清單中的參數,您可以使用 [額外的參數] 將其傳遞至基礎模型。 請參閱將額外的參數傳遞至模型。
建立 JSON 輸出
某些模型可以建立 JSON 輸出。 將 response_format
設定為 json_object
以啟用 JSON 模式,並保證模型產生的訊息為有效的 JSON。 您也必須透過系統或使用者訊息來指示模型自行產生 JSON。 此外,如果 finish_reason="length"
,則訊息內容可能會遭到部分截斷,這表示生成超過了 max_tokens
或交談超過了最大內容長度。
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that always generate responses in JSON format, using the following format: { \"answer\": \"response\" }"
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"response_format": { "type": "json_object" }
}
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718727522,
"model": "mistral-large-2407",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\"answer\": \"There are approximately 7,117 living languages in the world today, according to the latest estimates. However, this number can vary as some languages become extinct and others are newly discovered or classified.\"}",
"tool_calls": null
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 39,
"total_tokens": 87,
"completion_tokens": 48
}
}
將額外的參數傳遞至模型
Azure AI 模型推斷 API 可讓您將額外的參數傳遞至模型。 下列程式碼範例示範如何將額外的參數 logprobs
傳遞至模型。
POST https://<resource>.services.ai.azure.com/models/chat/completions?api-version=2024-05-01-preview
Authorization: Bearer <TOKEN>
Content-Type: application/json
extra-parameters: pass-through
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"logprobs": true
}
將額外的參數傳遞至 Azure AI 模型推斷 API 之前,請確定您的模型支援那些額外的參數。 對基礎模型提出要求時,會將標頭 extra-parameters
傳遞至具有 pass-through
值的模型。 這個值會告訴端點將額外的參數傳遞至模型。 搭配模型使用額外的參數,不保證模型實際上可以處理這些參數。 請參閱模型的文件,以了解支援哪些額外的參數。
使用工具
有些模型支援使用工具,當您需要從語言模型卸除特定工作時,這可以是非同尋常的資源,而是依賴更具決定性的系統,甚至是不同的語言模型。 Azure AI 模型推斷 API 可讓您以下列方式定義工具。
下列程式碼範例會建立工具定義,可查看來自兩個不同城市的航班資訊。
{
"type": "function",
"function": {
"name": "get_flight_info",
"description": "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
"parameters": {
"type": "object",
"properties": {
"origin_city": {
"type": "string",
"description": "The name of the city where the flight originates"
},
"destination_city": {
"type": "string",
"description": "The flight destination city"
}
},
"required": [
"origin_city",
"destination_city"
]
}
}
}
在此範例中,函式的輸出是所選路線沒有適合的航班,但使用者應考慮進行訓練。
注意
Cohere 模型需要工具的回應,才能成為格式化為字串的有效 JSON 內容。 建構「工具」類型的訊息時,請確定回應是有效的 JSON 字串。
使用此函式的說明,提示模型來預訂航班:
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that help users to find information about traveling, how to get to places and the different transportations options. You care about the environment and you always have that in mind when answering inqueries"
},
{
"role": "user",
"content": "When is the next flight from Miami to Seattle?"
}
],
"tool_choice": "auto",
"tools": [
{
"type": "function",
"function": {
"name": "get_flight_info",
"description": "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
"parameters": {
"type": "object",
"properties": {
"origin_city": {
"type": "string",
"description": "The name of the city where the flight originates"
},
"destination_city": {
"type": "string",
"description": "The flight destination city"
}
},
"required": [
"origin_city",
"destination_city"
]
}
}
}
]
}
您可以檢查回應,以找出是否需要呼叫工具。 檢查完成原因,以判斷是否應該呼叫工具。 請記住,可以指定多個工具類型。 此範例示範 function
類型的工具。
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718726007,
"model": "mistral-large-2407",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "abc0dF1gh",
"type": "function",
"function": {
"name": "get_flight_info",
"arguments": "{\"origin_city\": \"Miami\", \"destination_city\": \"Seattle\"}",
"call_id": null
}
}
]
},
"finish_reason": "tool_calls",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 190,
"total_tokens": 226,
"completion_tokens": 36
}
}
若要繼續,將此訊息附加至聊天記錄:
現在,是時候呼叫適當函式來處理工具呼叫。 下列程式碼片段會逐一查看回應中指定的所有工具呼叫,並使用適當的參數來呼叫對應的函式。 回應也會附加至聊天記錄。
檢視來自模型的回應:
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that help users to find information about traveling, how to get to places and the different transportations options. You care about the environment and you always have that in mind when answering inqueries"
},
{
"role": "user",
"content": "When is the next flight from Miami to Seattle?"
},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "abc0DeFgH",
"type": "function",
"function": {
"name": "get_flight_info",
"arguments": "{\"origin_city\": \"Miami\", \"destination_city\": \"Seattle\"}",
"call_id": null
}
}
]
},
{
"role": "tool",
"content": "{ \"info\": \"There are no flights available from Miami to Seattle. You should take a train, specially if it helps to reduce CO2 emissions.\" }",
"tool_call_id": "abc0DeFgH"
}
],
"tool_choice": "auto",
"tools": [
{
"type": "function",
"function": {
"name": "get_flight_info",
"description": "Returns information about the next flight between two cities. This includes the name of the airline, flight number and the date and time of the next flight",
"parameters":{
"type": "object",
"properties": {
"origin_city": {
"type": "string",
"description": "The name of the city where the flight originates"
},
"destination_city": {
"type": "string",
"description": "The flight destination city"
}
},
"required": ["origin_city", "destination_city"]
}
}
}
]
}
套用內容安全
Azure AI 模型推斷 API 支援 Azure AI 內容安全。 當您使用已開啟 Azure AI 內容安全的部署時,輸入和輸出都會通過旨在偵測及防止有害內容輸出的一組分類模型。 內容篩選系統會偵測並針對輸入提示和輸出完成中的特定類別的潛在有害內容採取動作。
下列範例示範當模型偵測到輸入提示中的有害內容並啟用內容安全時,如何處理事件。
{
"model": "mistral-large-2407",
"messages": [
{
"role": "system",
"content": "You are an AI assistant that helps people find information."
},
{
"role": "user",
"content": "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."
}
]
}
{
"error": {
"message": "The response was filtered due to the prompt triggering Microsoft's content management policy. Please modify your prompt and retry.",
"type": null,
"param": "prompt",
"code": "content_filter",
"status": 400
}
}
提示
若要深入了解如何設定及控制 Azure AI 內容安全設定,請參閱 Azure AI 內容安全文件。
搭配影像使用聊天完成
某些模型可能會根據這兩種輸入來推斷文字和影像,併產生文字完成。 在本節中,您會探索一些模型以聊天方式視覺的功能:
重要
有些模型在聊天交談中只支援每個回合的一個影像,而且只有最後一個影像會保留在內容中。 如果您新增多個影像,則會產生錯誤。
若要查看此功能,請下載影像,並將資訊編碼為 base64
字串。 產生的資料應該位於資料 URL 內:
提示
您必須使用文稿或程式設計語言來建構資料 URL。 本教學課程使用 JPEG 格式的這個範例影像。 資料 URL 的格式如下:data:image/jpg;base64,0xABCDFGHIJKLMNOPQRSTUVWXYZ...
。
將影像視覺化:
現在,請使用影像建立聊天完成要求:
{
"model": "phi-3.5-vision-instruct",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Which peculiar conclusion about LLMs and SLMs can be extracted from the following chart?"
},
{
"type": "image_url",
"image_url": {
"url": "data:image/jpg;base64,0xABCDFGHIJKLMNOPQRSTUVWXYZ..."
}
}
]
}
],
"temperature": 0,
"top_p": 1,
"max_tokens": 2048
}
回應如下所示,其中您可以查看模型的使用量統計資料:
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718726686,
"model": "phi-3.5-vision-instruct",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "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.",
"tool_calls": null
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 2380,
"completion_tokens": 126,
"total_tokens": 2506
}
}