跳转到主要内容

Microsoft Azure Ai Inference Python客户端库

项目描述

Azure AI Inference Python客户端库

使用推理客户端库(预览版)来

  • 验证服务
  • 获取AI模型信息
  • 执行聊天完成
  • 获取文本嵌入

推理客户端库支持部署到以下服务的AI模型

推理客户端库使用REST API版本 2024-05-01-preview 进行服务调用,如Azure AI模型推理API中所述。

产品文档 | 示例 | API 参考文档 | 包(Pypi) | SDK 源代码

入门

先决条件

  • 已安装 Python 3.8 或更高版本,包括 pip。工作室。
  • 对于 GitHub 模型
    • AI 模型名称,例如 "gpt-4o" 或 "mistral-large"。
    • GitHub 个人访问令牌。在此 创建一个。您不需要给令牌任何权限。令牌是一个以 github_pat_ 开头的字符串。
  • 对于无服务器 API 端点或托管计算端点
    • Azure 订阅
    • 通过 Azure AI Studio 部署的 目录中的 AI 模型
    • 您模型的端点 URL,形式为 https://<your-host-name>.<your-azure-region>.models.ai.azure.com,其中 your-host-name 是您唯一的模型部署主机名,your-azure-region 是模型部署的 Azure 区域(例如 eastus2)。
    • 根据您的认证偏好,您可能需要 API 密钥来对服务进行认证,或者 Entra ID 凭证。API 密钥是一个 32 个字符的字符串。
  • 对于 Azure OpenAI (AOAI) 服务
    • Azure 订阅
    • 通过 Azure OpenAI Studio 部署的 目录中的 OpenAI 模型
    • 您模型的端点 URL,形式为 https://<your-resouce-name>.openai.azure.com/openai/deployments/<your-deployment-name>,其中 your-resource-name 是您全局唯一的 AOAI 资源名称,your-deployment-name 是您的 AI 模型部署名称。
    • 根据您的认证偏好,您可能需要 API 密钥来对服务进行认证,或者 Entra ID 凭证。API 密钥是一个 32 个字符的字符串。
    • 一个 api-version。在 API 规范表 的 "数据平面 - 推理" 行中列出的最新预览版或 GA 版本。在撰写本文时,最新的 GA 版本是 "2024-06-01"。

安装包

要安装 Azure AI 推理包,请使用以下命令

pip install azure-ai-inference

要更新包的现有安装,请使用

pip install --upgrade azure-ai-inference

关键概念

直接使用 API 密钥或 GitHub 令牌创建和认证客户端

该包包括两个客户端 ChatCompletionsClientEmbeddingsClient。两者都可以以类似的方式创建。例如,假设 endpointkeygithub_token 是包含您的端点 URL、API 密钥或 GitHub 令牌的字符串,下面的 Python 代码将创建和认证一个同步的 ChatCompletionsClient

from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential

# For GitHub models
client = ChatCompletionsClient(
    endpoint="https://models.inference.ai.azure.com",
    credential=AzureKeyCredential(github_token),
    model="mistral-large" # Update as needed. Alternatively, you can include this is the `complete` call.
)

# For Serverless API or Managed Compute endpoints
client = ChatCompletionsClient(
    endpoint=endpoint,  # Of the form https://<your-host-name>.<your-azure-region>.models.ai.azure.com
    credential=AzureKeyCredential(key)
)

# For Azure OpenAI endpoint
client = ChatCompletionsClient(
    endpoint=endpoint,  # Of the form https://<your-resouce-name>.openai.azure.com/openai/deployments/<your-deployment-name>
    credential=AzureKeyCredential(""),  # Pass in an empty value.
    headers={"api-key": key},
    api_version="2024-06-01",  # AOAI api-version. Update as needed.
)

同步客户端支持同步推理方法,这意味着它们将阻塞直到服务响应推理结果。为了简单起见,下面的代码示例都使用了同步方法。客户端还提供了等效的异步方法,这些方法在生产中更常用。

要创建异步客户端,安装额外的包 aiohttp

pip install aiohttp

并将上面的代码更新为导入 asyncio,并从 azure.ai.inference.aio 命名空间导入 ChatCompletionsClient 而不是从 azure.ai.inference。例如

