你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

如何使用 Mistral 高级聊天模型

重要

本文介绍的某些功能可能仅在预览版中提供。 此预览版未提供服务级别协议,不建议将其用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

在本文中,你将了解 Mistral 高级聊天模型以及如何使用它们。 Mistral AI 提供两类模型。 高级模型(包括 Mistral Large 和 Mistral Small)以无服务器 API 的形式提供,并采用基于令牌的即用即付计费。 开放式模型(包括 Mistral NemoMixtral-8x7B-Instruct-v01、Mixtral-8x7B-v01、Mistral-7B-Instruct-v01 和 Mistral-7B-v01)也可供下载和在自承载托管终结点上运行。

Mistral 高级聊天模型

Mistral 高级聊天模型包括以下模型:

Mistral Large 是 Mistral AI 最先进的大型语言模型 (LLM)。 由于其先进的推理和知识能力,它可以用于任何基于语言的任务。

此外,Mistral Large:

  • 专用于 RAG。 重要信息不会在长上下文窗口(最多 32-K 个标记)中间丢失。
  • 编码能力强。 代码生成、代码评审和注释。 支持所有主流编码语言。
  • 多语言设计。 在法语、德语、西班牙语、意大利语和英语中表现优秀。 支持数十种语言。
  • 符合负责任 AI 原则。 模型中内置了高效的防护措施,并提供具有 safe_mode 选项的额外安全层。

Mistral Large (2407) 的特性包括:

  • 多语言设计。 支持数十种语言,包括英语、法语、德语、西班牙语和意大利语。
  • 精通编码。 使用 80 多种编码语言(包括 Python、Java、C、C++、JavaScript 和 Bash)进行了训练。 还对更具体的语言进行了训练,如 Swift 和 Fortran。
  • 以代理为中心。 拥有原生函数调用和 JSON 输出的代理功能。
  • 高级的推理能力。 具有先进的数学和推理能力。

以下模型可用:

提示

此外,MistralAI 还支持将定制的 API 与模型的特定功能配合使用。 若使用特定于模型提供商的 API,请查看 MistralAI 文档,或者参阅推理示例部分以编写示例。

先决条件

若要将 Mistral 高级聊天模型与 Azure AI Studio 配合使用,需要满足以下先决条件:

模型部署

部署到无服务器 API

Mistral 高级聊天模型可以部署到无服务器 API 终结点,并采用即用即付计费。 这种部署可以将模型作为 API 使用,而无需将它们托管在你的订阅上,同时保持组织所需的企业安全性和合规性。

部署到无服务器 API 终结点不需要消耗订阅的配额。 如果尚未部署模型,可使用 Azure AI Studio、适用于 Python 的 Azure 机器学习 SDK、Azure CLI 或 ARM 模板将模型部署为无服务器 API

已安装推理包

可以通过将 azure-ai-inference 包与 Python 配合使用来使用此模型中的预测。 若要安装此包,需要满足以下先决条件:

  • 已安装 Python 3.8 或更高版本,包括 pip。
  • 终结点 URL。 若要构造客户端库,需要传入终结点 URL。 终结点 URL 采用 https://your-host-name.your-azure-region.inference.ai.azure.com 的形式,其中 your-host-name 是唯一的模型部署主机名,your-azure-region 是部署模型的 Azure 区域(例如 eastus2)。
  • 根据模型部署和身份验证首选项,需要密钥来对服务进行身份验证,或者需要 Microsoft Entra ID 凭据。 密钥是一个包含 32 个字符的字符串。

满足这些先决条件后,使用以下命令安装 Azure AI 推理包:

pip install azure-ai-inference

详细了解 Azure AI 推理包和参考

使用聊天补全

在本部分中,将 Azure AI 模型推理 API 与聊天补全模型一起用于聊天。

提示

Azure AI 模型推理 API 允许与 Azure AI Studio 中部署的大多数模型进行对话,这些模型具有相同的代码和结构,包括 Mistral 高级聊天模型。

创建客户端以使用模型

首先,创建客户端以使用模型。 以下代码使用存储在环境变量中的终结点 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"]),
)

获取模型的功能

/info 路由返回有关部署到终结点的模型的信息。 通过调用以下方法返回模型的信息:

model_info = client.get_model_info()

响应如下所示:

