你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
Azure AI Foundry SDK
Azure AI Foundry SDK 是一个全面的工具链,旨在简化在 Azure 开发 AI 应用程序的流程。 借助它,开发人员能够:
- 通过单个接口从各种模型提供程序访问常用模型
- 轻松地结合使用模型、数据和 AI 服务来生成 AI 应用程序
- 跨开发、测试和生产环境评估、调试和提高应用程序的质量和安全性
Azure AI Foundry SDK 是一组旨在协同工作的包和服务。 你可以使用 Azure AI 项目客户端库,通过单个项目客户端和连接字符串轻松使用多个服务。 也可以单独使用服务和 SDK 直接连接到服务。
如果想要直接开始生成应用,请参阅:
项目入门
若要开始使用 Azure AI Foundry SDK,最佳方式是使用项目。 AI 项目将生成 AI 应用程序所需的不同数据、资产和服务都汇集在了一起。 借助 AI 项目客户端,可以使用单个连接字符串轻松通过代码访问这些项目组件。
首先,请按照创建 AI 项目中的步骤创建 AI 项目(如果还没有)。
使用用于访问 AI 项目的同一帐户通过 Azure CLI 登录:
az login
安装 Azure AI 项目客户端库:
pip install azure-ai-projects azure-identity
使用代码创建项目客户端:
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity
添加 using 语句:
using Azure.Identity;
using Azure.AI.Projects;
使用代码创建项目客户端:
从项目的“概述”页复制“项目连接字符串”,并更新上述连接字符串值。
创建项目客户端后,可以将客户端用于以下各部分中涉及的功能。
Azure OpenAI 服务
Azure OpenAI 服务提供对 OpenAI 模型的访问,包括 GPT-4o、GPT-4o mini、GPT-4、GPT-4 Turbo with Vision、DALLE-3、Whisper 和 Embeddings 模型系列以及 Azure 的数据驻留、可伸缩性、安全、安全性和企业功能。
如果有使用 OpenAI SDK 的代码,就可以轻松将代码定向到使用 Azure OpenAI 服务。 首先,安装 OpenAI SDK:
pip install openai
如果有使用 OpenAI SDK 的现有代码,则可以使用项目客户端创建 AzureOpenAI
客户端,其会使用项目的 Azure OpenAI 连接:
openai = project.inference.get_azure_openai_client(api_version="2024-06-01")
response = openai.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful writing assistant"},
{"role": "user", "content": "Write me a poem about flowers"},
]
)
print(response.choices[0].message.content)
dotnet add package Azure.AI.OpenAI
添加 using 语句:
using OpenAI.Chat;
using Azure.AI.OpenAI;
如果有使用 OpenAI SDK 的现有代码,则可以使用项目客户端创建 AzureOpenAI
客户端,其会使用项目的 Azure OpenAI 连接:
var connections = projectClient.GetConnectionsClient();
ConnectionResponse connection = connections.GetDefaultConnection(ConnectionType.AzureOpenAI, withCredential: true);
var properties = connection.Properties as ConnectionPropertiesApiKeyAuth;
if (properties == null) {
throw new Exception("Invalid auth type, expected API key auth");
}
// Create and use an Azure OpenAI client
AzureOpenAIClient azureOpenAIClient = new(
new Uri(properties.Target),
new AzureKeyCredential(properties.Credentials.Key));
// This must match the custom deployment name you chose for your model
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");
ChatCompletion completion = chatClient.CompleteChat(
[
new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
new UserChatMessage("Do other Azure AI services support this too?")
]);
Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");
如果已直接通过 Azure OpenAI SDK 使用 Azure OpenAI 服务,则该项目会提供便捷的方式,让你能够同时使用 Azure OpenAI 服务功能和其余 Azure AI Foundry 功能。
Azure AI 模型推理服务
借助 Azure AI 模型推理服务,你可以访问由 OpenAI、Microsoft、Meta 等领先提供商提供的强大模型。 这些模型支持内容生成、汇总和代码生成等任务。
若要使用模型推理服务,请先确保项目已连接 AI 服务(在管理中心)。
安装 azure-ai-inference
客户端库:
pip install azure-ai-inference
可以使用项目客户端获取已配置并经过身份验证的 ChatCompletionsClient
或 EmbeddingsClient
:
# get an chat inferencing client using the project's default model inferencing endpoint
chat = project.inference.get_chat_completions_client()
# run a chat completion using the inferencing client
response = chat.complete(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful writing assistant"},
{"role": "user", "content": "Write me a poem about flowers"},
]
)
print(response.choices[0].message.content)
dotnet add package Azure.AI.Inference
添加 using 语句:
using Azure.AI.Inference;
可以使用项目客户端获取已配置并经过身份验证的 ChatCompletionsClient
或 EmbeddingsClient
:
var connectionString = Environment.GetEnvironmentVariable("AIPROJECT_CONNECTION_STRING");
var projectClient = new AIProjectClient(connectionString, new DefaultAzureCredential());
ChatCompletionsClient chatClient = projectClient.GetChatCompletionsClient();
var requestOptions = new ChatCompletionsOptions()
{
Messages =
{
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many feet are in a mile?"),
},
Model = "gpt-4o-mini"
};
Response<ChatCompletions> response = chatClient.Complete(requestOptions);
Console.WriteLine(response.Value.Content);
可以将模型名称更改为部署到推理服务或 Azure OpenAI 服务的任何模型。
若要详细了解如何使用 Azure AI 推理客户端,请参阅 Azure AI 模型推理参考。
提示模板
推理客户端支持通过模板创建提示消息。 借助该模板,你可以使用运行时提供的输入内容动态生成提示。
若要使用提示模板,请安装 azure-ai-inference
包:
pip install azure-ai-inference
可以从内联字符串呈现提示模板:
from azure.ai.inference.prompts import PromptTemplate
# create a prompt template from an inline string (using mustache syntax)
prompt_template = PromptTemplate.from_string(prompt_template="""
system:
You are a helpful writing assistant.
The user's first name is {{first_name}} and their last name is {{last_name}}.
user:
Write me a poem about flowers
""")
# generate system message from the template, passing in the context as variables
messages = prompt_template.create_messages(first_name="Jane", last_name="Doe")
print(messages)
注意
系统会自动去除输入字符串中的前导空格。
此代码会输出消息,你可以将这些消息传递到聊天补全调用中:
[
{'role': 'system', 'content': "You are a helpful writing assistant.\nThe user's first name is Jane and their last name is Doe."}
{'role': 'user', 'content': 'Write me a poem about flowers'}
]
此外,你也可以通过 Prompty
文件加载提示,这样还可以通过 .prompty
文件加载模型名称和参数:
from azure.ai.inference.prompts import PromptTemplate
prompt_template = PromptTemplate.from_prompty("myprompt.prompty")
messages = prompt_template.create_messages(first_name="Jane", last_name="Doe")
response = chat.complete(
messages=messages,
model=prompt_template.model_name,
**prompt_template.parameters,
)
Azure AI 搜索
如果已将 Azure AI 搜索资源连接到项目,则还可以使用项目客户端通过项目连接创建 Azure AI 搜索客户端。
安装 Azure AI 搜索客户端库:
pip install azure-search-documents
根据需要实例化搜索和/或搜索索引客户端:
from azure.core.credentials import AzureKeyCredential
from azure.ai.projects.models import ConnectionType
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
# use the project client to get the default search connection
search_connection = project.connections.get_default(
connection_type=ConnectionType.AZURE_AI_SEARCH,
with_credentials=True)
# Create a client to create and manage search indexes
index_client = SearchIndexClient(
endpoint=search_connection.endpoint_url,
credential=AzureKeyCredential(key=search_connection.key)
)
# Create a client to run search queries
search_client = SearchClient(
index_name="your_index_name",
endpoint=search_connection.endpoint_url,
credential=AzureKeyCredential(key=search_connection.key)
)
dotnet add package Azure.Search.Documents
添加 using 语句:
using Azure.Search.Documents;
using Azure.Search.Documents.Models;
根据需要实例化搜索和/或搜索索引客户端:
var connections = projectClient.GetConnectionsClient();
var connection = connections.GetDefaultConnection(ConnectionType.AzureAISearch, withCredential: true).Value;
var properties = connection.Properties as ConnectionPropertiesApiKeyAuth;
if (properties == null) {
throw new Exception("Invalid auth type, expected API key auth");
}
SearchClient searchClient = new SearchClient(
new Uri(properties.Target),
"products",
new AzureKeyCredential(properties.Credentials.Key));
若要详细了解如何使用 Azure AI 搜索,请参阅 Azure AI 搜索文档。
Azure AI 代理服务
Azure AI 代理服务是一项完全托管的服务,旨在使开发人员能够安全地生成、部署和缩放高质量且可扩展的 AI 代理。 Azure AI 代理服务使用丰富的生态系统,汇集 OpenAI、Microsoft 和第三方提供商提供的模型、工具和功能于一体,为各种生成式 AI 用例生成代理。
计算
你可以使用项目客户端轻松连接到 Azure AI 评估服务和运行评估程序所需的模型。
pip install azure-ai-evaluation
使用 project.scope
参数实例化 ViolenceEvaluator
:
from azure.ai.evaluation import ViolenceEvaluator
from azure.identity import DefaultAzureCredential
# Initializing Violence Evaluator with project information
violence_eval = ViolenceEvaluator(
azure_ai_project=project.scope,
credential=DefaultAzureCredential())
# Running Violence Evaluator on single input row
violence_score = violence_eval(query="what's the capital of france", response="Paris")
print(violence_score)
注意:若要运行暴力评估程序,项目需位于美国东部 2、瑞典中部、美国中北部、法国中部。
若要了解详细信息,请查看使用 SDK 进行评估。
Azure AI 评估包在 C# 中尚不可用。 有关如何使用 Prompty 和 Semantic Kernel 进行评估的示例,请参阅 contoso-chat-csharp-prompty 示例。
跟踪
若要启用跟踪,请先确保项目已附加 Application Insights 资源。 转到项目的“跟踪”页,按照说明创建或附加 Application Insights。
安装 Azure Monitor OpenTelemetry 包:
pip install azure-monitor-opentelemetry
使用以下代码检测 Azure AI 推理 SDK 并将日志记录到 AI 项目:
from azure.monitor.opentelemetry import configure_azure_monitor
# Enable instrumentation of AI packages (inference, agents, openai, langchain)
project.telemetry.enable()
# Log traces to the project's application insights resource
application_insights_connection_string = project.telemetry.get_connection_string()
if application_insights_connection_string:
configure_azure_monitor(connection_string=application_insights_connection_string)
跟踪尚未集成到项目包中。 有关如何从 Azure AI 推理包检测和记录跟踪的说明,请参阅 azure-sdk-for-dotnet。
相关内容
下面是可与 Azure AI Foundry SDK 配合使用的其他服务和框架的一些有用链接。
Azure AI 服务
客户端库:
管理库:
框架
Azure 机器学习
提示流
语义内核
语义内核概述代理框架