快速入門:建立新代理人(經典版)

註

本文件指的是 Microsoft Foundry(經典版)入口網站。

Agents(經典版)現已棄用,將於 2027 年 3 月 31 日退役。 請使用普遍可用的 Microsoft Foundry Agents Service 中的新代理。 請依照 遷移指南 更新你的工作負載。

註

本快速入門適用於先前版本的代理程式。 要使用新版本的 API,請參閱 Microsoft Foundry 的快速入門。

Foundry Agent Service 允許你透過自訂指令,並輔以程式碼解譯器及自訂功能等先進工具,打造符合你需求的 AI 代理。

先決條件

  • Azure訂閱 - 免費創建一個。

  • 確保建立帳號和專案的個人在訂閱範圍內擁有 Foundry 帳戶擁有者 角色,這會授予建立專案所需的權限

    重要

    Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。

    • 或者,在訂閱層級擁有貢獻者或擁有者角色將能建立專案。
  • 建立專案後,請確認負責在該專案中建立 Agent 的使用者在專案層級具有 Foundry 使用者角色

重要

Microsoft Foundry 入口網站目前僅支援基本的代理設定。 如果你想執行標準代理設定,請參考環境 設定 文章了解更多。

在 Foundry 入口網站建立 Foundry 帳號與專案

要在 Foundry 中建立帳號和專案,請遵循以下步驟:

  1. 去鑄造廠。 如果你正在專案中,請在頁面左上角選擇 Foundry 前往首頁。

  2. 使用代理程式的入門建立流程,以獲得最快速的體驗。 點擊 建立代理人。

    Foundry 傳送門的截圖。

  3. 請輸入專案名稱。 如果你想自訂預設值,請選擇 進階選項。

    這是建立專案的進階選項截圖。

  4. 選擇 「建立」。

  5. 請等待資源配置完成。

    1. 會建立一個帳號和專案(你帳號的子資源)。
    2. GPT-4o 型號將自動部署
    3. 會建立一個預設代理
  6. 完成後,你會直接進入特工遊樂場,開始創建特工。 你可以給你的代理指示該做什麼以及怎麼做。 例如:「 你是一位能回答地理相關問題的熱心客服人員。」 然後你就可以開始和你的經紀人聊天。

    特工遊樂場的截圖。

    註

    如果你在設定或建立代理程式時出現權限錯誤,請確保你在專案中有 Foundry 使用者 。

| 參考文件 | Samples | 函式庫原始碼 | 套件 (NuGet) |

先決條件

  • 一個設定好的代理環境

  • 將 Foundry UserRBAC 角色 指派給每位需要使用 SDK 或 Agent Playground 建立或編輯代理的團隊成員

    重要

    Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。

    • 此角色必須在專案範圍內指定
    • 最低必要權限: agents/*/read、 agents/*/action、 agents/*/delete

設定並執行代理程式

建立一個 .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>

重要

自 2025 年 5 月起,Azure AI Agent 服務改用端點來處理 Foundry 專案,取代先前用於中樞型專案的連接字串。 如果你使用的是樞紐型專案,就無法使用目前版本的 SDK 和 REST API。 欲了解更多資訊,請參閱 SDK 與樞紐專案的使用情況。

你可以在 Microsoft Foundry 入口網站 的 overview 中,在 Libraries>Foundry 下找到你的專案端點。

一張顯示 Foundry 入口網站端點的截圖。

將此端點設於一個名為 ProjectEndpoint的環境變數中。

你還需要你模型的部署名稱。 你可以在左側導覽選單的 Models + Endpoints 找到它。

顯示 Foundry 入口網站中模型部署畫面的螢幕擷取畫面。

將你的模型部署名稱存為一個名為 ModelDeploymentName的環境變數。

using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using System.Diagnostics;

var projectEndpoint = System.Environment.GetEnvironmentVariable("ProjectEndpoint");
var modelDeploymentName = System.Environment.GetEnvironmentVariable("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 begin 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;
        }
    }
}

//If you want to delete your agent, uncomment the following lines:
//client.Threads.DeleteThread(threadId: thread.Id);
//client.Administration.DeleteAgent(agentId: agent.Id);

| 參考文件 | 取樣 | 函式庫原始碼 | 套件(PyPi) |

先決條件

  • 一個設定好的代理環境

  • 將 Foundry UserRBAC 角色 指派給每位需要使用 SDK 或 Agent Playground 建立或編輯代理的團隊成員

    重要

    Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。

    • 此角色必須在專案範圍內指定
    • 最低必要權限: agents/*/read、 agents/*/action、 agents/*/delete