print("Model name:", model_info.model_name)
print("Model type:", model_info.model_type)
print("Model provider name:", model_info.model_provider_name)
Model name: Mistral-Large
Model type: chat-completions
Model provider name: MistralAI

创建聊天补全请求

以下示例演示如何创建对模型的基本聊天补全请求。

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?"),
    ],
)

响应如下所示,可从中查看模型的使用统计信息:

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
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

检查响应中的 usage 部分,查看用于提示的令牌数、生成的令牌总数以及用于补全的令牌数。

流式传输内容

默认情况下,补全 API 会在单个响应中返回整个生成的内容。 如果要生成长补全内容,等待响应可能需要几秒钟时间。

可以流式传输内容,以在生成内容时获取它。 通过流式处理内容,可以在内容可用时开始处理补全。 此模式返回一个对象,该对象将响应作为仅数据服务器发送的事件进行流式传输。 从增量字段(而不是消息字段)中提取区块。

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,
)

若要流式传输补全,请在调用模型时设置 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=ChatCompletionsResponseFormatText(),
)

如果要传递未包含在受支持参数列表中的参数,可以使用额外参数将其传递给基础模型。 请参阅将额外参数传递给模型

创建 JSON 输出

Mistral 高级聊天模型可以创建 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=ChatCompletionsResponseFormatJSON()
)

将额外参数传递给模型

Azure AI 模型推理 API 允许将额外参数传递给模型。 以下代码示例演示如何将额外参数 logprobs 传递给模型。

将额外参数传递给 Azure AI 模型推理 API 之前,请确保模型支持这些额外参数。 向基础模型发出请求时,标头 extra-parameters 将传递给具有值 pass-through 的模型。 此值告知终结点将额外参数传递给模型。 在模型中使用额外参数并不能保证模型能够实际处理它们。 请阅读模型的文档以了解哪些额外参数受支持。

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many languages are in the world?"),
    ],
    model_extras={
        "logprobs": True
    }
)

以下额外参数可以传递给 Mistral 高级聊天模型:

名称 说明 类型
ignore_eos 是否忽略 EOS 令牌,并在生成 EOS 令牌后继续生成令牌。 boolean
safe_mode 是否在所有对话之前插入安全提示。 boolean

安全模式

Mistral 高级聊天模型支持参数 safe_prompt。 可以切换安全提示,以在消息前面添加以下系统提示:

始终以关心、尊重和实事求是的态度进行协助。 以最大的实用性和安全性进行响应。 避免有害、不道德、有偏见或负面的内容。 确保回复可促进公平性和积极性。

Azure AI 模型推理 API 允许传递此额外参数,如下所示:

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many languages are in the world?"),
    ],
    model_extras={
        "safe_mode": True
    }
)

使用工具

Mistral 高级聊天模型支持使用工具,当你需要从语言模型中卸载特定任务,转而依赖于更具确定性的系统甚至是不同的语言模型时,这些工具可能是非常出色的资源。 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."
    }

在此函数的帮助下提示模型预订航班:

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 内容安全文档

Mistral 高级聊天模型

Mistral 高级聊天模型包括以下模型:

Mistral Large 是 Mistral AI 最先进的大型语言模型 (LLM)。 由于其先进的推理和知识能力,它可以用于任何基于语言的任务。

此外,Mistral Large:

  • 专用于 RAG。 重要信息不会在长上下文窗口(最多 32-K 个标记)中间丢失。
  • 编码能力强。 代码生成、代码评审和注释。 支持所有主流编码语言。
  • 多语言设计。 在法语、德语、西班牙语、意大利语和英语中表现优秀。 支持数十种语言。
  • 符合负责任 AI 原则。 模型中内置了高效的防护措施,并提供具有 safe_mode 选项的额外安全层。

Mistral Large (2407) 的特性包括:

  • 多语言设计。 支持数十种语言,包括英语、法语、德语、西班牙语和意大利语。
  • 精通编码。 使用 80 多种编码语言(包括 Python、Java、C、C++、JavaScript 和 Bash)进行了训练。 还对更具体的语言进行了训练,如 Swift 和 Fortran。
  • 以代理为中心。 拥有原生函数调用和 JSON 输出的代理功能。
  • 高级的推理能力。 具有先进的数学和推理能力。

以下模型可用:

提示

