你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
使用 Azure AI Foundry 代理服务,可以通过自定义说明创建根据需求定制的 AI 代理,并通过高级工具(如代码解释器和自定义函数)进行扩充。
先决条件
- Azure 订阅 - 免费创建订阅。
- 确保创建帐户和项目的个人在订阅范围内具有 Azure AI 帐户所有者 角色
- 或者,在订阅级别具有 参与者 或 认知服务参与者 角色也满足此要求。
重要
Azure AI Foundry 门户目前仅支持基本代理集。 若要执行标准代理设置,请参阅 环境设置 文章以了解详细信息。
在 Azure AI Foundry 门户中创建 Foundry 帐户和项目
若要在 Azure AI Foundry 中创建帐户和项目,请执行以下步骤:
| 参考文档 | 示例 | 库源代码 | 包 (NuGet) |
先决条件
- 设置代理环境
- 将 Azure AI 用户RBAC 角色 分配给需要使用 SDK 或代理 Playground 创建或编辑代理的每个团队成员
- 必须在项目范围内分配此角色
- 所需的最低权限: agents/*/read、 agents/*/action、 agents/*/delete
配置并运行代理
组件 | 说明 |
---|---|
代理 | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
跑步 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
创建 .NET 控制台项目。
dotnet new console
将 .NET 包安装到项目。 例如,如果使用 .NET CLI,请运行以下命令。
dotnet add package Azure.AI.Agents.Persistent
dotnet add package Azure.Identity
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要获取项目的终结点。 此字符串采用以下格式:
https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>
提示
还可以在 Azure AI Foundry 门户的库>Azure AI Foundry中,在项目的概述下找到终结点。
例如,终结点可能如下所示:
https://myresource.services.ai.azure.com/api/projects/myproject
在名为 ProjectEndpoint
.. 的 appsetting 变量中设置此终结点。
using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
var projectEndpoint = configuration["ProjectEndpoint"];
var modelDeploymentName = configuration["ModelDeploymentName"];
//Create a PersistentAgentsClient and PersistentAgent.
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());
//Give PersistentAgent a tool to execute code using CodeInterpreterToolDefinition.
PersistentAgent agent = client.Administration.CreateAgent(
model: modelDeploymentName,
name: "My Test Agent",
instructions: "You politely help with math questions. Use the code interpreter tool when asked to visualize numbers.",
tools: [new CodeInterpreterToolDefinition()]
);
//Create a thread to establish a session between Agent and a User.
PersistentAgentThread thread = client.Threads.CreateThread();
//Ask a question of the Agent.
client.Messages.CreateMessage(
thread.Id,
MessageRole.User,
"Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9.");
//Have Agent beging processing user's question with some additional instructions associated with the ThreadRun.
ThreadRun run = client.Runs.CreateRun(
thread.Id,
agent.Id,
additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");
//Poll for completion.
do
{
Thread.Sleep(TimeSpan.FromMilliseconds(500));
run = client.Runs.GetRun(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
|| run.Status == RunStatus.InProgress
|| run.Status == RunStatus.RequiresAction);
//Get the messages in the PersistentAgentThread. Includes Agent (Assistant Role) and User (User Role) messages.
Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
threadId: thread.Id,
order: ListSortOrder.Ascending);
//Display each message and open the image generated using CodeInterpreterToolDefinition.
foreach (PersistentThreadMessage threadMessage in messages)
{
foreach (MessageContent content in threadMessage.ContentItems)
{
switch (content)
{
case MessageTextContent textItem:
Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
break;
case MessageImageFileContent imageFileContent:
Console.WriteLine($"[{threadMessage.Role}]: Image content file ID = {imageFileContent.FileId}");
BinaryData imageContent = client.Files.GetFileContent(imageFileContent.FileId);
string tempFilePath = Path.Combine(AppContext.BaseDirectory, $"{Guid.NewGuid()}.png");
File.WriteAllBytes(tempFilePath, imageContent.ToArray());
client.Files.DeleteFile(imageFileContent.FileId);
ProcessStartInfo psi = new()
{
FileName = tempFilePath,
UseShellExecute = true
};
Process.Start(psi);
break;
}
}
}
//Clean up test resources.
client.Threads.DeleteThread(threadId: thread.Id);
client.Administration.DeleteAgent(agentId: agent.Id);
| 参考文档 | 示例 | 库源代码 | 包 (PyPi) |
先决条件
- 设置代理环境
- 将 Azure AI 用户RBAC 角色 分配给需要使用 SDK 或代理 Playground 创建或编辑代理的每个团队成员
- 必须在项目范围内分配此角色
- 所需的最低权限: agents/*/read、 agents/*/action、 agents/*/delete
配置并运行代理
组件 | 说明 |
---|---|
代理 | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
跑步 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤使您能够了解代理程序如何获得结果。 |
运行以下命令以安装 python 包。
pip install azure-ai-projects
pip install azure-identity
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要获取项目的终结点。 此字符串采用以下格式:
https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>
提示
还可以在 Azure AI Foundry 门户的库>Azure AI Foundry中,在项目的概述下找到终结点。
例如,终结点可能如下所示:
https://myresource.services.ai.azure.com/api/projects/myproject
将此终结点设置为名为 PROJECT_ENDPOINT
的环境变量。
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.agents.models import CodeInterpreterTool
# Create an Azure AI Client from an endpoint, copied from your Azure AI Foundry project.
# You need to login to Azure subscription via Azure CLI and set the environment variables
project_endpoint = os.environ["PROJECT_ENDPOINT"] # Ensure the PROJECT_ENDPOINT environment variable is set
# Create an AIProjectClient instance
project_client = AIProjectClient(
endpoint=project_endpoint,
credential=DefaultAzureCredential(), # Use Azure Default Credential for authentication
api_version="latest",
)
code_interpreter = CodeInterpreterTool()
with project_client:
# Create an agent with the Bing Grounding tool
agent = project_client.agents.create_agent(
model=os.environ["MODEL_DEPLOYMENT_NAME"], # Model deployment name
name="my-agent", # Name of the agent
instructions="You are a helpful agent", # Instructions for the agent
tools=code_interpreter.definitions, # Attach the tool
)
print(f"Created agent, ID: {agent.id}")
# Create a thread for communication
thread = project_client.agents.threads.create()
print(f"Created thread, ID: {thread.id}")
# Add a message to the thread
message = project_client.agents.messages.create(
thread_id=thread.id,
role="user", # Role of the message sender
content="What is the weather in Seattle today?", # Message content
)
print(f"Created message, ID: {message['id']}")
# Create and process an agent run
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")
# Check if the run failed
if run.status == "failed":
print(f"Run failed: {run.last_error}")
# Fetch and log all messages
messages = project_client.agents.messages.list(thread_id=thread.id)
for message in messages.data:
print(f"Role: {message.role}, Content: {message.content}")
# Delete the agent when done
project_client.agents.delete_agent(agent.id)
print("Deleted agent")
| 参考文档 | 示例 | 库源代码 | 包 (npm) |
先决条件
- 设置代理环境
- 将 Azure AI 用户RBAC 角色 分配给需要使用 SDK 或代理 Playground 创建或编辑代理的每个团队成员
- 必须在项目范围内分配此角色
- 所需的最低权限: agents/*/read、 agents/*/action、 agents/*/delete
配置并运行代理
组件 | 说明 |
---|---|
代理 | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
跑步 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤使您能够了解代理程序如何获得结果。 |
此代码中的关键对象包括:
首先,通过运行来初始化新项目:
npm init -y
运行以下命令以安装所需的 npm 包。
npm install @azure/ai-agents @azure/identity
npm install dotenv
接下来,为了验证 API 请求并运行程序,请使用 az login 命令登录 Azure 订阅。
az login
使用以下代码创建并运行代理。 若要运行此代码,需要获取项目的终结点。 此字符串采用以下格式:
https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>
提示
还可以在 Azure AI Foundry 门户的项目概述中,在库>Azure AI Foundry下找到终结点。
例如,终结点可能如下所示:
https://myresource.services.ai.azure.com/api/projects/myproject
将此终结点设置为文件中命名 PROJECT_ENDPOINT
的 .env
环境变量。
重要
- 本快速入门代码使用环境变量进行敏感配置。 请务必确保在您的
.env
文件中列出.env
,以避免将.gitignore
文件提交到版本控制系统。 - 请记住:如果意外提交了敏感信息,请将这些凭据视为已泄露,并立即更换这些凭据。
接下来,创建一个 index.js
文件并粘贴以下代码:
const {
RunStreamEvent,
MessageStreamEvent,
DoneEvent,
ErrorEvent,
AgentsClient,
isOutputOfType,
ToolUtility,
} = require("@azure/ai-agents");
const { DefaultAzureCredential } = require("@azure/identity");
const fs = require("fs");
const path = require("node:path");
require("dotenv/config");
const projectEndpoint = process.env["PROJECT_ENDPOINT"];
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
async function main() {
// Create an Azure AI Client
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
// Upload file and wait for it to be processed
const filePath = "./data/nifty500QuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const localFile = await client.files.upload(localFileStream, "assistants", {
fileName: "myLocalFile",
});
console.log(`Uploaded local file, file ID : ${localFile.id}`);
// Create code interpreter tool
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);
// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
const agent = await client.createAgent(modelDeploymentName, {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [codeInterpreterTool.definition],
toolResources: codeInterpreterTool.resources,
});
console.log(`Created agent, agent ID: ${agent.id}`);
// Create a thread
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
// Create a message
const message = await client.messages.create(
thread.id,
"user",
"Could you please create a bar chart in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provide the file to me?",
);
console.log(`Created message, message ID: ${message.id}`);
// Create and execute a run
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
for await (const eventMessage of streamEventMessages) {
switch (eventMessage.event) {
case RunStreamEvent.ThreadRunCreated:
console.log(`ThreadRun status: ${eventMessage.data.status}`);
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";
console.log(`Text delta received:: ${textValue}`);
}
});
}
break;
case RunStreamEvent.ThreadRunCompleted:
console.log("Thread Run Completed");
break;
case ErrorEvent.Error:
console.log(`An error occurred. Data ${eventMessage.data}`);
break;
case DoneEvent.Done:
console.log("Stream completed.");
break;
}
}
// Delete the original file from the agent to free up space (note: this does not delete your version of the file)
await client.files.delete(localFile.id);
console.log(`Deleted file, file ID : ${localFile.id}`);
// Print the messages from the agent
const messagesIterator = client.messages.list(thread.id);
const messagesArray = [];
for await (const m of messagesIterator) {
messagesArray.push(m);
}
console.log("Messages:", messagesArray);
// Get most recent message from the assistant
const assistantMessage = messagesArray.find((msg) => msg.role === "assistant");
if (assistantMessage) {
const textContent = assistantMessage.content.find((content) => isOutputOfType(content, "text"));
if (textContent) {
// Save the newly created file
console.log(`Saving new files...`);
const imageFileOutput = messagesArray[0].content[0];
const imageFile = imageFileOutput.imageFile.fileId;
const imageFileName = path.resolve(
"./data/" + (await client.files.get(imageFile)).filename + "ImageFile.png",
);
console.log(`Image file name : ${imageFileName}`);
const fileContent = await (await client.files.getContent(imageFile).asNodeStream()).body;
if (fileContent) {
const chunks = [];
for await (const chunk of fileContent) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const buffer = Buffer.concat(chunks);
fs.writeFileSync(imageFileName, buffer);
} else {
console.log("No file content available");
}
}
}
// Iterate through messages and print details for each annotation
console.log(`Message Details:`);
messagesArray.forEach((m) => {
console.log(`File Paths:`);
console.log(`Type: ${m.content[0].type}`);
if (isOutputOfType(m.content[0], "text")) {
const textContent = m.content[0];
console.log(`Text: ${textContent.text.value}`);
}
console.log(`File ID: ${m.id}`);
// firstId and lastId are properties of the paginator, not the messages array
// Removing these references as they don't exist in this context
});
// Delete the agent once done
await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
module.exports = { main };
使用node index.js
运行代码并观察。
输出包含提示和答案。
Type: text
Text: Sure, I can help you solve the equation \(3x + 11 = 14\).
To solve for \(x\), we need to isolate \(x\) on one side of the equation. Here are the steps:
1. Subtract 11 from both sides of the equation:
\[3x + 11 - 11 = 14 - 11\]
\[3x = 3\]
2. Divide both sides of the equation by 3:
\[\frac{3x}{3} = \frac{3}{3}\]
\[x = 1\]
So the solution to the equation \(3x + 11 = 14\) is \(x = 1\).
Type: text
Text: I need to solve the equation `3x + 11 = 14`. Can you help me?
| 参考文档 | 示例 | 库源代码 | 包 (npm) |
先决条件
- Azure 订阅 - 免费创建订阅。
- Node.js LTS
- TypeScript 5.x
- 确保希望使用代理场或 SDK 创建或编辑代理的每个团队成员都已为该项目分配了内置的 Azure AI 开发人员RBAC 角色 。
- 注意:在部署模板后分配这些角色
- 所需的最小权限集为: agents/*/read、 agents/*/action、 agents/*/delete
- 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色。
- 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。
配置并运行代理
组件 | 说明 |
---|---|
代理 | 将 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 门户的库>Azure AI Foundry中,在项目的概述下找到终结点。
可以通过导航到你的 HostName
并移除前导的 discovery_url
和尾随的 https://
来找到 /discovery
。 若要查找 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 {
AIProjectsClient,
DoneEvent,
ErrorEvent,
isOutputOfType,
MessageStreamEvent,
RunStreamEvent,
ToolUtility
} from "@azure/ai-projects";
import type {
MessageDeltaChunk,
MessageDeltaTextContent,
MessageTextContentOutput
} from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
import dotenv from 'dotenv';
dotenv.config();
// Set the connection string from the environment variable
const connectionString = process.env.PROJECT_CONNECTION_STRING;
const model = "gpt-4o";
// Throw an error if the connection string is not set
if (!connectionString) {
throw new Error("Please set the PROJECT_CONNECTION_STRING environment variable.");
}
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(model, {
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 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
const messagesArray = messages.data;
for (let i = messagesArray.length - 1; i >= 0; i--) {
const m = messagesArray[i];
console.log(`Type: ${m.content[0].type}`);
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
const textContent = m.content[0] as MessageTextContentOutput;
console.log(`Text: ${textContent.text.value}`);
}
}
// 7. Delete the agent once done
await client.agents.deleteAgent(agent.id);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
生成 TypeScript 代码,然后使用 node index.js
运行代码并观察结果。
输出包含提示和答案。
Type: text
Text: Sure, I can help you solve the equation \(3x + 11 = 14\).
To solve for \(x\), we need to isolate \(x\) on one side of the equation. Here are the steps:
1. Subtract 11 from both sides of the equation:
\[3x + 11 - 11 = 14 - 11\]
\[3x = 3\]
2. Divide both sides of the equation by 3:
\[\frac{3x}{3} = \frac{3}{3}\]
\[x = 1\]
So the solution to the equation \(3x + 11 = 14\) is \(x = 1\).
Type: text
Text: I need to solve the equation `3x + 11 = 14`. Can you help me?
| 参考文档 |
先决条件
- 设置代理环境
- 将 Azure AI 用户RBAC 角色 分配给需要使用 SDK 或代理 Playground 创建或编辑代理的每个团队成员
- 必须在项目范围内分配此角色
- 所需的最低权限: agents/*/read、 agents/*/action、 agents/*/delete
配置并运行代理
组件 | 说明 |
---|---|
代理 | 将 AI 模型与工具结合使用的自定义 AI。 |
工具 | 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。 |
线程 | 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。 |
消息 | 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。 |
跑步 | 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。 |
运行步骤 | 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤使您能够了解代理程序如何获得结果。 |
API 调用信息
为了验证 API 请求,请使用 az login 命令登录 Azure 订阅。
az login
接下来,你需要获取 Entra ID 令牌,用作对 API 调用的授权。 使用 CLI 命令提取令牌:
az account get-access-token --resource 'https://ai.azure.com' | jq -r .accessToken | tr -d '"'
将访问令牌设置为名为 AGENT_TOKEN
的环境变量。
若要成功对 Azure AI Foundry 代理服务进行 REST API 调用,需要使用终结点,如下所示:
https://<your_ai_service_name>.services.ai.azure.com/api/projects/<your_project_name>
例如,终结点可能如下所示:
https://exampleaiservice.services.ai.azure.com/api/projects/project
将此终结点设置为名为 AZURE_AI_FOUNDRY_PROJECT_ENDPOINT
的环境变量。
注意
- 对于
api-version
参数,GA API 版本是2025-05-01
最新的预览版 API 版本2025-05-15-preview
。 对于处于预览状态的工具,必须使用预览 API。 - 请考虑使 API 版本成为环境变量,例如
$API_VERSION
。
创建代理
注意
使用 Azure AI 代理服务时,model
参数需要模型部署名称。 如果模型部署名称与基础模型名称不同,则需要将代码调整为 "model": "{your-custom-model-deployment-name}"
。
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=2025-05-01 \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"instructions": "You are a helpful agent.",
"name": "my-agent",
"tools": [{"type": "code_interpreter"}],
"model": "gpt-4o-mini"
}'
创建线程
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads?api-version=2025-05-01 \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d ''
将用户问题添加到线程
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=2025-05-01 \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"role": "user",
"content": "I need to solve the equation `3x + 11 = 14`. Can you help me?"
}'
运行线程
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs?api-version=2025-05-01 \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"assistant_id": "asst_abc123",
}'
检索运行状态
curl --request GET \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs/run_abc123?api-version=2025-05-01 \
-H "Authorization: Bearer $AGENT_TOKEN"
检索代理响应
curl --request GET \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=2025-05-01 \
-H "Authorization: Bearer $AGENT_TOKEN"