В этом кратком руководстве вы узнаете, как приступить к использованию моделей и агентов в Foundry.
Вы будете:
- Создание ответа из модели
- Создайте агента с заданным запросом
- Вести многозаходный диалог с агентом
Предпосылки
- Модель, развернутая в 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"
Следуйте инструкциям ниже или получите код:
Войдите с помощью команды CLI az login для проверки подлинности перед выполнением скриптов Python.
Следуйте инструкциям ниже или получите код:
Войдите с помощью команды CLI для проверки подлинности перед выполнением скриптов C#.
Следуйте инструкциям ниже или получите код:
Войдите с помощью команды CLI для проверки подлинности перед выполнением скриптов TypeScript.
Следуйте инструкциям ниже или получите код:
Войдите с помощью команды CLI az login для проверки подлинности перед выполнением скриптов Java.
Следуйте инструкциям ниже или получите код:
Войдите с помощью команды CLI для проверки подлинности перед выполнением следующей команды.
Получите временный токен доступа. Срок действия истекает через 60–90 минут, после этого потребуется обновить его.
az account get-access-token --scope https://ai.azure.com/.default
Сохраните результаты в качестве переменной среды.
Код не требуется при использовании портала Foundry.
Установка и проверка подлинности
Установите правильную версию пакетов, как показано здесь.
Установите текущую версию . В этой версии используется новый API проектов Foundry.
pip install azure-ai-projects>=2.0.0
Войдите с помощью команды CLI az login для проверки подлинности перед выполнением скриптов Python.
Установка пакетов:
Добавьте пакеты NuGet с помощью CLI .NET через интегрированный терминал: эти пакеты используют API Foundry projects (новый).
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.AI.Projects.OpenAI --prerelease
dotnet add package Azure.Identity
Войдите с помощью команды CLI для проверки подлинности перед выполнением скриптов C#.
Установите текущую версию . В этой версии используется новый API проектов Foundry.
npm install @azure/ai-projects
Войдите с помощью команды CLI для проверки подлинности перед выполнением скриптов TypeScript.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0-beta.2</version>
</dependency>
- Войдите с помощью команды CLI
az login для проверки подлинности перед выполнением скриптов Java.
Войдите с помощью команды CLI для проверки подлинности перед выполнением следующей команды.
Получите временный токен доступа. Срок действия истекает через 60–90 минут, после этого потребуется обновить его.
az account get-access-token --scope https://ai.azure.com/.default
Сохраните результаты в качестве переменной среды.
Установка не требуется для использования портала Foundry.
Чат с моделью
Взаимодействие с моделью — это базовый стандартный блок приложений ИИ. Отправьте входные данные и получите ответ от модели:
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?"
}'
После развертывания модели вы автоматически перемещаетесь из Главная в раздел Сборка. Ваша новая модель выбрана и готова для испытания.
Начните чаты с вашей моделью, например: "Напишите мне стихотворение о цветах".
После выполнения кода в консоли отображается созданный моделью ответ (например, короткое стихотворение или ответ на запрос). Это подтверждает правильность работы конечной точки проекта, проверки подлинности и развертывания модели.
Создание агента
Создайте агент с помощью развернутой модели.
Агент определяет основное поведение. После создания он гарантирует согласованные ответы в взаимодействиях пользователей без повторения инструкций каждый раз. Вы можете обновлять или удалять агенты в любое время.
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 вы видите имя агента и идентификатор, напечатанные в консоли.
Чат с агентом
Используйте ранее созданный агент с именем 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?"
}'
Взаимодействие с агентом.
- Добавьте инструкции, такие как "Вы полезный помощник по написанию".
- Начните общаться с агентом, например "Напишите стихотворение о солнце".
- Продолжим с "Как насчёт хайку?"
Вы увидите ответы агента на оба запроса. Дополнительный ответ демонстрирует, что агент сохраняет историю беседы на протяжении всей беседы.
Очистите ресурсы
Если вам больше не нужен какой-либо из созданных ресурсов, удалите группу ресурсов, связанную с проектом.
- На портале #REF! выберите группу ресурсов и выберите Delete. Убедитесь, что вы хотите удалить группу ресурсов.
Следующий шаг
Идея прототипа — создание и оценка корпоративного агента