此外,MistralAI 还支持将定制的 API 与模型的特定功能配合使用。 若使用特定于模型提供商的 API,请查看 MistralAI 文档,或者参阅推理示例部分以编写示例。

先决条件

若要将 Mistral 高级聊天模型与 Azure AI Studio 配合使用,需要满足以下先决条件:

模型部署

部署到无服务器 API

Mistral 高级聊天模型可以部署到无服务器 API 终结点,并采用即用即付计费。 这种部署可以将模型作为 API 使用,而无需将它们托管在你的订阅上,同时保持组织所需的企业安全性和合规性。

部署到无服务器 API 终结点不需要消耗订阅的配额。 如果尚未部署模型,可使用 Azure AI Studio、适用于 Python 的 Azure 机器学习 SDK、Azure CLI 或 ARM 模板将模型部署为无服务器 API

已安装推理包

可以通过使用来自 npm@azure-rest/ai-inference 包来使用此模型中的预测。 若要安装此包,需要满足以下先决条件:

  • 带有 npmNode.js 的 LTS 版本。
  • 终结点 URL。 若要构造客户端库,需要传入终结点 URL。 终结点 URL 采用 https://your-host-name.your-azure-region.inference.ai.azure.com 的形式,其中 your-host-name 是唯一的模型部署主机名,your-azure-region 是部署模型的 Azure 区域(例如 eastus2)。
  • 根据模型部署和身份验证首选项,需要密钥来对服务进行身份验证,或者需要 Microsoft Entra ID 凭据。 密钥是一个包含 32 个字符的字符串。

满足这些先决条件后,使用以下命令安装适用于 JavaScript 的 Azure 推理库:

npm install @azure-rest/ai-inference

使用聊天补全

在本部分中,将 Azure AI 模型推理 API 与聊天补全模型一起用于聊天。

提示

Azure AI 模型推理 API 允许与 Azure AI Studio 中部署的大多数模型进行对话,这些模型具有相同的代码和结构,包括 Mistral 高级聊天模型。

创建客户端以使用模型

首先,创建客户端以使用模型。 以下代码使用存储在环境变量中的终结点 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)
);

获取模型的功能

/info 路由返回有关部署到终结点的模型的信息。 通过调用以下方法返回模型的信息:

var model_info = await client.path("/info").get()

响应如下所示:

console.log("Model name: ", model_info.body.model_name)
console.log("Model type: ", model_info.body.model_type)
console.log("Model provider name: ", model_info.body.model_provider_name)
Model name: Mistral-Large
Model type: chat-completions
Model provider name: MistralAI

创建聊天补全请求

以下示例演示如何创建对模型的基本聊天补全请求。

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,
    }
});

响应如下所示,可从中查看模型的使用统计信息:

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
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

检查响应中的 usage 部分,查看用于提示的令牌数、生成的令牌总数以及用于补全的令牌数。

流式传输内容

默认情况下,补全 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,
    }
}).asNodeStream();

若要流式传输补全,请在调用模型时使用 .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 输出

Mistral 高级聊天模型可以创建 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 传递给模型。

将额外参数传递给 Azure AI 模型推理 API 之前,请确保模型支持这些额外参数。 向基础模型发出请求时,标头 extra-parameters 将传递给具有值 pass-through 的模型。 此值告知终结点将额外参数传递给模型。 在模型中使用额外参数并不能保证模型能够实际处理它们。 请阅读模型的文档以了解哪些额外参数受支持。

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
    }
});

以下额外参数可以传递给 Mistral 高级聊天模型:

名称 说明 类型
ignore_eos 是否忽略 EOS 令牌,并在生成 EOS 令牌后继续生成令牌。 boolean
safe_mode 是否在所有对话之前插入安全提示。 boolean

安全模式

Mistral 高级聊天模型支持参数 safe_prompt。 可以切换安全提示,以在消息前面添加以下系统提示:

始终以关心、尊重和实事求是的态度进行协助。 以最大的实用性和安全性进行响应。 避免有害、不道德、有偏见或负面的内容。 确保回复可促进公平性和积极性。

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({
    headers: {
        "extra-params": "pass-through"
    },
    body: {
        messages: messages,
        safe_mode: true
    }
});

使用工具

Mistral 高级聊天模型支持使用工具,当你需要从语言模型中卸载特定任务,转而依赖于更具确定性的系统甚至是不同的语言模型时,这些工具可能是非常出色的资源。 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."
    }
}

