Note
本快速入門適用於先前版本的代理程式。 請參閱 Microsoft Foundry 快速入門 ,了解如何使用新版本的 API。
Foundry Agent Service 允許你透過自訂指令,並輔以程式碼解譯器及自訂功能等先進工具,打造符合你需求的 AI 代理。
Prerequisites
- Azure 訂用帳戶 - 建立免費帳戶。
- 確定建立帳戶和專案的個人在訂用帳戶範圍具有 Azure AI 帳戶擁有者 角色,這會授與建立專案所需的許可權
- 或者,在訂用帳戶層級擁有 參與者 或 認知服務參與者 角色,將允許建立專案
- 建立項目之後,請確定專案內建立代理程式的個別人員在專案層級具有 Azure AI 使用者 角色
Important
Microsoft Foundry 入口網站目前僅支援基本的代理設定。 如果您想要執行標準代理程式設定,請參閱 環境設定 一文以深入瞭解。
在 Foundry 入口網站建立 Foundry 帳號與專案
要在 Foundry 中建立帳號和專案,請遵循以下步驟:
去鑄造廠。 如果你正在專案中,請在頁面左上角選擇 Foundry 前往首頁。
使用代理程式開始使用建立流程,以取得最快的體驗。 按兩下 [建立代理程式]。
輸入專案名稱。 如果您想要自定義預設值,請選取 [ 進階選項]。
選取 ,創建。
等候佈建您的資源。
- 將會建立帳戶和專案(您的帳戶的子資源)。
- gpt-4o 模型將會自動部署
- 將會建立預設代理程式
完成後,您將直接進入代理程式遊樂場中,即可開始建立代理程式。 您可以向代理提供指示說明要做什麼以及怎麼做。 例如: 「您是一個實用的代理程式,可以回答地理相關問題。 然後,您可以開始與代理程式聊天。
Note
如果您在嘗試設定或建立代理程式時收到許可權錯誤,請確定您在專案上有 Azure AI 使用者 。
| 參考檔案 | 範例 | 連結庫原始程式碼 | 套件 (NuGet) |
Prerequisites
- 設定代理程式環境
- 將 Azure AI 使用者RBAC 角色 指派給需要使用 SDK 或代理程式遊樂場建立或編輯代理程式的每個小組成員
- 此角色必須在專案範圍指派
- 最低必要許可權: 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>
Important
從 2025 年 5 月開始,Azure AI 代理程式服務會針對 Foundry 專案 使用端點,而不是先前用於中樞型專案的連接字串。 如果您使用中樞型專案,您將無法使用目前版本的 SDK 和 REST API。 如需詳細資訊,請參閱 SDK 使用於中樞型專案。
您可以在 Microsoft Foundry 入口網站中的專案概觀中,在 [程式庫>Foundry] 底下,找到您的端點。
在名為 ProjectEndpoint的環境變數中設定此端點。
您也需要模型的部署名稱。 您可以在左側導覽選單中的 [模型 + 端點 ] 中找到它。
將模型部署名稱的名稱儲存為名為的 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) |
Prerequisites
- 設定代理程式環境
- 將 Azure AI 使用者RBAC 角色 指派給需要使用 SDK 或代理程式遊樂場建立或編輯代理程式的每個小組成員
- 此角色必須在專案範圍指派
- 最低必要許可權: 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>
Important
從 2025 年 5 月開始,Azure AI 代理程式服務會針對 Foundry 專案 使用端點,而不是先前用於中樞型專案的連接字串。 如果您使用中樞型專案,您將無法使用目前版本的 SDK 和 REST API。 如需詳細資訊,請參閱 SDK 使用於中樞型專案。
您可以在 Microsoft Foundry 入口網站中的專案概觀中,在 [程式庫>Foundry] 底下,找到您的端點。
將此端點設定為名為的 PROJECT_ENDPOINT環境變數。
您也需要模型的部署名稱。 您可以在左側導覽選單中的 [模型 + 端點 ] 中找到它。
將模型部署名稱的名稱儲存為名為的 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) |
Prerequisites
- 設定代理程式環境
- 將 Azure AI 使用者RBAC 角色 指派給需要使用 SDK 或代理程式遊樂場建立或編輯代理程式的每個小組成員
- 此角色必須在專案範圍指派
- 最低必要許可權: 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 入口網站中的專案概觀中,在 [程式庫>Foundry] 底下,找到您的端點。
將此端點設定為檔案中名為 PROJECT_ENDPOINT 的 .env 環境變數。
您也需要模型的部署名稱。 您可以在左側導覽選單中的 [模型 + 端點 ] 中找到它。
將模型部署名稱的名稱儲存為名為的 MODEL_DEPLOYMENT_NAME環境變數。
Important
- 本快速入門程式代碼會使用環境變數進行敏感性設定。 絕不要將
.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 ======================
========================================================
完整的 範例原始程式碼 可供使用。
| 參考檔 | 樣品 | 連結庫原始程式碼 | 套件 (Maven) |
Prerequisites
- 設定代理程式環境
- 將 Azure AI 使用者RBAC 角色 指派給需要使用 SDK 或代理程式遊樂場建立或編輯代理程式的每個小組成員
- 此角色必須在專案範圍指派
- 最低必要許可權: 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>
Important
從 2025 年 5 月開始,Azure AI 代理程式服務會針對 Foundry 專案 使用端點,而不是先前用於中樞型專案的連接字串。 如果您使用中樞型專案,您將無法使用目前版本的 SDK 和 REST API。 如需詳細資訊,請參閱 SDK 使用於中樞型專案。
您可以在 Microsoft Foundry 入口網站中的專案概觀中,在 [程式庫>Foundry] 底下,找到您的端點。
在名為 PROJECT_ENDPOINT的環境變數中設定此端點。
您也需要模型的部署名稱。 您可以在左側導覽選單中的 [模型 + 端點 ] 中找到它。
將模型部署名稱的名稱儲存為名為的 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 insturctions
.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());
}
}
}
| 參考文件 |
Prerequisites
- 設定代理程式環境
- 將 Azure AI 使用者RBAC 角色 指派給需要使用 SDK 或代理程式遊樂場建立或編輯代理程式的每個小組成員
- 此角色必須在專案範圍指派
- 最低必要許可權: 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環境變數。
Note
- 對於
api-version參數,GA API 版本為2025-05-01,而最新的預覽 API 版本為2025-05-15-preview。 您必須針對處於預覽狀態的工具使用預覽 API。 - 請考慮讓您的 API 版本成為環境變數,例如
$API_VERSION。
建立專員
Note
使用 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"
後續步驟
瞭解可用於擴充客服專員功能的工具,例如存取網頁、提供基礎資訊等。