共用方式為


快速入門:建立新的代理程式

Azure AI 代理程式服務可讓您透過自定義指示,以及透過程式代碼解釋器和自定義函式等進階工具來建立專為您需求量身打造的 AI 代理程式。

| 參考檔案 | 範例 | 連結庫原始程式碼 | 套件 (NuGet) |

必要條件

設定您的 Azure AI Hub 和代理程式專案

下一節說明如何設定開始使用 Azure AI 代理程式服務所需的資源:

  1. 建立 Azure AI Hub 來設定您的應用程式環境和 Azure 資源。

  2. 在您的中樞下建立 Azure AI 專案會建立端點以供應用程式呼叫,並設定應用程式服務以存取租使用者中的資源。

  3. 聯機 Azure OpenAI 資源或 Azure AI 服務資源

選擇 [基本] 或 [標準代理程式設定]

基本設定:代理程式會使用由 Microsoft 完全管理的多租用戶搜尋和記憶體資源。 您沒有這些基礎 Azure 資源的可見度或控制權。

標準設定:代理程式會使用客戶擁有的單一租用戶搜尋和記憶體資源。 透過此設定,您可以完全控制這些資源並查看這些資源,但會根據使用量產生成本。

描述和自動部署 圖表(按兩下以放大)
部署使用受控識別進行驗證的基本代理程序設定。 AI 中樞、AI 專案、記憶體帳戶和 AI 服務的資源會為您建立。

AI 服務帳戶會連線到您的專案和中樞,gpt-4o-mini 模型會部署在 eastus 區域中。 預設會使用Microsoft管理的金鑰保存庫。

部署至 Azure
基本代理程式設定的架構圖表。
部署使用受控識別進行驗證的標準代理程序設定。

系統會為您建立 AI 中樞、AI 專案、金鑰保存庫、記憶體帳戶、AI 服務和 AI 搜尋的資源。

AI 服務、AI 搜尋、金鑰保存庫和記憶體帳戶會連線到您的專案和中樞。 gpt-4o-mini 模型部署在 eastus 區域中。

部署至 Azure
標準代理程式設定的架構圖表。

[選擇性]自動部署範本中的模型選取

您可以編輯自動部署範本中的模型參數,以自訂代理程式所使用的模型。 若要部署不同的模型,您必須至少 modelName 更新 和 modelVersion 參數。

根據預設,部署範本會使用下列值進行設定:

模型參數 預設值
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資源標識碼,使用現有的 AI 服務、Azure OpenAI、AI 搜尋和/或 Azure Blob 儲存體 資源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果您想要使用現有的 Azure OpenAI 資源,您必須更新 aiServiceAccountResourceId 參數檔案中的 和 aiServiceKind 參數。 參數 aiServiceKind 應設定為 AzureOpenAI

如需詳細資訊,請參閱 如何使用您自己的資源

設定和執行代理程式

元件 描述
代理程式 搭配工具使用 AI 模型的自訂 AI。
工具 工具可協助擴充代理程式在交談期間可靠且準確地回應的能力。 例如連線到使用者定義 知識庫 將模型連線到地面,或讓 Web 搜尋提供目前的資訊。
Thread 代理程式與使用者之間的交談會話。 對話會儲存訊息,並自動處理截斷,以將內容放入模型的內容中。
訊息 代理程式或使用者所建立的訊息。 訊息可以包含文字、影像和其他檔案。 訊息會儲存為對話上的清單。
執行 啟用代理程式,以根據 Thread 的內容開始執行。 代理程式會使用其組態和線程的訊息,藉由呼叫模型和工具來執行工作。 在執行中,代理程式會將訊息附加至線程。
執行步驟 代理程式在執行時所採取步驟的詳細清單。 代理程式可以在執行期間呼叫工具或建立訊息。 檢查執行步驟可讓您瞭解代理程式如何取得其結果。

將 .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 入口網站中 連接字串 的螢幕快照。

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環境變數。

// 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 AI Hub 和代理程式專案

下一節說明如何設定開始使用 Azure AI 代理程式服務所需的資源:

  1. 建立 Azure AI Hub 來設定您的應用程式環境和 Azure 資源。

  2. 在您的中樞下建立 Azure AI 專案會建立端點以供應用程式呼叫,並設定應用程式服務以存取租使用者中的資源。

  3. 聯機 Azure OpenAI 資源或 Azure AI 服務資源

選擇 [基本] 或 [標準代理程式設定]

基本設定:代理程式會使用由 Microsoft 完全管理的多租用戶搜尋和記憶體資源。 您沒有這些基礎 Azure 資源的可見度或控制權。