import asyncio
from azure.ai.inference.aio import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential

# For Serverless API or Managed Compute endpoints
client = ChatCompletionsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key)
)

直接使用 Entra ID 创建和认证客户端

注意:在撰写本文时,只有托管计算端点和 Azure OpenAI 端点支持 Entra ID 认证。

要使用 Entra ID 令牌凭证,首先安装 azure-identity

pip install azure.identity

您需要提供从该包获取的所需凭证类型。一个常见的选择是 DefaultAzureCredential,它可以如下使用

from azure.ai.inference import ChatCompletionsClient
from azure.identity import DefaultAzureCredential

# For Managed Compute endpoints
client = ChatCompletionsClient(
    endpoint=endpoint,
    credential=DefaultAzureCredential(exclude_interactive_browser_credential=False)
)

# For Azure OpenAI endpoint
client = ChatCompletionsClient(
    endpoint=endpoint,
    credential=DefaultAzureCredential(exclude_interactive_browser_credential=False),
    credential_scopes=["https://cognitiveservices.azure.com/.default"],
    api_version="2024-06-01",  # AOAI api-version. Update as needed.
)

在应用程序开发过程中,您通常会通过以下步骤设置使用 Entra ID 进行身份验证的环境:首先安装 Azure CLI,然后在控制台窗口中运行az login命令,接着在打开的浏览器窗口中输入您的凭据。然后调用DefaultAzureCredential()将成功。在该调用中将exclude_interactive_browser_credential=False设置为False将启用在用户尚未登录的情况下启动浏览器窗口。

在创建客户端时定义默认设置

在构建相关客户端时,您可以定义默认的聊天补全或嵌入配置。这些配置将应用于所有未来的服务调用。

例如,在此示例中,我们使用 API 密钥身份验证创建一个ChatCompletionsClient,并应用两个设置:temperaturemax_tokens

from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential

# For Serverless API or Managed Compute endpoints
client = ChatCompletionsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key)
    temperature=0.5,
    max_tokens=1000
)

可以在单个服务调用中覆盖默认设置。

使用load_client创建和验证客户端

如果您正在使用无服务器 API 或托管计算端点,创建特定客户端有另一种方法。您可以使用load_client函数根据提供的端点返回相关客户端(类型为ChatCompletionsClientEmbeddingsClient)。

from azure.ai.inference import load_client
from azure.core.credentials import AzureKeyCredential

# For Serverless API or Managed Compute endpoints only.
# This will not work on GitHub Models endpoint or Azure OpenAI endpoint.
client = load_client(
    endpoint=endpoint,
    credential=AzureKeyCredential(key)
)

print(f"Created client of type `{type(client).__name__}`.")

要加载异步客户端,请从azure.ai.inference.aio导入load_client函数。

load_client函数也支持 Entra ID 身份验证。例如,用credential=DefaultAzureCredential(exclude_interactive_browser_credential=False)替换上述密钥身份验证。

获取 AI 模型信息

如果您正在使用无服务器 API 或托管计算端点,您可以通过调用客户端方法get_model_info来检索 AI 模型信息。这将向提供的端点上的/info路由发出 REST 调用,如REST API 参考中所述。此调用不适用于 GitHub 模型或 Azure OpenAI 端点。

model_info = client.get_model_info()

print(f"Model name: {model_info.model_name}")
print(f"Model provider name: {model_info.model_provider_name}")
print(f"Model type: {model_info.model_type}")

AI 模型信息在客户端中缓存,对get_model_info的进一步调用将访问缓存的值,而不会导致 REST API 调用。请注意,如果您使用load_client函数创建了客户端,则模型信息已经缓存在客户端中。

当您print(client)时,会显示 AI 模型信息(如果可用)。

聊天补全

ChatCompletionsClient有一个名为complete的方法。该方法向提供的端点上的/chat/completions路由发出 REST API 调用,如REST API 参考中所述。

下面是简单的聊天补全示例。更多示例可以在samples文件夹中找到。

文本嵌入

EmbeddingsClient有一个名为embedding的方法。该方法向提供的端点上的/embeddings路由发出 REST API 调用,如REST API 参考中所述。

