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

快速入门:创建新代理(预览版)

Azure AI 代理服务允许通过自定义指令和代码解释器等高级工具以及自定义函数来创建符合需求的 AI 代理。

先决条件

基本代理设置支持

在开始之前,请确定是要执行基本代理设置还是标准代理设置。 Azure AI Foundry 仅支持基本代理设置。

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。 可以使用 Azure AI Foundry 门户或自动化 bicep 模板创建基本设置。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。 标准设置只能使用自动化 bicep 模板执行。

重要

Azure AI Foundry 门户目前仅支持基本设置。 如果要执行标准代理设置,请使用文章顶部的其他选项卡来了解标准代理配置。

在 Azure AI Foundry 门户中创建中心和项目

若要创建新的中心和项目,你需要具有资源组或现有中心的“所有者”或“参与者”角色。 如果由于权限而无法创建中心,请联系管理员。

要在 Azure AI Foundry 中创建项目,请执行以下步骤:

  1. 转到 Azure AI Foundry。 如果你已进入项目,请选择页面左上角的“Azure AI Foundry”以转到“主页”。

  2. 选择“+ 创建项目”

  3. 输入项目的名称。

  4. 如果你有一个中心,会选择最近使用过的中心。

  5. 如果你有权访问多个中心,可以从下拉列表中选择一个不同的中心。

  6. 如果要创建新中心,请选择“创建新中心”并输入名称。 若要自定义默认值,请参阅 Azure AI Foundry 文档

    “创建项目”对话框中的项目详细信息页的屏幕截图。

  7. 选择创建

部署模型

  1. 登录到 Azure AI Foundry

  2. 转到你的项目或在 Azure AI Foundry 门户中创建新项目

  3. 在项目概览中,选择位于“生成和自定义”下的“代理”。

  4. 选择 Azure OpenAI 资源。

    初始代理屏幕的屏幕截图。

  5. 选择要让代理使用的模型部署。 如果没有,则部署新模型的屏幕将打开。 否则,可以选择“部署模型”。

    模型选择屏幕的屏幕截图。

    可用模型的屏幕截图。

使用代理操场

代理操场让你无需运行任何代码,即可浏览、处理原型和测试代理。 在此页中,可以快速循环访问和试验这些新想法。

  1. 在“创建和调试代理”屏幕中,选择代理,或使用“新建代理”新建一个。 右侧的“设置”窗格可以更改其参数和工具。

    可以选择为代理提供一个名称,以代替为其生成的名称,并添加指令以帮助提高其性能。 为代理提供有关执行什么操作以及如何执行此操作的明确指示。 包括特定任务、顺序以及任何特殊指令,如语气或互动风格。

    代理创建和调试屏幕的屏幕截图。

    提示

    代理可以访问多个工具,例如扩展其功能的代码解释器,例如使用必应搜索网页、运行代码等能力。 在“设置”窗格中,向下滚动到“知识”和“操作”,然后选择“添加”以查看可用的工具。 代理工具选项的屏幕截图。

另请参阅

查看可用于代理的模型

| 参考文档 | 示例 | 库源代码 | 包 (NuGet) |

先决条件

设置 Azure AI 中心和代理项目

以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:

  1. 创建 Azure AI 中心以设置应用环境和 Azure 资源。

  2. 在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。

  3. 连接 Azure OpenAI 资源或 Azure AI 服务资源

选择基本或标准代理设置

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。

注意

可以使用以下自动化 bicep 模板执行标准代理或基本代理。 还可以使用 Azure AI Foundry 门户创建基本代理。 Azure AI Foundry 目前不支持标准代理设置。

说明和自动部署 关系图(单击放大)
部署使用托管标识进行身份验证的基本代理设置。 系统会为你创建 AI 中心、AI 项目、存储帐户和 AI 服务的资源。

AI 服务帐户已连接到你的项目和中心,gpt-4o-mini 模型部署在 eastus 区域中。 默认情况下使用 Microsoft 管理的密钥保管库。

部署到 Azure
基本代理设置的体系结构关系图。
部署使用托管标识进行身份验证的标准代理设置。