標準設定:代理程式會使用客戶擁有的單一租用戶搜尋和記憶體資源。 透過此設定,您可以完全控制這些資源並查看這些資源,但會根據使用量產生成本。

描述和自動部署 圖表(按兩下以放大)
部署使用受控識別進行驗證的基本代理程序設定。 AI 中樞、AI 專案、記憶體帳戶和 AI 服務的資源會為您建立。

AI 服務帳戶會連線到您的專案和中樞,gpt-4o-mini 模型會部署在 eastus 區域中。 預設會使用Microsoft管理的金鑰保存庫。

部署至 Azure
基本代理程式設定的架構圖表。
部署使用受控識別進行驗證的標準代理程序設定。

系統會為您建立 AI 中樞、AI 專案、金鑰保存庫、記憶體帳戶、AI 服務和 AI 搜尋的資源。

AI 服務、AI 搜尋、金鑰保存庫和記憶體帳戶會連線到您的專案和中樞。 gpt-4o-mini 模型部署在 eastus 區域中。

部署至 Azure
標準代理程式設定的架構圖表。

[選擇性]自動部署範本中的模型選取

您可以編輯自動部署範本中的模型參數,以自訂代理程式所使用的模型。 若要部署不同的模型,您必須至少 modelName 更新 和 modelVersion 參數。

根據預設,部署範本會使用下列值進行設定:

模型參數 預設值
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 資源識別符,使用現有的 AI 服務、Azure OpenAI、AI 搜尋和/或 Azure Blob 儲存體 資源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果您想要使用現有的 Azure OpenAI 資源,您必須更新 aiServiceAccountResourceId 參數檔案中的 和 aiServiceKind 參數。 參數 aiServiceKind 應設定為 AzureOpenAI

如需詳細資訊,請參閱 如何使用您自己的資源

設定和執行代理程式

元件 描述
代理程式 搭配工具使用 AI 模型的自訂 AI。
工具 工具可協助擴充代理程式在交談期間可靠且準確地回應的能力。 例如連線到使用者定義 知識庫 將模型連線到地面,或讓 Web 搜尋提供目前的資訊。
Thread 代理程式與使用者之間的交談會話。 對話會儲存訊息,並自動處理截斷,以將內容放入模型的內容中。
訊息 代理程式或使用者所建立的訊息。 訊息可以包含文字、影像和其他檔案。 訊息會儲存為對話上的清單。
執行 啟用代理程式,以根據 Thread 的內容開始執行。 代理程式會使用其組態和線程的訊息,藉由呼叫模型和工具來執行工作。 在執行中,代理程式會將訊息附加至線程。
執行步驟 代理程式在執行時所採取步驟的詳細清單。 代理程式可以在執行期間呼叫工具或建立訊息。 檢查執行步驟可讓您瞭解代理程式如何取得其結果。

執行下列命令以安裝 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 入口網站中 連接字串 的螢幕快照。

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環境變數。

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 Hub 和代理程式專案

下一節說明如何設定開始使用 Azure AI 代理程式服務所需的資源:

  1. 建立 Azure AI Hub 來設定您的應用程式環境和 Azure 資源。

  2. 在您的中樞下建立 Azure AI 專案會建立端點以供應用程式呼叫,並設定應用程式服務以存取租使用者中的資源。

  3. 聯機 Azure OpenAI 資源或 Azure AI 服務資源

選擇 [基本] 或 [標準代理程式設定]

基本設定:代理程式會使用由 Microsoft 完全管理的多租用戶搜尋和記憶體資源。 您沒有這些基礎 Azure 資源的可見度或控制權。

標準設定:代理程式會使用客戶擁有的單一租用戶搜尋和記憶體資源。 透過此設定,您可以完全控制這些資源並查看這些資源,但會根據使用量產生成本。

描述和自動部署 圖表(按兩下以放大)
部署使用受控識別進行驗證的基本代理程序設定。 AI 中樞、AI 專案、記憶體帳戶和 AI 服務的資源會為您建立。

AI 服務帳戶會連線到您的專案和中樞,gpt-4o-mini 模型會部署在 eastus 區域中。 預設會使用Microsoft管理的金鑰保存庫。

部署至 Azure
基本代理程式設定的架構圖表。
部署使用受控識別進行驗證的標準代理程序設定。

系統會為您建立 AI 中樞、AI 專案、金鑰保存庫、記憶體帳戶、AI 服務和 AI 搜尋的資源。

AI 服務、AI 搜尋、金鑰保存庫和記憶體帳戶會連線到您的專案和中樞。 gpt-4o-mini 模型部署在 eastus 區域中。