下面是简单的文本嵌入示例。更多示例可以在samples文件夹中找到。

示例

在以下部分中,您将找到以下简单示例:

以下示例假设使用无服务器 API 或托管计算端点创建同步客户端。根据关键概念中描述的修改客户端构造代码,使其与 GitHub 模型端点或 Azure OpenAI 端点一起使用。为了简化,只显示必需的输入设置。

有关同步和异步客户端的完整工作示例,请参阅Samples文件夹。

聊天补全示例

本示例演示了如何生成单个聊天补全,针对无服务器API或托管计算端点,使用密钥认证,假设已定义endpointkey。对于Entra ID认证,GitHub模型端点或Azure OpenAI端点,根据上述部分修改代码以创建客户端。

from azure.ai.inference import ChatCompletionsClient
from azure.ai.inference.models import SystemMessage, UserMessage
from azure.core.credentials import AzureKeyCredential

client = ChatCompletionsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many feet are in a mile?"),
    ]
)

print(response.choices[0].message.content)

支持以下类型或消息:SystemMessageUserMessageAssistantMessageToolMessage。请参阅示例

或者,您可以使用字典提供消息,而不是使用强类型类如SystemMessageUserMessage

response = client.complete(
    {
        "messages": [
            {
                "role": "system",
                "content": "You are an AI assistant that helps people find information. Your replies are short, no more than two sentences.",
            },
            {
                "role": "user",
                "content": "What year was construction of the International Space Station mostly done?",
            },
            {
                "role": "assistant",
                "content": "The main construction of the International Space Station (ISS) was completed between 1998 and 2011. During this period, more than 30 flights by US space shuttles and 40 by Russian rockets were conducted to transport components and modules to the station.",
            },
            {
                "role": "user",
                "content": "And what was the estimated cost to build it?"
            },
        ]
    }
)

要为额外消息生成补全,只需多次使用相同的client调用client.complete即可。

流式聊天补全示例

本示例演示了如何为无服务器API或托管计算端点生成单个聊天补全,具有流式响应,使用密钥认证,假设已定义endpointkey。只需将stream=True添加到complete调用中即可启用流式传输。

对于Entra ID认证,GitHub模型端点或Azure OpenAI端点,根据上述部分修改代码以创建客户端。

from azure.ai.inference import ChatCompletionsClient
from azure.ai.inference.models import SystemMessage, UserMessage
from azure.core.credentials import AzureKeyCredential

client = ChatCompletionsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

response = client.complete(
    stream=True,
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="Give me 5 good reasons why I should exercise every day."),
    ],
)

for update in response:
    print(update.choices[0].delta.content or "", end="", flush=True)

client.close()

在上面的for循环中打印结果时,您应该看到答案随着更新流式传输到客户端而逐渐变长。

要为额外消息生成补全,只需多次使用相同的client调用client.complete即可。

具有额外模型特定参数的聊天补全

在此示例中,通过在调用complete方法时设置model_extras,在请求体根处插入额外的JSON元素。这些是为需要超出REST APIRequest Body中定义的参数的AI模型设计的。

response = client.complete(
    messages=[
        SystemMessage(content="You are a helpful assistant."),
        UserMessage(content="How many feet are in a mile?"),
    ],
    model_extras={"key1": "value1", "key2": "value2"},  # Optional. Additional parameters to pass to the model.
)

在上面的示例中,这将是在HTTP请求中的JSON有效负载

{
    "messages":
    [
        {"role":"system","content":"You are a helpful assistant."},
        {"role":"user","content":"How many feet are in a mile?"}
    ],
    "key1": "value1",
    "key2": "value2"
}

请注意,默认情况下,服务将拒绝任何包含额外参数的请求有效负载。为了更改默认服务行为,当在complete方法中包含model_extras时,客户端库将自动添加HTTP请求头"extra-parameters": "pass-through"

文本嵌入示例

本示例演示了如何获取文本嵌入,针对无服务器API或托管计算端点,使用密钥认证,假设已定义endpointkey。对于Entra ID认证,GitHub模型端点或Azure OpenAI端点,根据上述部分修改代码以创建客户端。

from azure.ai.inference import EmbeddingsClient
from azure.core.credentials import AzureKeyCredential

client = EmbeddingsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

response = client.embed(input=["first phrase", "second phrase", "third phrase"])

for item in response.data:
    length = len(item.embedding)
    print(
        f"data[{item.index}]: length={length}, [{item.embedding[0]}, {item.embedding[1]}, "
        f"..., {item.embedding[length-2]}, {item.embedding[length-1]}]"
    )

嵌入向量的长度取决于模型,但您应该看到类似这样的内容

data[0]: length=1024, [0.0013399124, -0.01576233, ..., 0.007843018, 0.000238657]
data[1]: length=1024, [0.036590576, -0.0059547424, ..., 0.011405945, 0.004863739]
data[2]: length=1024, [0.04196167, 0.029083252, ..., -0.0027484894, 0.0073127747]

要为额外短语生成嵌入,只需多次使用相同的client调用client.embed即可。

故障排除

异常

客户端上的completeembedget_model_info方法会引发HttpResponseError异常,对于来自服务的非成功HTTP状态代码响应。异常的status_code将包含HTTP响应状态码(reason显示友好名称)。异常的error.message包含可能有助于诊断问题的详细消息。

from azure.core.exceptions import HttpResponseError

...

try:
    result = client.complete( ... )
except HttpResponseError as e:
    print(f"Status code: {e.status_code} ({e.reason})")
    print(e.message)

例如,当您提供一个错误的认证密钥时

Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'

或者当您创建一个EmbeddingsClient并调用客户端上的embed,但端点不支持/embeddings路由时

Status code: 405 (Method Not Allowed)
Operation returned an invalid status 'Method Not Allowed'

日志记录

客户端使用标准Python日志库。SDK记录HTTP请求和响应的详细信息,这可能有助于故障排除。要将日志输出到标准输出,请添加以下内容

import sys
import logging

# Acquire the logger for this client library. Use 'azure' to affect both
# 'azure.core` and `azure.ai.inference' libraries.
logger = logging.getLogger("azure")

# Set the desired logging level. logging.INFO or logging.DEBUG are good options.
logger.setLevel(logging.DEBUG)

# Direct logging output to stdout:
handler = logging.StreamHandler(stream=sys.stdout)
# Or direct logging output to a file:
# handler = logging.FileHandler(filename="sample.log")
logger.addHandler(handler)

# Optional: change the default logging format. Here we add a timestamp.
formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")
handler.setFormatter(formatter)

默认情况下,日志会删除URL查询字符串的值、某些HTTP请求和响应头(包括包含密钥或令牌的Authorization)以及请求和响应的有效负载。要创建不进行删除的日志,请执行以下两个步骤

  1. 在构建客户端库时,或在调用客户端的completeembed方法时,设置方法参数logging_enable = True
    client = ChatCompletionsClient(
        endpoint=endpoint,
        credential=AzureKeyCredential(key),
        logging_enable=True
    )
    
  2. 将日志级别设置为logging.DEBUG。具有其他任何日志级别的日志都会被删除。

请确保保护未删除的日志,以避免泄露安全信息。

有关更多信息,请参阅配置Python Azure库中的日志

报告问题

要报告客户端库的问题或请求更多功能,请在此处创建GitHub问题here

下一步

  • 查看Samples文件夹,其中包含用于使用同步和异步客户端进行推理的完整可运行的Python代码。

贡献

本项目欢迎贡献和建议。大多数贡献都需要您同意贡献者许可协议(CLA),声明您有权并且实际上授予我们使用您贡献的权利。有关详细信息,请访问https://cla.microsoft.com

提交拉取请求时,CLA机器人将自动确定您是否需要提供CLA并相应地装饰PR(例如,标签、注释)。只需遵循机器人提供的说明即可。您只需在整个使用我们的CLA的仓库中做一次。

本项目已采用Microsoft开源行为准则。有关更多信息,请参阅行为准则FAQ或联系opencode@microsoft.com以获取任何额外的问题或评论。

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

azure-ai-inference-1.0.0b4.tar.gz (108.3 kB 查看哈希值)

上传时间

构建分发

azure_ai_inference-1.0.0b4-py3-none-any.whl (85.0 kB 查看哈希值)

上传时间 Python 3

由以下支持