設定並執行代理程式

執行以下指令安裝 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>

重要

自 2025 年 5 月起,Azure AI Agent 服務改用端點來處理 Foundry 專案,取代先前用於中樞型專案的連接字串。 如果你使用的是樞紐型專案,就無法使用目前版本的 SDK 和 REST API。 欲了解更多資訊,請參閱 SDK 與樞紐專案的使用情況。

你可以在 Microsoft Foundry 入口網站 的 overview 中,在 Libraries>Foundry 下找到你的專案端點。

一張顯示 Foundry 入口網站端點的截圖。

將此端點設為名為 PROJECT_ENDPOINT的環境變數。

你還需要你模型的部署名稱。 你可以在左側導覽選單的 Models + Endpoints 找到它。

顯示 Foundry 入口網站中模型部署畫面的螢幕擷取畫面。

將你的模型部署名稱存為一個名為 MODEL_DEPLOYMENT_NAME的環境變數。

import os
from pathlib import Path
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.agents.models import CodeInterpreterTool

# Create an AIProjectClient instance
project_client = AIProjectClient(
    endpoint=os.getenv("PROJECT_ENDPOINT"),
    credential=DefaultAzureCredential(),  
    # Use Azure Default Credential for authentication
)

with project_client:

    code_interpreter = CodeInterpreterTool()

    agent = project_client.agents.create_agent(
        model=os.getenv("MODEL_DEPLOYMENT_NAME"),  # Model deployment name
        name="my-agent",  # Name of the agent
        instructions="""You politely help with math questions. 
        Use the Code Interpreter tool when asked to visualize numbers.""",  
        # Instructions for the agent
        tools=code_interpreter.definitions,  # Attach the tool
        tool_resources=code_interpreter.resources,  # Attach tool resources
    )
    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}")

    question = """Draw a graph for a line with a slope of 4 
    and y-intercept of 9 and provide the file to me?"""

    # Add a message to the thread
    message = project_client.agents.messages.create(
        thread_id=thread.id,
        role="user",  # Role of the message sender
        content=question,  # 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,
        additional_instructions="""Please address the user as Jane Doe.
        The user has a premium account.""",
    )

    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)
    print(f"Messages: {messages}")

    for message in messages:
        print(f"Role: {message.role}, Content: {message.content}")
        for this_content in message.content:
            print(f"Content Type: {this_content.type}, Content Data: {this_content}")
            if this_content.text.annotations:
                for annotation in this_content.text.annotations:
                    print(f"Annotation Type: {annotation.type}, Text: {annotation.text}")
                    print(f"Start Index: {annotation.start_index}")
                    print(f"End Index: {annotation.end_index}")
                    print(f"File ID: {annotation.file_path.file_id}")
                    # Save every image file in the message
                    file_id = annotation.file_path.file_id
                    file_name = f"{file_id}_image_file.png"
                    project_client.agents.files.save(file_id=file_id, file_name=file_name)
                    print(f"Saved image file to: {Path.cwd() / file_name}")
    #Uncomment these lines to delete the agent when done
    #project_client.agents.delete_agent(agent.id)
    #print("Deleted agent")

| 參考文件 | 範例 | 程式庫原始碼 | 套件(npm) |