部署至 Azure
標準代理程式設定的架構圖表。

[選擇性]自動部署範本中的模型選取

您可以編輯自動部署範本中的模型參數,以自訂代理程式所使用的模型。 若要部署不同的模型,您必須至少 modelName 更新 和 modelVersion 參數。

根據預設,部署範本會使用下列值進行設定:

模型參數 預設值
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資源標識碼,使用現有的 AI 服務、Azure OpenAI、AI 搜尋和/或 Azure Blob 儲存體 資源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果您想要使用現有的 Azure OpenAI 資源,您必須更新 aiServiceAccountResourceId 參數檔案中的 和 aiServiceKind 參數。 參數 aiServiceKind 應設定為 AzureOpenAI

如需詳細資訊,請參閱 如何使用您自己的資源

設定和執行代理程式

元件 描述
代理程式 搭配工具使用 AI 模型的自訂 AI。
工具 工具可協助擴充代理程式在交談期間可靠且準確地回應的能力。 例如連線到使用者定義 知識庫 將模型連線到地面,或讓 Web 搜尋提供目前的資訊。
Thread 代理程式與使用者之間的交談會話。 對話會儲存訊息,並自動處理截斷,以將內容放入模型的內容中。
訊息 代理程式或使用者所建立的訊息。 訊息可以包含文字、影像和其他檔案。 訊息會儲存為對話上的清單。
執行 啟用代理程式,以根據 Thread 的內容開始執行。 代理程式會使用其組態和線程的訊息,藉由呼叫模型和工具來執行工作。 在執行中,代理程式會將訊息附加至線程。
執行步驟 代理程式在執行時所採取步驟的詳細清單。 代理程式可以在執行期間呼叫工具或建立訊息。 檢查執行步驟可讓您瞭解代理程式如何取得其結果。

執行下列命令以安裝 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 入口網站中 連接字串 的螢幕快照。

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環境變數。

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 Hub 和代理程式專案

下一節說明如何設定開始使用 Azure AI 代理程式服務所需的資源:

  1. 建立 Azure AI Hub 來設定您的應用程式環境和 Azure 資源。

  2. 在您的中樞下建立 Azure AI 專案會建立端點以供應用程式呼叫,並設定應用程式服務以存取租使用者中的資源。

  3. 聯機 Azure OpenAI 資源或 Azure AI 服務資源

選擇 [基本] 或 [標準代理程式設定]

基本設定:代理程式會使用由 Microsoft 完全管理的多租用戶搜尋和記憶體資源。 您沒有這些基礎 Azure 資源的可見度或控制權。

標準設定:代理程式會使用客戶擁有的單一租用戶搜尋和記憶體資源。 透過此設定,您可以完全控制這些資源並查看這些資源,但會根據使用量產生成本。

描述和自動部署 圖表(按兩下以放大)
部署使用受控識別進行驗證的基本代理程序設定。 AI 中樞、AI 專案、記憶體帳戶和 AI 服務的資源會為您建立。

AI 服務帳戶會連線到您的專案和中樞,gpt-4o-mini 模型會部署在 eastus 區域中。 預設會使用Microsoft管理的金鑰保存庫。

部署至 Azure
基本代理程式設定的架構圖表。
部署使用受控識別進行驗證的標準代理程序設定。

系統會為您建立 AI 中樞、AI 專案、金鑰保存庫、記憶體帳戶、AI 服務和 AI 搜尋的資源。

AI 服務、AI 搜尋、金鑰保存庫和記憶體帳戶會連線到您的專案和中樞。 gpt-4o-mini 模型部署在 eastus 區域中。

部署至 Azure
標準代理程式設定的架構圖表。

[選擇性]自動部署範本中的模型選取

您可以編輯自動部署範本中的模型參數,以自訂代理程式所使用的模型。 若要部署不同的模型,您必須至少 modelName 更新 和 modelVersion 參數。

根據預設,部署範本會使用下列值進行設定:

模型參數 預設值
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資源標識碼,使用現有的 AI 服務、Azure OpenAI、AI 搜尋和/或 Azure Blob 儲存體 資源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果您想要使用現有的 Azure OpenAI 資源,您必須更新 aiServiceAccountResourceId 參數檔案中的 和 aiServiceKind 參數。 參數 aiServiceKind 應設定為 AzureOpenAI

如需詳細資訊,請參閱 如何使用您自己的資源

設定和執行代理程式

