在本快速入门中,你将开始使用 Foundry 中的模型和代理。
你将:
- 从模型生成响应
- 使用定义的提示创建代理
- 与代理进行多回合对话
先决条件
设置环境变量并获取代码
将项目终结点和模型名称存储为环境变量。 此示例 quickstart-responses.py 读取以下值:
AZURE_AI_PROJECT_ENDPOINT=https://<resource-name>.services.ai.azure.com/api/projects/<project-name>
MODEL_DEPLOYMENT=gpt-5-mini
quickstart-create-agent.py 和 quickstart-chat-with-agent.py 示例不读取环境变量。 在每个文件中,将 PROJECT_ENDPOINT 和 AGENT_NAME 的值替换为你的端点和一个代理名称,例如 MyAgent。
这些示例使用你在设置 Microsoft Foundry 资源中创建的gpt-5-mini部署。 如果以其他名称部署了模型,请在示例代码中更新模型名称。
请查看下文或查看代码:
将项目终结点和模型名称存储为环境变量。 此示例 quickstart-responses.cs 读取以下值:
AZURE_AI_PROJECT_ENDPOINT=https://<resource-name>.services.ai.azure.com/api/projects/<project-name>
MODEL_DEPLOYMENT=gpt-5-mini
quickstart-create-agent.cs 和 quickstart-chat-with-agent.cs 示例不读取环境变量。 在每个文件中,将 ProjectEndpoint 和 AgentName 的值分别替换为你的端点和代理名称,例如 MyAgent。
这些示例使用你在设置 Microsoft Foundry 资源中创建的gpt-5-mini部署。 如果以其他名称部署了模型,请在示例代码中更新模型名称。
请查看下文或查看代码:
TypeScript 示例不会读取环境变量。 在每个文件中,将这些值替换为 项目终结点 和代理名称,例如 MyAgent:
const PROJECT_ENDPOINT = "https://<resource-name>.services.ai.azure.com/api/projects/<project-name>";
const AGENT_NAME = "MyAgent";
这些示例使用你在设置 Microsoft Foundry 资源中创建的gpt-5-mini部署。 如果以其他名称部署了模型,请在示例代码中更新模型名称。
请查看下文或查看代码:
Java示例不读取环境变量。 在每个文件中,将这些值替换为 项目终结点 和代理名称,例如 MyAgent:
String ProjectEndpoint = "https://<resource-name>.services.ai.azure.com/api/projects/<project-name>";
String AgentName = "MyAgent";
这些示例使用你在设置 Microsoft Foundry 资源中创建的gpt-5-mini部署。 如果以其他名称部署了模型,请在示例代码中更新模型名称。
请查看下文或查看代码:
在每个请求 URL 中,将 YOUR-FOUNDRY-RESOURCE-NAME 和 替换为 YOUR-PROJECT-NAME 中的值,其格式为 https://<resource-name>.services.ai.azure.com/api/projects/<project-name>。
chat-with-agent 请求会从环境变量中读取智能体名称:
AGENT_NAME=MyAgent
这些示例使用你在设置 Microsoft Foundry 资源中创建的gpt-5-mini部署。 如果以其他名称部署了模型,请更新 model 请求正文中的值。
请查看下文或查看代码:
安装和进行身份验证
请确保安装正确版本的包,如下所示。
安装当前版本的 azure-ai-projects. 此版本使用Foundry 项目(新版)API。 这些示例使用来自 azure-identity 的 DefaultAzureCredential 进行身份验证。
pip install "azure-ai-projects>=2.3.0" azure-identity
使用 CLI az login 命令登录,以便在运行Python脚本之前进行身份验证。
安装软件包:
在集成终端中使用 .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>
- 使用 CLI
az login 命令登录,以便在运行Java脚本之前进行身份验证。
在运行下一个命令之前,使用 CLI az login 命令登录以进行身份验证。
获取临时访问令牌。 它将在 60-90 分钟内过期,之后需要刷新。
az account get-access-token --scope https://ai.azure.com/.default
将结果保存为环境变量 AZURE_AI_AUTH_TOKEN。
与模型聊天
与模型交互是 AI 应用程序的基本构建基块。 发送输入并从模型接收响应:
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = os.getenv("AZURE_AI_PROJECT_ENDPOINT", "your_project_endpoint")
MODEL_DEPLOYMENT = os.getenv("MODEL_DEPLOYMENT", "gpt-5-mini")
# 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=MODEL_DEPLOYMENT,
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 projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? "your_project_endpoint";
var modelDeployment = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT") ?? "gpt-5-mini";
// 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.ProjectOpenAIClient.GetProjectResponsesClientForModel(modelDeployment);
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 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 = 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);
package com.azure.ai.agents;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class CreateResponse {
public static void main(String[] args) {
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String ProjectEndpoint = "your_project_endpoint";
// Create responses client to call Foundry API
ResponsesClient responsesClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(ProjectEndpoint)
.buildResponsesClient();
// Run a responses API call
ResponseCreateParams responseRequest = new ResponseCreateParams.Builder()
.input("What is the size of France in square miles?")
.model("gpt-5-mini")
.build();
Response response = responsesClient.getResponseService().create(responseRequest);
System.out.println(response.output());
}
}
将 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?"
}'
模型部署后,您将自动从 主页 移动到 构建 部分。 已选择新模型,可供试用。
提示
如果跳过部署,请在 主页中选择“在操场中进行测试 ”。 选择要使用的即时访问模型,例如 gpt-5-mini。 (在预览期间,这些即时访问模型仅适用于 美国西部的项目。
例如,开始与模型聊天,例如,“给我写一首关于鲜花的诗”。
运行代码后,控制台中会显示模型生成的响应(例如,提示的简短诗或答案)。 这确认项目终结点、身份验证和模型部署正常工作。
创建代理
使用已部署的模型创建代理。
代理定义核心行为。 创建后,它可确保用户交互中的一致响应,而无需每次重复说明。 可以随时更新或删除代理。
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"
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.Agents;
using Azure.AI.Extensions.OpenAI;
// Format: "https://resource_name.services.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
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(
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.services.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.services.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());
}
}
将 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 打印到控制台。
与代理聊天
使用之前创建的名为“MyAgent”的代理,通过提问和相关的后续问题进行交互。 交互过程中会话会保留历史记录。
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
# Format: "https://resource_name.services.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=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Get an OpenAI client pre-bound to the specified agent
openai = project.get_openai_client(agent_name=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.Extensions.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Format: "https://resource_name.services.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.ProjectOpenAIClient.GetProjectConversationsClient().CreateProjectConversation();
// Chat with the agent to answer questions
ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient.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.services.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 = project.getOpenAIClient({
azureConfig: { allowPreview: true, agentName: 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(console.error);
package com.azure.ai.agents;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.client.OpenAIClient;
import com.openai.models.conversations.Conversation;
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.services.ai.azure.com/api/projects/project_name"
String ProjectEndpoint = "your_project_endpoint";
String AgentName = "your_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(ProjectEndpoint);
// Create an OpenAI client bound to the agent endpoint
OpenAIClient openai = builder.buildAgentScopedOpenAIClient(AgentName);
// Create a conversation for multi-turn chat
Conversation conversation = openai.conversations().create();
// Chat with the agent to answer questions
Response response = openai.responses().create(
ResponseCreateParams.builder()
.conversation(conversation.id())
.input("What is the size of France in square miles?")
.build());
printResponse(response);
// Ask a follow-up question in the same conversation
Response followUp = openai.responses().create(
ResponseCreateParams.builder()
.conversation(conversation.id())
.input("And what is the capital city?")
.build());
printResponse(followUp);
}
private static void printResponse(Response response) {
response.output().forEach(item -> item.message().ifPresent(message ->
message.content().forEach(content -> content.outputText().ifPresent(
text -> System.out.println(text.text())))));
}
}
将 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/${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/${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/${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 门户中,选择资源组,然后选择 Delete。 确认要删除资源组。
下一步