先決條件

  • 一個設定好的代理環境

  • 將 Foundry UserRBAC 角色 指派給每位需要使用 SDK 或 Agent Playground 建立或編輯代理的團隊成員

    重要

    Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。

    • 此角色必須在專案範圍內指定
    • 最低必要權限: agents/*/read、 agents/*/action、 agents/*/delete

設定並執行代理程式

此程式碼中的關鍵物件包括:

首先,透過執行以下方式初始化一個新的 TypeScript 專案:

npm init -y
npm pkg set type="module"

執行以下指令安裝所需的 npm 套件。

npm install @azure/ai-agents @azure/identity
npm install @types/node typescript --save-dev

接著,要驗證你的 API 請求並執行程式,請使用 az login 指令登入你的 Azure 訂閱。

az login

請使用以下程式碼來回答數學題 I need to solve the equation '3x + 11 = 14'. Can you help me?目。 要執行這段程式碼,你需要取得專案的端點。 這串字串的格式如下:

https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>

你可以在 Microsoft Foundry 入口網站 的 overview 中,在 Libraries>Foundry 下找到你的專案端點。

一張顯示 Foundry 入口網站端點的截圖。

將此端點設為一個在檔案中命名PROJECT_ENDPOINT.env的環境變數。

你還需要你模型的部署名稱。 你可以在左側導覽選單的 Models + Endpoints 找到它。

顯示 Foundry 入口網站中模型部署畫面的螢幕擷取畫面。

將你的模型部署名稱存為一個名為 MODEL_DEPLOYMENT_NAME的環境變數。

重要

  • 這段快速入門程式碼使用環境變數來進行敏感設定。 千萬不要把檔案 .env 提交給版本控制,確保 .env 它已經在你的 .gitignore 檔案裡。
  • 請記住:如果你不小心洩漏了敏感資訊,請立即將這些憑證視為外洩並更換。

建立一個包含以下內容的 tsconfig.json 檔案:

{
  "compilerOptions": {
    "module": "nodenext",
    "target": "esnext",
    "types": ["node"],
    "lib": ["esnext"],
    "sourceMap": true,
    "declaration": true,
    "declarationMap": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "strict": true,
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "noUncheckedSideEffectImports": true,
    "moduleDetection": "force",
    "skipLibCheck": true,
  }
}

接著,建立一個 index.ts 檔案並貼上以下程式碼:

import { AgentsClient } from "@azure/ai-agents";
import { DefaultAzureCredential } from "@azure/identity";

const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>";
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";

export async function main(): Promise<void> {
  // Create an Azure AI Client
  const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

  // Create an agent
  const agent = await client.createAgent(modelDeploymentName, {
    name: "my-agent",
    instructions: "You are a helpful agent specialized in math. When providing mathematical explanations, use plain text formatting with simple characters like +, -, *, / for operations. Do not use LaTeX formatting with backslashes or special notation. Make your explanations clear and easy to read in a terminal.",
  });
  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}`);

  // List all threads for the agent
  const threads = client.threads.list();
  console.log(`Threads for agent ${agent.id}:`);
  for await (const t of threads) {
    console.log(`Thread ID: ${t.id} created at: ${t.createdAt}`);
  }

  // Create a message
  const message = await client.messages.create(thread.id, "user", "I need to solve the equation `3x + 11 = 14`. Can you help me?");
  console.log(`Created message, message ID : ${message.id}`);

  // Create and poll a run
  console.log("Creating run...");
  const run = await client.runs.createAndPoll(thread.id, agent.id, {
    pollingOptions: {
      intervalInMs: 2000,
    },
    onResponse: (response): void => {
      const parsedBody =
        typeof response.parsedBody === "object" && response.parsedBody !== null
          ? response.parsedBody
          : null;
      const status = parsedBody && "status" in parsedBody ? parsedBody.status : "unknown";
      console.log(`Received response with status: ${status}`);
    },
  });
  console.log(`Run finished with status: ${run.status}`);

  const messagesIterator = client.messages.list(thread.id);
  console.log("\n\n========================================================");
  console.log("=================== CONVERSATION RESULTS ===================");
  console.log("========================================================\n");
  
  // Collect all messages first
  const messages = [];
  for await (const m of messagesIterator) {
    messages.push(m);
  }
  
  // Reverse the order of messages (or sort by timestamp if available)
  messages.reverse();
  
  // Display messages in the new order
  for (const m of messages) {
    if (m.role === "user") {
      console.log(`\n❓ USER QUESTION: ${
        Array.isArray(m.content) && m.content[0]?.type === "text" && 'text' in m.content[0]
          ? m.content[0].text.value
          : JSON.stringify(m.content)
      }`);
    } else if (m.role === "assistant") {
      console.log("\n🤖 ASSISTANT'S ANSWER:");
      console.log("--------------------------------------------------");
      
      // Extract and print the text content in a more readable format
      if (m.content && Array.isArray(m.content)) {
        for (const content of m.content) {
          if (content.type === "text" && 'text' in content) {
            console.log(content.text?.value);
          } else {
            console.log(content);
          }
        }
      } else {
        console.log(JSON.stringify(m.content, null, 2));
      }
      console.log("--------------------------------------------------\n");
    }
  }
  
  console.log("\n========================================================");
  console.log("====================== END OF RESULTS ======================");
  console.log("========================================================\n");

  // Clean up
  await client.threads.delete(thread.id);
  await client.deleteAgent(agent.id);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

用 npx tsx -r dotenv/config index.ts. 來執行程式碼。 此程式碼回答了問題 I need to solve the equation '3x + 11 = 14'. Can you help me?。 回應並非決定性的,你的輸出會與以下類似:

Created agent, agent ID : asst_X4yDNWrdWKb8LN0SQ6xlzhWk
Created thread, thread ID : thread_TxqZcHL2BqkNWl9dFzBYMIU6
Threads for agent asst_X4yDNWrdWKb8LN0SQ6xlzhWk:
...
Created message, message ID : msg_R0zDsXdc2UbfsNXvS1zeS6hk
Creating run...
Received response with status: queued
Received response with status: in_progress
Received response with status: completed
Run finished with status: completed

========================================================
=================== CONVERSATION RESULTS ===================
========================================================

❓ USER QUESTION: I need to solve the equation `3x + 11 = 14`. Can you help me?

🤖 ASSISTANT'S ANSWER:
--------------------------------------------------
Certainly! Let's solve the equation step by step:

We have:
3x + 11 = 14

### Step 1: Eliminate the constant (+11) on the left-hand side.
Subtract 11 from both sides:
3x + 11 - 11 = 14 - 11
This simplifies to:
3x = 3

We have:
3x + 11 = 14

### Step 1: Eliminate the constant (+11) on the left-hand side.
Subtract 11 from both sides:
3x + 11 - 11 = 14 - 11
This simplifies to:
3x = 3

### Step 2: Solve for x.
Divide both sides by 3:
3x / 3 = 3 / 3
This simplifies to:
x = 1

### Final Answer:
x = 1
--------------------------------------------------

========================================================
====================== END OF RESULTS ======================
========================================================

完整範例原始碼可取得。

| 參考文件 | Samples | 函式庫原始碼 | 套件(Maven) |

先決條件

  • 一個設定好的代理環境

  • 將 Foundry UserRBAC 角色 指派給每位需要使用 SDK 或 Agent Playground 建立或編輯代理的團隊成員

    重要

    Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。

    • 此角色必須在專案範圍內指定
    • 最低必要權限: agents/*/read、 agents/*/action、 agents/*/delete