系统会为你创建 AI 中心、AI 项目、密钥保管库、存储帐户、AI 服务和 AI 搜索的资源。

AI 服务、AI 搜索、密钥保管库和存储帐户已连接到项目和中心。 gpt-4o-mini 模型部署在 eastus 区域中。

部署到 Azure
标准代理设置的体系结构关系图。

[可选]自动部署模板中的模型选择

可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelNamemodelVersion 参数。

默认情况下,部署模板配置了以下值:

模型参数 默认值
modelName gpt-4o-mini
modelFormat OpenAI(适用于 Azure OpenAI)
modelVersion 2024-07-18
modelSkuName GlobalStandard
modelLocation eastus

重要

不要更改 modelFormat 参数。

模板仅支持部署 Azure OpenAI 模型。 请在 Azure AI 代理服务模型支持文档中查看哪些 Azure OpenAI 模型受支持。

[可选] 在代理设置过程中使用自己的资源

注意

如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。

通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceIdaiServiceKind 参数。 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 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。 显示 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("PROJECT_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 AI 中心和代理项目

以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:

  1. 创建 Azure AI 中心以设置应用环境和 Azure 资源。

  2. 在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。

  3. 连接 Azure OpenAI 资源或 Azure AI 服务资源

选择基本或标准代理设置

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。

注意

可以使用以下自动化 bicep 模板执行标准代理或基本代理。 还可以使用 Azure AI Foundry 门户创建基本代理。 Azure AI Foundry 目前不支持标准代理设置。

说明和自动部署 关系图(单击放大)
部署使用托管标识进行身份验证的基本代理设置。 系统会为你创建 AI 中心、AI 项目、存储帐户和 AI 服务的资源。

AI 服务帐户已连接到你的项目和中心,gpt-4o-mini 模型部署在 eastus 区域中。 默认情况下使用 Microsoft 管理的密钥保管库。

部署到 Azure
基本代理设置的体系结构关系图。
部署使用托管标识进行身份验证的标准代理设置。

系统会为你创建 AI 中心、AI 项目、密钥保管库、存储帐户、AI 服务和 AI 搜索的资源。

AI 服务、AI 搜索、密钥保管库和存储帐户已连接到项目和中心。 gpt-4o-mini 模型部署在 eastus 区域中。

部署到 Azure
标准代理设置的体系结构关系图。

[可选]自动部署模板中的模型选择

可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelNamemodelVersion 参数。

默认情况下,部署模板配置了以下值:

模型参数 默认值
modelName gpt-4o-mini
modelFormat OpenAI(适用于 Azure OpenAI)
modelVersion 2024-07-18
modelSkuName GlobalStandard
modelLocation eastus

重要

不要更改 modelFormat 参数。

模板仅支持部署 Azure OpenAI 模型。 请在 Azure AI 代理服务模型支持文档中查看哪些 Azure OpenAI 模型受支持。

[可选] 在代理设置过程中使用自己的资源

注意

如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。

通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceIdaiServiceKind 参数。 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 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。 显示 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")

| 参考文档 | 库源代码 | 包 (PyPi) |

先决条件

设置 Azure AI 中心和代理项目

以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:

  1. 创建 Azure AI 中心以设置应用环境和 Azure 资源。

  2. 在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。

  3. 连接 Azure OpenAI 资源或 Azure AI 服务资源

选择基本或标准代理设置

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。

注意

可以使用以下自动化 bicep 模板执行标准代理或基本代理。 还可以使用 Azure AI Foundry 门户创建基本代理。 Azure AI Foundry 目前不支持标准代理设置。

说明和自动部署 关系图(单击放大)
部署使用托管标识进行身份验证的基本代理设置。 系统会为你创建 AI 中心、AI 项目、存储帐户和 AI 服务的资源。

AI 服务帐户已连接到你的项目和中心,gpt-4o-mini 模型部署在 eastus 区域中。 默认情况下使用 Microsoft 管理的密钥保管库。

部署到 Azure
基本代理设置的体系结构关系图。
部署使用托管标识进行身份验证的标准代理设置。

系统会为你创建 AI 中心、AI 项目、密钥保管库、存储帐户、AI 服务和 AI 搜索的资源。

AI 服务、AI 搜索、密钥保管库和存储帐户已连接到项目和中心。 gpt-4o-mini 模型部署在 eastus 区域中。

部署到 Azure
标准代理设置的体系结构关系图。

[可选]自动部署模板中的模型选择

可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelNamemodelVersion 参数。

默认情况下,部署模板配置了以下值:

模型参数 默认值
modelName gpt-4o-mini
modelFormat OpenAI(适用于 Azure OpenAI)
modelVersion 2024-07-18
modelSkuName GlobalStandard
modelLocation eastus

重要

不要更改 modelFormat 参数。

模板仅支持部署 Azure OpenAI 模型。 请在 Azure AI 代理服务模型支持文档中查看哪些 Azure OpenAI 模型受支持。

[可选] 在代理设置过程中使用自己的资源

注意

如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。

通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceIdaiServiceKind 参数。 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 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。 显示 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 AI 中心和代理项目

以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:

  1. 创建 Azure AI 中心以设置应用环境和 Azure 资源。

  2. 在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。

  3. 连接 Azure OpenAI 资源或 Azure AI 服务资源

选择基本或标准代理设置

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。

注意

可以使用以下自动化 bicep 模板执行标准代理或基本代理。 还可以使用 Azure AI Foundry 门户创建基本代理。 Azure AI Foundry 目前不支持标准代理设置。

说明和自动部署 关系图(单击放大)
部署使用托管标识进行身份验证的基本代理设置。 系统会为你创建 AI 中心、AI 项目、存储帐户和 AI 服务的资源。

AI 服务帐户已连接到你的项目和中心,gpt-4o-mini 模型部署在 eastus 区域中。 默认情况下使用 Microsoft 管理的密钥保管库。

部署到 Azure
基本代理设置的体系结构关系图。
部署使用托管标识进行身份验证的标准代理设置。

系统会为你创建 AI 中心、AI 项目、密钥保管库、存储帐户、AI 服务和 AI 搜索的资源。

AI 服务、AI 搜索、密钥保管库和存储帐户已连接到项目和中心。 gpt-4o-mini 模型部署在 eastus 区域中。

部署到 Azure
标准代理设置的体系结构关系图。

[可选]自动部署模板中的模型选择

可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelNamemodelVersion 参数。

默认情况下,部署模板配置了以下值:

模型参数 默认值
modelName gpt-4o-mini
modelFormat OpenAI(适用于 Azure OpenAI)
modelVersion 2024-07-18
modelSkuName GlobalStandard
modelLocation eastus

重要

不要更改 modelFormat 参数。

模板仅支持部署 Azure OpenAI 模型。 请在 Azure AI 代理服务模型支持文档中查看哪些 Azure OpenAI 模型受支持。

[可选] 在代理设置过程中使用自己的资源

注意

如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。

通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceIdaiServiceKind 参数。 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 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。 显示 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 AI 中心和代理项目

以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:

  1. 创建 Azure AI 中心以设置应用环境和 Azure 资源。

  2. 在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。

  3. 连接 Azure OpenAI 资源或 Azure AI 服务资源

选择基本或标准代理设置

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。

注意

可以使用以下自动化 bicep 模板执行标准代理或基本代理。 还可以使用 Azure AI Foundry 门户创建基本代理。 Azure AI Foundry 目前不支持标准代理设置。

说明和自动部署 关系图(单击放大)
部署使用托管标识进行身份验证的基本代理设置。 系统会为你创建 AI 中心、AI 项目、存储帐户和 AI 服务的资源。

AI 服务帐户已连接到你的项目和中心,gpt-4o-mini 模型部署在 eastus 区域中。 默认情况下使用 Microsoft 管理的密钥保管库。

部署到 Azure
基本代理设置的体系结构关系图。
部署使用托管标识进行身份验证的标准代理设置。

系统会为你创建 AI 中心、AI 项目、密钥保管库、存储帐户、AI 服务和 AI 搜索的资源。

AI 服务、AI 搜索、密钥保管库和存储帐户已连接到项目和中心。 gpt-4o-mini 模型部署在 eastus 区域中。

部署到 Azure
标准代理设置的体系结构关系图。

[可选]自动部署模板中的模型选择

可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelNamemodelVersion 参数。

默认情况下,部署模板配置了以下值:

模型参数 默认值
modelName gpt-4o-mini
modelFormat OpenAI(适用于 Azure OpenAI)
modelVersion 2024-07-18
modelSkuName GlobalStandard
modelLocation eastus

重要

不要更改 modelFormat 参数。

模板仅支持部署 Azure OpenAI 模型。 请在 Azure AI 代理服务模型支持文档中查看哪些 Azure OpenAI 模型受支持。

[可选] 在代理设置过程中使用自己的资源

注意

如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。

通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceIdaiServiceKind 参数。 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 门户中项目“概述”的“项目详细信息”>“项目连接字符串”下查找连接字符串。 显示 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!
---------------------------------

| 参考文档 |

先决条件

  • Azure 订阅 - 免费创建订阅
  • 请确保在适当的级别分配了 Azure AI 开发人员RBAC 角色
  • 需要分配有认知服务 OpenAI 用户角色才能使用 Azure AI 服务资源。
  • 安装 Azure CLI 和机器学习扩展。 如果已安装 CLI,请确保它已更新到最新版本。

设置 Azure AI 中心和代理项目

以下部分介绍如何设置开始使用 Azure AI 代理服务所需的资源:

  1. 创建 Azure AI 中心以设置应用环境和 Azure 资源。

  2. 在中心下创建 Azure AI 项目时,会创建一个终结点供应用调用,并会设置应用服务以访问租户中的资源。

  3. 连接 Azure OpenAI 资源或 Azure AI 服务资源

选择基本或标准代理设置

基本设置:代理使用完全由 Microsoft 管理的多租户搜索和存储资源。 你无法查看或控制这些基础 Azure 资源。

标准设置:代理使用客户拥有的单租户搜索和存储资源。 通过此设置,可以完全控制这些资源并查看这些资源,但会根据使用情况产生成本。

注意

可以使用以下自动化 bicep 模板执行标准代理或基本代理。 还可以使用 Azure AI Foundry 门户创建基本代理。 Azure AI Foundry 目前不支持标准代理设置。

说明和自动部署 关系图(单击放大)
部署使用托管标识进行身份验证的基本代理设置。 系统会为你创建 AI 中心、AI 项目、存储帐户和 AI 服务的资源。

AI 服务帐户已连接到你的项目和中心,gpt-4o-mini 模型部署在 eastus 区域中。 默认情况下使用 Microsoft 管理的密钥保管库。

部署到 Azure
基本代理设置的体系结构关系图。
部署使用托管标识进行身份验证的标准代理设置。

系统会为你创建 AI 中心、AI 项目、密钥保管库、存储帐户、AI 服务和 AI 搜索的资源。

AI 服务、AI 搜索、密钥保管库和存储帐户已连接到项目和中心。 gpt-4o-mini 模型部署在 eastus 区域中。

部署到 Azure
标准代理设置的体系结构关系图。

[可选]自动部署模板中的模型选择

可以通过编辑自动部署模板中的模型参数来自定义代理使用的模型。 若要部署其他模型,至少需要更新 modelNamemodelVersion 参数。

默认情况下,部署模板配置了以下值:

模型参数 默认值
modelName gpt-4o-mini
modelFormat OpenAI(适用于 Azure OpenAI)
modelVersion 2024-07-18
modelSkuName GlobalStandard
modelLocation eastus

重要

不要更改 modelFormat 参数。

模板仅支持部署 Azure OpenAI 模型。 请在 Azure AI 代理服务模型支持文档中查看哪些 Azure OpenAI 模型受支持。

[可选] 在代理设置过程中使用自己的资源

注意

如果使用现有的 AI 服务或 Azure OpenAI 资源,则不会部署任何模型。 可以在代理设置完成后将模型部署到资源。

通过在参数文件中提供完整的 arm 资源 ID,使用现有的 AI 服务、Azure OpenAI、AI 搜索和/或 Azure Blob 存储资源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果要使用现有的 Azure OpenAI 资源,则需要更新参数文件中的 aiServiceAccountResourceIdaiServiceKind 参数。 aiServiceKind 参数应设置为 AzureOpenAI

有关详细信息,请参阅如何使用自己的资源

配置并运行代理

组件 说明
Agent 将 AI 模型与工具结合使用的自定义 AI。
工具 工具有助于扩展代理在对话期间可靠准确地响应的能力。 例如,连接到用户定义的知识库以使模型接地,或启用 Web 搜索以提供当前信息。
线程 代理和用户之间的对话会话。 线程存储消息并自动处理截断,使内容适合模型的上下文。
消息 代理或用户创建的消息。 消息可以包括文本、图像和其他文件。 消息以列表的形式存储在线程上。
运行 激活代理以根据线程的内容开始运行。 代理使用其配置和线程的消息通过调用模型和工具来执行任务。 在运行期间,代理会将消息追加到线程。
运行步骤 代理在运行期间所采取的步骤的详细列表。 代理可以在运行期间调用工具或创建消息。 检查运行步骤让你可以了解代理如何获得结果。

为了验证 API 请求,请使用 az login 命令登录 Azure 订阅。

az login

接下来,需要提取 Entra ID 令牌以作为授权提供给 API 调用。 使用 CLI 命令提取令牌:

az account get-access-token --resource 'https://ml.azure.com/' | jq -r .accessToken | tr -d '"'

将访问令牌设置为名为 AZURE_AI_AGENTS_TOKEN 的环境变量。

若要成功向 Azure AI 代理服务进行 REST API 调用,需要使用终结点,如下所示:

https://<HostName>/agents/v1.0/subscriptions/<AzureSubscriptionId>/resourceGroups/<ResourceGroup>/providers/Microsoft.MachineLearningServices/workspaces/<ProjectName>

可以通过导航到你的 discovery_url 并移除前导的 https:// 和尾随的 /discovery 来找到 HostName。 若要查找 discovery_url,请运行以下 CLI 命令:

az ml workspace show -n {project_name} --subscription {subscription_name} --resource-group {resource_group_name} --query discovery_url

例如,终结点可能如下所示:

https://eastus.api.azureml.ms/agents/v1.0/subscriptions/12345678-abcd-1234-abcd-123456789000/resourceGroups/my-resource-group/providers/Microsoft.MachineLearningServices/workspaces/my-project-name

将此终结点设置为名为 AZURE_AI_AGENTS_ENDPOINT 的环境变量。

创建代理

注意

使用 Azure AI 代理服务时,model 参数需要模型部署名称。 如果模型部署名称与基础模型名称不同,则需要将代码调整为 "model": "{your-custom-model-deployment-name}"

curl $AZURE_AI_AGENTS_ENDPOINT/assistants?api-version=2024-12-01-preview \
  -H "Authorization: Bearer $AZURE_AI_AGENTS_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 $AZURE_AI_AGENTS_ENDPOINT/threads?api-version=2024-12-01-preview \
  -H "Authorization: Bearer $AZURE_AI_AGENTS_TOKEN" \
  -H "Content-Type: application/json" \
  -d ''

将用户问题添加到线程

curl $AZURE_AI_AGENTS_ENDPOINT/threads/thread_abc123/messages?api-version=2024-12-01-preview \
  -H "Authorization: Bearer $AZURE_AI_AGENTS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
      "role": "user",
      "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?"
    }'

运行线程

curl $AZURE_AI_AGENTS_ENDPOINT/threads/thread_abc123/runs?api-version=2024-12-01-preview \
  -H "Authorization: Bearer $AZURE_AI_AGENTS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "assistant_id": "asst_abc123",
  }'

检索运行状态

curl $AZURE_AI_AGENTS_ENDPOINT/threads/thread_abc123/runs/run_abc123?api-version=2024-12-01-preview \
  -H "Authorization: Bearer $AZURE_AI_AGENTS_TOKEN"

检索代理响应

curl $AZURE_AI_AGENTS_ENDPOINT/threads/thread_abc123/messages?api-version=2024-12-01-preview \
  -H "Authorization: Bearer $AZURE_AI_AGENTS_TOKEN"