元件 描述
代理程式 搭配工具使用 AI 模型的自訂 AI。
工具 工具可協助擴充代理程式在交談期間可靠且準確地回應的能力。 例如,連線到使用者定義的 知識庫 以將模型停在地上,或讓 Web 搜尋提供目前的資訊。
Thread 代理程式與使用者之間的交談會話。 對話會儲存訊息,並自動處理截斷,以將內容放入模型的內容中。
訊息 代理程式或使用者所建立的訊息。 訊息可以包含文字、影像和其他檔案。 訊息會儲存為對話上的清單。
執行 啟用代理程式,以根據 Thread 的內容開始執行。 代理程式會使用其組態和線程的訊息,藉由呼叫模型和工具來執行工作。 在執行中,代理程式會將訊息附加至線程。
執行步驟 代理程式在執行時所採取步驟的詳細清單。 代理程式可以在執行期間呼叫工具或建立訊息。 檢查執行步驟可讓您瞭解代理程式如何取得其結果。

執行下列命令以安裝 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.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 Hub 和代理程式專案

下一節說明如何設定開始使用 Azure AI 代理程式服務所需的資源:

  1. 建立 Azure AI Hub 來設定您的應用程式環境和 Azure 資源。

  2. 在您的中樞下建立 Azure AI 專案會建立端點以供應用程式呼叫,並設定應用程式服務以存取租使用者中的資源。

  3. 聯機 Azure OpenAI 資源或 Azure AI 服務資源

選擇 [基本] 或 [標準代理程式設定]

基本設定:代理程式會使用由 Microsoft 完全管理的多租用戶搜尋和記憶體資源。 您沒有這些基礎 Azure 資源的可見度或控制權。

標準設定:代理程式會使用客戶擁有的單一租用戶搜尋和記憶體資源。 透過此設定,您可以完全控制這些資源並查看這些資源,但會根據使用量產生成本。

描述和自動部署 圖表(按兩下以放大)
部署使用受控識別進行驗證的基本代理程序設定。 AI 中樞、AI 專案、記憶體帳戶和 AI 服務的資源會為您建立。

AI 服務帳戶會連線到您的專案和中樞,gpt-4o-mini 模型會部署在 eastus 區域中。 預設會使用Microsoft管理的金鑰保存庫。

部署至 Azure
基本代理程式設定的架構圖表。
部署使用受控識別進行驗證的標準代理程序設定。

系統會為您建立 AI 中樞、AI 專案、金鑰保存庫、記憶體帳戶、AI 服務和 AI 搜尋的資源。

AI 服務、AI 搜尋、金鑰保存庫和記憶體帳戶會連線到您的專案和中樞。 gpt-4o-mini 模型部署在 eastus 區域中。

部署至 Azure
標準代理程式設定的架構圖表。

[選擇性]自動部署範本中的模型選取

您可以編輯自動部署範本中的模型參數,以自訂代理程式所使用的模型。 若要部署不同的模型,您必須至少 modelName 更新 和 modelVersion 參數。

根據預設,部署範本會使用下列值進行設定:

模型參數 預設值
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資源標識碼,使用現有的 AI 服務、Azure OpenAI、AI 搜尋和/或 Azure Blob 儲存體 資源:

  • aiServiceAccountResourceId
  • aiSearchServiceResourceId
  • aiStorageAccountResourceId

如果您想要使用現有的 Azure OpenAI 資源,您必須更新 aiServiceAccountResourceId 參數檔案中的 和 aiServiceKind 參數。 參數 aiServiceKind 應設定為 AzureOpenAI

如需詳細資訊,請參閱 如何使用您自己的資源

設定和執行代理程式

元件 描述
代理程式 搭配工具使用 AI 模型的自訂 AI。
工具 工具可協助擴充代理程式在交談期間可靠且準確地回應的能力。 例如連線到使用者定義的 知識庫 以將模型停在地上,或讓 Web 搜尋提供目前的資訊。
Thread 代理程式與使用者之間的交談會話。 對話會儲存訊息,並自動處理截斷,以將內容放入模型的內容中。
訊息 代理程式或使用者所建立的訊息。 訊息可以包含文字、影像和其他檔案。 訊息會儲存為對話上的清單。
執行 啟用代理程式,以根據 Thread 的內容開始執行。 代理程式會使用其組態和線程的訊息,藉由呼叫模型和工具來執行工作。 在執行中,代理程式會將訊息附加至線程。
執行步驟 代理程式在執行時所採取步驟的詳細清單。 代理程式可以在執行期間呼叫工具或建立訊息。 檢查執行步驟可讓您瞭解代理程式如何取得其結果。

執行下列命令以安裝 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 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!
---------------------------------