設定並執行代理程式

首先,建立一個新的 Java 主控台專案。 你需要以下相依關係來執行程式碼:

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-agents-persistent</artifactId>
        <version>1.0.0-beta.2</version>
    </dependency>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.17.0-beta.1</version>
    </dependency>
</dependencies>

接著,要驗證你的 API 請求並執行程式,請使用 az login 指令登入你的 Azure 訂閱。

az login

請使用以下程式碼建立並執行代理程式。 要執行這段程式碼,你需要取得專案的端點。 這串字串的格式如下:

https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>

重要

自 2025 年 5 月起,Azure AI Agent 服務改用端點來處理 Foundry 專案,取代先前用於中樞型專案的連接字串。 如果你使用的是樞紐型專案,就無法使用目前版本的 SDK 和 REST API。 欲了解更多資訊,請參閱 SDK 與樞紐專案的使用情況。

你可以在 Microsoft Foundry 入口網站 的 overview 中,在 Libraries>Foundry 下找到你的專案端點。

一張顯示 Foundry 入口網站端點的截圖。

將此端點設於一個名為 PROJECT_ENDPOINT的環境變數中。

你還需要你模型的部署名稱。 你可以在左側導覽選單的 Models + Endpoints 找到它。

顯示 Foundry 入口網站中模型部署畫面的螢幕擷取畫面。

將你的模型部署名稱存為一個名為 MODEL_DEPLOYMENT_NAME的環境變數。

程式碼範例

package com.example.agents;

import com.azure.ai.agents.persistent.MessagesClient;
import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient;
import com.azure.ai.agents.persistent.PersistentAgentsClient;
import com.azure.ai.agents.persistent.PersistentAgentsClientBuilder;
import com.azure.ai.agents.persistent.RunsClient;
import com.azure.ai.agents.persistent.ThreadsClient;
import com.azure.ai.agents.persistent.models.CodeInterpreterToolDefinition;
import com.azure.ai.agents.persistent.models.CreateAgentOptions;
import com.azure.ai.agents.persistent.models.CreateRunOptions;
import com.azure.ai.agents.persistent.models.MessageImageFileContent;
import com.azure.ai.agents.persistent.models.MessageRole;
import com.azure.ai.agents.persistent.models.MessageTextContent;
import com.azure.ai.agents.persistent.models.PersistentAgent;
import com.azure.ai.agents.persistent.models.PersistentAgentThread;
import com.azure.ai.agents.persistent.models.RunStatus;
import com.azure.ai.agents.persistent.models.ThreadMessage;
import com.azure.ai.agents.persistent.models.ThreadRun;
import com.azure.ai.agents.persistent.models.MessageContent;
import com.azure.core.http.rest.PagedIterable;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.util.Arrays;