在此函数的帮助下提示模型预订航班:

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 内容安全文档

Mistral 高级聊天模型

Mistral 高级聊天模型包括以下模型:

Mistral Large 是 Mistral AI 最先进的大型语言模型 (LLM)。 由于其先进的推理和知识能力,它可以用于任何基于语言的任务。

此外,Mistral Large:

  • 专用于 RAG。 重要信息不会在长上下文窗口(最多 32-K 个标记)中间丢失。
  • 编码能力强。 代码生成、代码评审和注释。 支持所有主流编码语言。
  • 多语言设计。 在法语、德语、西班牙语、意大利语和英语中表现优秀。 支持数十种语言。
  • 符合负责任 AI 原则。 模型中内置了高效的防护措施,并提供具有 safe_mode 选项的额外安全层。

Mistral Large (2407) 的特性包括:

  • 多语言设计。 支持数十种语言,包括英语、法语、德语、西班牙语和意大利语。
  • 精通编码。 使用 80 多种编码语言(包括 Python、Java、C、C++、JavaScript 和 Bash)进行了训练。 还对更具体的语言进行了训练,如 Swift 和 Fortran。
  • 以代理为中心。 拥有原生函数调用和 JSON 输出的代理功能。
  • 高级的推理能力。 具有先进的数学和推理能力。

以下模型可用:

提示

此外,MistralAI 还支持将定制的 API 与模型的特定功能配合使用。 若使用特定于模型提供商的 API,请查看 MistralAI 文档,或者参阅推理示例部分以编写示例。

先决条件

若要将 Mistral 高级聊天模型与 Azure AI Studio 配合使用,需要满足以下先决条件:

模型部署

部署到无服务器 API

Mistral 高级聊天模型可以部署到无服务器 API 终结点,并采用即用即付计费。 这种部署可以将模型作为 API 使用,而无需将它们托管在你的订阅上,同时保持组织所需的企业安全性和合规性。

部署到无服务器 API 终结点不需要消耗订阅的配额。 如果尚未部署模型,可使用 Azure AI Studio、适用于 Python 的 Azure 机器学习 SDK、Azure CLI 或 ARM 模板将模型部署为无服务器 API

已安装推理包

可以通过使用来自 NugetAzure.AI.Inference 包来使用此模型中的预测。 若要安装此包,需要满足以下先决条件:

  • 终结点 URL。 若要构造客户端库,需要传入终结点 URL。 终结点 URL 采用 https://your-host-name.your-azure-region.inference.ai.azure.com 的形式,其中 your-host-name 是唯一的模型部署主机名,your-azure-region 是部署模型的 Azure 区域(例如 eastus2)。
  • 根据模型部署和身份验证首选项,需要密钥来对服务进行身份验证,或者需要 Microsoft Entra ID 凭据。 密钥是一个包含 32 个字符的字符串。

满足这些先决条件后,请使用以下命令安装 Azure AI 推理库:

dotnet add package Azure.AI.Inference --prerelease

也可使用 Microsoft Entra ID(以前称为 Azure Active Directory)进行身份验证。 若要使用 Azure SDK 提供的凭据提供程序,请安装 Azure.Identity 包:

dotnet add package Azure.Identity

导入下列命名空间:

using Azure;
using Azure.Identity;
using Azure.AI.Inference;

此示例还使用以下命名空间,但你可能并不总是需要它们:

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Reflection;

使用聊天补全

在本部分中,将 Azure AI 模型推理 API 与聊天补全模型一起用于聊天。

提示

Azure AI 模型推理 API 允许与 Azure AI Studio 中部署的大多数模型进行对话,这些模型具有相同的代码和结构,包括 Mistral 高级聊天模型。

创建客户端以使用模型

首先,创建客户端以使用模型。 以下代码使用存储在环境变量中的终结点 URL 和密钥。

ChatCompletionsClient client = new ChatCompletionsClient(
    new Uri(Environment.GetEnvironmentVariable("AZURE_INFERENCE_ENDPOINT")),
    new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_INFERENCE_CREDENTIAL"))
);

获取模型的功能

/info 路由返回有关部署到终结点的模型的信息。 通过调用以下方法返回模型的信息:

Response<ModelInfo> modelInfo = client.GetModelInfo();

响应如下所示:

