En esta guía rápida, empezarás a usar modelos y agentes en Foundry.
Hará lo siguiente:
- Generación de una respuesta a partir de un modelo
- Crear un agente con una indicación definida
- Tener una conversación multiturno con el agente
Prerrequisitos
- Un modelo implementado en Microsoft Foundry. Si no tiene un modelo, complete primero inicio rápido: Configuración de recursos de Microsoft Foundry.
- Los entornos de ejecución de lenguaje necesarios, las herramientas globales y las extensiones de Visual Studio Code tal y como se describe en Prepare el entorno de desarrollo.
Establecimiento de variables de entorno y obtención del código
Almacene el punto de conexión del proyecto como una variable de entorno. Establezca también estos valores para usarlos en los scripts.
- 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
-
C#
-
TypeScript
-
Java
-
REST API
-
Portal de la Fundición
Siga estos pasos a continuación o obtenga el código:
Inicie sesión usando el comando az login de la CLI para autenticarse antes de ejecutar los scripts de Python.
Siga estos pasos a continuación o obtenga el código:
Inicie sesión con el comando de la CLI para autenticarse antes de ejecutar los scripts de C#.
Siga estos pasos a continuación o obtenga el código:
Inicie sesión con el comando de la CLI para autenticarse antes de ejecutar los scripts de TypeScript.
Siga estos pasos a continuación o obtenga el código:
Inicie sesión usando el comando CLI az login para autenticarse antes de ejecutar sus scripts de Java.
Siga estos pasos a continuación o obtenga el código:
Inicie sesión con el comando de la CLI para autenticarse antes de ejecutar el comando siguiente.
Obtenga un token de acceso temporal. Expirará en 60-90 minutos, necesitará actualizarlo después de eso.
az account get-access-token --scope https://ai.azure.com/.default
Guarde los resultados como la variable de entorno .
No es necesario ningún código al usar el portal de Foundry.
Instalación y autenticación
Asegúrese de instalar la versión correcta de los paquetes como se muestra aquí.
-
Python
-
C#
-
TypeScript
-
Java
-
REST API
-
Portal de la Fundición
Instale la versión actual de . Esta versión usa la API Foundry projects (new) .
pip install azure-ai-projects>=2.0.0
Inicie sesión usando el comando az login de la CLI para autenticarse antes de ejecutar los scripts de Python.
Instale los paquetes:
Agregue paquetes NuGet mediante la CLI de .NET en la terminal integrada: estos paquetes utilizan la API Foundry projects (nueva).
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.AI.Projects.OpenAI --prerelease
dotnet add package Azure.Identity
Inicie sesión con el comando de la CLI para autenticarse antes de ejecutar los scripts de C#.
Instale la versión actual de . Esta versión usa la API de proyectos de Foundry (nueva).
npm install @azure/ai-projects
Inicie sesión con el comando de la CLI para autenticarse antes de ejecutar los scripts de TypeScript.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0-beta.2</version>
</dependency>
- Inicie sesión usando el comando
az login de la CLI para autenticarse antes de ejecutar sus scripts Java.
Inicie sesión con el comando de la CLI para autenticarse antes de ejecutar el comando siguiente.
Obtenga un token de acceso temporal. Expirará en 60-90 minutos, necesitará actualizarlo después de eso.
az account get-access-token --scope https://ai.azure.com/.default
Guarde los resultados como la variable de entorno .
No es necesario realizar ninguna instalación para usar el portal de Foundry.
Chatear con un modelo
La interacción con un modelo es el bloque de creación básico de las aplicaciones de inteligencia artificial. Envíe una entrada y reciba una respuesta del modelo:
-
Python
-
C#
-
TypeScript
-
Java
-
REST API
-
Portal de la Fundición
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);
}
}
Reemplace con sus valores:
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?"
}'
Una vez implementado el modelo, se le mueve automáticamente de Inicio a la sección Compilación . El nuevo modelo está seleccionado y listo para probarlo.
Comience a chatear con su modelo, por ejemplo, "Escribirme un poema sobre flores".
Después de ejecutar el código, verá una respuesta generada por el modelo en la consola (por ejemplo, un poema corto o una respuesta al mensaje). Esto confirma que el punto de conexión del proyecto, la autenticación y la implementación del modelo funcionan correctamente.
Crear un agente
Cree un agente mediante el modelo implementado.
Un agente define el comportamiento principal. Una vez creado, garantiza respuestas coherentes en las interacciones del usuario sin repetir instrucciones cada vez. Puede actualizar o eliminar agentes en cualquier momento.
-
Python
-
C#
-
TypeScript
-
Java
-
REST API
-
Portal de la Fundición
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());
}
}
Reemplace con sus valores:
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"
}
}'
Ahora cree un agente e interactúe con él.
- Aún en la sección Compilación , seleccione Agentes en el panel izquierdo.
- Seleccione Crear agente y asígnele un nombre.
La salida confirma que se creó el agente. En el caso de las pestañas del SDK, verá el nombre del agente y el identificador impresos en la consola.
Chatear con un agente
Use el agente creado anteriormente denominado "MyAgent" para interactuar mediante la formulación de una pregunta y un seguimiento relacionado. La conversación mantiene un registro de estas interacciones.
-
Python
-
C#
-
TypeScript
-
Java
-
REST API
-
Portal de la Fundición
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);
}
}
Reemplace con sus valores:
# 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?"
}'
Interactúe con el agente.
- Agregue instrucciones, como "Usted es un asistente de escritura útil".
- Comience a chatear con su agente, por ejemplo, "Escribir un poema sobre el sol".
- Siga con "¿Qué hay de un haiku?"
Verá las respuestas del agente a ambas solicitudes. La respuesta de seguimiento muestra que el agente mantiene el historial de conversaciones entre turnos.
Limpieza de recursos
Si ya no necesita ninguno de los recursos que ha creado, elimine el grupo de recursos asociado al proyecto.
- En el portal Azure, seleccione el grupo de recursos y, a continuación, seleccione Delete. Confirme que desea eliminar el grupo de recursos.
Paso siguiente
De la idea al prototipo: desarrollar y evaluar un agente empresarial