在這個快速入門中,你將開始使用 Foundry 中的模型和代理人。
您將:
- 從模型產生回應
- 建立一個有明確提示的代理人
- 與 Agent 進行多回合對話。
先決條件
- 一個已部署於 Microsoft Foundry 的模型。 如果你還沒有模型,先完成 快速入門:設定 Microsoft Foundry 資源。
- 所需的語言執行環境、全域工具及 Visual Studio Code 擴充如 準備你的開發環境 所描述。
設定環境變數並取得程式碼
將 你的專案端 點儲存為環境變數。 此外,請設定這些值以用於指令碼。
- Python and JavaScript
PROJECT_ENDPOINT=<endpoint copied from welcome screen>
AGENT_NAME="MyAgent"
- C# and Java
ProjectEndpoint = <endpoint copied from welcome screen>
AgentName = "MyAgent"
按照以下說明或取得程式碼:
在執行 Python 腳本前,請使用 CLI az login 指令登入驗證。
按照以下說明或取得程式碼:
在執行 C# 腳本前,請使用 CLI 指令登入驗證。
按照以下說明或取得程式碼:
在執行 TypeScript 腳本前,請使用 CLI 指令登入驗證。
按照以下說明或取得程式碼:
在執行 Java 腳本前,請使用 CLI az login 指令登入驗證。
按照以下說明或取得程式碼:
在執行下一個指令前,請使用 CLI 指令登入驗證。
取得暫時存取令牌。 它將在 60-90 分鐘後過期,之後您需要重新整理。
az account get-access-token --scope https://ai.azure.com/.default
將結果儲存為環境變數 。
使用 Foundry 入口網站時不需要任何程式碼。
安裝和驗證
請確保你安裝的是這裡顯示的正確版本的套件。
安裝目前版本的 . 此版本使用 Foundry 專案(新)API 。
pip install azure-ai-projects>=2.0.0
在執行 Python 腳本前,請使用 CLI az login 指令登入驗證。
安裝套件:
在整合終端機中使用 .NET CLI 新增 NuGet 套件:這些套件使用 Foundry 專案(新)API。
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.AI.Projects.OpenAI --prerelease
dotnet add package Azure.Identity
在執行 C# 腳本前,請使用 CLI 指令登入驗證。
安裝目前版本的 . 本版本使用 Foundry 專案(新)API。:
npm install @azure/ai-projects
在執行 TypeScript 腳本前,請使用 CLI 指令登入驗證。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0-beta.2</version>
</dependency>
- 在執行 Java 腳本前,請使用 CLI
az login 指令登入驗證。
在執行下一個指令前,請使用 CLI 指令登入驗證。
取得暫時存取令牌。 它將在 60-90 分鐘後過期,之後您需要重新整理。
az account get-access-token --scope https://ai.azure.com/.default
將結果儲存為環境變數 。
小提示
程式碼使用 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.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create project and openai clients to call Foundry API
project = AIProjectClient(
endpoint=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?",
)
print(f"Response output: {response.output_text}")
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var ProjectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(ProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Run a responses API call
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForModel("gpt-5-mini"); // supports all Foundry direct models
ResponseResult response = await responseClient.CreateResponseAsync(
"What is the size of France in square miles?");
Console.WriteLine(response.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
async function main(): Promise<void> {
// Create project and openai clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Run a responses API call
const response = await openai.responses.create({
model: "gpt-5-mini", // supports all Foundry direct models
input: "What is the size of France in square miles?",
});
console.log(`Response output: ${response.output_text}`);
}
main().catch(console.error);
package com.azure.ai.agents;
import com.azure.ai.agents.models.AgentDetails;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.AuthenticationUtil;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.azure.AzureOpenAIServiceVersion;
import com.openai.azure.AzureUrlPathMode;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.items.ItemCreateParams;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class ChatWithAgent {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String ProjectEndpoint = "your_project_endpoint";
String AgentName = "your_agent_name";
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(ProjectEndpoint)
.buildAgentsClient();
AgentDetails agent = agentsClient.getAgent(AgentName);
Conversation conversation = conversationsClient.getConversationService().create();
conversationsClient.getConversationService().items().create(
ItemCreateParams.builder()
.conversationId(conversation.id())
.addItem(EasyInputMessage.builder()
.role(EasyInputMessage.Role.SYSTEM)
.content("You are a helpful assistant that speaks like a pirate.")
.build()
).addItem(EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Hello, agent!")
.build()
).build()
);
AgentReference agentReference = new AgentReference(agent.getName()).setVersion(agent.getVersion());
Response response = responsesClient.createWithAgentConversation(agentReference, conversation.id());
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(ProjectEndpoint.endsWith("/") ? ProjectEndpoint + "openai" : ProjectEndpoint + "/openai")
.azureUrlPathMode(AzureUrlPathMode.UNIFIED)
.credential(BearerTokenCredential.create(AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(), "https://ai.azure.com/.default")))
.azureServiceVersion(AzureOpenAIServiceVersion.fromString("2025-11-15-preview"))
.build();
ResponseCreateParams responseRequest = new ResponseCreateParams.Builder()
.input("Hello, how can you help me?")
.model("gpt-5-mini") //supports all Foundry direct models
.build();
Response result = client.responses().create(responseRequest);
}
}
將替換為您的值:
curl -X POST https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/openai/responses?api-version=2025-11-15-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"model": "gpt-4.1-mini",
"input": "What is the size of France in square miles?"
}'
模型部署之後,系統會自動將您從 [ 首頁 ] 移至 [建置] 區段。 您的新型號已選中並可供您試用。
開始與你的模特兒聊天,例如,“給我寫一首關於花的詩。
執行程式碼後,你會在主控台看到模型生成的回應(例如一首短詩或對提示的回答)。 這能確認你的專案端點、認證和模型部署都正常運作。
小提示
程式碼使用 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.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
# Create project client to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create an agent with a model and instructions
agent = project.agents.create_version(
agent_name=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.OpenAI;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var ProjectEndpoint = "your_project_endpoint";
var AgentName = "your_agent_name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(ProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create an agent with a model and instructions
AgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini") // supports all Foundry direct models
{
Instructions = "You are a helpful assistant that answers general questions",
};
AgentVersion agent = projectClient.Agents.CreateAgentVersion(
AgentName,
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.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
async function main(): Promise<void> {
// Create project client to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
// Create an agent with a model and instructions
const agent = await project.agents.createVersion(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);
package com.azure.ai.agents;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
public class CreateAgent {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String ProjectEndpoint = "your_project_endpoint";
String AgentName = "your_agent_name";
// Create agents client to call Foundry API
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(ProjectEndpoint)
.buildAgentsClient();
// Create an agent with a model and instructions
PromptAgentDefinition request = new PromptAgentDefinition("gpt-5-mini") // supports all Foundry direct models
.setInstructions("You are a helpful assistant that answers general questions");
AgentVersionDetails agent = agentsClient.createAgentVersion(AgentName, request);
System.out.println("Agent ID: " + agent.getId());
System.out.println("Agent Name: " + agent.getName());
System.out.println("Agent Version: " + agent.getVersion());
}
}
將替換為您的值:
curl -X POST https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents?api-version=2025-11-15-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"name": "MyAgent",
"definition": {
"kind": "prompt",
"model": "gpt-4.1-mini",
"instructions": "You are a helpful assistant that answers general questions"
}
}'
現在建立代理程式並與之互動。
- 仍在 [建置] 區段中,於左窗格選取 [代理程式]。
- 選取 [建立代理程式 ] 並為其命名。
輸出確認代理程式已被建立。 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
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
# Create project and openai clients to call Foundry API
project = AIProjectClient(
endpoint=FOUNDRY_PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# 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,
extra_body={"agent_reference": {"name": FOUNDRY_AGENT_NAME, "type": "agent_reference"}},
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,
extra_body={"agent_reference": {"name": FOUNDRY_AGENT_NAME, "type": "agent_reference"}},
input="And what is the capital city?",
)
print(response.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var ProjectEndpoint = "your_project_endpoint";
var AgentName = "your_agent_name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(ProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create a conversation for multi-turn chat
ProjectConversation conversation = projectClient.OpenAI.Conversations.CreateProjectConversation();
// Chat with the agent to answer questions
ProjectResponsesClient responsesClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(
defaultAgent: AgentName,
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.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
async function main(): Promise<void> {
// Create project and openai clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// 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?",
},
{
body: { agent: { name: AGENT_NAME, type: "agent_reference" } },
},
);
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?",
},
{
body: { agent: { name: FOUNDRY_AGENT_NAME, type: "agent_reference" } },
},
);
console.log(response2.output_text);
}
main().catch(console.error);
package com.azure.ai.agents;
import com.azure.ai.agents.models.AgentDetails;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.AuthenticationUtil;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.azure.AzureOpenAIServiceVersion;
import com.openai.azure.AzureUrlPathMode;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.items.ItemCreateParams;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class ChatWithAgent {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String ProjectEndpoint = "your_project_endpoint";
String AgentName = "your_agent_name";
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(ProjectEndpoint)
.buildAgentsClient();
AgentDetails agent = agentsClient.getAgent(AgentName);
Conversation conversation = conversationsClient.getConversationService().create();
conversationsClient.getConversationService().items().create(
ItemCreateParams.builder()
.conversationId(conversation.id())
.addItem(EasyInputMessage.builder()
.role(EasyInputMessage.Role.SYSTEM)
.content("You are a helpful assistant that speaks like a pirate.")
.build()
).addItem(EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Hello, agent!")
.build()
).build()
);
AgentReference agentReference = new AgentReference(agent.getName()).setVersion(agent.getVersion());
Response response = responsesClient.createWithAgentConversation(agentReference, conversation.id());
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(ProjectEndpoint.endsWith("/") ? ProjectEndpoint + "openai" : ProjectEndpoint + "/openai")
.azureUrlPathMode(AzureUrlPathMode.UNIFIED)
.credential(BearerTokenCredential.create(AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(), "https://ai.azure.com/.default")))
.azureServiceVersion(AzureOpenAIServiceVersion.fromString("2025-11-15-preview"))
.build();
ResponseCreateParams responseRequest = new ResponseCreateParams.Builder()
.input("Hello, how can you help me?")
.model("gpt-5-mini") //supports all Foundry direct models
.build();
Response result = client.responses().create(responseRequest);
}
}
將替換為您的值:
# 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/openai/conversations?api-version=2025-11-15-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{}'
# Lets say Conversation ID created is conv_123456789. Use this in the next step
#Chat with the agent to answer questions
curl -X POST https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/openai/responses?api-version=2025-11-15-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"agent": {"type": "agent_reference", "name": "MyAgent"},
"conversation" : "<YOUR_CONVERSATION_ID>",
"input" : "What is the size of France in square miles?"
}'
#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/openai/responses?api-version=2025-11-15-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"agent": {"type": "agent_reference", "name": "MyAgent"},
"conversation" : "<YOUR_CONVERSATION_ID>",
"input" : "And what is the capital city?"
}'
與您的客服人員互動。
- 新增指示,例如「您是實用的寫作助理」。
- 開始與您的經紀人聊天,例如,“寫一首關於太陽的詩。
- 接著說“俳句怎麼樣?
你會看到代理人對兩個提示的回應。 後續回應顯示代理人會維持跨回合的對話紀錄。
小提示
程式碼使用 Azure AI Projects 2.x,與 Azure AI Projects 1.x 不相容。
請參閱 Foundry(經典)文件 以了解 Azure AI Projects 1.x 版本。
清理資源
如果您不再需要您所建立的任何資源,請刪除與您的專案相關聯的資源群組。
下一個步驟