Console.WriteLine($"Model name: {modelInfo.Value.ModelName}");
Console.WriteLine($"Model type: {modelInfo.Value.ModelType}");
Console.WriteLine($"Model provider name: {modelInfo.Value.ModelProviderName}");
Model name: Mistral-Large
Model type: chat-completions
Model provider name: MistralAI

创建聊天补全请求

以下示例演示如何创建对模型的基本聊天补全请求。

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);

响应如下所示,可从中查看模型的使用统计信息:

Console.WriteLine($"Response: {response.Value.Choices[0].Message.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
Usage: 
  Prompt tokens: 19
  Total tokens: 91
  Completion tokens: 72

检查响应中的 usage 部分,查看用于提示的令牌数、生成的令牌总数以及用于补全的令牌数。

流式传输内容

默认情况下,补全 API 会在单个响应中返回整个生成的内容。 如果要生成长补全内容,等待响应可能需要几秒钟时间。

可以流式传输内容,以在生成内容时获取它。 通过流式处理内容,可以在内容可用时开始处理补全。 此模式返回一个对象,该对象将响应作为仅数据服务器发送的事件进行流式传输。 从增量字段(而不是消息字段)中提取区块。

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);
}

若要流式传输补全,请在调用模型时使用 CompleteStreamingAsync 方法。 请注意,在这个例子中,调用包装在一个异步方法中。

为了可视化输出,请定义一个异步方法,用于在控制台中输出流。

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.Choices[0].Message.Content}");

如果要传递未包含在受支持参数列表中的参数,可以使用额外参数将其传递给基础模型。 请参阅将额外参数传递给模型

创建 JSON 输出

Mistral 高级聊天模型可以创建 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.Choices[0].Message.Content}");

将额外参数传递给模型

Azure AI 模型推理 API 允许将额外参数传递给模型。 以下代码示例演示如何将额外参数 logprobs 传递给模型。

将额外参数传递给 Azure AI 模型推理 API 之前,请确保模型支持这些额外参数。 向基础模型发出请求时,标头 extra-parameters 将传递给具有值 pass-through 的模型。 此值告知终结点将额外参数传递给模型。 在模型中使用额外参数并不能保证模型能够实际处理它们。 请阅读模型的文档以了解哪些额外参数受支持。

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.Choices[0].Message.Content}");

以下额外参数可以传递给 Mistral 高级聊天模型:

名称 说明 类型
ignore_eos 是否忽略 EOS 令牌,并在生成 EOS 令牌后继续生成令牌。 boolean
safe_mode 是否在所有对话之前插入安全提示。 boolean

安全模式

Mistral 高级聊天模型支持参数 safe_prompt。 可以切换安全提示,以在消息前面添加以下系统提示:

始终以关心、尊重和实事求是的态度进行协助。 以最大的实用性和安全性进行响应。 避免有害、不道德、有偏见或负面的内容。 确保回复可促进公平性和积极性。

Azure AI 模型推理 API 允许传递此额外参数,如下所示:

requestOptions = new ChatCompletionsOptions()
{
    Messages = {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("How many languages are in the world?")
    },
    AdditionalProperties = { { "safe_mode", BinaryData.FromString("true") } },
};

response = client.Complete(requestOptions, extraParams: ExtraParameters.PassThrough);
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");

使用工具

Mistral 高级聊天模型支持使用工具,当你需要从语言模型中卸载特定任务,转而依赖于更具确定性的系统甚至是不同的语言模型时,这些工具可能是非常出色的资源。 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."
    });
}

在此函数的帮助下提示模型预订航班:

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 responseMenssage = response.Value.Choices[0].Message;
var toolsCall = responseMenssage.ToolCalls;

Console.WriteLine($"Finish reason: {response.Value.Choices[0].FinishReason}");
Console.WriteLine($"Tool call: {toolsCall[0].Id}");

若要继续,请将此消息附加到聊天历史记录中:

requestOptions.Messages.Add(new ChatRequestAssistantMessage(response.Value.Choices[0].Message));

现在,需要调用相应的函数来处理工具调用。 以下代码片段迭代响应中指示的所有工具调用,并使用相应的参数来调用相应的函数。 响应也会附加到聊天历史记录中。

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.Choices[0].Message.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 内容安全文档

Mistral 高级聊天模型

Mistral 高级聊天模型包括以下模型:

Mistral Large 是 Mistral AI 最先进的大型语言模型 (LLM)。 由于其先进的推理和知识能力,它可以用于任何基于语言的任务。

此外,Mistral Large:

  • 专用于 RAG。 重要信息不会在长上下文窗口(最多 32-K 个标记)中间丢失。
  • 编码能力强。 代码生成、代码评审和注释。 支持所有主流编码语言。
  • 多语言设计。 在法语、德语、西班牙语、意大利语和英语中表现优秀。 支持数十种语言。
  • 符合负责任 AI 原则。 模型中内置了高效的防护措施,并提供具有 safe_mode 选项的额外安全层。

Mistral Large (2407) 的特性包括:

  • 多语言设计。 支持数十种语言,包括英语、法语、德语、西班牙语和意大利语。
  • 精通编码。 使用 80 多种编码语言(包括 Python、Java、C、C++、JavaScript 和 Bash)进行了训练。 还对更具体的语言进行了训练,如 Swift 和 Fortran。
  • 以代理为中心。 拥有原生函数调用和 JSON 输出的代理功能。
  • 高级的推理能力。 具有先进的数学和推理能力。

以下模型可用:

提示

此外,MistralAI 还支持将定制的 API 与模型的特定功能配合使用。 若使用特定于模型提供商的 API,请查看 MistralAI 文档,或者参阅推理示例部分以编写示例。

先决条件

若要将 Mistral 高级聊天模型与 Azure AI Studio 配合使用,需要满足以下先决条件:

模型部署

部署到无服务器 API

Mistral 高级聊天模型可以部署到无服务器 API 终结点,并采用即用即付计费。 这种部署可以将模型作为 API 使用,而无需将它们托管在你的订阅上,同时保持组织所需的企业安全性和合规性。

部署到无服务器 API 终结点不需要消耗订阅的配额。 如果尚未部署模型,可使用 Azure AI Studio、适用于 Python 的 Azure 机器学习 SDK、Azure CLI 或 ARM 模板将模型部署为无服务器 API

一个 REST 客户端

通过 Azure AI 模型推理 API 部署的模型可以通过任何 REST 客户端使用。 若要使用 REST 客户端,需要满足以下先决条件:

  • 若要构造请求,需要传入终结点 URL。 终结点 URL 采用 https://your-host-name.your-azure-region.inference.ai.azure.com 的形式,其中 your-host-name`` is your unique model deployment host name and your-azure-region`` 是部署模型的 Azure 区域(例如 eastus2)。
  • 根据模型部署和身份验证首选项,需要密钥来对服务进行身份验证,或者需要 Microsoft Entra ID 凭据。 密钥是一个包含 32 个字符的字符串。

使用聊天补全

在本部分中,将 Azure AI 模型推理 API 与聊天补全模型一起用于聊天。

提示

Azure AI 模型推理 API 允许与 Azure AI Studio 中部署的大多数模型进行对话,这些模型具有相同的代码和结构,包括 Mistral 高级聊天模型。

创建客户端以使用模型

首先,创建客户端以使用模型。 以下代码使用存储在环境变量中的终结点 URL 和密钥。

获取模型的功能

/info 路由返回有关部署到终结点的模型的信息。 通过调用以下方法返回模型的信息:

GET /info HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json

响应如下所示:

{
    "model_name": "Mistral-Large",
    "model_type": "chat-completions",
    "model_provider_name": "MistralAI"
}

创建聊天补全请求

以下示例演示如何创建对模型的基本聊天补全请求。

{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ]
}

响应如下所示,可从中查看模型的使用统计信息:

{
    "id": "0a1234b5de6789f01gh2i345j6789klm",
    "object": "chat.completion",
    "created": 1718726686,
    "model": "Mistral-Large",
    "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 会在单个响应中返回整个生成的内容。 如果要生成长补全内容,等待响应可能需要几秒钟时间。

可以流式传输内容,以在生成内容时获取它。 通过流式处理内容,可以在内容可用时开始处理补全。 此模式返回一个对象,该对象将响应作为仅数据服务器发送的事件进行流式传输。 从增量字段(而不是消息字段)中提取区块。

{
    "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",
    "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",
    "choices": [
        {
            "index": 0,
            "delta": {
                "content": ""
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 19,
        "total_tokens": 91,
        "completion_tokens": 72
    }
}

浏览推理客户端支持的更多参数

浏览可以在推理客户端中指定的其他参数。 有关所有受支持的参数及其相应文档的完整列表,请参阅 Azure AI 模型推理 API 参考

{
    "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",
    "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 输出

Mistral 高级聊天模型可以创建 JSON 输出。 将 response_format 设置为 json_object 可启用 JSON 模式,这可以保证模型生成的消息是有效的 JSON。 还必须使用系统或用户消息指示模型自己生成 JSON。 此外,如果使用 finish_reason="length",则消息内容可能会部分截断,这表示生成超过了 max_tokens,或者对话超过了最大上下文长度。

{
    "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",
    "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 传递给模型。

将额外参数传递给 Azure AI 模型推理 API 之前,请确保模型支持这些额外参数。 向基础模型发出请求时,标头 extra-parameters 将传递给具有值 pass-through 的模型。 此值告知终结点将额外参数传递给模型。 在模型中使用额外参数并不能保证模型能够实际处理它们。 请阅读模型的文档以了解哪些额外参数受支持。

POST /chat/completions HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json
extra-parameters: pass-through
{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "logprobs": true
}

以下额外参数可以传递给 Mistral 高级聊天模型:

名称 说明 类型
ignore_eos 是否忽略 EOS 令牌,并在生成 EOS 令牌后继续生成令牌。 boolean
safe_mode 是否在所有对话之前插入安全提示。 boolean

安全模式

Mistral 高级聊天模型支持参数 safe_prompt。 可以切换安全提示,以在消息前面添加以下系统提示:

始终以关心、尊重和实事求是的态度进行协助。 以最大的实用性和安全性进行响应。 避免有害、不道德、有偏见或负面的内容。 确保回复可促进公平性和积极性。

Azure AI 模型推理 API 允许传递此额外参数,如下所示:

POST /chat/completions HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json
extra-parameters: pass-through
{
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "safemode": true
}

使用工具

Mistral 高级聊天模型支持使用工具,当你需要从语言模型中卸载特定任务,转而依赖于更具确定性的系统甚至是不同的语言模型时,这些工具可能是非常出色的资源。 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"
            ]
        }
    }
}

在此示例中,函数的输出是所选路线没有可用的航班,但用户应考虑进行训练。

在此函数的帮助下提示模型预订航班:

{
    "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",
    "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
    }
}

若要继续,请将此消息附加到聊天历史记录中:

现在,需要调用相应的函数来处理工具调用。 以下代码片段迭代响应中指示的所有工具调用,并使用相应的参数来调用相应的函数。 响应也会附加到聊天历史记录中。

查看模型的响应:

{
    "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 内容安全的情况下使用部署时,输入和输出会经过一系列分类模型,旨在检测和防止输出有害内容。 内容筛选系统会在输入提示和输出补全中检测特定类别的潜在有害内容并对其采取措施。

以下示例展示了当模型在输入提示中检测到有害内容且内容安全已启用时如何处理事件。

{
    "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 内容安全文档

更多推理示例

有关如何使用 Mistral 的更多示例,请参阅以下示例和教程:

说明 语言 示例
CURL 请求 Bash 链接
适用于 JavaScript 的 Azure AI 推理包 JavaScript 链接
适用于 Python 的 Azure AI 推理包 Python 链接
Python Web 请求 Python 链接
OpenAI SDK(实验性) Python 链接
LangChain Python 链接
Mistral AI Python 链接
LiteLLM Python 链接

部署为无服务器 API 终结点的 Mistral 模型系列的成本和配额注意事项

配额是按部署管理的。 每个部署的速率限制为每分钟 200,000 个令牌和每分钟 1,000 个 API 请求。 但是,我们目前的限制为每个项目每个模型一个部署。 如果当前速率限制不能满足你的方案,请联系 Microsoft Azure 支持部门。

部署为无服务器 API 的 Mistral 模型由 Mistral AI 通过 Azure 市场提供,并与 Azure AI Studio 集成以供使用。 部署模型时,可以看到 Azure 市场定价。

每次项目从 Azure 市场订阅给定产品/服务时,都会创建一个新资源来跟踪与其消耗相关的成本。 同一资源用于跟踪与推理相关的成本。但是,可以使用多个计量器来独立跟踪每个方案。

有关如何跟踪成本的详细信息,请参阅监视通过 Azure 市场提供的模型的成本