Agent Framework de Microsoft para salvar la Navidad
Introducción
Encontrar los regalos de Navidad perfectos puede resultar estresante. Entre intercambiar ideas sobre regalos, comparar precios entre tiendas y asegurarse de que todo llegue a tiempo, las compras navideñas rápidamente se vuelven abrumadoras. ¿Qué pasaría si pudiéramos delegar estas tareas a agentes de IA especializados que trabajen juntos? En esta publicación, exploraremos cómo usar Agent Framework de Microsoft para crear un sistema de múltiples agentes donde cada agente se especializa en una tarea específica, desde generar ideas para regalos hasta comparar precios, todo coordinado a través de flujos de trabajo.
Calendario tecnológico festivo 2025

Este proyecto es parte de mi sesión en el Festive Tech Calendar 2025, un increíble evento comunitario que celebra la tecnología durante la temporada navideña. Puede encontrar más información sobre el evento en Sessionize.
¿Qué es el marco de agentes de Microsoft?
Agent Framework es la solución de Microsoft para crear, orquestar e implementar agentes de IA y sistemas multiagente. Proporciona una base flexible para crear agentes que puedan trabajar de forma secuencial, simultánea o mediante patrones de transferencia. El marco es compatible con los modelos OpenAI, Azure OpenAI y Microsoft Foundry, lo que lo hace increíblemente versátil.
Las características clave incluyen:
- Orquestación multiagente: chat grupal, patrones secuenciales, simultáneos y de transferencia
- Ecosistema de complementos: Ampliación con funciones nativas, OpenAPI y protocolo de contexto modelo (MCP)
- Soporte de flujo de trabajo: cree canales de agentes complejos con ejecutores y bordes
Requisitos previos
Antes de profundizar en el código, asegúrese de tener:
- .NET 9
- Acceso a Azure OpenAI (o clave API de OpenAI)
- Visual Studio o Código de Visual Studio
Instale los paquetes necesarios (tenga en cuenta que el indicador --prerelease es obligatorio durante la vista previa):
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
dotnet add package Microsoft.Agents.AI.Workflows --prerelease
dotnet add package Azure.AI.OpenAI
dotnet add package Azure.Identity
dotnet add package Azure.AI.Agents.Persistent --prerelease
Los agentes de compras de regalos
Nuestro buscador de regalos de Navidad estará formado por tres agentes especializados que trabajarán juntos:
- Agente de ideas de regalos: genera sugerencias de regalos creativas basadas en el perfil del destinatario.
- Agente de comparación de precios: encuentra los mejores precios en diferentes tiendas
- Agente de resumen: compila las recomendaciones finales.
Los modelos
Comencemos definiendo nuestros modelos de datos que fluirán a través del canal del agente:
public class GiftRecipient
{
public string Name { get; set; } = string.Empty;
public int Age { get; set; }
public List<string> Interests { get; set; } = [];
public decimal Budget { get; set; }
}
public class GiftIdea
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string Category { get; set; } = string.Empty;
public decimal EstimatedPrice { get; set; }
}
public class PriceResult
{
public string GiftName { get; set; } = string.Empty;
public string Store { get; set; } = string.Empty;
public decimal Price { get; set; }
public string Url { get; set; } = string.Empty;
}
public class GiftRecommendation
{
public GiftIdea Gift { get; set; } = new();
public List<PriceResult> Prices { get; set; } = [];
public PriceResult? BestDeal { get; set; }
}
Construyendo los agentes
La belleza de Agent Framework es lo fácil que es crear agentes especializados. Cada agente es simplemente un ChatClientAgent con un mensaje de sistema específico que define su experiencia.
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
public static class ChristmasAgentFactory
{
public static AIAgent CreateGiftIdeaAgent(IChatClient chatClient)
{
return new ChatClientAgent(
chatClient,
@"You are a creative Christmas gift advisor. When given information about a person
(age, interests, budget), you suggest thoughtful and personalized gift ideas.
For each suggestion, provide:
- Gift name
- Brief description of why it's a good fit
- Category (Electronics, Books, Fashion, Home, Experience, etc.)
- Estimated price range
Always suggest 3-5 gift options within the specified budget.
Format your response as a structured list.");
}
public static AIAgent CreatePriceComparisonAgent(IChatClient chatClient)
{
return new ChatClientAgent(
chatClient,
@"You are a price comparison specialist. Given a list of gift ideas,
you research and compare prices from different online retailers.
For each gift, provide:
- Store name (Amazon, Best Buy, Target, Walmart, etc.)
- Current price
- Any available discounts or deals
Always highlight the best deal for each item.
Consider shipping costs and delivery times for Christmas.");
}
public static AIAgent CreateSummaryAgent(IChatClient chatClient)
{
return new ChatClientAgent(
chatClient,
@"You are a gift recommendation summarizer. Take the gift ideas and price
comparisons and create a final recommendation report.
Your summary should:
- Rank gifts by value (quality vs price)
- Highlight the top pick with reasoning
- Include total cost estimate
- Add any tips for holiday shopping
Make the summary cheerful and festive!");
}
}
Creando el flujo de trabajo
Ahora viene la parte divertida: conectar a nuestros agentes en un flujo de trabajo secuencial. Agent Framework proporciona WorkflowBuilder y AgentWorkflowBuilder para componer agentes en diferentes patrones.
public static class ChristmasGiftWorkflow
{
public static async Task RunAsync()
{
// Set up the Azure OpenAI client
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME")
?? "gpt-4o-mini";
var chatClient = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsIChatClient();
// Create our specialized agents
AIAgent giftIdeaAgent = ChristmasAgentFactory.CreateGiftIdeaAgent(chatClient);
AIAgent priceAgent = ChristmasAgentFactory.CreatePriceComparisonAgent(chatClient);
AIAgent summaryAgent = ChristmasAgentFactory.CreateSummaryAgent(chatClient);
// Build a sequential workflow: Ideas -> Prices -> Summary
var workflow = AgentWorkflowBuilder.BuildSequential(
"ChristmasGiftFinder",
[giftIdeaAgent, priceAgent, summaryAgent]);
// Define our gift recipient
var recipient = new GiftRecipient
{
Name = "Mom",
Age = 55,
Interests = ["gardening", "cooking", "reading", "yoga"],
Budget = 100
};
var prompt = $@"Find Christmas gifts for {recipient.Name},
age {recipient.Age}, who enjoys {string.Join(", ", recipient.Interests)}.
Budget: ${recipient.Budget}";
// Execute the workflow with streaming
await using StreamingRun run = await InProcessExecution.StreamAsync(
workflow,
new ChatMessage(ChatRole.User, prompt));
// Send the turn token to start processing
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
// Watch for workflow events
await foreach (WorkflowEvent evt in run.WatchStreamAsync())
{
if (evt is AgentRunUpdateEvent agentUpdate)
{
Console.Write(agentUpdate.Data);
}
else if (evt is WorkflowOutputEvent outputEvent)
{
Console.WriteLine("\n🎄 Final Recommendations:");
Console.WriteLine(outputEvent.Data);
}
}
}
}
Ejecutando agentes simultáneamente
¿Qué pasa si queremos buscar regalos para varias personas a la vez? Agent Framework admite la ejecución simultánea, lo cual es perfecto para este escenario:
public static async Task FindGiftsForEveryoneAsync(IChatClient chatClient, List<GiftRecipient> recipients)
{
// Create an agent for each recipient
var agents = recipients.Select(r => new ChatClientAgent(
chatClient,
$@"Find the perfect Christmas gift for {r.Name} (age {r.Age}),
who loves {string.Join(", ", r.Interests)}. Budget: ${r.Budget}.
Provide one well-researched recommendation with price."
)).ToList();
// Build a concurrent workflow - all agents run in parallel
var workflow = AgentWorkflowBuilder.BuildConcurrent(
"FamilyGiftFinder",
agents);
await using StreamingRun run = await InProcessExecution.StreamAsync(
workflow,
new ChatMessage(ChatRole.User, "Find gifts now!"));
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
await foreach (WorkflowEvent evt in run.WatchStreamAsync())
{
if (evt is WorkflowOutputEvent output)
{
Console.WriteLine("🎁 All gift recommendations ready!");
Console.WriteLine(output.Data);
}
}
}
Ejecutores personalizados para mayor controlPara escenarios más complejos, puede crear ejecutores personalizados que le brinden un control detallado sobre el flujo de trabajo:
public sealed class GiftValidatorExecutor : Executor<List<ChatMessage>, List<ChatMessage>>
{
public GiftValidatorExecutor() : base("GiftValidator") { }
public override async ValueTask<List<ChatMessage>> HandleAsync(
List<ChatMessage> messages,
IWorkflowContext context,
CancellationToken cancellationToken = default)
{
var lastMessage = messages.LastOrDefault()?.Text ?? "";
// Validate that suggestions are within budget
if (lastMessage.Contains("over budget", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("⚠️ Some suggestions exceeded budget, filtering...");
// Add validation logic here
}
Console.WriteLine("✅ Gift suggestions validated!");
return messages;
}
}
Luego puede insertar este ejecutor en su flujo de trabajo:
var validator = new GiftValidatorExecutor();
var workflow = new WorkflowBuilder(giftIdeaAgent)
.AddEdge(giftIdeaAgent, validator)
.AddEdge(validator, priceAgent)
.AddEdge(priceAgent, summaryAgent)
.WithOutputFrom(summaryAgent)
.Build();
Agregar búsqueda web real con Bing Grounding
Hasta ahora, nuestros agentes generan respuestas basadas en el conocimiento del modelo de IA. Pero, ¿qué pasa si queremos buscar en la web los precios y la disponibilidad reales de los productos? Aquí es donde entra en juego Grounding with Bing Search. Es una herramienta disponible en Microsoft Foundry (anteriormente Azure AI Foundry) que permite a sus agentes incorporar datos web públicos en tiempo real al generar respuestas.
Primero, deberá crear un recurso Grounding with Bing Search en el Portal Azure. Asegúrese de crearlo en el mismo grupo de recursos que su proyecto de IA.
Configuración de conexión a tierra con Bing Search
Lo bueno de Grounding with Bing Search es que se integra directamente con los agentes de Azure AI. El agente decide cuándo utilizar la herramienta de búsqueda en función de la consulta del usuario, busca en la web y utiliza los resultados para generar una respuesta fundamentada.
using Azure.AI.Agents.Persistent;
using Azure.Identity;
public static class BingGroundingSetup
{
public static async Task<PersistentAgent> CreateAgentWithBingGroundingAsync(
string projectEndpoint,
string modelDeploymentName,
string bingConnectionId)
{
// Create the Persistent Agents client
var agentClient = new PersistentAgentsClient(projectEndpoint, new DefaultAzureCredential());
// Configure the Bing Grounding tool
var bingGroundingTool = new BingGroundingToolDefinition(
new BingGroundingSearchToolParameters(
[new BingGroundingSearchConfiguration(bingConnectionId)]
)
);
// Create the agent with Bing Grounding enabled
var agent = await agentClient.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "ChristmasPriceHunter",
instructions: @"You are a Christmas gift price comparison specialist.
When given gift ideas, use Bing to search for:
- Current prices at major retailers (Amazon, Best Buy, Target, Walmart)
- Available discounts and holiday deals
- Shipping times to ensure delivery before Christmas
Always provide URLs to the products you find.
Highlight the best deals and recommend where to buy.",
tools: [bingGroundingTool]
);
return agent;
}
}
Creando un agente de comparación de precios con búsqueda real
Ahora creemos un agente de comparación de precios completo que busque en la web información real del producto:
using Azure.AI.Agents.Persistent;
using Azure.Identity;
public class ChristmasPriceAgent
{
private readonly PersistentAgentsClient _client;
private readonly string _modelDeployment;
private readonly string _bingConnectionId;
public ChristmasPriceAgent(string projectEndpoint, string modelDeployment, string bingConnectionId)
{
_client = new PersistentAgentsClient(projectEndpoint, new DefaultAzureCredential());
_modelDeployment = modelDeployment;
_bingConnectionId = bingConnectionId;
}
public async Task<string> FindGiftPricesAsync(string giftIdeas)
{
// Create agent with Bing Grounding
var bingTool = new BingGroundingToolDefinition(
new BingGroundingSearchToolParameters(
[new BingGroundingSearchConfiguration(_bingConnectionId)]
)
);
var agent = await _client.Administration.CreateAgentAsync(
model: _modelDeployment,
name: "PriceHunter",
instructions: @"Search the web for current prices on the given gift ideas.
For each gift, find prices from at least 2-3 different stores.
Include direct links to the products.
Note any Christmas sales or discounts available.",
tools: [bingTool]
);
try
{
// Create a thread for the conversation
var thread = await _client.Threads.CreateThreadAsync();
// Add the gift ideas as a message
await _client.Messages.CreateMessageAsync(
thread.Id,
MessageRole.User,
$"Find current prices for these gift ideas: {giftIdeas}"
);
// Run the agent
var run = await _client.Runs.CreateRunAsync(thread.Id, agent.Id);
// Wait for completion
do
{
await Task.Delay(500);
run = await _client.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
// Get the response
var messages = _client.Messages.GetMessages(thread.Id);
var response = messages
.Where(m => m.Role == MessageRole.Agent)
.SelectMany(m => m.ContentItems)
.OfType<MessageTextContent>()
.FirstOrDefault();
// Clean up
await _client.Threads.DeleteThreadAsync(thread.Id);
return response?.Text ?? "No results found.";
}
finally
{
// Clean up the agent
await _client.Administration.DeleteAgentAsync(agent.Id);
}
}
}
Integración de Bing Grounding en el flujo de trabajo
A continuación se explica cómo utilizar el agente de precios de Bing en un flujo de trabajo completo de búsqueda de regalos:
public static async Task RunWithBingGroundingAsync()
{
var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT")!;
var modelDeployment = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") ?? "gpt-4o";
var bingConnectionId = Environment.GetEnvironmentVariable("BING_CONNECTION_ID")!;
// Connection ID format: /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}/connections/{connection}
Console.WriteLine("🔍 Searching the web for real prices with Bing Grounding...\n");
var priceAgent = new ChristmasPriceAgent(projectEndpoint, modelDeployment, bingConnectionId);
// First, generate gift ideas (could come from another agent)
var giftIdeas = "1. Milwaukee cordless drill set, 2. Weber portable grill, 3. Carhartt beanie";
// Search for real prices
var priceResults = await priceAgent.FindGiftPricesAsync(giftIdeas);
Console.WriteLine("📊 Price Comparison Results:");
Console.WriteLine(priceResults);
Console.WriteLine("\n🎁 Happy Shopping! 🎁");
}
Procesamiento de citas a partir de resultados de Bing
Un aspecto importante de Grounding with Bing Search es que las respuestas incluyen citas con enlaces a los sitios web de origen. A continuación se explica cómo extraerlos y mostrarlos:
public static void ProcessBingGroundingResponse(IEnumerable<PersistentThreadMessage> messages)
{
foreach (var message in messages.Where(m => m.Role == MessageRole.Agent))
{
foreach (var content in message.ContentItems)
{
if (content is MessageTextContent textContent)
{
var response = textContent.Text;
// Process URL citations
if (textContent.Annotations != null)
{
foreach (var annotation in textContent.Annotations)
{
if (annotation is MessageTextUriCitationAnnotation uriAnnotation)
{
// Replace citation placeholder with markdown link
response = response.Replace(
uriAnnotation.Text,
$" [{uriAnnotation.UriCitation.Title}]({uriAnnotation.UriCitation.Uri})"
);
}
}
}
Console.WriteLine(response);
}
}
}
}
Ahora, cuando se ejecuta el agente de comparación de precios, utiliza Conexión a tierra con Bing Search para encontrar listados de productos reales, precios actuales y ofertas disponibles en la web en vivo. El agente decide automáticamente cuándo buscar en función de la consulta y devuelve respuestas fundamentadas con las citas adecuadas.
El programa completo
Así es como todo se combina en Program.cs:
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
Console.WriteLine("🎄 Christmas Gift Finder - Powered by AI Agents 🎄\n");
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!;
var deployment = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
var chatClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
.GetChatClient(deployment)
.AsIChatClient();
// Create the agent team
var ideaAgent = ChristmasAgentFactory.CreateGiftIdeaAgent(chatClient);
var priceAgent = ChristmasAgentFactory.CreatePriceComparisonAgent(chatClient);
var summaryAgent = ChristmasAgentFactory.CreateSummaryAgent(chatClient);
// Build the workflow
var workflow = AgentWorkflowBuilder.BuildSequential(
"ChristmasGiftWorkflow",
[ideaAgent, priceAgent, summaryAgent]);
Console.Write("Who are you shopping for? ");
var recipientName = Console.ReadLine() ?? "Someone special";
Console.Write("What are their interests? ");
var interests = Console.ReadLine() ?? "general";
Console.Write("What's your budget? $");
var budget = Console.ReadLine() ?? "50";
var prompt = $"Find Christmas gifts for {recipientName} who enjoys {interests}. Budget: ${budget}";
Console.WriteLine("\n🔍 Searching for the perfect gifts...\n");
await using var run = await InProcessExecution.StreamAsync(
workflow,
new ChatMessage(ChatRole.User, prompt));
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
await foreach (var evt in run.WatchStreamAsync())
{
switch (evt)
{
case AgentRunUpdateEvent update:
Console.Write(update.Update.Text);
break;
case WorkflowOutputEvent output:
Console.WriteLine("\n\n🎁 Happy Shopping! 🎁");
break;
}
}
Conclusión
Agent Framework de Microsoft hace que sea sorprendentemente fácil crear sistemas multiagente donde cada agente se especializa en una tarea específica. Al coordinar a estos agentes a través de flujos de trabajo, podemos abordar problemas complejos como las compras navideñas de forma estructurada y eficiente.
Lo que hace que esto sea aún más poderoso es la capacidad de agregar capacidades del mundo real a través de herramientas. Al integrar Grounding con Bing Search de Microsoft Foundry, nuestro agente de comparación de precios puede buscar en la web precios, ofertas y disponibilidad actuales, convirtiendo un simple chatbot de IA en un asistente de compras verdaderamente útil con las citas adecuadas.
El soporte del marco para patrones secuenciales, concurrentes y de transferencia significa que puede diseñar sistemas de agentes que satisfagan sus necesidades exactas. Ya sea encontrar regalos, planificar viajes o cualquier otra tarea de varios pasos, Agent Framework proporciona los elementos básicos para hacerlo realidad.¡Esta temporada navideña, deja que los agentes de IA se encarguen de la investigación mientras tú te concentras en envolver regalos y disfrutar del tiempo con la familia!
Código fuente
Los conceptos que se muestran en esta publicación se basan en los ejemplos oficiales de Agent Framework. Puede explorar más ejemplos en el repositorio GitHub de Microsoft Agent Framework.
¡Felices fiestas y feliz codificación! 🎄