你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
快速入门:创建新代理
Azure AI 代理服务允许通过自定义指令和代码解释器等高级工具以及自定义函数来创建符合需求的 AI 代理。
| 参考文档 | 示例 | 库源代码 | 包 (NuGet) |
先决条件
- Azure 订阅 - 免费创建订阅。
- 最新版本的 .NET
- 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色。
- 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。
设置 Azure AI 中心和代理项目
以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:
创建 Azure AI 中心以设置应用环境和 Azure 资源。
在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。
连接 Azure OpenAI 资源或 Azure AI 服务资源
选择基本或标准代理设置
基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。
标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。
[可选]自动部署模板中的模型选择
可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelName
和 modelVersion
参数。
默认情况下,部署模板配置了以下值:
模型参数 | 默认值 |
---|---|
modelName | gpt-4o-mini |
modelFormat | OpenAI(适用于 Azure OpenAI) |
modelVersion | 2024-07-18 |
modelSkuName | GlobalStandard |
modelLocation | eastus |
[可选] 在代理设置过程中使用自己的资源
注意
如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。
通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:
aiServiceAccountResourceId
aiSearchServiceResourceId
aiStorageAccountResourceId
如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceId
和 aiServiceKind
参数。
aiServiceKind
参数应设置为 AzureOpenAI
。
有关详细信息,请参阅如何使用自己的资源。
配置并运行代理
组件 | 说明 |
---|---|
Agent | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
运行 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤让你可以了解代理如何获得结果。 |
将 .NET 包安装到项目。 例如,如果使用 .NET CLI,请运行以下命令。
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要使用项目中的信息创建连接字符串。 此字符串采用以下格式:
<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>
提示
还可以在 Azure AI Foundry 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。
可以通过导航到你的 discovery_url
并移除前导的 https://
和尾随的 /discovery
来找到 HostName
。 若要查找 discovery_url
,请运行以下 CLI 命令:
az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
例如,连接字符串可能如下所示:
eastus.api.azureml.ms;12345678-abcd-1234-9fc6-62780b3d3e05;my-resource-group;my-project-name
将此连接字符串设置为名为 PROJECT_CONNECTION_STRING
的环境变量。
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#nullable disable
using Azure.Identity;
namespace Azure.AI.Projects.Tests;
public class Sample_Agent
{
static async Task Main()
{
var connectionString = Environment.GetEnvironmentVariable("AZURE_AI_CONNECTION_STRING");
AgentsClient client = new AgentsClient(connectionString, new DefaultAzureCredential());
// Step 1: Create an agent
Response<Agent> agentResponse = await client.CreateAgentAsync(
model: "gpt-4o-mini",
name: "My Agent",
instructions: "You are a helpful agent.",
tools: new List<ToolDefinition> { new CodeInterpreterToolDefinition() });
Agent agent = agentResponse.Value;
// Intermission: agent should now be listed
Response<PageableList<Agent>> agentListResponse = await client.GetAgentsAsync();
//// Step 2: Create a thread
Response<AgentThread> threadResponse = await client.CreateThreadAsync();
AgentThread thread = threadResponse.Value;
// Step 3: Add a message to a thread
Response<ThreadMessage> messageResponse = await client.CreateMessageAsync(
thread.Id,
MessageRole.User,
"I need to solve the equation `3x + 11 = 14`. Can you help me?");
ThreadMessage message = messageResponse.Value;
// Intermission: message is now correlated with thread
// Intermission: listing messages will retrieve the message just added
Response<PageableList<ThreadMessage>> messagesListResponse = await client.GetMessagesAsync(thread.Id);
//Assert.That(messagesListResponse.Value.Data[0].Id == message.Id);
// Step 4: Run the agent
Response<ThreadRun> runResponse = await client.CreateRunAsync(
thread.Id,
agent.Id,
additionalInstructions: "");
ThreadRun run = runResponse.Value;
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
runResponse = await client.GetRunAsync(thread.Id, runResponse.Value.Id);
}
while (runResponse.Value.Status == RunStatus.Queued
|| runResponse.Value.Status == RunStatus.InProgress);
Response<PageableList<ThreadMessage>> afterRunMessagesResponse
= await client.GetMessagesAsync(thread.Id);
IReadOnlyList<ThreadMessage> messages = afterRunMessagesResponse.Value.Data;
// Note: messages iterate from newest to oldest, with the messages[0] being the most recent
foreach (ThreadMessage threadMessage in messages)
{
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
foreach (MessageContent contentItem in threadMessage.ContentItems)
{
if (contentItem is MessageTextContent textItem)
{
Console.Write(textItem.Text);
}
else if (contentItem is MessageImageFileContent imageFileItem)
{
Console.Write($"<image from ID: {imageFileItem.FileId}");
}
Console.WriteLine();
}
}
}
}
| 参考文档 | 示例 | 库源代码 | 包 (PyPi) |
先决条件
- Azure 订阅 - 免费创建订阅。
- Python 3.8 或更高版本
- 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色。
- 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。
设置 Azure AI 中心和代理项目
以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:
创建 Azure AI 中心以设置应用环境和 Azure 资源。
在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。
连接 Azure OpenAI 资源或 Azure AI 服务资源
选择基本或标准代理设置
基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。
标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。
[可选]自动部署模板中的模型选择
可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelName
和 modelVersion
参数。
默认情况下,部署模板配置了以下值:
模型参数 | 默认值 |
---|---|
modelName | gpt-4o-mini |
modelFormat | OpenAI(适用于 Azure OpenAI) |
modelVersion | 2024-07-18 |
modelSkuName | GlobalStandard |
modelLocation | eastus |
[可选] 在代理设置过程中使用自己的资源
注意
如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。
通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:
aiServiceAccountResourceId
aiSearchServiceResourceId
aiStorageAccountResourceId
如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceId
和 aiServiceKind
参数。
aiServiceKind
参数应设置为 AzureOpenAI
。
有关详细信息,请参阅如何使用自己的资源。
配置并运行代理
组件 | 说明 |
---|---|
Agent | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
运行 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤让你可以了解代理如何获得结果。 |
运行以下命令以安装 python 包。
pip install azure-ai-projects
pip install azure-identity
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要使用项目中的信息创建连接字符串。 此字符串采用以下格式:
<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>
提示
还可以在 Azure AI Foundry 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。
可以通过导航到你的 discovery_url
并移除前导的 https://
和尾随的 /discovery
来找到 HostName
。 若要查找 discovery_url
,请运行以下 CLI 命令:
az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
例如,连接字符串可能如下所示:
eastus.api.azureml.ms;12345678-abcd-1234-9fc6-62780b3d3e05;my-resource-group;my-project-name
将此连接字符串设置为名为 PROJECT_CONNECTION_STRING
的环境变量。
import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterTool
from azure.identity import DefaultAzureCredential
from typing import Any
from pathlib import Path
# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
# HostName can be found by navigating to your discovery_url and removing the leading "https://" and trailing "/discovery"
# To find your discovery_url, run the CLI command: az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
# Project Connection example: eastus.api.azureml.ms;12345678-abcd-1234-9fc6-62780b3d3e05;my-resource-group;my-project-name
# Customer needs to login to Azure subscription via Azure CLI and set the environment variables
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"]
)
with project_client:
# Create an instance of the CodeInterpreterTool
code_interpreter = CodeInterpreterTool()
# The CodeInterpreterTool needs to be included in creation of the agent
agent = project_client.agents.create_agent(
model="gpt-4o-mini",
name="my-agent",
instructions="You are helpful agent",
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
print(f"Created agent, agent ID: {agent.id}")
# Create a thread
thread = project_client.agents.create_thread()
print(f"Created thread, thread ID: {thread.id}")
# Create a message
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="Could you please create a bar chart for the operating profit using the following data and provide the file to me? Company A: $1.2 million, Company B: $2.5 million, Company C: $3.0 million, Company D: $1.8 million",
)
print(f"Created message, message ID: {message.id}")
# Run the agent
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
print(f"Run finished with status: {run.status}")
if run.status == "failed":
# Check if you got "Rate limit is exceeded.", then you want to get more quota
print(f"Run failed: {run.last_error}")
# Get messages from the thread
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
# Get the last message from the sender
last_msg = messages.get_last_text_message_by_role("assistant")
if last_msg:
print(f"Last Message: {last_msg.text.value}")
# Generate an image file for the bar chart
for image_content in messages.image_contents:
print(f"Image File ID: {image_content.image_file.file_id}")
file_name = f"{image_content.image_file.file_id}_image_file.png"
project_client.agents.save_file(file_id=image_content.image_file.file_id, file_name=file_name)
print(f"Saved image file to: {Path.cwd() / file_name}")
# Print the file path(s) from the messages
for file_path_annotation in messages.file_path_annotations:
print(f"File Paths:")
print(f"Type: {file_path_annotation.type}")
print(f"Text: {file_path_annotation.text}")
print(f"File ID: {file_path_annotation.file_path.file_id}")
print(f"Start Index: {file_path_annotation.start_index}")
print(f"End Index: {file_path_annotation.end_index}")
project_client.agents.save_file(file_id=file_path_annotation.file_path.file_id, file_name=Path(file_path_annotation.text).name)
# Delete the agent once done
project_client.agents.delete_agent(agent.id)
print("Deleted agent")
先决条件
- Azure 订阅 - 免费创建订阅。
- Python 3.8 或更高版本
- 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色。
- 需要分配有认知服务 OpenAI 用户角色才能使用 Azure AI 服务资源。
- 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。
设置 Azure AI 中心和代理项目
以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:
创建 Azure AI 中心以设置应用环境和 Azure 资源。
在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。
连接 Azure OpenAI 资源或 Azure AI 服务资源
选择基本或标准代理设置
基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。
标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。
[可选]自动部署模板中的模型选择
可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelName
和 modelVersion
参数。
默认情况下,部署模板配置了以下值:
模型参数 | 默认值 |
---|---|
modelName | gpt-4o-mini |
modelFormat | OpenAI(适用于 Azure OpenAI) |
modelVersion | 2024-07-18 |
modelSkuName | GlobalStandard |
modelLocation | eastus |
[可选] 在代理设置过程中使用自己的资源
注意
如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。
通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:
aiServiceAccountResourceId
aiSearchServiceResourceId
aiStorageAccountResourceId
如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceId
和 aiServiceKind
参数。
aiServiceKind
参数应设置为 AzureOpenAI
。
有关详细信息,请参阅如何使用自己的资源。
配置并运行代理
组件 | 说明 |
---|---|
Agent | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
运行 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤让你可以了解代理如何获得结果。 |
运行以下命令以安装 python 包。
pip install azure-ai-projects
pip install azure-identity
pip install openai
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要使用项目中的信息创建连接字符串。 此字符串采用以下格式:
<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>
提示
还可以在 Azure AI Foundry 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。
可以通过导航到你的 discovery_url
并移除前导的 https://
和尾随的 /discovery
来找到 HostName
。 若要查找 discovery_url
,请运行以下 CLI 命令:
az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
例如,连接字符串可能如下所示:
eastus.api.azureml.ms;12345678-abcd-1234-9fc6-62780b3d3e05;my-resource-group;my-project-name
将此连接字符串设置为名为 PROJECT_CONNECTION_STRING
的环境变量。
import os, time
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from openai import AzureOpenAI
with AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
) as project_client:
# Explicit type hinting for IntelliSense
client: AzureOpenAI = project_client.inference.get_azure_openai_client(
# The latest API version is 2024-10-01-preview
api_version = os.environ.get("AZURE_OPENAI_API_VERSION"),
)
with client:
agent = client.beta.assistants.create(
model="gpt-4o-mini", name="my-agent", instructions="You are a helpful agent"
)
print(f"Created agent, agent ID: {agent.id}")
thread = client.beta.threads.create()
print(f"Created thread, thread ID: {thread.id}")
message = client.beta.threads.messages.create(thread_id=thread.id, role="user", content="Hello, tell me a joke")
print(f"Created message, message ID: {message.id}")
run = client.beta.threads.runs.create(thread_id=thread.id, assistant_id=agent.id)
# Poll the run while run status is queued or in progress
while run.status in ["queued", "in_progress", "requires_action"]:
time.sleep(1) # Wait for a second
run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
print(f"Run status: {run.status}")
client.beta.assistants.delete(agent.id)
print("Deleted agent")
messages = client.beta.threads.messages.list(thread_id=thread.id)
print(f"Messages: {messages}")
| 参考文档 | 示例 | 库源代码 | 包 (npm) |
先决条件
- Azure 订阅 - 免费创建订阅。
- Node.js LTS
- 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色。
- 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。
设置 Azure AI 中心和代理项目
以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:
创建 Azure AI 中心以设置应用环境和 Azure 资源。
在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。
连接 Azure OpenAI 资源或 Azure AI 服务资源
选择基本或标准代理设置
基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。
标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。
[可选]自动部署模板中的模型选择
可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelName
和 modelVersion
参数。
默认情况下,部署模板配置了以下值:
模型参数 | 默认值 |
---|---|
modelName | gpt-4o-mini |
modelFormat | OpenAI(适用于 Azure OpenAI) |
modelVersion | 2024-07-18 |
modelSkuName | GlobalStandard |
modelLocation | eastus |
[可选] 在代理设置过程中使用自己的资源
注意
如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。
通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:
aiServiceAccountResourceId
aiSearchServiceResourceId
aiStorageAccountResourceId
如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceId
和 aiServiceKind
参数。
aiServiceKind
参数应设置为 AzureOpenAI
。
有关详细信息,请参阅如何使用自己的资源。
配置并运行代理
组件 | 说明 |
---|---|
Agent | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
运行 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤让你可以了解代理如何获得结果。 |
运行以下命令以安装 npm 包。
npm install @azure/ai-projects
npm install @azure/identity
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要使用项目中的信息创建连接字符串。 此字符串采用以下格式:
<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>
提示
还可以在 Azure AI Foundry 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。
可以通过导航到你的 discovery_url
并移除前导的 https://
和尾随的 /discovery
来找到 HostName
。 若要查找 discovery_url
,请运行以下 CLI 命令:
az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
例如,连接字符串可能如下所示:
eastus.api.azureml.ms;12345678-abcd-1234-9fc6-62780b3d3e05;my-resource-group;my-project-name
将此连接字符串设置为名为 PROJECT_CONNECTION_STRING
的环境变量。
// index.js
import {
AIProjectsClient,
DoneEvent,
ErrorEvent,
isOutputOfType,
MessageStreamEvent,
RunStreamEvent,
ToolUtility,
} from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
const connectionString =
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
if (!connectionString) {
throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set in the environment variables");
}
export async function main() {
const client = AIProjectsClient.fromConnectionString(
connectionString || "",
new DefaultAzureCredential(),
);
// Step 1 code interpreter tool
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool();
// Step 2 an agent
const agent = await client.agents.createAgent("gpt-4o-mini", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [codeInterpreterTool.definition],
toolResources: codeInterpreterTool.resources,
});
// Step 3 a thread
const thread = await client.agents.createThread();
// Step 4 a message to thread
await client.agents.createMessage(
thread.id, {
role: "user",
content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
});
// Intermission is now correlated with thread
// Intermission messages will retrieve the message just added
// Step 5 the agent
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
for await (const eventMessage of streamEventMessages) {
switch (eventMessage.event) {
case RunStreamEvent.ThreadRunCreated:
break;
case MessageStreamEvent.ThreadMessageDelta:
{
const messageDelta = eventMessage.data;
messageDelta.delta.content.forEach((contentPart) => {
if (contentPart.type === "text") {
const textContent = contentPart;
const textValue = textContent.text?.value || "No text";
}
});
}
break;
case RunStreamEvent.ThreadRunCompleted:
break;
case ErrorEvent.Error:
console.log(`An error occurred. Data ${eventMessage.data}`);
break;
case DoneEvent.Done:
break;
}
}
// 6. Print the messages from the agent
const messages = await client.agents.listMessages(thread.id);
// Messages iterate from oldest to newest
// messages[0] is the most recent
for (let i = messages.data.length - 1; i >= 0; i--) {
const m = messages.data[i];
if (isOutputOfType(m.content[0], "text")) {
const textContent = m.content[0];
console.log(`${textContent.text.value}`);
console.log(`---------------------------------`);
}
}
// 7. Delete the agent once done
await client.agents.deleteAgent(agent.id);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
输出包含提示和答案。
I need to solve the equation `3x + 11 = 14`. Can you help me?
---------------------------------
Sure! I can help you solve the equation \(3x + 11 = 14\).
To solve this equation, we need to isolate the variable \(x\). Let's go ahead and solve it.
---------------------------------
The solution to the equation \(3x + 11 = 14\) is \(x = 1\).
Therefore, the value of \(x\) that satisfies the equation is 1.
Let me know if you need help with anything else!
---------------------------------
| 参考文档 | 示例 | 库源代码 | 包 (npm) |
先决条件
- Azure 订阅 - 免费创建订阅。
- Node.js LTS
- TypeScript 5.x
- 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色。
- 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。
设置 Azure AI 中心和代理项目
以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:
创建 Azure AI 中心以设置应用环境和 Azure 资源。
在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。
连接 Azure OpenAI 资源或 Azure AI 服务资源
选择基本或标准代理设置
基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。
标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。
[可选]自动部署模板中的模型选择
可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelName
和 modelVersion
参数。
默认情况下,部署模板配置了以下值:
模型参数 | 默认值 |
---|---|
modelName | gpt-4o-mini |
modelFormat | OpenAI(适用于 Azure OpenAI) |
modelVersion | 2024-07-18 |
modelSkuName | GlobalStandard |
modelLocation | eastus |
[可选] 在代理设置过程中使用自己的资源
注意
如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。
通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:
aiServiceAccountResourceId
aiSearchServiceResourceId
aiStorageAccountResourceId
如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceId
和 aiServiceKind
参数。
aiServiceKind
参数应设置为 AzureOpenAI
。
有关详细信息,请参阅如何使用自己的资源。
配置并运行代理
组件 | 说明 |
---|---|
Agent | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
运行 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤让你可以了解代理如何获得结果。 |
运行以下命令以安装 npm 包。
npm install @azure/ai-projects
npm install @azure/identity
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要使用项目中的信息创建连接字符串。 此字符串采用以下格式:
<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>
提示
还可以在 Azure AI Foundry 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。
可以通过导航到你的 discovery_url
并移除前导的 https://
和尾随的 /discovery
来找到 HostName
。 若要查找 discovery_url
,请运行以下 CLI 命令:
az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
例如,连接字符串可能如下所示:
eastus.api.azureml.ms;12345678-abcd-1234-9fc6-62780b3d3e05;my-resource-group;my-project-name
将此连接字符串设置为名为 PROJECT_CONNECTION_STRING
的环境变量。
// index.ts
import type {
MessageDeltaChunk,
MessageDeltaTextContent,
MessageTextContentOutput,
} from "@azure/ai-projects";
import {
AIProjectsClient,
DoneEvent,
ErrorEvent,
isOutputOfType,
MessageStreamEvent,
RunStreamEvent,
ToolUtility,
} from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
const connectionString =
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
if (!connectionString) {
throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set in the environment variables");
}
export async function main(): Promise<void> {
const client = AIProjectsClient.fromConnectionString(
connectionString || "",
new DefaultAzureCredential(),
);
// Step 1: Create code interpreter tool
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool();
// Step 2: Create an agent
const agent = await client.agents.createAgent("gpt-4o-mini", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [codeInterpreterTool.definition],
toolResources: codeInterpreterTool.resources,
});
// Step 3: Create a thread
const thread = await client.agents.createThread();
// Step 4: Add a message to thread
await client.agents.createMessage(
thread.id, {
role: "user",
content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
});
// Intermission: message is now correlated with thread
// Intermission: listing messages will retrieve the message just added
// Step 5: Run the agent
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
for await (const eventMessage of streamEventMessages) {
switch (eventMessage.event) {
case RunStreamEvent.ThreadRunCreated:
break;
case MessageStreamEvent.ThreadMessageDelta:
{
const messageDelta = eventMessage.data as MessageDeltaChunk;
messageDelta.delta.content.forEach((contentPart) => {
if (contentPart.type === "text") {
const textContent = contentPart as MessageDeltaTextContent;
const textValue = textContent.text?.value || "No text";
}
});
}
break;
case RunStreamEvent.ThreadRunCompleted:
break;
case ErrorEvent.Error:
console.log(`An error occurred. Data ${eventMessage.data}`);
break;
case DoneEvent.Done:
break;
}
}
// 6. Print the messages from the agent
const messages = await client.agents.listMessages(thread.id);
// Messages iterate from oldest to newest
// messages[0] is the most recent
for (let i = messages.data.length - 1; i >= 0; i--) {
const m = messages.data[i];
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
const textContent = m.content[0] as MessageTextContentOutput;
console.log(`${textContent.text.value}`);
console.log(`---------------------------------`);
}
}
// 7. Delete the agent once done
await client.agents.deleteAgent(agent.id);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
输出包含提示和答案。
I need to solve the equation `3x + 11 = 14`. Can you help me?
---------------------------------
Sure! I can help you solve the equation \(3x + 11 = 14\).
To solve this equation, we need to isolate the variable \(x\). Let's go ahead and solve it.
---------------------------------
The solution to the equation \(3x + 11 = 14\) is \(x = 1\).
Therefore, the value of \(x\) that satisfies the equation is 1.
Let me know if you need help with anything else!
---------------------------------