在這個快速入門中,你將開始使用 Foundry 中的模型和代理人。
你將:
- 從模型產生回應
- 建立一個有明確提示的代理人
- 與 Agent 進行多回合對話。
先決條件
拿到程式碼並設定你的數值
Python 範例不會讀取環境變數。 在每個檔案中,替換以下佔位值:
-
your_project_endpoint:您的專案端點,格式為 https://<resource-name>.services.ai.azure.com/api/projects/<project-name>。
-
your_agent_name:你的代理人名稱,例如 MyAgent。
這些範例會使用您在 設定 Microsoft Foundry 資源 中建立的gpt-5-mini部署。 如果你部署的模型名稱不同,請在範例程式碼中更新模型名稱。
請繼續以下操作或取得代碼:
C# 的取樣不會讀取環境變數。 在每個檔案中,替換以下佔位值:
-
your_project_endpoint:您的專案端點,格式為 https://<resource-name>.services.ai.azure.com/api/projects/<project-name>。
-
your_agent_name:你的代理人名稱,例如 MyAgent。
這些範例會使用您在 設定 Microsoft Foundry 資源 中建立的gpt-5-mini部署。 如果你部署的模型名稱不同,請在範例程式碼中更新模型名稱。
請繼續以下操作或取得代碼:
TypeScript 的範例不會讀取環境變數。 在每個檔案中,將這些值替換為 你的專案端點 和代理名稱,例如 MyAgent:
const FOUNDRY_PROJECT_ENDPOINT = "https://<resource-name>.services.ai.azure.com/api/projects/<project-name>";
const FOUNDRY_AGENT_NAME = "MyAgent";
這些範例會使用您在 設定 Microsoft Foundry 資源 中建立的gpt-5-mini部署。 如果你部署的模型名稱不同,請在範例程式碼中更新模型名稱。
請繼續以下操作或取得代碼:
Java 範例不會讀取環境變數。 在每個檔案中,將這些值替換為 你的專案端點 和代理名稱,例如 MyAgent:
String foundryProjectEndpoint = "https://<resource-name>.services.ai.azure.com/api/projects/<project-name>";
String foundryAgentName = "MyAgent";
這些範例會使用您在 設定 Microsoft Foundry 資源 中建立的gpt-5-mini部署。 如果你部署的模型名稱不同,請在範例程式碼中更新模型名稱。
請繼續以下操作或取得代碼:
在每個請求 URL 中,將 YOUR-PROJECT-NAME 和 YOUR-FOUNDRY-RESOURCE-NAME 替換為來自 您的專案端點 的值,其格式為 https://<resource-name>.services.ai.azure.com/api/projects/<project-name>。
chat-with-agent 請求會從環境變數讀取代理名稱:
FOUNDRY_AGENT_NAME=MyAgent
這些範例會使用您在 設定 Microsoft Foundry 資源 中建立的gpt-5-mini部署。 如果你部署的模型名稱不同,請更新 model 請求文中的值。
請繼續以下操作或取得代碼:
使用 Foundry 入口網站時不需要任何程式碼。
安裝與認證
請確保你安裝的是這裡顯示的正確版本的套件。
安裝目前版本的 azure-ai-projects. 此版本使用 Foundry 專案(新)API。 範例使用 DefaultAzureCredential 進行驗證,而 DefaultAzureCredential 來自 azure-identity。
pip install "azure-ai-projects>=2.3.0" azure-identity
在執行 Python 腳本前,請使用 CLI az login 指令登入驗證。
安裝套件:
在整合終端機中使用 .NET CLI 新增 NuGet 套件:這些套件使用 Foundry 專案(新)API。
dotnet add package Azure.AI.Projects
dotnet add package Azure.AI.Projects.Agents
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.Identity
在執行 C# 腳本前,請使用 CLI az login 指令登入驗證。
安裝目前版本的 @azure/ai-projects. 本版本使用 Foundry 專案(新)API。:
npm install @azure/ai-projects @azure/identity
在執行 TypeScript 腳本前,請使用 CLI az login 指令登入驗證。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.57.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.1</version>
</dependency>
- 在執行 Java 腳本前,請使用 CLI
az login 指令登入驗證。
在執行下一個指令前,請使用 CLI az login 指令登入驗證。
申請臨時存取權。 它會在 60-90 分鐘內到期,之後你需要更新。
az account get-access-token --scope https://ai.azure.com/.default
將結果儲存為環境變數 AZURE_AI_AUTH_TOKEN。
提示
程式碼使用 Azure AI Projects 2.x,且與 Azure AI Projects 1.x 不相容。
請參閱 Foundry(經典)文件 以了解 Azure AI Projects 1.x 版本。
與模特兒聊天
與模型互動是 AI 應用的基本建構要素。 發送輸入並接收模型的回應:
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint"
# Create project and openai clients to call Foundry API
project = AIProjectClient(
endpoint=FOUNDRY_PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Run a responses API call
response = openai.responses.create(
model="gpt-5-mini", # supports all Foundry direct models
input="What is the size of France in square miles?",
)
if not response.output_text or not response.output_text.strip():
raise RuntimeError("Response output text was empty.")
print(f"Response output: {response.output_text}")
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var foundryProjectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(foundryProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Run a responses API call
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForModel(
"gpt-5-mini"); // supports all Foundry direct models
ResponseResult response = await responseClient.CreateResponseAsync(
"What is the size of France in square miles?");
string outputText = response.GetOutputText();
if (string.IsNullOrWhiteSpace(outputText))
{
throw new InvalidOperationException("Response output text was empty.");
}
Console.WriteLine(outputText);
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint";
async function main(): Promise<void> {
// Create project and openai clients to call Foundry API
const project = new AIProjectClient(FOUNDRY_PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Run a responses API call
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "What is the size of France in square miles?",
});
console.log(`Response output: ${response.output_text}`);
}
main().catch(console.error);
用你的價值觀替換 YOUR-FOUNDRY-RESOURCE-NAME :
curl -X POST https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/openai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"model": "gpt-5-mini",
"input": "What is the size of France in square miles?"
}'
模型部署後,你會自動從 Home 區移到 Build 區塊。 你的新型號已經選定,準備好讓你試用。
提示
如果您跳過部署,請在首頁中選取在 Playground 中測試。 選擇你想使用的即時存取模式,例如 gpt-5-mini。 (預覽期間,這些即時存取模型僅適用於 West US3 的專案。)
開始和你的模特兒聊天,例如:「寫一首關於花的詩給我。」
執行程式碼後,你會在主控台看到模型生成的回應(例如一首短詩或對提示的回答)。 這能確認你的專案端點、認證和模型部署都正常運作。
提示
程式碼使用 Azure AI Projects 2.x,且與 Azure AI Projects 1.x 不相容。
請參閱 Foundry(經典)文件 以了解 Azure AI Projects 1.x 版本。
建立代理人
用你部署的模型建立一個代理程式。
代理人定義核心行為。 一旦建立,它能確保使用者互動中回應一致,且不會每次重複指令。 你可以隨時更新或刪除代理人。
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint"
FOUNDRY_AGENT_NAME = "your-agent-name"
# Create project client to call Foundry API
project = AIProjectClient(
endpoint=FOUNDRY_PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create an agent with a model and instructions
agent = project.agents.create_version(
agent_name=FOUNDRY_AGENT_NAME,
definition=PromptAgentDefinition(
model="gpt-5-mini", # supports all Foundry direct models
instructions="You are a helpful assistant that answers general questions",
),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var foundryProjectEndpoint = "your_project_endpoint";
var foundryAgentName = "your-agent-name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(foundryProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create an agent with a model and instructions
ProjectsAgentDefinition agentDefinition = new DeclarativeAgentDefinition("gpt-5-mini") // supports all Foundry direct models
{
Instructions = "You are a helpful assistant that answers general questions",
};
ProjectsAgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
foundryAgentName,
options: new(agentDefinition));
Console.WriteLine($"Agent created (id: {agent.Id}, name: {agent.Name}, version: {agent.Version})");
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint";
const FOUNDRY_AGENT_NAME = "your_agent_name";
async function main(): Promise<void> {
// Create project client to call Foundry API
const project = new AIProjectClient(FOUNDRY_PROJECT_ENDPOINT, new DefaultAzureCredential());
// Create an agent with a model and instructions
const agent = await project.agents.createVersion(FOUNDRY_AGENT_NAME, {
kind: "prompt",
model: "gpt-5-mini", //supports all Foundry direct models
instructions: "You are a helpful assistant that answers general questions",
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
}
main().catch(console.error);
用你的價值觀替換 YOUR-FOUNDRY-RESOURCE-NAME :
curl -X POST https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents?api-version=v1 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"name": "MyAgent",
"definition": {
"kind": "prompt",
"model": "gpt-5-mini",
"instructions": "You are a helpful assistant that answers general questions"
}
}'
現在建立一個代理人並與它互動。
- 仍在 建構 區塊,在左側窗格中,選擇 代理人。
- 選擇 「建立代理」 並命名,例如「MyAgent」。
輸出確認代理程式已成功創建。 SDK 分頁中,你會看到代理程式名稱和 ID 印在主控台上。
提示
程式碼使用 Azure AI Projects 2.x,且與 Azure AI Projects 1.x 不相容。
請參閱 Foundry(經典)文件 以了解 Azure AI Projects 1.x 版本。
與經紀人聊天
使用先前建立的名為「MyAgent」的代理,透過提問及相關追蹤來互動。 對話在這些互動中保存記錄。
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint"
FOUNDRY_AGENT_NAME = "your-agent-name"
# Create project and openai clients to call Foundry API
project = AIProjectClient(
endpoint=FOUNDRY_PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create the agent (or a new version, if it already exists)
project.agents.create_version(
agent_name=FOUNDRY_AGENT_NAME,
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant that answers general questions",
),
)
# Get an OpenAI client pre-bound to the specified agent
openai = project.get_openai_client(agent_name=FOUNDRY_AGENT_NAME)
# Create a conversation for multi-turn chat
conversation = openai.conversations.create()
# Chat with the agent to answer questions
response = openai.responses.create(
conversation=conversation.id,
input="What is the size of France in square miles?",
)
print(response.output_text)
# Ask a follow-up question in the same conversation
response = openai.responses.create(
conversation=conversation.id,
input="And what is the capital city?",
)
print(response.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var foundryProjectEndpoint = "your_project_endpoint";
var foundryAgentName = "your-agent-name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(foundryProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create the agent (or a new version, if it already exists)
ProjectsAgentDefinition agentDefinition = new DeclarativeAgentDefinition("gpt-5-mini") // supports all Foundry direct models
{
Instructions = "You are a helpful assistant that answers general questions",
};
projectClient.AgentAdministrationClient.CreateAgentVersion(
foundryAgentName,
options: new(agentDefinition));
// Create a conversation for multi-turn chat
ProjectConversation conversation = projectClient.ProjectOpenAIClient.GetProjectConversationsClient().CreateProjectConversation();
// Chat with the agent to answer questions
ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(
defaultAgent: foundryAgentName,
defaultConversationId: conversation.Id);
ResponseResult response = responsesClient.CreateResponse("What is the size of France in square miles?");
Console.WriteLine(response.GetOutputText());
// Ask a follow-up question in the same conversation
response = responsesClient.CreateResponse("And what is the capital city?");
Console.WriteLine(response.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint";
const FOUNDRY_AGENT_NAME = "your-agent-name";
async function createAgentVersion(projectEndpoint: string, agentName: string): Promise<void> {
const credential = new DefaultAzureCredential();
const token = await credential.getToken("https://ai.azure.com/.default");
if (!token) {
throw new Error("Failed to acquire a Foundry access token");
}
const response = await fetch(
`${projectEndpoint.replace(/\/$/, "")}/agents/${encodeURIComponent(agentName)}/versions?api-version=v1`,
{
method: "POST",
headers: {
"Authorization": ["Bearer", token.token].join(" "),
"Content-Type": "application/json",
},
body: JSON.stringify({
definition: {
kind: "prompt",
model: "gpt-5-mini", //supports all Foundry direct models
instructions: "You are a helpful assistant that answers general questions",
},
}),
},
);
if (!response.ok) {
throw new Error(`Failed to create agent version: ${response.status} ${await response.text()}`);
}
}
async function main(): Promise<void> {
// Create project and openai clients to call Foundry API
const project = new AIProjectClient(FOUNDRY_PROJECT_ENDPOINT, new DefaultAzureCredential());
// Create the agent (or a new version, if it already exists)
await createAgentVersion(FOUNDRY_PROJECT_ENDPOINT, FOUNDRY_AGENT_NAME);
const openai = project.getOpenAIClient({
azureConfig: { allowPreview: true, agentName: FOUNDRY_AGENT_NAME },
});
// Create a conversation for multi-turn chat
const conversation = await openai.conversations.create();
// Chat with the agent to answer questions
const response = await openai.responses.create({
conversation: conversation.id,
input: "What is the size of France in square miles?",
});
console.log(response.output_text);
// Ask a follow-up question in the same conversation
const response2 = await openai.responses.create({
conversation: conversation.id,
input: "And what is the capital city?",
});
console.log(response2.output_text);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
用你的價值觀替換 YOUR-FOUNDRY-RESOURCE-NAME :
# Generate a response using the agent
curl -X POST "https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents/${FOUNDRY_AGENT_NAME}/endpoint/protocols/openai/responses?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"input": [{"role": "user", "content": "What is the size of France in square miles?"}]
}'
# Optional Step: Create a conversation to use with the agent
curl -X POST "https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents/${FOUNDRY_AGENT_NAME}/endpoint/protocols/openai/conversations?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"items": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What is the size of France in square miles?"
}
]
}
]
}'
# Lets say Conversation ID created is conv_123456789. Use this in the next step
#Optional Step: Ask a follow-up question in the same conversation
curl -X POST "https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents/${FOUNDRY_AGENT_NAME}/endpoint/protocols/openai/responses?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"conversation": "<CONVERSATION_ID>",
"input": [{"role": "user", "content": "And what is the capital?"}]
}'
與你的經紀人互動。
- 並附上指示,例如:「你是一位有幫助的寫作助理。」
- 開始和你的經紀人聊天,例如:「寫一首關於太陽的詩。」
- 接著問「來個俳句怎麼樣?」
你會看到代理人對兩個提示的回應。 後續回應顯示代理人會維持跨回合的對話紀錄。
提示
程式碼使用 Azure AI Projects 2.x,且與 Azure AI Projects 1.x 不相容。
請參閱 Foundry(經典)文件 以了解 Azure AI Projects 1.x 版本。
清理資源
如果你不再需要你建立的任何資源,請刪除與專案相關的資源群組。
下一步