public class AgentSample {

    public static void main(String[] args) {
        // variables for authenticating requests to the agent service 
        String projectEndpoint = System.getenv("PROJECT_ENDPOINT");
        String modelName = System.getenv("MODEL_DEPLOYMENT_NAME");

        // initialize clients to manage various aspects of agent runtime
        PersistentAgentsClientBuilder clientBuilder = new PersistentAgentsClientBuilder()
            .endpoint(projectEndpoint)
            .credential(new DefaultAzureCredentialBuilder().build());
        PersistentAgentsClient agentsClient = clientBuilder.buildClient();
        PersistentAgentsAdministrationClient administrationClient = agentsClient.getPersistentAgentsAdministrationClient();
        ThreadsClient threadsClient = agentsClient.getThreadsClient();
        MessagesClient messagesClient = agentsClient.getMessagesClient();
        RunsClient runsClient = agentsClient.getRunsClient();
        
        
        String agentName = "my-agent"; // the name of the agent
        CreateAgentOptions createAgentOptions = new CreateAgentOptions(modelName)
            .setName(agentName)
            .setInstructions("You are a helpful agent") // system instructions
            .setTools(Arrays.asList(new CodeInterpreterToolDefinition()));
        PersistentAgent agent = administrationClient.createAgent(createAgentOptions);

        PersistentAgentThread thread = threadsClient.createThread();
        ThreadMessage createdMessage = messagesClient.createMessage(
            thread.getId(),
            MessageRole.USER,
            "I need to solve the equation `3x + 11 = 14`. Can you help me?"); // The message to the agent

        try {
            //run the agent
            CreateRunOptions createRunOptions = new CreateRunOptions(thread.getId(), agent.getId())
                .setAdditionalInstructions("");
            ThreadRun threadRun = runsClient.createRun(createRunOptions);
            // wait for the run to complete before printing the message
            waitForRunCompletion(thread.getId(), threadRun, runsClient);
            printRunMessages(messagesClient, thread.getId());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //cleanup - uncomment these lines if you want to delete the agent
            //threadsClient.deleteThread(thread.getId());
            //administrationClient.deleteAgent(agent.getId());
        }
    }

    // A helper function to print messages from the agent
    public static void printRunMessages(MessagesClient messagesClient, String threadId) {

        PagedIterable<ThreadMessage> runMessages = messagesClient.listMessages(threadId);
        for (ThreadMessage message : runMessages) {
            System.out.print(String.format("%1$s - %2$s : ", message.getCreatedAt(), message.getRole()));
            for (MessageContent contentItem : message.getContent()) {
                if (contentItem instanceof MessageTextContent) {
                    System.out.print((((MessageTextContent) contentItem).getText().getValue()));
                } else if (contentItem instanceof MessageImageFileContent) {
                    String imageFileId = (((MessageImageFileContent) contentItem).getImageFile().getFileId());
                    System.out.print("Image from ID: " + imageFileId);
                }
                System.out.println();
            }
        }
    }

    // a helper function to wait until a run has completed running
    public static void waitForRunCompletion(String threadId, ThreadRun threadRun, RunsClient runsClient)
        throws InterruptedException {

        do {
            Thread.sleep(500);
            threadRun = runsClient.getRun(threadId, threadRun.getId());
        }
        while (
            threadRun.getStatus() == RunStatus.QUEUED
                || threadRun.getStatus() == RunStatus.IN_PROGRESS
                || threadRun.getStatus() == RunStatus.REQUIRES_ACTION);

        if (threadRun.getStatus() == RunStatus.FAILED) {
            System.out.println(threadRun.getLastError().getMessage());
        }
    }
}

| 參考文件 |

先決條件

  • 一個設定好的代理環境

  • 將 Foundry UserRBAC 角色 指派給每位需要使用 SDK 或 Agent Playground 建立或編輯代理的團隊成員

    重要

    Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。

    • 此角色必須在專案範圍內指定
    • 最低必要權限: agents/*/read、 agents/*/action、 agents/*/delete

設定並執行代理程式

要驗證你的 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的環境變數。

要成功呼叫 REST API 至 Foundry Agent Service,您需要使用專案的端點:

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 ,最新預覽版為 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"

下一步

了解 工具 如何用來擴展智能代理的能力,例如存取網路、提供基礎資訊等。