diff --git a/docs/00-setup.md b/docs/00-setup.md index 4172d04..7934343 100644 --- a/docs/00-setup.md +++ b/docs/00-setup.md @@ -76,8 +76,8 @@ For the workshop, we strongly recommend using GitHub Codespaces to save time set You might see a message like the one below: ```text - You don't have write access to the Azure-Samples/maf-workshop-in-a-day-ko repository, so you cannot push changes to it. - To obtain write access we will point this codespace at your fork of Azure-Samples/maf-workshop-in-a-day-ko, creating that fork if it doesn't exist. + You don't have write access to the Azure-Samples/multi-agent-orchestration-workshop repository, so you cannot push changes to it. + To obtain write access we will point this codespace at your fork of Azure-Samples/multi-agent-orchestration-workshop, creating that fork if it doesn't exist. Would you like to proceed? ``` @@ -93,10 +93,10 @@ For the workshop, we strongly recommend using GitHub Codespaces to save time set This time, you should see the following four lines. ```text - origin https://github.com/{{YOUR_GITHUB_ID}}/maf-workshop-in-a-day-ko.git (fetch) - origin https://github.com/{{YOUR_GITHUB_ID}}/maf-workshop-in-a-day-ko.git (push) - upstream https://github.com/Azure-Samples/maf-workshop-in-a-day-ko (fetch) - upstream https://github.com/Azure-Samples/maf-workshop-in-a-day-ko (push) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) ``` If you don't see those four lines, delete and recreate the GitHub Codespaces instance. @@ -174,10 +174,10 @@ If you already have a GitHub Codespaces instance, skip this section and go direc You should see the following four lines. ```text - origin https://github.com/{{YOUR_GITHUB_ID}}/maf-workshop-in-a-day-ko.git (fetch) - origin https://github.com/{{YOUR_GITHUB_ID}}/maf-workshop-in-a-day-ko.git (push) - upstream https://github.com/Azure-Samples/maf-workshop-in-a-day-ko (fetch) - upstream https://github.com/Azure-Samples/maf-workshop-in-a-day-ko (push) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) ``` 1. Open the repository in VS Code. diff --git a/localization/es-es/README.md b/localization/es-es/README.md new file mode 100644 index 0000000..c4e6c53 --- /dev/null +++ b/localization/es-es/README.md @@ -0,0 +1,65 @@ +# Taller de Orquestación Multi-Agente + +Este es material de taller para construir aplicaciones multi-agente basadas en .NET utilizando [Microsoft Agent Framework](https://aka.ms/agent-framework), [Microsoft Foundry](https://aka.ms/microsoft-foundry), y [Aspire](https://aspire.dev). + +![Taller MAF + Foundry](../../images/hero.jpg) + +## ¿Para qué es este taller? + +Construir una aplicación de un solo agente es fácil. Sin embargo, hay muchos casos de uso del mundo real que requieren múltiples agentes trabajando juntos, y construir una aplicación multi-agente no es tan simple como construir una de un solo agente. [Microsoft Agent Framework](https://aka.ms/agent-framework) ofrece cinco patrones de orquestación multi-agente: + +| Patrón | Descripción | +|----------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------| +| [Secuencial](https://learn.microsoft.com/agent-framework/workflows/orchestrations/sequential?pivots=programming-language-csharp) | Los agentes se ejecutan uno tras otro en un orden definido | +| [Concurrente](https://learn.microsoft.com/agent-framework/workflows/orchestrations/concurrent?pivots=programming-language-csharp) | Los agentes se ejecutan en paralelo | +| [Handoff](https://learn.microsoft.com/agent-framework/workflows/orchestrations/handoff?pivots=programming-language-csharp) | Los agentes transfieren el control entre sí según el contexto | +| [Group Chat](https://learn.microsoft.com/agent-framework/workflows/orchestrations/group-chat?pivots=programming-language-csharp) | Los agentes colaboran en una conversación compartida | +| [Magentic](https://learn.microsoft.com/agent-framework/workflows/orchestrations/magentic?pivots=programming-language-python) | Un agente administrador coordina dinámicamente agentes especializados | + +## Características + +En este taller, construimos todos los patrones de orquestación multi-agente excepto el patrón Magentic. Una vez que complete cada patrón, tendrá la siguiente arquitectura: + +- Frontend [Blazor](https://blazor.net) para la interfaz de chat +- Backend [ASP.NET](https://asp.net) con [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) para el alojamiento de agentes +- [Aspire](https://aspire.dev) para la orquestación de aplicaciones nativas en la nube + +> [!NOTE] +> La versión .NET del SDK de Microsoft Agent Framework admitirá el patrón Magentic en una próxima versión. + +## Requisitos previos + +- [Suscripción de Azure (gratuita)](http://azure.microsoft.com/free) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) o superior +- [Visual Studio 2026](https://visualstudio.microsoft.com/downloads/) o [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) +- [Docker Desktop](https://docs.docker.com/desktop/) o equivalente +- [GitHub CLI](https://cli.github.com) +- [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) +- [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) +- [Aspire CLI](https://aspire.dev/get-started/install-cli/) + +## Sesiones del taller + +| Sesión | Documento | Ejemplo de código | +|---------------------------|-------------------------------------------------------------|----------------------------------------------------------| +| 00 Configuración | [00-setup.md](./docs/00-setup.md) | | +| 01 Patrón Secuencial | [01-sequential-pattern.md](./docs/01-sequential-pattern.md) | [01-sequential-pattern](./samples/01-sequential-pattern) | +| 02 Patrón Concurrente | [02-concurrent-pattern.md](./docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./samples/02-concurrent-pattern) | +| 03 Patrón Handoff | [03-handoff-pattern.md](./docs/03-handoff-pattern.md) | [03-handoff-pattern](./samples/03-handoff-pattern) | +| 04 Patrón Group Chat | [04-group-chat-pattern.md](./docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./samples/04-group-chat-pattern) | + +## ¡Use su idioma preferido! + +Este material de taller está disponible en los siguientes idiomas. + +[English](../../README.md) | [Español](./README.md) | [日本語](../ja-jp/README.md) | [한국어](../ko-kr/README.md) | [Português](../pt-br/README.md) | [中文(简体)](../zh-cn/README.md) + +## Recursos + +- [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Agent Framework - Workflow Orchestrations](https://learn.microsoft.com/agent-framework/workflows/orchestrations) +- [Microsoft Foundry](https://aka.ms/microsoft-foundry) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) +- [Model Context Protocol (MCP)](https://modelcontextprotocol.io) +- [Aspire](https://aspire.dev) diff --git a/localization/es-es/docs/00-setup.md b/localization/es-es/docs/00-setup.md new file mode 100644 index 0000000..76f2613 --- /dev/null +++ b/localization/es-es/docs/00-setup.md @@ -0,0 +1,215 @@ +# 00 Configuración + +En esta sesión, configuraremos un entorno de desarrollo ya sea en su máquina o en GitHub Codespaces. + +## Requisitos previos + +- Navegador web: [Microsoft Edge](https://microsoft.com/edge) o [Google Chrome](http://chrome.google.com) +- [Suscripción de Azure](https://azure.microsoft.com/free) + +## Configuración en GitHub Codespaces + +Para el taller, recomendamos encarecidamente usar GitHub Codespaces para ahorrar tiempo configurando su entorno de desarrollo. Si prefiere configurar el entorno de desarrollo en su máquina local, omita esta sección y vaya a la sección [Configuración en VS Code](#configuración-en-vs-code). + +1. Haga clic en el botón de abajo para crear una nueva instancia de GitHub Codespaces. + + [![Crear una nueva instancia de GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/multi-agent-orchestration-workshop) + +1. Una vez creada, ejecute los siguientes comandos para verificar que las herramientas necesarias estén correctamente instaladas. + + ```bash + # .NET SDK + dotnet --list-sdks + + # node.js + node --version + npm --version + + # PowerShell + pwsh --version + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +1. Verifique su estado de inicio de sesión en GitHub. + + ```bash + gh auth status + ``` + +1. Obtenga los detalles del repositorio remoto. + + ```bash + git remote -v + ``` + + Debería ver lo siguiente. + + ```text + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (push) + ``` + + Si no ve esas dos líneas, elimine la instancia actual de GitHub Codespaces y créela nuevamente. + +1. Dado que la instancia de GitHub Codespaces NO está bajo su cuenta, haga un fork del repositorio para transferir la propiedad usando los siguientes comandos. + + ```bash + git remote -v > remote.txt + git add . && git commit -m "Add remote.txt for forking" + ``` + + Podría ver un mensaje como el siguiente: + + ```text + You don't have write access to the Azure-Samples/multi-agent-orchestration-workshop repository, so you cannot push changes to it. + To obtain write access we will point this codespace at your fork of Azure-Samples/multi-agent-orchestration-workshop, creating that fork if it doesn't exist. + + Would you like to proceed? + ``` + + Ingrese `y` para continuar. Automáticamente se hará un fork del repositorio bajo su cuenta. + +1. Verifique el estado del repositorio remoto. + + ```bash + git remote -v + ``` + + Esta vez, debería ver las siguientes cuatro líneas. + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + + Si no ve esas cuatro líneas, elimine y vuelva a crear la instancia de GitHub Codespaces. + +## Configuración en VS Code + +Si ya tiene una instancia de GitHub Codespaces, omita esta sección y vaya directamente a la sección [Iniciar sesión en Azure](#iniciar-sesión-en-azure). + +1. Instale las siguientes herramientas en su máquina. + + - [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) + - [Docker Desktop](https://docs.docker.com/desktop/) o equivalente + - [GitHub CLI](https://cli.github.com) + - [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) + - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) + - [Aspire CLI](https://aspire.dev/get-started/install-cli/) + + Luego, ejecute los siguientes comandos para verificar que estén correctamente instalados. + + ```bash + # .NET SDK + dotnet --list-sdks + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +### Iniciar sesión en GitHub + +1. Inicie sesión en GitHub. + + ```bash + gh auth login + ``` + + Una vez que haya iniciado sesión, ejecute el siguiente comando para verificar el estado de inicio de sesión. + + ```bash + gh auth status + ``` + +### Clonar el proyecto + +1. Haga un fork de este repositorio en su máquina local. + + ```bash + gh repo fork Azure-Samples/multi-agent-orchestration-workshop --clone + ``` + +1. Navegue al directorio clonado. + + ```bash + cd multi-agent-orchestration-workshop + ``` + +1. Verifique el estado del repositorio remoto. + + ```bash + git remote -v + ``` + + Debería ver las siguientes cuatro líneas. + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + +1. Abra el repositorio en VS Code. + + ```bash + code . + ``` + +## Iniciar sesión en Azure + +1. Inicie sesión en Azure. + + ```bash + # Azure Developer CLI + azd auth login + + # Azure CLI + az login + ``` + + Una vez que haya iniciado sesión, ejecute el siguiente comando para verificar el estado de inicio de sesión. + + ```bash + # Azure Develper CLI + azd auth login --check-status + + # Azure Login + az account show + ``` + +--- + +¡Felicitaciones! 🎉 Acaba de completar la configuración del entorno de desarrollo. ¡Continuemos! + +👈 [README](../README.md) | [01: Patrón Secuencial](./01-sequential-pattern.md) 👉 diff --git a/localization/es-es/docs/01-sequential-pattern.md b/localization/es-es/docs/01-sequential-pattern.md new file mode 100644 index 0000000..0e53fb4 --- /dev/null +++ b/localization/es-es/docs/01-sequential-pattern.md @@ -0,0 +1,415 @@ +# 01 Patrón Secuencial + +En un patrón secuencial, los agentes trabajan uno tras otro en un pipeline definido, donde la salida de cada agente alimenta al siguiente. Este enfoque funciona bien para tareas que siguen una progresión natural, como flujos de trabajo de creación de contenido, transformaciones de datos por etapas o análisis paso a paso. + +## Escenario + +Está escribiendo una publicación técnica de blog con agentes: agente de investigación, agente de esquema, agente de redacción y agente de edición. + +
+ Arquitectura - Patrón Secuencial +
+ +## Obtener la raíz del repositorio + +1. Obtenga la variable `$REPOSITORY_ROOT` primero. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar el proyecto inicial + +1. Si ya tiene el directorio `workshop`, renómbrelo o elimínelo primero. + +1. Ejecute el script de configuración para copiar el proyecto inicial al directorio `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 01-sequential-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 01-sequential-pattern + ``` + +## Desplegar agentes + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue al directorio `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar los agentes definidos anteriormente en Microsoft Foundry. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez que el aprovisionamiento y el despliegue hayan finalizado, ejecute el siguiente comando para confirmar que los agentes se han desplegado correctamente. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Debería ver los cuatro nombres de agentes. + + ```text + editor-agent + writer-agent + outliner-agent + research-agent + ``` + +1. Navegue de vuelta al directorio del taller. + + ```bash + popd + ``` + +## Configurar la orquestación de Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique que toda la información necesaria de los agentes haya sido registrada. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Debería ver los valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` y `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, busque el comentario `// Add resource for Microsoft Foundry` y agregue el código justo debajo. Esto agrega los detalles de conexión del proyecto de Microsoft Foundry. + + ```csharp + // Add resource for Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Analicemos el código. + + - `builder.AddFoundry("foundry")`: Esto agrega los detalles de conexión de Microsoft Foundry a través de un recurso personalizado, `FoundryResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add resource for agents on Microsoft Foundry` y agregue el código justo debajo. Esto expone la lista de detalles de los agentes a la aplicación que los referencia. + + ```csharp + // Add resource for agents on Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Analicemos el código. + + - `builder.AddAgents("agents")`: Esto agrega la lista de detalles de los agentes a través de un recurso personalizado, `AgentResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add backend agent service` y agregue el código justo debajo. Esto define el servicio de agente del backend que referencia el recurso `foundry` — todos los detalles de conexión de Microsoft Foundry se pasan a la aplicación del servicio de agente del backend. + + ```csharp + // Add backend agent service + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Analicemos el código. + + - `builder.AddProject("agent")`: Esto agrega la aplicación del servicio de agente del backend como un proyecto .NET. + - `.WithReference(foundry)`: Esto referencia el recurso foundry creado anteriormente, que pasa los detalles de conexión de Microsoft Foundry a la aplicación del servicio de agente del backend. + +1. En el mismo archivo, busque el comentario `// Add frontend web UI` y agregue el código justo debajo. Esto define la interfaz web del frontend que referencia tanto los recursos `agents` como `agent` — los detalles de los agentes y los detalles de conexión del backend se pasan a la aplicación de la interfaz web del frontend. + + ```csharp + // Add frontend web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Analicemos el código. + + - `builder.AddProject("webui")`: Esto agrega la aplicación de la interfaz web del frontend como un proyecto .NET. + - `.WithExternalHttpEndpoints()`: Esto expone esta aplicación de interfaz web del frontend a Internet, haciéndola accesible públicamente. + - `.WithReference(agents)`: Esto referencia el recurso de agentes creado anteriormente, que pasa la lista de agentes a la aplicación de la interfaz web del frontend. + - `.WithReference(agent)`: Esto referencia la aplicación del servicio de agente del backend, que pasa los detalles de conexión a la aplicación de la interfaz web del frontend. + +## Implementar el patrón secuencial en el servicio de agente del backend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, busque el comentario `// Create AIProjectClient instance with EntraID authentication` y agregue el código justo debajo. Esto se conecta al proyecto de Microsoft Foundry. + + ```csharp + // Create AIProjectClient instance with EntraID authentication + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + Analicemos el código. + + - `new DefaultAzureCredential(...)`: Esto inicia sesión en Azure sin una clave API. Utiliza los datos de inicio de sesión de Azure CLI o Azure Developer CLI en su máquina local, y Managed Identity cuando la aplicación se despliega en Azure. + - `new AIProjectClient(endpoint, credential)`: Esto se conecta a la instancia del proyecto de Microsoft Foundry usando el endpoint y los datos de inicio de sesión. + +1. En el mismo archivo, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto obtiene los detalles de los agentes del proyecto de Microsoft Foundry y los registra en el contenedor IoC como servicios singleton. + + ```csharp + // Register all agents passed from Aspire + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Analicemos el código. + + - Ya conocemos la lista de agentes pero solo sabemos sus nombres. Por lo tanto, el código ejecuta el bucle `foreach` para cada agente. + - `new AgentReference(name, version)`: Usando la información de cada agente, esto crea una instancia de referencia. + - `projectClient.AsAIAgent(reference, factory)`: Esto se conecta al agente real usando los detalles de referencia. + - `builder.Services.AddKeyedSingleton(name, agent)`: Esto registra la instancia del agente como un servicio singleton. + + > **NOTA**: Puede notar la clase `AgentRecordShimChatClient`. Es una solución temporal para una incompatibilidad de versiones entre Microsoft Agent Framework y el SDK de Microsoft Foundry, que será eliminada pronto. + +1. En el mismo archivo, busque el comentario `// Build a sequential workflow pattern with the agents registered` y agregue el código justo debajo. + + ```csharp + // Build a sequential workflow pattern with the agents registered + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [.. agents.Select(a => sp.GetRequiredKeyedService(a.Name))] + )).AddAsAIAgent("publisher"); + ``` + + Analicemos el código. + + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: Esto agrega el flujo de trabajo multi-agente como otra instancia de agente llamada `publisher` y lo registra como singleton. + - `AgentWorkflowBuilder.BuildSequential(...)`: Este es el constructor del flujo de trabajo secuencial que usa el mismo nombre, `publisher`. + + Note que agrega múltiples agentes de los servicios previamente registrados en el orden declarado por el arreglo `agents`. + +1. En el mismo archivo, busque el comentario `// Map AGUI to the publisher workflow agent` y agregue el código justo debajo. El flujo de trabajo se expone como un endpoint API en `ag-ui` para que la interfaz web del frontend pueda comunicarse con esta aplicación del servicio de agente del backend. + + ```csharp + // Map AGUI to the publisher workflow agent + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## Implementar el patrón secuencial en la interfaz web del frontend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto registra todos los detalles de los agentes para que la interfaz web sepa qué agente está respondiendo. + + ```csharp + // Register all agents passed from Aspire + builder.Services.AddSingleton(agents); + ``` + +1. En el mismo archivo, busque el comentario `// Register the backend agent service as an HTTP client` y agregue el código justo debajo. Aspire ya proporciona a la aplicación de la interfaz web del frontend los detalles de conexión del servicio de agente del backend. + + ```csharp + // Register the backend agent service as an HTTP client + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. En el mismo archivo, busque el comentario `// Register AGUI client` y agregue el código justo debajo. Usando este cliente AGUI, la aplicación de la interfaz web del frontend se comunica con la aplicación del servicio de agente del backend a través del endpoint `ag-ui`. + + ```csharp + // Register AGUI client + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Ejecutar Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Asegúrese de haber iniciado sesión en Azure usando tanto Azure CLI como Azure Developer CLI. Si no está seguro, siga [este paso](./00-setup.md#iniciar-sesión-en-azure) nuevamente. + +1. Ejecute el siguiente comando para iniciar todas las aplicaciones a través de Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. El panel de Aspire se abre automáticamente. + + ![Panel de Aspire](../../../docs/images/step-01-image-01.png) + + Haga clic en la aplicación del servicio de agente del backend. + +1. Cuando se abra la página Dev UI, cambie el agente a `publisher` y haga clic en el botón "Configure & Run". + + ![Microsoft Agent Framework Dev UI - Patrón secuencial](../../../docs/images/step-01-image-02.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Dev UI - Enviar solicitud](../../../docs/images/step-01-image-03.png) + + Observe el resultado y cómo el flujo de trabajo progresa en el lado izquierdo de la pantalla. + + ![Microsoft Agent Framework Dev UI - Ejecución del flujo de trabajo](../../../docs/images/step-01-image-04.png) + +1. Regrese al panel de Aspire y haga clic en la aplicación de la interfaz web. + + ![Panel de Aspire](../../../docs/images/step-01-image-05.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Chat UI - Enviar solicitud](../../../docs/images/step-01-image-06.png) + + Observe el resultado. + +1. Presione `Ctrl`+`C` para terminar todas las aplicaciones en ejecución. + +## Desplegar en Azure + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar tanto la interfaz web del frontend como las aplicaciones del servicio de agente del backend en Azure. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez completado, verá la URL de la aplicación de la interfaz web en la pantalla del terminal. Ábrala en su navegador web y envíe una solicitud. + + ![Microsoft Agent Framework en Azure Container Apps - Enviar solicitud](../../../docs/images/step-01-image-07.png) + + Observe el resultado. + +1. Una vez que todo esté listo, elimine todas las aplicaciones y agentes de Azure. + + ```bash + # Eliminar tanto la interfaz web como las aplicaciones del servicio de agente. + azd down --purge --force + + # Eliminar todos los agentes y el recurso de Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +¡Felicitaciones! 🎉 Acaba de completar el primer escenario de orquestación multi-agente: el patrón secuencial. ¡Continuemos! + +👈 [00: Configuración](./00-setup.md) | [02: Patrón Concurrente](./02-concurrent-pattern.md) 👉 diff --git a/localization/es-es/docs/02-concurrent-pattern.md b/localization/es-es/docs/02-concurrent-pattern.md new file mode 100644 index 0000000..3c10439 --- /dev/null +++ b/localization/es-es/docs/02-concurrent-pattern.md @@ -0,0 +1,446 @@ +# 02 Patrón Concurrente + +En un patrón concurrente, múltiples agentes analizan la misma entrada simultáneamente, cada uno aportando su propia experiencia. Una vez que todos los agentes completan su tarea, sus salidas se combinan en un resultado unificado. Esto es ideal para tareas que se benefician de múltiples puntos de vista trabajando al mismo tiempo, como análisis multi-perspectiva, evaluación en conjunto o toma de decisiones colaborativa. + +## Escenario + +Usted trabaja para una firma de capital de riesgo y está analizando una presentación de startup con agentes: agente de análisis de mercado, agente de viabilidad tecnológica, agente de modelo financiero, agente de evaluación de riesgos y agente agregador. + +
+ Arquitectura - Patrón Concurrente +
+ +## Obtener la raíz del repositorio + +1. Obtenga la variable `$REPOSITORY_ROOT` primero. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar el proyecto inicial + +1. Si ya tiene el directorio `workshop`, renómbrelo o elimínelo primero. + +1. Ejecute el script de configuración para copiar el proyecto inicial al directorio `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 02-concurrent-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 02-concurrent-pattern + ``` + +## Desplegar agentes + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue al directorio `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar los agentes definidos anteriormente en Microsoft Foundry. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez que el aprovisionamiento y el despliegue hayan finalizado, ejecute el siguiente comando para confirmar que los agentes se han desplegado correctamente. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Debería ver los cinco nombres de agentes. + + ```text + aggregator-agent + risk-assessment-agent + financial-model-agent + technology-feasibility-agent + market-analysis-agent + ``` + +1. Navegue de vuelta al directorio del taller. + + ```bash + popd + ``` + +## Configurar la orquestación de Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique que toda la información necesaria de los agentes haya sido registrada. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Debería ver los valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` y `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, busque el comentario `// Add resource for Microsoft Foundry` y agregue el código justo debajo. Esto agrega los detalles de conexión del proyecto de Microsoft Foundry. + + ```csharp + // Add resource for Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Analicemos el código. + + - `builder.AddFoundry("foundry")`: Esto agrega los detalles de conexión de Microsoft Foundry a través de un recurso personalizado, `FoundryResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add resource for agents on Microsoft Foundry` y agregue el código justo debajo. Esto expone la lista de detalles de los agentes a la aplicación que los referencia. + + ```csharp + // Add resource for agents on Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Analicemos el código. + + - `builder.AddAgents("agents")`: Esto agrega la lista de detalles de los agentes a través de un recurso personalizado, `AgentResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add backend agent service` y agregue el código justo debajo. Esto define el servicio de agente del backend que referencia el recurso `foundry` — todos los detalles de conexión de Microsoft Foundry se pasan a la aplicación del servicio de agente del backend. + + ```csharp + // Add backend agent service + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Analicemos el código. + + - `builder.AddProject("agent")`: Esto agrega la aplicación del servicio de agente del backend como un proyecto .NET. + - `.WithReference(foundry)`: Esto referencia el recurso foundry creado anteriormente, que pasa los detalles de conexión de Microsoft Foundry a la aplicación del servicio de agente del backend. + +1. En el mismo archivo, busque el comentario `// Add frontend web UI` y agregue el código justo debajo. Esto define la interfaz web del frontend que referencia tanto los recursos `agents` como `agent` — los detalles de los agentes y los detalles de conexión del backend se pasan a la aplicación de la interfaz web del frontend. + + ```csharp + // Add frontend web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Analicemos el código. + + - `builder.AddProject("webui")`: Esto agrega la aplicación de la interfaz web del frontend como un proyecto .NET. + - `.WithExternalHttpEndpoints()`: Esto expone esta aplicación de interfaz web del frontend a Internet, haciéndola accesible públicamente. + - `.WithReference(agents)`: Esto referencia el recurso de agentes creado anteriormente, que pasa la lista de agentes a la aplicación de la interfaz web del frontend. + - `.WithReference(agent)`: Esto referencia la aplicación del servicio de agente del backend, que pasa los detalles de conexión a la aplicación de la interfaz web del frontend. + +## Implementar el patrón concurrente en el servicio de agente del backend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, busque el comentario `// Create AIProjectClient instance with EntraID authentication` y agregue el código justo debajo. Esto se conecta al proyecto de Microsoft Foundry. + + ```csharp + // Create AIProjectClient instance with EntraID authentication + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + Analicemos el código. + + - `new DefaultAzureCredential(...)`: Esto inicia sesión en Azure sin una clave API. Utiliza los datos de inicio de sesión de Azure CLI o Azure Developer CLI en su máquina local, y Managed Identity cuando la aplicación se despliega en Azure. + - `new AIProjectClient(endpoint, credential)`: Esto se conecta a la instancia del proyecto de Microsoft Foundry usando el endpoint y los datos de inicio de sesión. + +1. En el mismo archivo, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto obtiene los detalles de los agentes del proyecto de Microsoft Foundry y los registra en el contenedor IoC como servicios singleton. + + ```csharp + // Register all agents passed from Aspire + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Analicemos el código. + + - Ya conocemos la lista de agentes pero solo sabemos sus nombres. Por lo tanto, el código ejecuta el bucle `foreach` para cada agente. + - `new AgentReference(name, version)`: Usando la información de cada agente, esto crea una instancia de referencia. + - `projectClient.AsAIAgent(reference, factory)`: Esto se conecta al agente real usando los detalles de referencia. + - `builder.Services.AddKeyedSingleton(name, agent)`: Esto registra la instancia del agente como un servicio singleton. + + > **NOTA**: Puede notar la clase `AgentRecordShimChatClient`. Es una solución temporal para una incompatibilidad de versiones entre Microsoft Agent Framework y el SDK de Microsoft Foundry, que será eliminada pronto. + +1. En el mismo archivo, busque el comentario `// Build a concurrent workflow pattern with the agents registered` y agregue el código justo debajo. + + ```csharp + // Build a concurrent workflow pattern with the agents registered + var concurrentAgents = agents.Where(a => a.Name != "aggregator-agent"); + var aggregatorAgent = agents.SingleOrDefault(a => a.Name == "aggregator-agent"); + + builder.AddWorkflow("concurrent-analysis", (sp, key) => AgentWorkflowBuilder.BuildConcurrent( + workflowName: key, + agents: [.. concurrentAgents.Select(a => sp.GetRequiredKeyedService(a.Name))], + aggregator: null + )).AddAsAIAgent("concurrent-analysis"); + + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [ + sp.GetRequiredKeyedService("concurrent-analysis"), + sp.GetRequiredKeyedService(aggregatorAgent!.Name) + ] + )).AddAsAIAgent("publisher"); + ``` + + Analicemos el código. + + - `builder.AddWorkflow("concurrent-analysis", ...).AddAsAIAgent("concurrent-analysis")`: Esto agrega el flujo de trabajo multi-agente como otra instancia de agente llamada `concurrent-analysis` y lo registra como singleton. + - `AgentWorkflowBuilder.BuildConcurrent(...)`: Este es el constructor del flujo de trabajo concurrente que usa el mismo nombre, `concurrent-analysis`. + + Note que agrega múltiples agentes de los servicios previamente registrados declarados por el arreglo `agents`. + + También note que pasa `null` para el agregador, de modo que podamos usar el `aggregator-agent` proporcionado por Microsoft Foundry en su lugar. + - `builder.AddWorkflow("publisher, ...).AddAsAIAgent("publisher")`: Esto agrega el flujo de trabajo multi-agente como otra instancia de agente llamada `publisher` y lo registra como singleton. + - `AgentWorkflowBuilder.BuildSequential(...)`: Este es el constructor del flujo de trabajo secuencial que usa el mismo nombre, `publisher`. + + Note que agrega tanto el flujo de trabajo `concurrent-analysis` como el `aggregator-agent` para que el agente agregador resuma lo que cada agente respondió en el flujo de trabajo concurrente. + +1. En el mismo archivo, busque el comentario `// Map AGUI to the publisher workflow agent` y agregue el código justo debajo. El flujo de trabajo se expone como un endpoint API en `ag-ui` para que la interfaz web del frontend pueda comunicarse con esta aplicación del servicio de agente del backend. + + ```csharp + // Map AGUI to the publisher workflow agent + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## Implementar el patrón concurrente en la interfaz web del frontend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto registra todos los detalles de los agentes para que la interfaz web sepa qué agente está respondiendo. + + ```csharp + // Register all agents passed from Aspire + builder.Services.AddSingleton(agents); + ``` + +1. En el mismo archivo, busque el comentario `// Register the backend agent service as an HTTP client` y agregue el código justo debajo. Aspire ya proporciona a la aplicación de la interfaz web del frontend los detalles de conexión del servicio de agente del backend. + + ```csharp + // Register the backend agent service as an HTTP client + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. En el mismo archivo, busque el comentario `// Register AGUI client` y agregue el código justo debajo. Usando este cliente AGUI, la aplicación de la interfaz web del frontend se comunica con la aplicación del servicio de agente del backend a través del endpoint `ag-ui`. + + ```csharp + // Register AGUI client + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Ejecutar Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Asegúrese de haber iniciado sesión en Azure usando tanto Azure CLI como Azure Developer CLI. Si no está seguro, siga [este paso](./00-setup.md#iniciar-sesión-en-azure) nuevamente. + +1. Ejecute el siguiente comando para iniciar todas las aplicaciones a través de Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. El panel de Aspire se abre automáticamente. + + ![Panel de Aspire](../../../docs/images/step-02-image-01.png) + + Haga clic en la aplicación del servicio de agente del backend. + +1. Cuando se abra la página Dev UI, cambie el agente a `concurrent-analysis` y observe que todos los agentes se ejecutan concurrentemente. + + ![Microsoft Agent Framework Dev UI - Patrón concurrente](../../../docs/images/step-02-image-02.png) + + Luego, cambie el agente a `publisher` y observe cómo el patrón secuencial combina `concurrent-analysis` con el `aggregator-agent`. + + ![Microsoft Agent Framework Dev UI - Patrón secuencial](../../../docs/images/step-02-image-03.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Dev UI - Enviar solicitud](../../../docs/images/step-02-image-04.png) + + Observe el resultado y cómo el flujo de trabajo progresa en el lado izquierdo de la pantalla. + + ![Microsoft Agent Framework Dev UI - Ejecución del flujo de trabajo](../../../docs/images/step-02-image-05.png) + +1. Regrese al panel de Aspire y haga clic en la aplicación de la interfaz web. + + ![Panel de Aspire](../../../docs/images/step-02-image-06.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Chat UI - Enviar solicitud](../../../docs/images/step-02-image-07.png) + + Observe el resultado. + +1. Presione `Ctrl`+`C` para terminar todas las aplicaciones en ejecución. + +## Desplegar en Azure + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar tanto la interfaz web del frontend como las aplicaciones del servicio de agente del backend en Azure. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez completado, verá la URL de la aplicación de la interfaz web en la pantalla del terminal. Ábrala en su navegador web y envíe una solicitud. + + ![Microsoft Agent Framework en Azure Container Apps - Enviar solicitud](../../../docs/images/step-02-image-08.png) + + Observe el resultado. + +1. Una vez que todo esté listo, elimine todas las aplicaciones y agentes de Azure. + + ```bash + # Eliminar tanto la interfaz web como las aplicaciones del servicio de agente. + azd down --purge --force + + # Eliminar todos los agentes y el recurso de Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +¡Felicitaciones! 🎉 Acaba de completar el segundo escenario de orquestación multi-agente: el patrón concurrente. ¡Continuemos! + +👈 [01: Patrón Secuencial](./01-sequential-pattern.md) | [03: Patrón Handoff](./03-handoff-pattern.md) 👉 diff --git a/localization/es-es/docs/03-handoff-pattern.md b/localization/es-es/docs/03-handoff-pattern.md new file mode 100644 index 0000000..8c36ad5 --- /dev/null +++ b/localization/es-es/docs/03-handoff-pattern.md @@ -0,0 +1,449 @@ +# 03 Patrón Handoff + +En un patrón handoff, los agentes pasan dinámicamente el control entre sí según el contexto de la conversación. Un agente de triaje recibe la solicitud inicial y la dirige al especialista más adecuado para manejarla. Los especialistas también pueden redirigir a otros cuando el problema cruza dominios. Esto funciona bien para escenarios como soporte de TI, servicio al cliente o cualquier flujo de trabajo donde se necesita diferente experiencia en diferentes etapas. + +## Escenario + +Usted trabaja para un equipo de soporte de TI con agentes: agente de soporte general, agente especialista en redes, agente de garantía y agente de triaje. + +
+ Arquitectura - Patrón Handoff +
+ +## Obtener la raíz del repositorio + +1. Obtenga la variable `$REPOSITORY_ROOT` primero. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar el proyecto inicial + +1. Si ya tiene el directorio `workshop`, renómbrelo o elimínelo primero. + +1. Ejecute el script de configuración para copiar el proyecto inicial al directorio `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 03-handoff-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 03-handoff-pattern + ``` + +## Desplegar agentes + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue al directorio `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar los agentes definidos anteriormente en Microsoft Foundry. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez que el aprovisionamiento y el despliegue hayan finalizado, ejecute el siguiente comando para confirmar que los agentes se han desplegado correctamente. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Debería ver los cuatro nombres de agentes. + + ```text + warranty-agent + network-specialist-agent + general-support-agent + triage-agent + ``` + +1. Navegue de vuelta al directorio del taller. + + ```bash + popd + ``` + +## Configurar la orquestación de Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique que toda la información necesaria de los agentes haya sido registrada. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Debería ver los valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` y `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, busque el comentario `// Add resource for Microsoft Foundry` y agregue el código justo debajo. Esto agrega los detalles de conexión del proyecto de Microsoft Foundry. + + ```csharp + // Add resource for Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Analicemos el código. + + - `builder.AddFoundry("foundry")`: Esto agrega los detalles de conexión de Microsoft Foundry a través de un recurso personalizado, `FoundryResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add resource for agents on Microsoft Foundry` y agregue el código justo debajo. Esto expone la lista de detalles de los agentes a la aplicación que los referencia. + + ```csharp + // Add resource for agents on Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Analicemos el código. + + - `builder.AddAgents("agents")`: Esto agrega la lista de detalles de los agentes a través de un recurso personalizado, `AgentResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add backend agent service` y agregue el código justo debajo. Esto define el servicio de agente del backend que referencia el recurso `foundry` — todos los detalles de conexión de Microsoft Foundry se pasan a la aplicación del servicio de agente del backend. + + ```csharp + // Add backend agent service + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Analicemos el código. + + - `builder.AddProject("agent")`: Esto agrega la aplicación del servicio de agente del backend como un proyecto .NET. + - `.WithReference(foundry)`: Esto referencia el recurso foundry creado anteriormente, que pasa los detalles de conexión de Microsoft Foundry a la aplicación del servicio de agente del backend. + +1. En el mismo archivo, busque el comentario `// Add frontend web UI` y agregue el código justo debajo. Esto define la interfaz web del frontend que referencia tanto los recursos `agents` como `agent` — los detalles de los agentes y los detalles de conexión del backend se pasan a la aplicación de la interfaz web del frontend. + + ```csharp + // Add frontend web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Analicemos el código. + + - `builder.AddProject("webui")`: Esto agrega la aplicación de la interfaz web del frontend como un proyecto .NET. + - `.WithExternalHttpEndpoints()`: Esto expone esta aplicación de interfaz web del frontend a Internet, haciéndola accesible públicamente. + - `.WithReference(agents)`: Esto referencia el recurso de agentes creado anteriormente, que pasa la lista de agentes a la aplicación de la interfaz web del frontend. + - `.WithReference(agent)`: Esto referencia la aplicación del servicio de agente del backend, que pasa los detalles de conexión a la aplicación de la interfaz web del frontend. + +## Implementar el patrón handoff en el servicio de agente del backend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, busque el comentario `// Create AzureOpenAIClient instance with EntraID authentication` y agregue el código justo debajo. Esto se conecta al proyecto de Microsoft Foundry. + + ```csharp + // Create AzureOpenAIClient instance with EntraID authentication + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + + var url = new Uri(endpoint.GetAzureOpenAIResponsesEndpoint()); + var chatClient = new AzureOpenAIClient(url, credential) + .GetResponsesClient() + .AsIChatClient(model); + ``` + + Analicemos el código. + + - `new DefaultAzureCredential(...)`: Esto inicia sesión en Azure sin una clave API. Utiliza los datos de inicio de sesión de Azure CLI o Azure Developer CLI en su máquina local, y Managed Identity cuando la aplicación se despliega en Azure. + - `endpoint.GetAzureOpenAIResponsesEndpoint()`: Esto convierte el endpoint del proyecto de Microsoft Foundry al endpoint de Microsoft Foundry OpenAI porque el SDK de Microsoft Foundry actualmente no admite el patrón handoff. + - `new AzureOpenAIClient(url, credential)`: Esto se conecta a la instancia de Azure OpenAI usando el endpoint y los datos de inicio de sesión y lo convierte a una instancia de `IChatClient`. + +1. En el mismo archivo, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto obtiene los detalles de los agentes del proyecto de Microsoft Foundry y los registra en el contenedor IoC como servicios singleton. + + ```csharp + // Register all agents passed from Aspire + foreach (var agentSettings in agents) + { + var instruction = await File.ReadAllTextAsync( + Path.Combine(AppContext.BaseDirectory, "Prompts", $"{agentSettings.Name}.txt")); + + var agent = new ChatClientAgent( + chatClient, + instructions: instruction, + name: agentSettings.Name); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Analicemos el código. + + - Ya conocemos la lista de agentes pero solo sabemos sus nombres. Por lo tanto, el código ejecuta el bucle `foreach` para cada agente. + - `await File.ReadAllTextAsync(...)`: Esto importa el archivo de instrucciones del agente. + - `new ChatClientAgent(chatClient, instructions, name)`: Usando la información de cada agente, las instrucciones y la instancia de `IChatClient`, esto crea una instancia del agente. + - `builder.Services.AddKeyedSingleton(name, agent)`: Esto registra la instancia del agente como un servicio singleton. + +1. En el mismo archivo, busque el comentario `// Build a handoff workflow pattern with the agents registered` y agregue el código justo debajo. + + ```csharp + // Build a handoff workflow pattern with the agents registered + builder.AddWorkflow("publisher", (sp, key) => + { + var triage = sp.GetRequiredKeyedService("triage-agent"); + var generalSupport = sp.GetRequiredKeyedService("general-support-agent"); + var networkSpecialist = sp.GetRequiredKeyedService("network-specialist-agent"); + var warranty = sp.GetRequiredKeyedService("warranty-agent"); + + var specialists = new[] { generalSupport, networkSpecialist, warranty }; + + var workflow = AgentWorkflowBuilder.CreateHandoffBuilderWith(triage) + // El triaje puede transferir a cualquier especialista + .WithHandoffs(triage, specialists) + // Cada especialista puede transferir a otros especialistas + .WithHandoffs(generalSupport, [networkSpecialist, warranty]) + .WithHandoffs(networkSpecialist, [generalSupport, warranty]) + .WithHandoffs(warranty, [generalSupport, networkSpecialist]) + // Todos los especialistas transfieren de vuelta al triaje + .WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing") + .Build(); + + // HandoffWorkflowBuilder.Build() doesn't set the workflow name. + // Set it via reflection so AddWorkflow's name validation passes. + typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key); + + return workflow; + }).AddAsAIAgent("publisher"); + ``` + + Analicemos el código. + + - `var specialists = new[] { generalSupport, networkSpecialist, warranty };`: Esto define la lista de agentes especialistas. El agente de triaje es el punto de partida que redirige la solicitud del usuario a uno de los agentes especialistas. + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: Esto agrega el flujo de trabajo multi-agente como otra instancia de agente llamada `publisher` y lo registra como singleton. + - `AgentWorkflowBuilder.CreateHandoffBuilderWith(triage)`: Este es el constructor del flujo de trabajo handoff con el agente de triaje. + - `.WithHandoffs(triage, specialists)`: Esto define la transferencia del agente de triaje a los agentes especialistas. + - `.WithHandoffs(generalSupport, [networkSpecialist, warranty])`: Esto define la transferencia del agente de soporte general a los otros agentes especialistas. + - `.WithHandoffs(networkSpecialist, [generalSupport, warranty])`: Esto define la transferencia del agente especialista en redes a los otros agentes especialistas. + - `.WithHandoffs(warranty, [generalSupport, networkSpecialist])`: Esto define la transferencia del agente de garantía a los otros agentes especialistas. + - `.WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing")`: Esto define la transferencia de todos los agentes especialistas de vuelta al agente de triaje cuando el problema se resuelve o necesita redirección adicional. + - `typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key);`: Esto inyecta el nombre del flujo de trabajo, que es una solución temporal. + +1. En el mismo archivo, busque el comentario `// Map AGUI to the publisher workflow agent` y agregue el código justo debajo. El flujo de trabajo se expone como un endpoint API en `ag-ui` para que la interfaz web del frontend pueda comunicarse con esta aplicación del servicio de agente del backend. + + ```csharp + // Map AGUI to the publisher workflow agent + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + .CreateFixedAgent() + ); + ``` + + Note que `.CreateFixedAgent()` es una solución temporal hasta que el flujo de salida se maneje correctamente. + +## Implementar el patrón handoff en la interfaz web del frontend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto registra todos los detalles de los agentes para que la interfaz web sepa qué agente está respondiendo. + + ```csharp + // Register all agents passed from Aspire + builder.Services.AddSingleton(agents); + ``` + +1. En el mismo archivo, busque el comentario `// Register the backend agent service as an HTTP client` y agregue el código justo debajo. Aspire ya proporciona a la aplicación de la interfaz web del frontend los detalles de conexión del servicio de agente del backend. + + ```csharp + // Register the backend agent service as an HTTP client + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. En el mismo archivo, busque el comentario `// Register AGUI client` y agregue el código justo debajo. Usando este cliente AGUI, la aplicación de la interfaz web del frontend se comunica con la aplicación del servicio de agente del backend a través del endpoint `ag-ui`. + + ```csharp + // Register AGUI client + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Ejecutar Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Asegúrese de haber iniciado sesión en Azure usando tanto Azure CLI como Azure Developer CLI. Si no está seguro, siga [este paso](./00-setup.md#iniciar-sesión-en-azure) nuevamente. + +1. Ejecute el siguiente comando para iniciar todas las aplicaciones a través de Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. El panel de Aspire se abre automáticamente. + + ![Panel de Aspire](../../../docs/images/step-03-image-01.png) + + Haga clic en la aplicación del servicio de agente del backend. + +1. Cuando se abra la página Dev UI, cambie el agente a `publisher` y observe que el agente de triaje distribuye la solicitud a los otros agentes. + + ![Microsoft Agent Framework Dev UI - Patrón handoff](../../../docs/images/step-03-image-02.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Dev UI - Enviar solicitud](../../../docs/images/step-03-image-03.png) + + Observe el resultado y cómo el flujo de trabajo progresa en el lado izquierdo de la pantalla. + + ![Microsoft Agent Framework Dev UI - Ejecución del flujo de trabajo](../../../docs/images/step-03-image-04.png) + +1. Regrese al panel de Aspire y haga clic en la aplicación de la interfaz web. + + ![Panel de Aspire](../../../docs/images/step-03-image-05.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Chat UI - Enviar solicitud](../../../docs/images/step-03-image-06.png) + + Observe el resultado. + +1. Presione `Ctrl`+`C` para terminar todas las aplicaciones en ejecución. + +## Desplegar en Azure + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar tanto la interfaz web del frontend como las aplicaciones del servicio de agente del backend en Azure. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez completado, verá la URL de la aplicación de la interfaz web en la pantalla del terminal. Ábrala en su navegador web y envíe una solicitud. + + ![Microsoft Agent Framework en Azure Container Apps - Enviar solicitud](../../../docs/images/step-03-image-07.png) + + Observe el resultado. + +1. Una vez que todo esté listo, elimine todas las aplicaciones y agentes de Azure. + + ```bash + # Eliminar tanto la interfaz web como las aplicaciones del servicio de agente. + azd down --purge --force + + # Eliminar todos los agentes y el recurso de Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +¡Felicitaciones! 🎉 Acaba de completar el tercer escenario de orquestación multi-agente: el patrón handoff. ¡Continuemos! + +👈 [02: Patrón Concurrente](./02-concurrent-pattern.md) | [04: Patrón Group Chat](./04-group-chat-pattern.md) 👉 diff --git a/localization/es-es/docs/04-group-chat-pattern.md b/localization/es-es/docs/04-group-chat-pattern.md new file mode 100644 index 0000000..87d37dc --- /dev/null +++ b/localization/es-es/docs/04-group-chat-pattern.md @@ -0,0 +1,421 @@ +# 04 Patrón Group Chat + +En un patrón group chat, múltiples agentes participan en una conversación compartida, tomando turnos para aportar su experiencia. Un orquestador administra el flujo de la discusión, decidiendo qué agente habla a continuación y cuándo debe terminar la conversación. Esto es adecuado para planificación interfuncional, lluvia de ideas creativa o cualquier tarea donde perspectivas diversas necesiten interactuar y construir unas sobre otras de manera iterativa. + +## Escenario + +Usted está en un equipo de producto interfuncional que planifica el lanzamiento de un nuevo producto con agentes: agente de estrategia de producto, agente de experiencia de usuario, agente técnico y agente de negocios. + +
+ Arquitectura - Patrón Group Chat +
+ +## Obtener la raíz del repositorio + +1. Obtenga la variable `$REPOSITORY_ROOT` primero. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar el proyecto inicial + +1. Si ya tiene el directorio `workshop`, renómbrelo o elimínelo primero. + +1. Ejecute el script de configuración para copiar el proyecto inicial al directorio `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 04-group-chat-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 04-group-chat-pattern + ``` + +## Desplegar agentes + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue al directorio `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar los agentes definidos anteriormente en Microsoft Foundry. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez que el aprovisionamiento y el despliegue hayan finalizado, ejecute el siguiente comando para confirmar que los agentes se han desplegado correctamente. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Debería ver los cuatro nombres de agentes. + + ```text + business-agent + technical-agent + user-experience-agent + product-strategy-agent + ``` + +1. Navegue de vuelta al directorio del taller. + + ```bash + popd + ``` + +## Configurar la orquestación de Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique que toda la información necesaria de los agentes haya sido registrada. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Debería ver los valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` y `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, busque la línea de comentario `// Add agents` y agregue la propiedad `Agents` debajo de ella. + + ```jsonc + { + ... + // Add agents + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, busque el comentario `// Add resource for Microsoft Foundry` y agregue el código justo debajo. Esto agrega los detalles de conexión del proyecto de Microsoft Foundry. + + ```csharp + // Add resource for Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Analicemos el código. + + - `builder.AddFoundry("foundry")`: Esto agrega los detalles de conexión de Microsoft Foundry a través de un recurso personalizado, `FoundryResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add resource for agents on Microsoft Foundry` y agregue el código justo debajo. Esto expone la lista de detalles de los agentes a la aplicación que los referencia. + + ```csharp + // Add resource for agents on Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Analicemos el código. + + - `builder.AddAgents("agents")`: Esto agrega la lista de detalles de los agentes a través de un recurso personalizado, `AgentResource`. Si desea saber más sobre el recurso personalizado de Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. En el mismo archivo, busque el comentario `// Add backend agent service` y agregue el código justo debajo. Esto define el servicio de agente del backend que referencia el recurso `foundry` — todos los detalles de conexión de Microsoft Foundry se pasan a la aplicación del servicio de agente del backend. + + ```csharp + // Add backend agent service + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Analicemos el código. + + - `builder.AddProject("agent")`: Esto agrega la aplicación del servicio de agente del backend como un proyecto .NET. + - `.WithReference(foundry)`: Esto referencia el recurso foundry creado anteriormente, que pasa los detalles de conexión de Microsoft Foundry a la aplicación del servicio de agente del backend. + +1. En el mismo archivo, busque el comentario `// Add frontend web UI` y agregue el código justo debajo. Esto define la interfaz web del frontend que referencia tanto los recursos `agents` como `agent` — los detalles de los agentes y los detalles de conexión del backend se pasan a la aplicación de la interfaz web del frontend. + + ```csharp + // Add frontend web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Analicemos el código. + + - `builder.AddProject("webui")`: Esto agrega la aplicación de la interfaz web del frontend como un proyecto .NET. + - `.WithExternalHttpEndpoints()`: Esto expone esta aplicación de interfaz web del frontend a Internet, haciéndola accesible públicamente. + - `.WithReference(agents)`: Esto referencia el recurso de agentes creado anteriormente, que pasa la lista de agentes a la aplicación de la interfaz web del frontend. + - `.WithReference(agent)`: Esto referencia la aplicación del servicio de agente del backend, que pasa los detalles de conexión a la aplicación de la interfaz web del frontend. + +## Implementar el patrón group chat en el servicio de agente del backend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, busque el comentario `// Create AIProjectClient instance with EntraID authentication` y agregue el código justo debajo. Esto se conecta al proyecto de Microsoft Foundry. + + ```csharp + // Create AIProjectClient instance with EntraID authentication + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + Analicemos el código. + + - `new DefaultAzureCredential(...)`: Esto inicia sesión en Azure sin una clave API. Utiliza los datos de inicio de sesión de Azure CLI o Azure Developer CLI en su máquina local, y Managed Identity cuando la aplicación se despliega en Azure. + - `new AIProjectClient(endpoint, credential)`: Esto se conecta a la instancia del proyecto de Microsoft Foundry usando el endpoint y los datos de inicio de sesión. + +1. En el mismo archivo, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto obtiene los detalles de los agentes del proyecto de Microsoft Foundry y los registra en el contenedor IoC como servicios singleton. + + ```csharp + // Register all agents passed from Aspire + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Analicemos el código. + + - Ya conocemos la lista de agentes pero solo sabemos sus nombres. Por lo tanto, el código ejecuta el bucle `foreach` para cada agente. + - `new AgentReference(name, version)`: Usando la información de cada agente, esto crea una instancia de referencia. + - `projectClient.AsAIAgent(reference, factory)`: Esto se conecta al agente real usando los detalles de referencia. + - `builder.Services.AddKeyedSingleton(name, agent)`: Esto registra la instancia del agente como un servicio singleton. + + > **NOTA**: Puede notar la clase `AgentRecordShimChatClient`. Es una solución temporal para una incompatibilidad de versiones entre Microsoft Agent Framework y el SDK de Microsoft Foundry, que será eliminada pronto. + +1. En el mismo archivo, busque el comentario `// Build a group chat workflow pattern with the agents registered` y agregue el código justo debajo. + + ```csharp + // Build a group chat workflow pattern with the agents registered + builder.AddWorkflow("publisher", (sp, key) => + { + var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name)); + + return AgentWorkflowBuilder.CreateGroupChatBuilderWith(agentList => + new RoundRobinGroupChatManager(agentList) { MaximumIterationCount = participants.Count() * 2 }) + .AddParticipants(participants) + .WithName(key) + .Build(); + }).AddAsAIAgent("publisher"); + ``` + + Analicemos el código. + + - `var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name));`: Esto identifica la lista de agentes participantes en el group chat. + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: Esto agrega el flujo de trabajo multi-agente como otra instancia de agente llamada `publisher` y lo registra como singleton. + - `AgentWorkflowBuilder.CreateGroupChatBuilderWith(...)`: Este es el constructor del flujo de trabajo de group chat que usa el mismo nombre, `publisher`. + - `new RoundRobinGroupChatManager(...)`: Esto establece la estrategia del group chat en round-robin. También define el número máximo de iteraciones. En este código, cada agente responde dos veces durante el ciclo round-robin. + +1. En el mismo archivo, busque el comentario `// Map AGUI to the publisher workflow agent` y agregue el código justo debajo. El flujo de trabajo se expone como un endpoint API en `ag-ui` para que la interfaz web del frontend pueda comunicarse con esta aplicación del servicio de agente del backend. + + ```csharp + // Map AGUI to the publisher workflow agent + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## Implementar el patrón group chat en la interfaz web del frontend + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, busque el comentario `// Register all agents passed from Aspire` y agregue el código justo debajo. Esto registra todos los detalles de los agentes para que la interfaz web sepa qué agente está respondiendo. + + ```csharp + // Register all agents passed from Aspire + builder.Services.AddSingleton(agents); + ``` + +1. En el mismo archivo, busque el comentario `// Register the backend agent service as an HTTP client` y agregue el código justo debajo. Aspire ya proporciona a la aplicación de la interfaz web del frontend los detalles de conexión del servicio de agente del backend. + + ```csharp + // Register the backend agent service as an HTTP client + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. En el mismo archivo, busque el comentario `// Register AGUI client` y agregue el código justo debajo. Usando este cliente AGUI, la aplicación de la interfaz web del frontend se comunica con la aplicación del servicio de agente del backend a través del endpoint `ag-ui`. + + ```csharp + // Register AGUI client + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Ejecutar Aspire + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Asegúrese de haber iniciado sesión en Azure usando tanto Azure CLI como Azure Developer CLI. Si no está seguro, siga [este paso](./00-setup.md#iniciar-sesión-en-azure) nuevamente. + +1. Ejecute el siguiente comando para iniciar todas las aplicaciones a través de Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. El panel de Aspire se abre automáticamente. + + ![Panel de Aspire](../../../docs/images/step-04-image-01.png) + + Haga clic en la aplicación del servicio de agente del backend. + +1. Cuando se abra la página Dev UI, cambie el agente a `publisher` y haga clic en el botón "Configure & Run". + + ![Microsoft Agent Framework Dev UI - Patrón group chat](../../../docs/images/step-04-image-02.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Dev UI - Enviar solicitud](../../../docs/images/step-04-image-03.png) + + Observe el resultado y cómo el flujo de trabajo progresa en el lado izquierdo de la pantalla. + + ![Microsoft Agent Framework Dev UI - Ejecución del flujo de trabajo](../../../docs/images/step-04-image-04.png) + +1. Regrese al panel de Aspire y haga clic en la aplicación de la interfaz web. + + ![Panel de Aspire](../../../docs/images/step-04-image-05.png) + +1. Envíe cualquier solicitud. + + ![Microsoft Agent Framework Chat UI - Enviar solicitud](../../../docs/images/step-04-image-06.png) + + Observe el resultado. + +1. Presione `Ctrl`+`C` para terminar todas las aplicaciones en ejecución. + +## Desplegar en Azure + +1. Asegúrese de estar en el directorio `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Ejecute el siguiente comando para aprovisionar y desplegar tanto la interfaz web del frontend como las aplicaciones del servicio de agente del backend en Azure. + + ```bash + azd up + ``` + + Durante el aprovisionamiento, se le pedirá que ingrese un nombre de entorno, una suscripción de Azure y una ubicación. + +1. Una vez completado, verá la URL de la aplicación de la interfaz web en la pantalla del terminal. Ábrala en su navegador web y envíe una solicitud. + + ![Microsoft Agent Framework en Azure Container Apps - Enviar solicitud](../../../docs/images/step-04-image-07.png) + + Observe el resultado. + +1. Una vez que todo esté listo, elimine todas las aplicaciones y agentes de Azure. + + ```bash + # Eliminar tanto la interfaz web como las aplicaciones del servicio de agente. + azd down --purge --force + + # Eliminar todos los agentes y el recurso de Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +¡Felicitaciones! 🎉 Acaba de completar el cuarto escenario de orquestación multi-agente: el patrón group chat. ¡Ha terminado todo! + +👈 [03: Patrón Handoff](./03-handoff-pattern.md) | [README](../README.md) 👉 diff --git a/localization/es-es/docs/README.md b/localization/es-es/docs/README.md new file mode 100644 index 0000000..60ce4d2 --- /dev/null +++ b/localization/es-es/docs/README.md @@ -0,0 +1,10 @@ +# Materiales del Taller Multi-Agente + +Aquí se encuentra la lista de materiales del taller para construir patrones de orquestación multi-agente, junto con sus ejemplos de código. + +| Documento | Ejemplo de código | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](./01-sequential-pattern.md) | [01-sequential-pattern](../samples/01-sequential-pattern) | +| [02-concurrent-pattern.md](./02-concurrent-pattern.md) | [02-concurrent-pattern](../samples/02-concurrent-pattern) | +| [03-handoff-pattern.md](./03-handoff-pattern.md) | [03-handoff-pattern](../samples/03-handoff-pattern) | +| [04-group-chat-pattern.md](./04-group-chat-pattern.md) | [04-group-chat-pattern](../samples/04-group-chat-pattern) | diff --git a/localization/es-es/samples/01-sequential-pattern/README.md b/localization/es-es/samples/01-sequential-pattern/README.md new file mode 100644 index 0000000..b45900a --- /dev/null +++ b/localization/es-es/samples/01-sequential-pattern/README.md @@ -0,0 +1,13 @@ +# 01 Patrón Secuencial + +En un patrón secuencial, los agentes trabajan uno tras otro en un pipeline definido, donde la salida de cada agente alimenta al siguiente. Este enfoque funciona bien para tareas que siguen una progresión natural, como flujos de trabajo de creación de contenido, transformaciones de datos por etapas o análisis paso a paso. + +
+ Arquitectura - Patrón Secuencial +
+ +## Instrucciones + +Siga las instrucciones en [01-sequential-pattern.md](../../docs/01-sequential-pattern.md) con el proyecto [start](../../../../samples/01-sequential-pattern/start). + +Una vez que haya completado el ejercicio, compare su resultado con el proyecto [complete](../../../../samples/01-sequential-pattern/complete). diff --git a/localization/es-es/samples/02-concurrent-pattern/README.md b/localization/es-es/samples/02-concurrent-pattern/README.md new file mode 100644 index 0000000..825663a --- /dev/null +++ b/localization/es-es/samples/02-concurrent-pattern/README.md @@ -0,0 +1,13 @@ +# 02 Patrón Concurrente + +En un patrón concurrente, múltiples agentes analizan la misma entrada simultáneamente, cada uno aportando su propia experiencia. Una vez que todos los agentes completan su tarea, sus salidas se combinan en un resultado unificado. Esto es ideal para tareas que se benefician de múltiples puntos de vista trabajando al mismo tiempo, como análisis desde múltiples perspectivas, evaluación en conjunto o toma de decisiones colaborativa. + +
+ Arquitectura - Patrón Concurrente +
+ +## Instrucciones + +Siga las instrucciones en [02-concurrent-pattern.md](../../docs/02-concurrent-pattern.md) con el proyecto [start](../../../../samples/02-concurrent-pattern/start). + +Una vez que haya completado el ejercicio, compare su resultado con el proyecto [complete](../../../../samples/02-concurrent-pattern/complete). diff --git a/localization/es-es/samples/03-handoff-pattern/README.md b/localization/es-es/samples/03-handoff-pattern/README.md new file mode 100644 index 0000000..133bac1 --- /dev/null +++ b/localization/es-es/samples/03-handoff-pattern/README.md @@ -0,0 +1,13 @@ +# 03 Patrón de Transferencia + +En un patrón de transferencia, los agentes pasan dinámicamente el control entre sí según el contexto de la conversación. Un agente de clasificación recibe la solicitud inicial y la dirige al especialista más adecuado para manejarla. Los especialistas también pueden redirigir a otros cuando el problema cruza diferentes dominios. Esto funciona bien para escenarios como soporte de TI, atención al cliente o cualquier flujo de trabajo donde se necesita diferente experiencia en diferentes etapas. + +
+ Arquitectura - Patrón de Transferencia +
+ +## Instrucciones + +Siga las instrucciones en [03-handoff-pattern.md](../../docs/03-handoff-pattern.md) con el proyecto [start](../../../../samples/03-handoff-pattern/start). + +Una vez que haya completado el ejercicio, compare su resultado con el proyecto [complete](../../../../samples/03-handoff-pattern/complete). diff --git a/localization/es-es/samples/04-group-chat-pattern/README.md b/localization/es-es/samples/04-group-chat-pattern/README.md new file mode 100644 index 0000000..a3c039b --- /dev/null +++ b/localization/es-es/samples/04-group-chat-pattern/README.md @@ -0,0 +1,13 @@ +# 04 Patrón de Chat Grupal + +En un patrón de chat grupal, múltiples agentes participan en una conversación compartida, turnándose para aportar su experiencia. Un orquestador gestiona el flujo de la discusión, decidiendo qué agente habla a continuación y cuándo debe terminar la conversación. Esto es muy adecuado para planificación multifuncional, lluvia de ideas creativa o cualquier tarea donde diversas perspectivas necesitan interactuar y construir sobre las ideas de los demás de manera iterativa. + +
+ Arquitectura - Patrón de Chat Grupal +
+ +## Instrucciones + +Siga las instrucciones en [04-group-chat-pattern.md](../../docs/04-group-chat-pattern.md) con el proyecto [start](../../../../samples/04-group-chat-pattern/start). + +Una vez que haya completado el ejercicio, compare su resultado con el proyecto [complete](../../../../samples/04-group-chat-pattern/complete). diff --git a/localization/es-es/samples/README.md b/localization/es-es/samples/README.md new file mode 100644 index 0000000..7064f59 --- /dev/null +++ b/localization/es-es/samples/README.md @@ -0,0 +1,10 @@ +# Ejemplos de Código de Orquestación Multi-Agente + +A continuación se presenta la lista de patrones de orquestación multi-agente y sus ejemplos de código. + +| Documento | Ejemplo de Código | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](../docs/01-sequential-pattern.md) | [01-sequential-pattern](./01-sequential-pattern) | +| [02-concurrent-pattern.md](../docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./02-concurrent-pattern) | +| [03-handoff-pattern.md](../docs/03-handoff-pattern.md) | [03-handoff-pattern](./03-handoff-pattern) | +| [04-group-chat-pattern.md](../docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./04-group-chat-pattern) | diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md new file mode 100644 index 0000000..9b91cee --- /dev/null +++ b/localization/ja-jp/README.md @@ -0,0 +1,65 @@ +# マルチエージェント オーケストレーション ワークショップ + +これは、[Microsoft Agent Framework](https://aka.ms/agent-framework)、[Microsoft Foundry](https://aka.ms/microsoft-foundry)、および [Aspire](https://aspire.dev) を使用して .NET ベースのマルチエージェント アプリを構築するためのワークショップ資料です。 + +![MAF + Foundry ワークショップ](../../images/hero.jpg) + +## このワークショップの目的は? + +単一エージェント アプリの構築は簡単です。しかし、複数のエージェントが連携する必要がある実世界のユースケースは多く、マルチエージェント アプリの構築は単一エージェントのものほど単純ではありません。[Microsoft Agent Framework](https://aka.ms/agent-framework) は、5つのマルチエージェント オーケストレーション パターンを提供しています: + +| パターン | 説明 | +|----------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| +| [Sequential](https://learn.microsoft.com/agent-framework/workflows/orchestrations/sequential?pivots=programming-language-csharp) | エージェントが定義された順序で順番に実行されます | +| [Concurrent](https://learn.microsoft.com/agent-framework/workflows/orchestrations/concurrent?pivots=programming-language-csharp) | エージェントが並列で実行されます | +| [Handoff](https://learn.microsoft.com/agent-framework/workflows/orchestrations/handoff?pivots=programming-language-csharp) | エージェントがコンテキストに基づいて制御を相互に転送します | +| [Group Chat](https://learn.microsoft.com/agent-framework/workflows/orchestrations/group-chat?pivots=programming-language-csharp) | エージェントが共有の会話で協力します | +| [Magentic](https://learn.microsoft.com/agent-framework/workflows/orchestrations/magentic?pivots=programming-language-python) | マネージャー エージェントが専門エージェントを動的に調整します | + +## 特徴 + +このワークショップでは、Magentic パターンを除くすべてのマルチエージェント オーケストレーション パターンを構築します。各パターンを完了すると、以下のアーキテクチャが構築されます: + +- [Blazor](https://blazor.net) によるチャット UI のフロントエンド +- [ASP.NET](https://asp.net) と [Microsoft Agent Framework](https://aka.ms/agent-framework) によるバックエンド +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) によるエージェント ホスティング +- [Aspire](https://aspire.dev) によるクラウドネイティブ アプリ オーケストレーション + +> [!NOTE] +> Microsoft Agent Framework SDK の .NET バージョンは、今後のリリースで Magentic パターンをサポートする予定です。 + +## 前提条件 + +- [Azure サブスクリプション(無料)](http://azure.microsoft.com/free) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) 以上 +- [Visual Studio 2026](https://visualstudio.microsoft.com/downloads/) または [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) +- [Docker Desktop](https://docs.docker.com/desktop/) または同等のツール +- [GitHub CLI](https://cli.github.com) +- [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) +- [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) +- [Aspire CLI](https://aspire.dev/get-started/install-cli/) + +## ワークショップ セッション + +| セッション | ドキュメント | コードサンプル | +|-----------------------|-------------------------------------------------------------|----------------------------------------------------------| +| 00 セットアップ | [00-setup.md](./docs/00-setup.md) | | +| 01 Sequential パターン | [01-sequential-pattern.md](./docs/01-sequential-pattern.md) | [01-sequential-pattern](./samples/01-sequential-pattern) | +| 02 Concurrent パターン | [02-concurrent-pattern.md](./docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./samples/02-concurrent-pattern) | +| 03 Handoff パターン | [03-handoff-pattern.md](./docs/03-handoff-pattern.md) | [03-handoff-pattern](./samples/03-handoff-pattern) | +| 04 Group Chat パターン | [04-group-chat-pattern.md](./docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./samples/04-group-chat-pattern) | + +## お好みの言語をご利用ください! + +このワークショップ資料は以下の言語でご利用いただけます。 + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](./README.md) | [한국어](../ko-kr/README.md) | [Português](../pt-br/README.md) | [中文(简体)](../zh-cn/README.md) + +## リソース + +- [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Agent Framework - Workflow Orchestrations](https://learn.microsoft.com/agent-framework/workflows/orchestrations) +- [Microsoft Foundry](https://aka.ms/microsoft-foundry) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) +- [Model Context Protocol (MCP)](https://modelcontextprotocol.io) +- [Aspire](https://aspire.dev) diff --git a/localization/ja-jp/docs/00-setup.md b/localization/ja-jp/docs/00-setup.md new file mode 100644 index 0000000..5e71a55 --- /dev/null +++ b/localization/ja-jp/docs/00-setup.md @@ -0,0 +1,215 @@ +# 00 セットアップ + +このセッションでは、お使いのマシンまたは GitHub Codespaces で開発環境をセットアップします。 + +## 前提条件 + +- Web ブラウザー: [Microsoft Edge](https://microsoft.com/edge) または [Google Chrome](http://chrome.google.com) +- [Azure サブスクリプション](https://azure.microsoft.com/free) + +## GitHub Codespaces でのセットアップ + +ワークショップでは、開発環境のセットアップ時間を節約するために GitHub Codespaces の使用を強くお勧めします。ローカル マシンで開発環境をセットアップする場合は、このセクションをスキップして [VS Code でのセットアップ](#vs-code-でのセットアップ) セクションに進んでください。 + +1. 下のボタンをクリックして、新しい GitHub Codespaces インスタンスを作成します。 + + [![新しい GitHub Codespaces インスタンスを作成する](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/multi-agent-orchestration-workshop) + +1. 作成が完了したら、以下のコマンドを実行して、必要なツールが正しくインストールされていることを確認します。 + + ```bash + # .NET SDK + dotnet --list-sdks + + # node.js + node --version + npm --version + + # PowerShell + pwsh --version + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +1. GitHub のログイン状態を確認します。 + + ```bash + gh auth status + ``` + +1. リモート リポジトリの詳細を取得します。 + + ```bash + git remote -v + ``` + + 以下のように表示されるはずです。 + + ```text + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (push) + ``` + + これらの2行が表示されない場合は、現在の GitHub Codespaces インスタンスを削除して、再度作成してください。 + +1. GitHub Codespaces インスタンスはあなたのアカウント配下にないため、以下のコマンドを使用してリポジトリをフォークし、所有権を移転します。 + + ```bash + git remote -v > remote.txt + git add . && git commit -m "Add remote.txt for forking" + ``` + + 以下のようなメッセージが表示される場合があります: + + ```text + You don't have write access to the Azure-Samples/multi-agent-orchestration-workshop repository, so you cannot push changes to it. + To obtain write access we will point this codespace at your fork of Azure-Samples/multi-agent-orchestration-workshop, creating that fork if it doesn't exist. + + Would you like to proceed? + ``` + + `y` を入力して続行します。自動的にあなたのアカウント配下にリポジトリがフォークされます。 + +1. リモート リポジトリの状態を確認します。 + + ```bash + git remote -v + ``` + + 今度は以下の4行が表示されるはずです。 + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + + これらの4行が表示されない場合は、GitHub Codespaces インスタンスを削除して再作成してください。 + +## VS Code でのセットアップ + +GitHub Codespaces インスタンスを既にお持ちの場合は、このセクションをスキップして [Azure へのログイン](#azure-へのログイン) セクションに直接進んでください。 + +1. お使いのマシンに以下のツールをインストールします。 + + - [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) + - [Docker Desktop](https://docs.docker.com/desktop/) または同等のツール + - [GitHub CLI](https://cli.github.com) + - [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) + - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) + - [Aspire CLI](https://aspire.dev/get-started/install-cli/) + + 次に、以下のコマンドを実行して、正しくインストールされていることを確認します。 + + ```bash + # .NET SDK + dotnet --list-sdks + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +### GitHub へのログイン + +1. GitHub にログインします。 + + ```bash + gh auth login + ``` + + ログインしたら、以下のコマンドを実行してログイン状態を確認します。 + + ```bash + gh auth status + ``` + +### プロジェクトのクローン + +1. このリポジトリをローカル マシンにフォークします。 + + ```bash + gh repo fork Azure-Samples/multi-agent-orchestration-workshop --clone + ``` + +1. クローンしたディレクトリに移動します。 + + ```bash + cd multi-agent-orchestration-workshop + ``` + +1. リモート リポジトリの状態を確認します。 + + ```bash + git remote -v + ``` + + 以下の4行が表示されるはずです。 + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + +1. VS Code でリポジトリを開きます。 + + ```bash + code . + ``` + +## Azure へのログイン + +1. Azure にログインします。 + + ```bash + # Azure Developer CLI + azd auth login + + # Azure CLI + az login + ``` + + ログインしたら、以下のコマンドを実行してログイン状態を確認します。 + + ```bash + # Azure Developer CLI + azd auth login --check-status + + # Azure CLI + az account show + ``` + +--- + +おめでとうございます! 🎉 開発環境のセットアップが完了しました。次に進みましょう! + +👈 [README](../README.md) | [01: Sequential Pattern](./01-sequential-pattern.md) 👉 diff --git a/localization/ja-jp/docs/01-sequential-pattern.md b/localization/ja-jp/docs/01-sequential-pattern.md new file mode 100644 index 0000000..4e34982 --- /dev/null +++ b/localization/ja-jp/docs/01-sequential-pattern.md @@ -0,0 +1,415 @@ +# 01 Sequential パターン + +Sequential パターンでは、エージェントが定義されたパイプラインの中で順番に動作し、各エージェントの出力が次のエージェントに渡されます。このアプローチは、コンテンツ作成ワークフロー、段階的なデータ変換、ステップバイステップの分析など、自然な進行に従うタスクに適しています。 + +## シナリオ + +エージェントを使用して技術ブログ記事を執筆します – リサーチ エージェント、アウトライン エージェント、ライター エージェント、エディター エージェントです。 + +
+ アーキテクチャ - Sequential パターン +
+ +## リポジトリ ルートの取得 + +1. まず `$REPOSITORY_ROOT` 変数を取得します。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## スタート プロジェクトのコピー + +1. すでに `workshop` ディレクトリがある場合は、先にリネームまたは削除してください。 + +1. セットアップ スクリプトを実行して、スタート プロジェクトを `workshop` ディレクトリにコピーします。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 01-sequential-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 01-sequential-pattern + ``` + +## エージェントのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` ディレクトリに移動します。 + + ```bash + pushd resources-foundry + ``` + +1. 以下のコマンドを実行して、上記で定義したエージェントを Microsoft Foundry にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. プロビジョニングとデプロイが完了したら、以下のコマンドを実行して、エージェントが正常にデプロイされたことを確認します。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 4つのエージェント名が表示されるはずです。 + + ```text + editor-agent + writer-agent + outliner-agent + research-agent + ``` + +1. workshop ディレクトリに戻ります。 + + ```bash + popd + ``` + +## Aspire オーケストレーションの構成 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 必要なエージェント情報がすべて記録されていることを確認します。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP`、および `Foundry:Project:Endpoint` の値が表示されるはずです。 + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs` を開き、コメント `// Add resource for Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトの接続詳細が追加されます。 + + ```csharp + // Microsoft Foundry のリソースを追加 + var foundry = builder.AddFoundry("foundry"); + ``` + + コードの解説です。 + + - `builder.AddFoundry("foundry")`: カスタム リソース `FoundryResource` を通じて Microsoft Foundry の接続詳細を追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add resource for agents on Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、エージェントの詳細リストが参照アプリケーションに公開されます。 + + ```csharp + // Microsoft Foundry 上のエージェントのリソースを追加 + var agents = builder.AddAgents("agents"); + ``` + + コードの解説です。 + + - `builder.AddAgents("agents")`: カスタム リソース `AgentResource` を通じてエージェントの詳細リストを追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add backend agent service` を見つけて、そのすぐ下にコードを追加します。これにより、`foundry` リソースを参照するバックエンド エージェント サービスが定義されます – すべての Microsoft Foundry 接続詳細がバックエンド エージェント サービス アプリに渡されます。 + + ```csharp + // バックエンド エージェント サービスを追加 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + コードの解説です。 + + - `builder.AddProject("agent")`: バックエンド エージェント サービス アプリを .NET プロジェクトとして追加します。 + - `.WithReference(foundry)`: 上で作成した foundry リソースを参照し、Microsoft Foundry の接続詳細をバックエンド エージェント サービス アプリに渡します。 + +1. 同じファイルで、コメント `// Add frontend web UI` を見つけて、そのすぐ下にコードを追加します。これにより、`agents` と `agent` の両方のリソースを参照するフロントエンド Web UI が定義されます – エージェントの詳細とバックエンドの接続詳細の両方がフロントエンド Web UI アプリに渡されます。 + + ```csharp + // フロントエンド Web UI を追加 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + コードの解説です。 + + - `builder.AddProject("webui")`: フロントエンド Web UI アプリを .NET プロジェクトとして追加します。 + - `.WithExternalHttpEndpoints()`: このフロントエンド Web UI アプリをインターネットに公開し、パブリック アクセス可能にします。 + - `.WithReference(agents)`: 上で作成した agent リソースを参照し、エージェントのリストをフロントエンド Web UI アプリに渡します。 + - `.WithReference(agent)`: バックエンド エージェント サービス アプリを参照し、接続詳細をフロントエンド Web UI アプリに渡します。 + +## バックエンド エージェント サービスへの Sequential パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs` を開き、コメント `// Create AIProjectClient instance with EntraID authentication` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトに接続します。 + + ```csharp + // EntraID 認証で AIProjectClient インスタンスを作成 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + コードの解説です。 + + - `new DefaultAzureCredential(...)`: API キーなしで Azure にログインします。ローカル マシンでは Azure CLI または Azure Developer CLI のログイン情報を使用し、Azure にデプロイされたアプリではマネージド ID を使用します。 + - `new AIProjectClient(endpoint, credential)`: エンドポイントとログイン情報を使用して Microsoft Foundry プロジェクト インスタンスに接続します。 + +1. 同じファイルで、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトからエージェントの詳細を取得し、IoC コンテナーにシングルトン サービスとして登録します。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + コードの解説です。 + + - エージェントのリストは既に分かっていますが、名前のみ分かっています。そのため、コードは各エージェントに対して `foreach` ループを実行します。 + - `new AgentReference(name, version)`: 各エージェントの情報を使用して参照インスタンスを作成します。 + - `projectClient.AsAIAgent(reference, factory)`: 参照の詳細を使用して実際のエージェントに接続します。 + - `builder.Services.AddKeyedSingleton(name, agent)`: エージェント インスタンスをシングルトン サービスとして登録します。 + + > **注意**: `AgentRecordShimChatClient` クラスにお気づきかもしれません。これは Microsoft Agent Framework と Microsoft Foundry SDK 間のバージョンの不一致に対する一時的な回避策であり、まもなく削除される予定です。 + +1. 同じファイルで、コメント `// Build a sequential workflow pattern with the agents registered` を見つけて、そのすぐ下にコードを追加します。 + + ```csharp + // 登録されたエージェントで Sequential ワークフロー パターンを構築 + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [.. agents.Select(a => sp.GetRequiredKeyedService(a.Name))] + )).AddAsAIAgent("publisher"); + ``` + + コードの解説です。 + + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: マルチエージェント ワークフローを `publisher` という名前の別のエージェント インスタンスとして追加し、シングルトンとして登録します。 + - `AgentWorkflowBuilder.BuildSequential(...)`: 同じ名前 `publisher` を使用する Sequential ワークフロー ビルダーです。 + + `agents` 配列で宣言された順序で、以前に登録されたサービスから複数のエージェントが追加されることに注意してください。 + +1. 同じファイルで、コメント `// Map AGUI to the publisher workflow agent` を見つけて、そのすぐ下にコードを追加します。ワークフローは `ag-ui` の API エンドポイントとして公開され、フロントエンド Web UI がこのバックエンド エージェント サービス アプリと通信できるようになります。 + + ```csharp + // AGUI を publisher ワークフロー エージェントにマッピング + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## フロントエンド Web UI への Sequential パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs` を開き、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、すべてのエージェントの詳細が登録され、Web UI がどのエージェントが応答しているかを把握できるようになります。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + builder.Services.AddSingleton(agents); + ``` + +1. 同じファイルで、コメント `// Register the backend agent service as an HTTP client` を見つけて、そのすぐ下にコードを追加します。Aspire は既にフロントエンド Web UI アプリにバックエンド エージェント サービスの接続詳細を提供しています。 + + ```csharp + // バックエンド エージェント サービスを HTTP クライアントとして登録 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 同じファイルで、コメント `// Register AGUI client` を見つけて、そのすぐ下にコードを追加します。この AGUI クライアントを使用して、フロントエンド Web UI アプリは `ag-ui` エンドポイント経由でバックエンド エージェント サービス アプリと通信します。 + + ```csharp + // AGUI クライアントを登録 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire の実行 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI と Azure Developer CLI の両方で Azure に既にログインしていることを確認してください。不明な場合は、[こちらの手順](./00-setup.md#azure-へのログイン) を再度実行してください。 + +1. 以下のコマンドを実行して、Aspire を通じてすべてのアプリを起動します。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire ダッシュボードが自動的に開きます。 + + ![Aspire ダッシュボード](../../../docs/images/step-01-image-01.png) + + バックエンド エージェント サービス アプリをクリックします。 + +1. Dev UI ページが開いたら、エージェントを `publisher` に変更し、「Configure & Run」ボタンをクリックします。 + + ![Microsoft Agent Framework Dev UI - Sequential パターン](../../../docs/images/step-01-image-02.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Dev UI - リクエストの送信](../../../docs/images/step-01-image-03.png) + + 画面の左側で結果とワークフローの進行状況を確認します。 + + ![Microsoft Agent Framework Dev UI - ワークフローの実行](../../../docs/images/step-01-image-04.png) + +1. Aspire ダッシュボードに戻り、Web UI アプリをクリックします。 + + ![Aspire ダッシュボード](../../../docs/images/step-01-image-05.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Chat UI - リクエストの送信](../../../docs/images/step-01-image-06.png) + + 結果を確認します。 + +1. `Ctrl`+`C` を押してすべての実行中のアプリを終了します。 + +## Azure へのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 以下のコマンドを実行して、フロントエンド Web UI とバックエンド エージェント サービス アプリの両方を Azure にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. 完了すると、ターミナル画面に Web UI アプリケーションの URL が表示されます。Web ブラウザーで開き、リクエストを送信します。 + + ![Azure Container Apps 上の Microsoft Agent Framework - リクエストの送信](../../../docs/images/step-01-image-07.png) + + 結果を確認します。 + +1. すべて完了したら、Azure からすべてのアプリとエージェントを削除します。 + + ```bash + # Web UI とエージェント サービス アプリの両方を削除します。 + azd down --purge --force + + # すべてのエージェントと Microsoft Foundry リソースを削除します。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +おめでとうございます! 🎉 最初のマルチエージェント オーケストレーション シナリオ - Sequential パターンが完了しました。次に進みましょう! + +👈 [00: Setup](./00-setup.md) | [02: Concurrent Pattern](./02-concurrent-pattern.md) 👉 diff --git a/localization/ja-jp/docs/02-concurrent-pattern.md b/localization/ja-jp/docs/02-concurrent-pattern.md new file mode 100644 index 0000000..36a0923 --- /dev/null +++ b/localization/ja-jp/docs/02-concurrent-pattern.md @@ -0,0 +1,446 @@ +# 02 Concurrent パターン + +Concurrent パターンでは、複数のエージェントが同じ入力を同時に分析し、それぞれが独自の専門知識を発揮します。すべてのエージェントが完了すると、それらの出力が統合された結果にまとめられます。これは、マルチ視点分析、アンサンブル評価、協調的な意思決定など、同時に複数の視点が必要なタスクに最適です。 + +## シナリオ + +ベンチャーキャピタル企業で働いており、エージェントを使用してスタートアップのピッチを分析します – 市場分析エージェント、技術的実現可能性エージェント、財務モデル エージェント、リスク評価エージェント、およびアグリゲーター エージェントです。 + +
+ アーキテクチャ - Concurrent パターン +
+ +## リポジトリ ルートの取得 + +1. まず `$REPOSITORY_ROOT` 変数を取得します。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## スタート プロジェクトのコピー + +1. すでに `workshop` ディレクトリがある場合は、先にリネームまたは削除してください。 + +1. セットアップ スクリプトを実行して、スタート プロジェクトを `workshop` ディレクトリにコピーします。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 02-concurrent-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 02-concurrent-pattern + ``` + +## エージェントのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` ディレクトリに移動します。 + + ```bash + pushd resources-foundry + ``` + +1. 以下のコマンドを実行して、上記で定義したエージェントを Microsoft Foundry にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. プロビジョニングとデプロイが完了したら、以下のコマンドを実行して、エージェントが正常にデプロイされたことを確認します。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 5つのエージェント名が表示されるはずです。 + + ```text + aggregator-agent + risk-assessment-agent + financial-model-agent + technology-feasibility-agent + market-analysis-agent + ``` + +1. workshop ディレクトリに戻ります。 + + ```bash + popd + ``` + +## Aspire オーケストレーションの構成 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 必要なエージェント情報がすべて記録されていることを確認します。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP`、および `Foundry:Project:Endpoint` の値が表示されるはずです。 + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs` を開き、コメント `// Add resource for Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトの接続詳細が追加されます。 + + ```csharp + // Microsoft Foundry のリソースを追加 + var foundry = builder.AddFoundry("foundry"); + ``` + + コードの解説です。 + + - `builder.AddFoundry("foundry")`: カスタム リソース `FoundryResource` を通じて Microsoft Foundry の接続詳細を追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add resource for agents on Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、エージェントの詳細リストが参照アプリケーションに公開されます。 + + ```csharp + // Microsoft Foundry 上のエージェントのリソースを追加 + var agents = builder.AddAgents("agents"); + ``` + + コードの解説です。 + + - `builder.AddAgents("agents")`: カスタム リソース `AgentResource` を通じてエージェントの詳細リストを追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add backend agent service` を見つけて、そのすぐ下にコードを追加します。これにより、`foundry` リソースを参照するバックエンド エージェント サービスが定義されます — すべての Microsoft Foundry 接続詳細がバックエンド エージェント サービス アプリに渡されます。 + + ```csharp + // バックエンド エージェント サービスを追加 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + コードの解説です。 + + - `builder.AddProject("agent")`: バックエンド エージェント サービス アプリを .NET プロジェクトとして追加します。 + - `.WithReference(foundry)`: 上で作成した foundry リソースを参照し、Microsoft Foundry の接続詳細をバックエンド エージェント サービス アプリに渡します。 + +1. 同じファイルで、コメント `// Add frontend web UI` を見つけて、そのすぐ下にコードを追加します。これにより、`agents` と `agent` の両方のリソースを参照するフロントエンド Web UI が定義されます — エージェントの詳細とバックエンドの接続詳細の両方がフロントエンド Web UI アプリに渡されます。 + + ```csharp + // フロントエンド Web UI を追加 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + コードの解説です。 + + - `builder.AddProject("webui")`: フロントエンド Web UI アプリを .NET プロジェクトとして追加します。 + - `.WithExternalHttpEndpoints()`: このフロントエンド Web UI アプリをインターネットに公開し、パブリック アクセス可能にします。 + - `.WithReference(agents)`: 上で作成した agent リソースを参照し、エージェントのリストをフロントエンド Web UI アプリに渡します。 + - `.WithReference(agent)`: バックエンド エージェント サービス アプリを参照し、接続詳細をフロントエンド Web UI アプリに渡します。 + +## バックエンド エージェント サービスへの Concurrent パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs` を開き、コメント `// Create AIProjectClient instance with EntraID authentication` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトに接続します。 + + ```csharp + // EntraID 認証で AIProjectClient インスタンスを作成 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + コードの解説です。 + + - `new DefaultAzureCredential(...)`: API キーなしで Azure にログインします。ローカル マシンでは Azure CLI または Azure Developer CLI のログイン情報を使用し、Azure にデプロイされたアプリではマネージド ID を使用します。 + - `new AIProjectClient(endpoint, credential)`: エンドポイントとログイン情報を使用して Microsoft Foundry プロジェクト インスタンスに接続します。 + +1. 同じファイルで、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトからエージェントの詳細を取得し、IoC コンテナーにシングルトン サービスとして登録します。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + コードの解説です。 + + - エージェントのリストは既に分かっていますが、名前のみ分かっています。そのため、コードは各エージェントに対して `foreach` ループを実行します。 + - `new AgentReference(name, version)`: 各エージェントの情報を使用して参照インスタンスを作成します。 + - `projectClient.AsAIAgent(reference, factory)`: 参照の詳細を使用して実際のエージェントに接続します。 + - `builder.Services.AddKeyedSingleton(name, agent)`: エージェント インスタンスをシングルトン サービスとして登録します。 + + > **注意**: `AgentRecordShimChatClient` クラスにお気づきかもしれません。これは Microsoft Agent Framework と Microsoft Foundry SDK 間のバージョンの不一致に対する一時的な回避策であり、まもなく削除される予定です。 + +1. 同じファイルで、コメント `// Build a concurrent workflow pattern with the agents registered` を見つけて、そのすぐ下にコードを追加します。 + + ```csharp + // 登録されたエージェントで Concurrent ワークフロー パターンを構築 + var concurrentAgents = agents.Where(a => a.Name != "aggregator-agent"); + var aggregatorAgent = agents.SingleOrDefault(a => a.Name == "aggregator-agent"); + + builder.AddWorkflow("concurrent-analysis", (sp, key) => AgentWorkflowBuilder.BuildConcurrent( + workflowName: key, + agents: [.. concurrentAgents.Select(a => sp.GetRequiredKeyedService(a.Name))], + aggregator: null + )).AddAsAIAgent("concurrent-analysis"); + + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [ + sp.GetRequiredKeyedService("concurrent-analysis"), + sp.GetRequiredKeyedService(aggregatorAgent!.Name) + ] + )).AddAsAIAgent("publisher"); + ``` + + コードの解説です。 + + - `builder.AddWorkflow("concurrent-analysis", ...).AddAsAIAgent("concurrent-analysis")`: マルチエージェント ワークフローを `concurrent-analysis` という名前の別のエージェント インスタンスとして追加し、シングルトンとして登録します。 + - `AgentWorkflowBuilder.BuildConcurrent(...)`: 同じ名前 `concurrent-analysis` を使用する Concurrent ワークフロー ビルダーです。 + + `agents` 配列で宣言された、以前に登録されたサービスから複数のエージェントが追加されることに注意してください。 + + また、Microsoft Foundry が提供する `aggregator-agent` を代わりに使用するため、アグリゲーターに `null` を渡していることに注意してください。 + - `builder.AddWorkflow("publisher, ...).AddAsAIAgent("publisher")`: マルチエージェント ワークフローを `publisher` という名前の別のエージェント インスタンスとして追加し、シングルトンとして登録します。 + - `AgentWorkflowBuilder.BuildSequential(...)`: 同じ名前 `publisher` を使用する Sequential ワークフロー ビルダーです。 + + `concurrent-analysis` ワークフローと `aggregator-agent` の両方を追加して、アグリゲーター エージェントが Concurrent ワークフローで各エージェントが応答した内容をまとめることに注意してください。 + +1. 同じファイルで、コメント `// Map AGUI to the publisher workflow agent` を見つけて、そのすぐ下にコードを追加します。ワークフローは `ag-ui` の API エンドポイントとして公開され、フロントエンド Web UI がこのバックエンド エージェント サービス アプリと通信できるようになります。 + + ```csharp + // AGUI を publisher ワークフロー エージェントにマッピング + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## フロントエンド Web UI への Concurrent パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs` を開き、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、すべてのエージェントの詳細が登録され、Web UI がどのエージェントが応答しているかを把握できるようになります。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + builder.Services.AddSingleton(agents); + ``` + +1. 同じファイルで、コメント `// Register the backend agent service as an HTTP client` を見つけて、そのすぐ下にコードを追加します。Aspire は既にフロントエンド Web UI アプリにバックエンド エージェント サービスの接続詳細を提供しています。 + + ```csharp + // バックエンド エージェント サービスを HTTP クライアントとして登録 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 同じファイルで、コメント `// Register AGUI client` を見つけて、そのすぐ下にコードを追加します。この AGUI クライアントを使用して、フロントエンド Web UI アプリは `ag-ui` エンドポイント経由でバックエンド エージェント サービス アプリと通信します。 + + ```csharp + // AGUI クライアントを登録 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire の実行 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI と Azure Developer CLI の両方で Azure に既にログインしていることを確認してください。不明な場合は、[こちらの手順](./00-setup.md#azure-へのログイン) を再度実行してください。 + +1. 以下のコマンドを実行して、Aspire を通じてすべてのアプリを起動します。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire ダッシュボードが自動的に開きます。 + + ![Aspire ダッシュボード](../../../docs/images/step-02-image-01.png) + + バックエンド エージェント サービス アプリをクリックします。 + +1. Dev UI ページが開いたら、エージェントを `concurrent-analysis` に変更して、すべてのエージェントが並行して実行されることを確認します。 + + ![Microsoft Agent Framework Dev UI - Concurrent パターン](../../../docs/images/step-02-image-02.png) + + 次に、エージェントを `publisher` に変更して、Sequential パターンが `concurrent-analysis` と `aggregator-agent` をどのように組み合わせるかを確認します。 + + ![Microsoft Agent Framework Dev UI - Sequential パターン](../../../docs/images/step-02-image-03.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Dev UI - リクエストの送信](../../../docs/images/step-02-image-04.png) + + 画面の左側で結果とワークフローの進行状況を確認します。 + + ![Microsoft Agent Framework Dev UI - ワークフローの実行](../../../docs/images/step-02-image-05.png) + +1. Aspire ダッシュボードに戻り、Web UI アプリをクリックします。 + + ![Aspire ダッシュボード](../../../docs/images/step-02-image-06.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Chat UI - リクエストの送信](../../../docs/images/step-02-image-07.png) + + 結果を確認します。 + +1. `Ctrl`+`C` を押してすべての実行中のアプリを終了します。 + +## Azure へのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 以下のコマンドを実行して、フロントエンド Web UI とバックエンド エージェント サービス アプリの両方を Azure にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. 完了すると、ターミナル画面に Web UI アプリケーションの URL が表示されます。Web ブラウザーで開き、リクエストを送信します。 + + ![Azure Container Apps 上の Microsoft Agent Framework - リクエストの送信](../../../docs/images/step-02-image-08.png) + + 結果を確認します。 + +1. すべて完了したら、Azure からすべてのアプリとエージェントを削除します。 + + ```bash + # Web UI とエージェント サービス アプリの両方を削除します。 + azd down --purge --force + + # すべてのエージェントと Microsoft Foundry リソースを削除します。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +おめでとうございます! 🎉 2番目のマルチエージェント オーケストレーション シナリオ - Concurrent パターンが完了しました。次に進みましょう! + +👈 [01: Sequential Pattern](./01-sequential-pattern.md) | [03: Handoff Pattern](./03-handoff-pattern.md) 👉 diff --git a/localization/ja-jp/docs/03-handoff-pattern.md b/localization/ja-jp/docs/03-handoff-pattern.md new file mode 100644 index 0000000..613560b --- /dev/null +++ b/localization/ja-jp/docs/03-handoff-pattern.md @@ -0,0 +1,449 @@ +# 03 Handoff パターン + +Handoff パターンでは、エージェントが会話のコンテキストに基づいて動的に制御を相互に渡します。トリアージ エージェントが最初のリクエストを受け取り、それを処理するのに最も適した専門エージェントにルーティングします。専門エージェントは、問題が複数の領域にまたがる場合、互いにリダイレクトすることもできます。これは、IT サポート、カスタマー サービス、または異なる段階で異なる専門知識が必要なワークフローに適しています。 + +## シナリオ + +IT サポートチームで働いており、エージェントを使用します – 一般サポート エージェント、ネットワーク スペシャリスト エージェント、保証エージェント、およびトリアージ エージェントです。 + +
+ アーキテクチャ - Handoff パターン +
+ +## リポジトリ ルートの取得 + +1. まず `$REPOSITORY_ROOT` 変数を取得します。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## スタート プロジェクトのコピー + +1. すでに `workshop` ディレクトリがある場合は、先にリネームまたは削除してください。 + +1. セットアップ スクリプトを実行して、スタート プロジェクトを `workshop` ディレクトリにコピーします。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 03-handoff-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 03-handoff-pattern + ``` + +## エージェントのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` ディレクトリに移動します。 + + ```bash + pushd resources-foundry + ``` + +1. 以下のコマンドを実行して、上記で定義したエージェントを Microsoft Foundry にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. プロビジョニングとデプロイが完了したら、以下のコマンドを実行して、エージェントが正常にデプロイされたことを確認します。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 4つのエージェント名が表示されるはずです。 + + ```text + warranty-agent + network-specialist-agent + general-support-agent + triage-agent + ``` + +1. workshop ディレクトリに戻ります。 + + ```bash + popd + ``` + +## Aspire オーケストレーションの構成 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 必要なエージェント情報がすべて記録されていることを確認します。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP`、および `Foundry:Project:Endpoint` の値が表示されるはずです。 + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs` を開き、コメント `// Add resource for Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトの接続詳細が追加されます。 + + ```csharp + // Microsoft Foundry のリソースを追加 + var foundry = builder.AddFoundry("foundry"); + ``` + + コードの解説です。 + + - `builder.AddFoundry("foundry")`: カスタム リソース `FoundryResource` を通じて Microsoft Foundry の接続詳細を追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add resource for agents on Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、エージェントの詳細リストが参照アプリケーションに公開されます。 + + ```csharp + // Microsoft Foundry 上のエージェントのリソースを追加 + var agents = builder.AddAgents("agents"); + ``` + + コードの解説です。 + + - `builder.AddAgents("agents")`: カスタム リソース `AgentResource` を通じてエージェントの詳細リストを追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add backend agent service` を見つけて、そのすぐ下にコードを追加します。これにより、`foundry` リソースを参照するバックエンド エージェント サービスが定義されます — すべての Microsoft Foundry 接続詳細がバックエンド エージェント サービス アプリに渡されます。 + + ```csharp + // バックエンド エージェント サービスを追加 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + コードの解説です。 + + - `builder.AddProject("agent")`: バックエンド エージェント サービス アプリを .NET プロジェクトとして追加します。 + - `.WithReference(foundry)`: 上で作成した foundry リソースを参照し、Microsoft Foundry の接続詳細をバックエンド エージェント サービス アプリに渡します。 + +1. 同じファイルで、コメント `// Add frontend web UI` を見つけて、そのすぐ下にコードを追加します。これにより、`agents` と `agent` の両方のリソースを参照するフロントエンド Web UI が定義されます — エージェントの詳細とバックエンドの接続詳細の両方がフロントエンド Web UI アプリに渡されます。 + + ```csharp + // フロントエンド Web UI を追加 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + コードの解説です。 + + - `builder.AddProject("webui")`: フロントエンド Web UI アプリを .NET プロジェクトとして追加します。 + - `.WithExternalHttpEndpoints()`: このフロントエンド Web UI アプリをインターネットに公開し、パブリック アクセス可能にします。 + - `.WithReference(agents)`: 上で作成した agent リソースを参照し、エージェントのリストをフロントエンド Web UI アプリに渡します。 + - `.WithReference(agent)`: バックエンド エージェント サービス アプリを参照し、接続詳細をフロントエンド Web UI アプリに渡します。 + +## バックエンド エージェント サービスへの Handoff パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs` を開き、コメント `// Create AzureOpenAIClient instance with EntraID authentication` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトに接続します。 + + ```csharp + // EntraID 認証で AzureOpenAIClient インスタンスを作成 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + + var url = new Uri(endpoint.GetAzureOpenAIResponsesEndpoint()); + var chatClient = new AzureOpenAIClient(url, credential) + .GetResponsesClient() + .AsIChatClient(model); + ``` + + コードの解説です。 + + - `new DefaultAzureCredential(...)`: API キーなしで Azure にログインします。ローカル マシンでは Azure CLI または Azure Developer CLI のログイン情報を使用し、Azure にデプロイされたアプリではマネージド ID を使用します。 + - `endpoint.GetAzureOpenAIResponsesEndpoint()`: Microsoft Foundry プロジェクト エンドポイントを Microsoft Foundry OpenAI エンドポイントに変換します。これは、Microsoft Foundry SDK が現在 Handoff パターンをサポートしていないためです。 + - `new AzureOpenAIClient(url, credential)`: エンドポイントとログイン情報を使用して Azure OpenAI インスタンスに接続し、`IChatClient` インスタンスに変換します。 + +1. 同じファイルで、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトからエージェントの詳細を取得し、IoC コンテナーにシングルトン サービスとして登録します。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + foreach (var agentSettings in agents) + { + var instruction = await File.ReadAllTextAsync( + Path.Combine(AppContext.BaseDirectory, "Prompts", $"{agentSettings.Name}.txt")); + + var agent = new ChatClientAgent( + chatClient, + instructions: instruction, + name: agentSettings.Name); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + コードの解説です。 + + - エージェントのリストは既に分かっていますが、名前のみ分かっています。そのため、コードは各エージェントに対して `foreach` ループを実行します。 + - `await File.ReadAllTextAsync(...)`: エージェントの指示ファイルをインポートします。 + - `new ChatClientAgent(chatClient, instructions, name)`: 各エージェントの情報、指示、および `IChatClient` インスタンスを使用して、エージェント インスタンスを作成します。 + - `builder.Services.AddKeyedSingleton(name, agent)`: エージェント インスタンスをシングルトン サービスとして登録します。 + +1. 同じファイルで、コメント `// Build a handoff workflow pattern with the agents registered` を見つけて、そのすぐ下にコードを追加します。 + + ```csharp + // 登録されたエージェントで Handoff ワークフロー パターンを構築 + builder.AddWorkflow("publisher", (sp, key) => + { + var triage = sp.GetRequiredKeyedService("triage-agent"); + var generalSupport = sp.GetRequiredKeyedService("general-support-agent"); + var networkSpecialist = sp.GetRequiredKeyedService("network-specialist-agent"); + var warranty = sp.GetRequiredKeyedService("warranty-agent"); + + var specialists = new[] { generalSupport, networkSpecialist, warranty }; + + var workflow = AgentWorkflowBuilder.CreateHandoffBuilderWith(triage) + // トリアージはどの専門エージェントにもハンドオフ可能 + .WithHandoffs(triage, specialists) + // 各専門エージェントは他の専門エージェントにハンドオフ可能 + .WithHandoffs(generalSupport, [networkSpecialist, warranty]) + .WithHandoffs(networkSpecialist, [generalSupport, warranty]) + .WithHandoffs(warranty, [generalSupport, networkSpecialist]) + // すべての専門エージェントはトリアージに戻す + .WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing") + .Build(); + + // HandoffWorkflowBuilder.Build() はワークフロー名を設定しません。 + // AddWorkflow の名前検証を通過するためにリフレクションで設定します。 + typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key); + + return workflow; + }).AddAsAIAgent("publisher"); + ``` + + コードの解説です。 + + - `var specialists = new[] { generalSupport, networkSpecialist, warranty };`: グループ チャットに参加する専門エージェントのリストを定義します。トリアージ エージェントは、ユーザーのリクエストを専門エージェントの1つにルーティングする出発点です。 + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: マルチエージェント ワークフローを `publisher` という名前の別のエージェント インスタンスとして追加し、シングルトンとして登録します。 + - `AgentWorkflowBuilder.CreateHandoffBuilderWith(triage)`: トリアージ エージェントを使用した Handoff ワークフロー ビルダーです。 + - `.WithHandoffs(triage, specialists)`: トリアージ エージェントから専門エージェントへのハンドオフを定義します。 + - `.WithHandoffs(generalSupport, [networkSpecialist, warranty])`: 一般サポート エージェントから他の専門エージェントへのハンドオフを定義します。 + - `.WithHandoffs(networkSpecialist, [generalSupport, warranty])`: ネットワーク スペシャリスト エージェントから他の専門エージェントへのハンドオフを定義します。 + - `.WithHandoffs(warranty, [generalSupport, networkSpecialist])`: 保証エージェントから他の専門エージェントへのハンドオフを定義します。 + - `.WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing")`: 問題が解決したか、さらにルーティングが必要な場合に、すべての専門エージェントからトリアージ エージェントへのハンドオフを定義します。 + - `typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key);`: ワークフロー名を注入します。これは一時的な回避策です。 + +1. 同じファイルで、コメント `// Map AGUI to the publisher workflow agent` を見つけて、そのすぐ下にコードを追加します。ワークフローは `ag-ui` の API エンドポイントとして公開され、フロントエンド Web UI がこのバックエンド エージェント サービス アプリと通信できるようになります。 + + ```csharp + // AGUI を publisher ワークフロー エージェントにマッピング + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + .CreateFixedAgent() + ); + ``` + + `.CreateFixedAgent()` は、出力ストリームが適切に処理されるまでの一時的な回避策であることに注意してください。 + +## フロントエンド Web UI への Handoff パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs` を開き、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、すべてのエージェントの詳細が登録され、Web UI がどのエージェントが応答しているかを把握できるようになります。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + builder.Services.AddSingleton(agents); + ``` + +1. 同じファイルで、コメント `// Register the backend agent service as an HTTP client` を見つけて、そのすぐ下にコードを追加します。Aspire は既にフロントエンド Web UI アプリにバックエンド エージェント サービスの接続詳細を提供しています。 + + ```csharp + // バックエンド エージェント サービスを HTTP クライアントとして登録 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 同じファイルで、コメント `// Register AGUI client` を見つけて、そのすぐ下にコードを追加します。この AGUI クライアントを使用して、フロントエンド Web UI アプリは `ag-ui` エンドポイント経由でバックエンド エージェント サービス アプリと通信します。 + + ```csharp + // AGUI クライアントを登録 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire の実行 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI と Azure Developer CLI の両方で Azure に既にログインしていることを確認してください。不明な場合は、[こちらの手順](./00-setup.md#azure-へのログイン) を再度実行してください。 + +1. 以下のコマンドを実行して、Aspire を通じてすべてのアプリを起動します。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire ダッシュボードが自動的に開きます。 + + ![Aspire ダッシュボード](../../../docs/images/step-03-image-01.png) + + バックエンド エージェント サービス アプリをクリックします。 + +1. Dev UI ページが開いたら、エージェントを `publisher` に変更して、トリアージ エージェントがリクエストを他のエージェントに配分する様子を確認します。 + + ![Microsoft Agent Framework Dev UI - Handoff パターン](../../../docs/images/step-03-image-02.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Dev UI - リクエストの送信](../../../docs/images/step-03-image-03.png) + + 画面の左側で結果とワークフローの進行状況を確認します。 + + ![Microsoft Agent Framework Dev UI - ワークフローの実行](../../../docs/images/step-03-image-04.png) + +1. Aspire ダッシュボードに戻り、Web UI アプリをクリックします。 + + ![Aspire ダッシュボード](../../../docs/images/step-03-image-05.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Chat UI - リクエストの送信](../../../docs/images/step-03-image-06.png) + + 結果を確認します。 + +1. `Ctrl`+`C` を押してすべての実行中のアプリを終了します。 + +## Azure へのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 以下のコマンドを実行して、フロントエンド Web UI とバックエンド エージェント サービス アプリの両方を Azure にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. 完了すると、ターミナル画面に Web UI アプリケーションの URL が表示されます。Web ブラウザーで開き、リクエストを送信します。 + + ![Azure Container Apps 上の Microsoft Agent Framework - リクエストの送信](../../../docs/images/step-03-image-07.png) + + 結果を確認します。 + +1. すべて完了したら、Azure からすべてのアプリとエージェントを削除します。 + + ```bash + # Web UI とエージェント サービス アプリの両方を削除します。 + azd down --purge --force + + # すべてのエージェントと Microsoft Foundry リソースを削除します。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +おめでとうございます! 🎉 3番目のマルチエージェント オーケストレーション シナリオ – Handoff パターンが完了しました。次に進みましょう! + +👈 [02: Concurrent Pattern](./02-concurrent-pattern.md) | [04: Group Chat Pattern](./04-group-chat-pattern.md) 👉 diff --git a/localization/ja-jp/docs/04-group-chat-pattern.md b/localization/ja-jp/docs/04-group-chat-pattern.md new file mode 100644 index 0000000..b269aa1 --- /dev/null +++ b/localization/ja-jp/docs/04-group-chat-pattern.md @@ -0,0 +1,421 @@ +# 04 Group Chat パターン + +Group Chat パターンでは、複数のエージェントが共有の会話に参加し、順番にそれぞれの専門知識を提供します。オーケストレーターがディスカッションの流れを管理し、次にどのエージェントが発言するか、いつ会話を終了するかを決定します。これは、クロスファンクショナルな計画、クリエイティブなブレインストーミング、または多様な視点が反復的にやり取りし、お互いの意見を積み上げる必要があるタスクに適しています。 + +## シナリオ + +クロスファンクショナルなプロダクトチームで新製品の発売を計画しており、エージェントを使用します – プロダクト戦略エージェント、ユーザー エクスペリエンス エージェント、テクニカル エージェント、およびビジネス エージェントです。 + +
+ アーキテクチャ - Group Chat パターン +
+ +## リポジトリ ルートの取得 + +1. まず `$REPOSITORY_ROOT` 変数を取得します。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## スタート プロジェクトのコピー + +1. すでに `workshop` ディレクトリがある場合は、先にリネームまたは削除してください。 + +1. セットアップ スクリプトを実行して、スタート プロジェクトを `workshop` ディレクトリにコピーします。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 04-group-chat-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 04-group-chat-pattern + ``` + +## エージェントのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` ディレクトリに移動します。 + + ```bash + pushd resources-foundry + ``` + +1. 以下のコマンドを実行して、上記で定義したエージェントを Microsoft Foundry にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. プロビジョニングとデプロイが完了したら、以下のコマンドを実行して、エージェントが正常にデプロイされたことを確認します。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 4つのエージェント名が表示されるはずです。 + + ```text + business-agent + technical-agent + user-experience-agent + product-strategy-agent + ``` + +1. workshop ディレクトリに戻ります。 + + ```bash + popd + ``` + +## Aspire オーケストレーションの構成 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 必要なエージェント情報がすべて記録されていることを確認します。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP`、および `Foundry:Project:Endpoint` の値が表示されるはずです。 + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json` を開き、コメント行 `// Add agents` を見つけて、その下に `Agents` プロパティを追加します。 + + ```jsonc + { + ... + // エージェントを追加 + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs` を開き、コメント `// Add resource for Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトの接続詳細が追加されます。 + + ```csharp + // Microsoft Foundry のリソースを追加 + var foundry = builder.AddFoundry("foundry"); + ``` + + コードの解説です。 + + - `builder.AddFoundry("foundry")`: カスタム リソース `FoundryResource` を通じて Microsoft Foundry の接続詳細を追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add resource for agents on Microsoft Foundry` を見つけて、そのすぐ下にコードを追加します。これにより、エージェントの詳細リストが参照アプリケーションに公開されます。 + + ```csharp + // Microsoft Foundry 上のエージェントのリソースを追加 + var agents = builder.AddAgents("agents"); + ``` + + コードの解説です。 + + - `builder.AddAgents("agents")`: カスタム リソース `AgentResource` を通じてエージェントの詳細リストを追加します。Aspire のカスタム リソースについて詳しく知りたい場合は、[カスタム ホスティング統合の作成](https://aspire.dev/integrations/custom-integrations/hosting-integrations/) をご覧ください。 + +1. 同じファイルで、コメント `// Add backend agent service` を見つけて、そのすぐ下にコードを追加します。これにより、`foundry` リソースを参照するバックエンド エージェント サービスが定義されます – すべての Microsoft Foundry 接続詳細がバックエンド エージェント サービス アプリに渡されます。 + + ```csharp + // バックエンド エージェント サービスを追加 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + コードの解説です。 + + - `builder.AddProject("agent")`: バックエンド エージェント サービス アプリを .NET プロジェクトとして追加します。 + - `.WithReference(foundry)`: 上で作成した foundry リソースを参照し、Microsoft Foundry の接続詳細をバックエンド エージェント サービス アプリに渡します。 + +1. 同じファイルで、コメント `// Add frontend web UI` を見つけて、そのすぐ下にコードを追加します。これにより、`agents` と `agent` の両方のリソースを参照するフロントエンド Web UI が定義されます – エージェントの詳細とバックエンドの接続詳細の両方がフロントエンド Web UI アプリに渡されます。 + + ```csharp + // フロントエンド Web UI を追加 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + コードの解説です。 + + - `builder.AddProject("webui")`: フロントエンド Web UI アプリを .NET プロジェクトとして追加します。 + - `.WithExternalHttpEndpoints()`: このフロントエンド Web UI アプリをインターネットに公開し、パブリック アクセス可能にします。 + - `.WithReference(agents)`: 上で作成した agent リソースを参照し、エージェントのリストをフロントエンド Web UI アプリに渡します。 + - `.WithReference(agent)`: バックエンド エージェント サービス アプリを参照し、接続詳細をフロントエンド Web UI アプリに渡します。 + +## バックエンド エージェント サービスへの Group Chat パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs` を開き、コメント `// Create AIProjectClient instance with EntraID authentication` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトに接続します。 + + ```csharp + // EntraID 認証で AIProjectClient インスタンスを作成 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + コードの解説です。 + + - `new DefaultAzureCredential(...)`: API キーなしで Azure にログインします。ローカル マシンでは Azure CLI または Azure Developer CLI のログイン情報を使用し、Azure にデプロイされたアプリではマネージド ID を使用します。 + - `new AIProjectClient(endpoint, credential)`: エンドポイントとログイン情報を使用して Microsoft Foundry プロジェクト インスタンスに接続します。 + +1. 同じファイルで、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、Microsoft Foundry プロジェクトからエージェントの詳細を取得し、IoC コンテナーにシングルトン サービスとして登録します。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + コードの解説です。 + + - エージェントのリストは既に分かっていますが、名前のみ分かっています。そのため、コードは各エージェントに対して `foreach` ループを実行します。 + - `new AgentReference(name, version)`: 各エージェントの情報を使用して参照インスタンスを作成します。 + - `projectClient.AsAIAgent(reference, factory)`: 参照の詳細を使用して実際のエージェントに接続します。 + - `builder.Services.AddKeyedSingleton(name, agent)`: エージェント インスタンスをシングルトン サービスとして登録します。 + + > **注意**: `AgentRecordShimChatClient` クラスにお気づきかもしれません。これは Microsoft Agent Framework と Microsoft Foundry SDK 間のバージョンの不一致に対する一時的な回避策であり、まもなく削除される予定です。 + +1. 同じファイルで、コメント `// Build a group chat workflow pattern with the agents registered` を見つけて、そのすぐ下にコードを追加します。 + + ```csharp + // 登録されたエージェントで Group Chat ワークフロー パターンを構築 + builder.AddWorkflow("publisher", (sp, key) => + { + var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name)); + + return AgentWorkflowBuilder.CreateGroupChatBuilderWith(agentList => + new RoundRobinGroupChatManager(agentList) { MaximumIterationCount = participants.Count() * 2 }) + .AddParticipants(participants) + .WithName(key) + .Build(); + }).AddAsAIAgent("publisher"); + ``` + + コードの解説です。 + + - `var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name));`: グループ チャットに参加するエージェントのリストを特定します。 + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: マルチエージェント ワークフローを `publisher` という名前の別のエージェント インスタンスとして追加し、シングルトンとして登録します。 + - `AgentWorkflowBuilder.CreateGroupChatBuilderWith(...)`: 同じ名前 `publisher` を使用する Group Chat ワークフロー ビルダーです。 + - `new RoundRobinGroupChatManager(...)`: グループ チャットの戦略をラウンドロビンに設定します。また、最大反復回数を定義します。このコードでは、ラウンドロビン サイクル中に各エージェントが2回応答します。 + +1. 同じファイルで、コメント `// Map AGUI to the publisher workflow agent` を見つけて、そのすぐ下にコードを追加します。ワークフローは `ag-ui` の API エンドポイントとして公開され、フロントエンド Web UI がこのバックエンド エージェント サービス アプリと通信できるようになります。 + + ```csharp + // AGUI を publisher ワークフロー エージェントにマッピング + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## フロントエンド Web UI への Group Chat パターンの実装 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs` を開き、コメント `// Register all agents passed from Aspire` を見つけて、そのすぐ下にコードを追加します。これにより、すべてのエージェントの詳細が登録され、Web UI がどのエージェントが応答しているかを把握できるようになります。 + + ```csharp + // Aspire から渡されたすべてのエージェントを登録 + builder.Services.AddSingleton(agents); + ``` + +1. 同じファイルで、コメント `// Register the backend agent service as an HTTP client` を見つけて、そのすぐ下にコードを追加します。Aspire は既にフロントエンド Web UI アプリにバックエンド エージェント サービスの接続詳細を提供しています。 + + ```csharp + // バックエンド エージェント サービスを HTTP クライアントとして登録 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 同じファイルで、コメント `// Register AGUI client` を見つけて、そのすぐ下にコードを追加します。この AGUI クライアントを使用して、フロントエンド Web UI アプリは `ag-ui` エンドポイント経由でバックエンド エージェント サービス アプリと通信します。 + + ```csharp + // AGUI クライアントを登録 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire の実行 + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI と Azure Developer CLI の両方で Azure に既にログインしていることを確認してください。不明な場合は、[こちらの手順](./00-setup.md#azure-へのログイン) を再度実行してください。 + +1. 以下のコマンドを実行して、Aspire を通じてすべてのアプリを起動します。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire ダッシュボードが自動的に開きます。 + + ![Aspire ダッシュボード](../../../docs/images/step-04-image-01.png) + + バックエンド エージェント サービス アプリをクリックします。 + +1. Dev UI ページが開いたら、エージェントを `publisher` に変更し、「Configure & Run」ボタンをクリックします。 + + ![Microsoft Agent Framework Dev UI - Group Chat パターン](../../../docs/images/step-04-image-02.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Dev UI - リクエストの送信](../../../docs/images/step-04-image-03.png) + + 画面の左側で結果とワークフローの進行状況を確認します。 + + ![Microsoft Agent Framework Dev UI - ワークフローの実行](../../../docs/images/step-04-image-04.png) + +1. Aspire ダッシュボードに戻り、Web UI アプリをクリックします。 + + ![Aspire ダッシュボード](../../../docs/images/step-04-image-05.png) + +1. 任意のリクエストを送信します。 + + ![Microsoft Agent Framework Chat UI - リクエストの送信](../../../docs/images/step-04-image-06.png) + + 結果を確認します。 + +1. `Ctrl`+`C` を押してすべての実行中のアプリを終了します。 + +## Azure へのデプロイ + +1. `workshop` ディレクトリにいることを確認してください。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 以下のコマンドを実行して、フロントエンド Web UI とバックエンド エージェント サービス アプリの両方を Azure にプロビジョニングおよびデプロイします。 + + ```bash + azd up + ``` + + プロビジョニング中に、環境名、Azure サブスクリプション、およびロケーションの入力を求められます。 + +1. 完了すると、ターミナル画面に Web UI アプリケーションの URL が表示されます。Web ブラウザーで開き、リクエストを送信します。 + + ![Azure Container Apps 上の Microsoft Agent Framework - リクエストの送信](../../../docs/images/step-04-image-07.png) + + 結果を確認します。 + +1. すべて完了したら、Azure からすべてのアプリとエージェントを削除します。 + + ```bash + # Web UI とエージェント サービス アプリの両方を削除します。 + azd down --purge --force + + # すべてのエージェントと Microsoft Foundry リソースを削除します。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +おめでとうございます! 🎉 4番目のマルチエージェント オーケストレーション シナリオ – Group Chat パターンが完了しました。お疲れさまでした! + +👈 [03: Handoff Pattern](./03-handoff-pattern.md) | [README](../README.md) 👉 diff --git a/localization/ja-jp/docs/README.md b/localization/ja-jp/docs/README.md new file mode 100644 index 0000000..793e367 --- /dev/null +++ b/localization/ja-jp/docs/README.md @@ -0,0 +1,10 @@ +# マルチエージェント ワークショップ資料 + +マルチエージェント オーケストレーション パターンを構築するためのワークショップ資料とコードサンプルの一覧です。 + +| ドキュメント | コードサンプル | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](./01-sequential-pattern.md) | [01-sequential-pattern](../samples/01-sequential-pattern) | +| [02-concurrent-pattern.md](./02-concurrent-pattern.md) | [02-concurrent-pattern](../samples/02-concurrent-pattern) | +| [03-handoff-pattern.md](./03-handoff-pattern.md) | [03-handoff-pattern](../samples/03-handoff-pattern) | +| [04-group-chat-pattern.md](./04-group-chat-pattern.md) | [04-group-chat-pattern](../samples/04-group-chat-pattern) | diff --git a/localization/ja-jp/samples/01-sequential-pattern/README.md b/localization/ja-jp/samples/01-sequential-pattern/README.md new file mode 100644 index 0000000..c5df166 --- /dev/null +++ b/localization/ja-jp/samples/01-sequential-pattern/README.md @@ -0,0 +1,13 @@ +# 01 シーケンシャルパターン + +シーケンシャルパターンでは、エージェントが定義されたパイプラインの中で順番に動作し、各エージェントの出力が次のエージェントへの入力となります。このアプローチは、コンテンツ作成ワークフロー、段階的なデータ変換、ステップバイステップの分析など、自然な進行に従うタスクに適しています。 + +
+ アーキテクチャ - シーケンシャルパターン +
+ +## 手順 + +[start](../../../../samples/01-sequential-pattern/start) プロジェクトを使用して、[01-sequential-pattern.md](../../docs/01-sequential-pattern.md) の手順に従ってください。 + +完了したら、ご自身の成果物を [complete](../../../../samples/01-sequential-pattern/complete) プロジェクトと比較してください。 diff --git a/localization/ja-jp/samples/02-concurrent-pattern/README.md b/localization/ja-jp/samples/02-concurrent-pattern/README.md new file mode 100644 index 0000000..b119073 --- /dev/null +++ b/localization/ja-jp/samples/02-concurrent-pattern/README.md @@ -0,0 +1,13 @@ +# 02 コンカレントパターン + +コンカレントパターンでは、複数のエージェントが同じ入力を同時に分析し、それぞれが独自の専門知識を発揮します。すべてのエージェントが完了すると、それぞれの出力が統合された結果にまとめられます。これは、多角的な分析、アンサンブル評価、協調的な意思決定など、複数の視点から同時に取り組むことで効果が高まるタスクに最適です。 + +
+ アーキテクチャ - コンカレントパターン +
+ +## 手順 + +[start](../../../../samples/02-concurrent-pattern/start) プロジェクトを使用して、[02-concurrent-pattern.md](../../docs/02-concurrent-pattern.md) の手順に従ってください。 + +完了したら、ご自身の成果物を [complete](../../../../samples/02-concurrent-pattern/complete) プロジェクトと比較してください。 diff --git a/localization/ja-jp/samples/03-handoff-pattern/README.md b/localization/ja-jp/samples/03-handoff-pattern/README.md new file mode 100644 index 0000000..724092d --- /dev/null +++ b/localization/ja-jp/samples/03-handoff-pattern/README.md @@ -0,0 +1,13 @@ +# 03 ハンドオフパターン + +ハンドオフパターンでは、エージェントが会話のコンテキストに基づいて動的に制御を相互に引き渡します。トリアージエージェントが最初のリクエストを受け取り、それを処理するのに最も適した専門エージェントに振り分けます。問題が異なる領域にまたがる場合、専門エージェント同士でリダイレクトすることもできます。これは、ITサポート、カスタマーサービス、または異なる段階で異なる専門知識が必要なワークフローなどのシナリオに適しています。 + +
+ アーキテクチャ - ハンドオフパターン +
+ +## 手順 + +[start](../../../../samples/03-handoff-pattern/start) プロジェクトを使用して、[03-handoff-pattern.md](../../docs/03-handoff-pattern.md) の手順に従ってください。 + +完了したら、ご自身の成果物を [complete](../../../../samples/03-handoff-pattern/complete) プロジェクトと比較してください。 diff --git a/localization/ja-jp/samples/04-group-chat-pattern/README.md b/localization/ja-jp/samples/04-group-chat-pattern/README.md new file mode 100644 index 0000000..dd1b532 --- /dev/null +++ b/localization/ja-jp/samples/04-group-chat-pattern/README.md @@ -0,0 +1,13 @@ +# 04 グループチャットパターン + +グループチャットパターンでは、複数のエージェントが共有の会話に参加し、交代でそれぞれの専門知識を提供します。オーケストレーターが議論の流れを管理し、次にどのエージェントが発言するか、いつ会話を終了するかを決定します。これは、部門横断的な計画立案、クリエイティブなブレインストーミング、または多様な視点が相互作用し、反復的にアイデアを発展させる必要があるタスクに適しています。 + +
+ アーキテクチャ - グループチャットパターン +
+ +## 手順 + +[start](../../../../samples/04-group-chat-pattern/start) プロジェクトを使用して、[04-group-chat-pattern.md](../../docs/04-group-chat-pattern.md) の手順に従ってください。 + +完了したら、ご自身の成果物を [complete](../../../../samples/04-group-chat-pattern/complete) プロジェクトと比較してください。 diff --git a/localization/ja-jp/samples/README.md b/localization/ja-jp/samples/README.md new file mode 100644 index 0000000..ff7ebea --- /dev/null +++ b/localization/ja-jp/samples/README.md @@ -0,0 +1,10 @@ +# マルチエージェントオーケストレーション コードサンプル + +以下は、マルチエージェントオーケストレーションパターンとそのコードサンプルの一覧です。 + +| ドキュメント | コードサンプル | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](../docs/01-sequential-pattern.md) | [01-sequential-pattern](./01-sequential-pattern) | +| [02-concurrent-pattern.md](../docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./02-concurrent-pattern) | +| [03-handoff-pattern.md](../docs/03-handoff-pattern.md) | [03-handoff-pattern](./03-handoff-pattern) | +| [04-group-chat-pattern.md](../docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./04-group-chat-pattern) | diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md new file mode 100644 index 0000000..39ec8f9 --- /dev/null +++ b/localization/ko-kr/README.md @@ -0,0 +1,65 @@ +# 멀티 에이전트 오케스트레이션 워크숍 + +이 워크숍은 [Microsoft Agent Framework](https://aka.ms/agent-framework), [Microsoft Foundry](https://aka.ms/microsoft-foundry), [Aspire](https://aspire.dev)를 활용하여 .NET 기반 멀티 에이전트 앱을 구축하는 실습 자료입니다. + +![MAF + Foundry 워크숍](../../images/hero.jpg) + +## 이 워크숍은 무엇을 위한 것인가요? + +단일 에이전트 앱을 만드는 것은 쉽습니다. 하지만 실제로는 여러 에이전트가 함께 협력해야 하는 사례가 많으며, 멀티 에이전트 앱을 구축하는 것은 단일 에이전트 앱만큼 간단하지 않습니다. [Microsoft Agent Framework](https://aka.ms/agent-framework)는 다섯 가지 멀티 에이전트 오케스트레이션 패턴을 제공합니다: + +| 패턴 | 설명 | +|----------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| +| [Sequential](https://learn.microsoft.com/agent-framework/workflows/orchestrations/sequential?pivots=programming-language-csharp) | 에이전트가 정의된 순서대로 하나씩 차례로 실행됩니다 | +| [Concurrent](https://learn.microsoft.com/agent-framework/workflows/orchestrations/concurrent?pivots=programming-language-csharp) | 에이전트가 병렬로 실행됩니다 | +| [Handoff](https://learn.microsoft.com/agent-framework/workflows/orchestrations/handoff?pivots=programming-language-csharp) | 에이전트가 컨텍스트에 따라 서로 제어권을 넘깁니다 | +| [Group Chat](https://learn.microsoft.com/agent-framework/workflows/orchestrations/group-chat?pivots=programming-language-csharp) | 에이전트가 공유 대화에서 협업합니다 | +| [Magentic](https://learn.microsoft.com/agent-framework/workflows/orchestrations/magentic?pivots=programming-language-python) | 관리자 에이전트가 전문 에이전트를 동적으로 조율합니다 | + +## 특징 + +이 워크숍에서는 Magentic 패턴을 제외한 모든 멀티 에이전트 오케스트레이션 패턴을 구축합니다. 각 패턴을 완료하면 다음과 같은 아키텍처를 갖게 됩니다: + +- [Blazor](https://blazor.net) 채팅 UI용 프론트엔드 +- [ASP.NET](https://asp.net) 백엔드 + [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) 에이전트 호스팅 +- [Aspire](https://aspire.dev) 클라우드 네이티브 앱 오케스트레이션 + +> [!NOTE] +> Microsoft Agent Framework SDK의 .NET 버전은 향후 릴리스에서 Magentic 패턴을 지원할 예정입니다. + +## 사전 요구 사항 + +- [Azure 구독 (무료)](http://azure.microsoft.com/free) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) 이상 +- [Visual Studio 2026](https://visualstudio.microsoft.com/downloads/) 또는 [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) +- [Docker Desktop](https://docs.docker.com/desktop/) 또는 동등한 도구 +- [GitHub CLI](https://cli.github.com) +- [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) +- [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) +- [Aspire CLI](https://aspire.dev/get-started/install-cli/) + +## 워크숍 세션 + +| 세션 | 문서 | 코드 샘플 | +|-----------------------|-------------------------------------------------------------|----------------------------------------------------------| +| 00 설정 | [00-setup.md](./docs/00-setup.md) | | +| 01 Sequential 패턴 | [01-sequential-pattern.md](./docs/01-sequential-pattern.md) | [01-sequential-pattern](./samples/01-sequential-pattern) | +| 02 Concurrent 패턴 | [02-concurrent-pattern.md](./docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./samples/02-concurrent-pattern) | +| 03 Handoff 패턴 | [03-handoff-pattern.md](./docs/03-handoff-pattern.md) | [03-handoff-pattern](./samples/03-handoff-pattern) | +| 04 Group Chat 패턴 | [04-group-chat-pattern.md](./docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./samples/04-group-chat-pattern) | + +## 원하는 언어를 선택하세요! + +이 워크숍 자료는 다음 언어로 제공됩니다. + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](../ja-jp/README.md) | [한국어](./README.md) | [Português](../pt-br/README.md) | [中文(简体)](../zh-cn/README.md) + +## 리소스 + +- [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Agent Framework - Workflow Orchestrations](https://learn.microsoft.com/agent-framework/workflows/orchestrations) +- [Microsoft Foundry](https://aka.ms/microsoft-foundry) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) +- [Model Context Protocol (MCP)](https://modelcontextprotocol.io) +- [Aspire](https://aspire.dev) diff --git a/localization/ko-kr/docs/00-setup.md b/localization/ko-kr/docs/00-setup.md new file mode 100644 index 0000000..29d1a3a --- /dev/null +++ b/localization/ko-kr/docs/00-setup.md @@ -0,0 +1,215 @@ +# 00 설정 + +이 세션에서는 로컬 머신 또는 GitHub Codespaces에서 개발 환경을 설정합니다. + +## 사전 요구 사항 + +- 웹 브라우저: [Microsoft Edge](https://microsoft.com/edge) 또는 [Google Chrome](http://chrome.google.com) +- [Azure 구독](https://azure.microsoft.com/free) + +## GitHub Codespaces에서 설정하기 + +워크숍을 위해 개발 환경 설정 시간을 절약하기 위해 GitHub Codespaces 사용을 강력히 권장합니다. 로컬 머신에서 개발 환경을 설정하려면 이 섹션을 건너뛰고 [VS Code에서 설정하기](#vs-code에서-설정하기) 섹션으로 이동하세요. + +1. 아래 버튼을 클릭하여 새로운 GitHub Codespaces 인스턴스를 생성합니다. + + [![새 GitHub Codespaces 인스턴스 생성](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/multi-agent-orchestration-workshop) + +1. 생성이 완료되면 다음 명령어를 실행하여 필요한 도구가 올바르게 설치되었는지 확인합니다. + + ```bash + # .NET SDK + dotnet --list-sdks + + # node.js + node --version + npm --version + + # PowerShell + pwsh --version + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +1. GitHub 로그인 상태를 확인합니다. + + ```bash + gh auth status + ``` + +1. 원격 저장소 정보를 확인합니다. + + ```bash + git remote -v + ``` + + 다음과 같이 표시되어야 합니다. + + ```text + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (push) + ``` + + 위 두 줄이 보이지 않으면 현재 GitHub Codespaces 인스턴스를 삭제하고 다시 생성하세요. + +1. GitHub Codespaces 인스턴스는 본인 계정 소유가 아니므로, 다음 명령어를 사용하여 저장소를 포크하여 소유권을 이전합니다. + + ```bash + git remote -v > remote.txt + git add . && git commit -m "Add remote.txt for forking" + ``` + + 아래와 같은 메시지가 표시될 수 있습니다: + + ```text + You don't have write access to the Azure-Samples/multi-agent-orchestration-workshop repository, so you cannot push changes to it. + To obtain write access we will point this codespace at your fork of Azure-Samples/multi-agent-orchestration-workshop, creating that fork if it doesn't exist. + + Would you like to proceed? + ``` + + `y`를 입력하여 계속합니다. 자동으로 본인 계정 아래에 저장소가 포크됩니다. + +1. 원격 저장소 상태를 확인합니다. + + ```bash + git remote -v + ``` + + 이번에는 다음과 같이 네 줄이 표시되어야 합니다. + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + + 위 네 줄이 보이지 않으면 GitHub Codespaces 인스턴스를 삭제하고 다시 생성하세요. + +## VS Code에서 설정하기 + +이미 GitHub Codespaces 인스턴스가 있다면 이 섹션을 건너뛰고 [Azure에 로그인하기](#azure에-로그인하기) 섹션으로 직접 이동하세요. + +1. 다음 도구를 머신에 설치합니다. + + - [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) + - [Docker Desktop](https://docs.docker.com/desktop/) 또는 동등한 도구 + - [GitHub CLI](https://cli.github.com) + - [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) + - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) + - [Aspire CLI](https://aspire.dev/get-started/install-cli/) + + 설치 후 다음 명령어를 실행하여 올바르게 설치되었는지 확인합니다. + + ```bash + # .NET SDK + dotnet --list-sdks + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +### GitHub에 로그인하기 + +1. GitHub에 로그인합니다. + + ```bash + gh auth login + ``` + + 로그인 후 다음 명령어를 실행하여 로그인 상태를 확인합니다. + + ```bash + gh auth status + ``` + +### 프로젝트 복제하기 + +1. 이 저장소를 로컬 머신으로 포크합니다. + + ```bash + gh repo fork Azure-Samples/multi-agent-orchestration-workshop --clone + ``` + +1. 복제된 디렉터리로 이동합니다. + + ```bash + cd multi-agent-orchestration-workshop + ``` + +1. 원격 저장소 상태를 확인합니다. + + ```bash + git remote -v + ``` + + 다음과 같이 네 줄이 표시되어야 합니다. + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + +1. VS Code에서 저장소를 엽니다. + + ```bash + code . + ``` + +## Azure에 로그인하기 + +1. Azure에 로그인합니다. + + ```bash + # Azure Developer CLI + azd auth login + + # Azure CLI + az login + ``` + + 로그인 후 다음 명령어를 실행하여 로그인 상태를 확인합니다. + + ```bash + # Azure Developer CLI + azd auth login --check-status + + # Azure Login + az account show + ``` + +--- + +축하합니다! 🎉 개발 환경 설정을 완료했습니다. 다음 단계로 진행합시다! + +👈 [README](../README.md) | [01: Sequential Pattern](./01-sequential-pattern.md) 👉 diff --git a/localization/ko-kr/docs/01-sequential-pattern.md b/localization/ko-kr/docs/01-sequential-pattern.md new file mode 100644 index 0000000..b6e5fa6 --- /dev/null +++ b/localization/ko-kr/docs/01-sequential-pattern.md @@ -0,0 +1,415 @@ +# 01 Sequential 패턴 + +Sequential 패턴에서는 에이전트가 정의된 파이프라인에서 하나씩 차례로 작업하며, 각 에이전트의 출력이 다음 에이전트의 입력으로 전달됩니다. 이 접근 방식은 콘텐츠 생성 워크플로, 단계별 데이터 변환 또는 단계적 분석과 같이 자연스러운 흐름을 따르는 작업에 적합합니다. + +## 시나리오 + +에이전트를 사용하여 기술 블로그 게시물을 작성합니다 – 리서치 에이전트, 아웃라이너 에이전트, 작성 에이전트, 편집 에이전트. + +
+ 아키텍처 - Sequential 패턴 +
+ +## 저장소 루트 가져오기 + +1. 먼저 `$REPOSITORY_ROOT` 변수를 가져옵니다. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 시작 프로젝트 복사하기 + +1. 이미 `workshop` 디렉터리가 있다면 먼저 이름을 변경하거나 삭제합니다. + +1. 설정 스크립트를 실행하여 시작 프로젝트를 `workshop` 디렉터리에 복사합니다. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 01-sequential-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 01-sequential-pattern + ``` + +## 에이전트 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` 디렉터리로 이동합니다. + + ```bash + pushd resources-foundry + ``` + +1. 다음 명령어를 실행하여 위에서 정의한 에이전트를 Microsoft Foundry에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 프로비저닝과 배포가 완료되면 다음 명령어를 실행하여 에이전트가 성공적으로 배포되었는지 확인합니다. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 네 개의 에이전트 이름이 표시되어야 합니다. + + ```text + editor-agent + writer-agent + outliner-agent + research-agent + ``` + +1. workshop 디렉터리로 돌아갑니다. + + ```bash + popd + ``` + +## Aspire 오케스트레이션 구성하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 필요한 모든 에이전트 정보가 기록되었는지 확인합니다. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP`, `Foundry:Project:Endpoint` 값이 표시되어야 합니다. + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs`를 열고, `// Add resource for Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트 연결 정보를 추가합니다. + + ```csharp + // Microsoft Foundry 리소스 추가 + var foundry = builder.AddFoundry("foundry"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddFoundry("foundry")`: 커스텀 리소스 `FoundryResource`를 통해 Microsoft Foundry 연결 정보를 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add resource for agents on Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 에이전트 세부 정보 목록을 참조하는 애플리케이션에 노출합니다. + + ```csharp + // Microsoft Foundry의 에이전트 리소스 추가 + var agents = builder.AddAgents("agents"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddAgents("agents")`: 커스텀 리소스 `AgentResource`를 통해 에이전트 세부 정보 목록을 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add backend agent service` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `foundry` 리소스를 참조하는 백엔드 에이전트 서비스를 정의합니다 – 모든 Microsoft Foundry 연결 정보가 백엔드 에이전트 서비스 앱으로 전달됩니다. + + ```csharp + // 백엔드 에이전트 서비스 추가 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("agent")`: 백엔드 에이전트 서비스 앱을 .NET 프로젝트로 추가합니다. + - `.WithReference(foundry)`: 위에서 생성한 foundry 리소스를 참조하여 Microsoft Foundry 연결 정보를 백엔드 에이전트 서비스 앱으로 전달합니다. + +1. 같은 파일에서 `// Add frontend web UI` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `agents`와 `agent` 리소스를 모두 참조하는 프론트엔드 웹 UI를 정의합니다 – 에이전트 세부 정보와 백엔드 연결 정보가 모두 프론트엔드 웹 UI 앱으로 전달됩니다. + + ```csharp + // 프론트엔드 웹 UI 추가 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("webui")`: 프론트엔드 웹 UI 앱을 .NET 프로젝트로 추가합니다. + - `.WithExternalHttpEndpoints()`: 이 프론트엔드 웹 UI 앱을 인터넷에 노출하여 공개적으로 접근할 수 있게 합니다. + - `.WithReference(agents)`: 위에서 생성한 에이전트 리소스를 참조하여 에이전트 목록을 프론트엔드 웹 UI 앱으로 전달합니다. + - `.WithReference(agent)`: 백엔드 에이전트 서비스 앱을 참조하여 연결 정보를 프론트엔드 웹 UI 앱으로 전달합니다. + +## 백엔드 에이전트 서비스에서 Sequential 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs`를 열고, `// Create AIProjectClient instance with EntraID authentication` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에 연결합니다. + + ```csharp + // EntraID 인증으로 AIProjectClient 인스턴스 생성 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + 코드를 분석해 봅시다. + + - `new DefaultAzureCredential(...)`: API 키 없이 Azure에 로그인합니다. 로컬 머신에서는 Azure CLI 또는 Azure Developer CLI 로그인 정보를 사용하고, Azure에 앱이 배포되면 Managed Identity를 사용합니다. + - `new AIProjectClient(endpoint, credential)`: 엔드포인트와 로그인 정보를 사용하여 Microsoft Foundry 프로젝트 인스턴스에 연결합니다. + +1. 같은 파일에서 `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에서 에이전트 세부 정보를 가져와 IoC 컨테이너에 싱글톤 서비스로 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 코드를 분석해 봅시다. + + - 에이전트 목록은 이미 알고 있지만 이름만 알고 있으므로, 코드는 각 에이전트에 대해 `foreach` 루프를 실행합니다. + - `new AgentReference(name, version)`: 각 에이전트의 정보를 사용하여 참조 인스턴스를 생성합니다. + - `projectClient.AsAIAgent(reference, factory)`: 참조 정보를 사용하여 실제 에이전트에 연결합니다. + - `builder.Services.AddKeyedSingleton(name, agent)`: 에이전트 인스턴스를 싱글톤 서비스로 등록합니다. + + > **참고**: `AgentRecordShimChatClient` 클래스를 발견할 수 있습니다. 이 클래스는 Microsoft Agent Framework와 Microsoft Foundry SDK 간의 버전 불일치에 대한 임시 해결 방법이며, 곧 제거될 예정입니다. + +1. 같은 파일에서 `// Build a sequential workflow pattern with the agents registered` 주석을 찾아 바로 아래에 코드를 추가합니다. + + ```csharp + // 등록된 에이전트로 Sequential 워크플로 패턴 구축 + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [.. agents.Select(a => sp.GetRequiredKeyedService(a.Name))] + )).AddAsAIAgent("publisher"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: 멀티 에이전트 워크플로를 `publisher`라는 또 다른 에이전트 인스턴스로 추가하고 싱글톤으로 등록합니다. + - `AgentWorkflowBuilder.BuildSequential(...)`: 동일한 이름 `publisher`를 사용하는 Sequential 워크플로 빌더입니다. + + 이전에 등록된 서비스에서 `agents` 배열에 선언된 순서대로 여러 에이전트를 추가하는 점에 주목하세요. + +1. 같은 파일에서 `// Map AGUI to the publisher workflow agent` 주석을 찾아 바로 아래에 코드를 추가합니다. 워크플로는 `ag-ui` API 엔드포인트로 노출되어 프론트엔드 웹 UI가 이 백엔드 에이전트 서비스 앱과 통신할 수 있습니다. + + ```csharp + // publisher 워크플로 에이전트에 AGUI 매핑 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## 프론트엔드 웹 UI에서 Sequential 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs`를 열고, `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 웹 UI가 어떤 에이전트가 응답하는지 알 수 있도록 모든 에이전트 세부 정보를 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + builder.Services.AddSingleton(agents); + ``` + +1. 같은 파일에서 `// Register the backend agent service as an HTTP client` 주석을 찾아 바로 아래에 코드를 추가합니다. Aspire가 이미 프론트엔드 웹 UI 앱에 백엔드 에이전트 서비스의 연결 정보를 제공합니다. + + ```csharp + // 백엔드 에이전트 서비스를 HTTP 클라이언트로 등록 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 같은 파일에서 `// Register AGUI client` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 AGUI 클라이언트를 사용하여 프론트엔드 웹 UI 앱이 `ag-ui` 엔드포인트를 통해 백엔드 에이전트 서비스 앱과 통신합니다. + + ```csharp + // AGUI 클라이언트 등록 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire 실행하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI와 Azure Developer CLI를 모두 사용하여 이미 Azure에 로그인했는지 확인합니다. 확실하지 않다면 [이 단계](./00-setup.md#azure에-로그인하기)를 다시 따라하세요. + +1. 다음 명령어를 실행하여 Aspire를 통해 모든 앱을 시작합니다. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 대시보드가 자동으로 열립니다. + + ![Aspire 대시보드](../../../docs/images/step-01-image-01.png) + + 백엔드 에이전트 서비스 앱을 클릭합니다. + +1. Dev UI 페이지가 열리면 에이전트를 `publisher`로 변경하고 "Configure & Run" 버튼을 클릭합니다. + + ![Microsoft Agent Framework Dev UI - Sequential 패턴](../../../docs/images/step-01-image-02.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Dev UI - 요청 보내기](../../../docs/images/step-01-image-03.png) + + 결과를 확인하고 화면 왼쪽에서 워크플로가 어떻게 진행되는지 살펴보세요. + + ![Microsoft Agent Framework Dev UI - 워크플로 실행](../../../docs/images/step-01-image-04.png) + +1. Aspire 대시보드로 돌아가서 웹 UI 앱을 클릭합니다. + + ![Aspire 대시보드](../../../docs/images/step-01-image-05.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Chat UI - 요청 보내기](../../../docs/images/step-01-image-06.png) + + 결과를 확인합니다. + +1. `Ctrl`+`C`를 눌러 실행 중인 모든 앱을 종료합니다. + +## Azure에 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 다음 명령어를 실행하여 프론트엔드 웹 UI와 백엔드 에이전트 서비스 앱을 모두 Azure에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 완료되면 터미널 화면에 웹 UI 애플리케이션 URL이 표시됩니다. 웹 브라우저에서 열고 요청을 보내보세요. + + ![Azure Container Apps의 Microsoft Agent Framework - 요청 보내기](../../../docs/images/step-01-image-07.png) + + 결과를 확인합니다. + +1. 모든 작업이 완료되면 Azure에서 모든 앱과 에이전트를 삭제합니다. + + ```bash + # 웹 UI와 에이전트 서비스 앱을 모두 삭제합니다. + azd down --purge --force + + # 모든 에이전트와 Microsoft Foundry 리소스를 삭제합니다. + cd resources-foundry + azd down --purge --force + ``` + +--- + +축하합니다! 🎉 첫 번째 멀티 에이전트 오케스트레이션 시나리오인 Sequential 패턴을 완료했습니다. 다음 단계로 진행합시다! + +👈 [00: Setup](./00-setup.md) | [02: Concurrent Pattern](./02-concurrent-pattern.md) 👉 diff --git a/localization/ko-kr/docs/02-concurrent-pattern.md b/localization/ko-kr/docs/02-concurrent-pattern.md new file mode 100644 index 0000000..939dc5f --- /dev/null +++ b/localization/ko-kr/docs/02-concurrent-pattern.md @@ -0,0 +1,446 @@ +# 02 Concurrent 패턴 + +Concurrent 패턴에서는 여러 에이전트가 동일한 입력을 동시에 분석하며, 각 에이전트가 자신만의 전문성을 발휘합니다. 모든 에이전트가 완료되면 출력이 통합된 결과로 결합됩니다. 이 패턴은 다각적 분석, 앙상블 평가 또는 협력적 의사 결정과 같이 여러 관점이 동시에 작업하는 것이 유리한 작업에 이상적입니다. + +## 시나리오 + +벤처 캐피털 회사에서 에이전트를 사용하여 스타트업 피칭을 분석합니다 – 시장 분석 에이전트, 기술 실현 가능성 에이전트, 재무 모델 에이전트, 리스크 평가 에이전트, 집계 에이전트. + +
+ 아키텍처 - Concurrent 패턴 +
+ +## 저장소 루트 가져오기 + +1. 먼저 `$REPOSITORY_ROOT` 변수를 가져옵니다. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 시작 프로젝트 복사하기 + +1. 이미 `workshop` 디렉터리가 있다면 먼저 이름을 변경하거나 삭제합니다. + +1. 설정 스크립트를 실행하여 시작 프로젝트를 `workshop` 디렉터리에 복사합니다. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 02-concurrent-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 02-concurrent-pattern + ``` + +## 에이전트 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` 디렉터리로 이동합니다. + + ```bash + pushd resources-foundry + ``` + +1. 다음 명령어를 실행하여 위에서 정의한 에이전트를 Microsoft Foundry에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 프로비저닝과 배포가 완료되면 다음 명령어를 실행하여 에이전트가 성공적으로 배포되었는지 확인합니다. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 다섯 개의 에이전트 이름이 표시되어야 합니다. + + ```text + aggregator-agent + risk-assessment-agent + financial-model-agent + technology-feasibility-agent + market-analysis-agent + ``` + +1. workshop 디렉터리로 돌아갑니다. + + ```bash + popd + ``` + +## Aspire 오케스트레이션 구성하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 필요한 모든 에이전트 정보가 기록되었는지 확인합니다. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP`, `Foundry:Project:Endpoint` 값이 표시되어야 합니다. + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs`를 열고, `// Add resource for Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트 연결 정보를 추가합니다. + + ```csharp + // Microsoft Foundry 리소스 추가 + var foundry = builder.AddFoundry("foundry"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddFoundry("foundry")`: 커스텀 리소스 `FoundryResource`를 통해 Microsoft Foundry 연결 정보를 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add resource for agents on Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 에이전트 세부 정보 목록을 참조하는 애플리케이션에 노출합니다. + + ```csharp + // Microsoft Foundry의 에이전트 리소스 추가 + var agents = builder.AddAgents("agents"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddAgents("agents")`: 커스텀 리소스 `AgentResource`를 통해 에이전트 세부 정보 목록을 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add backend agent service` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `foundry` 리소스를 참조하는 백엔드 에이전트 서비스를 정의합니다 — 모든 Microsoft Foundry 연결 정보가 백엔드 에이전트 서비스 앱으로 전달됩니다. + + ```csharp + // 백엔드 에이전트 서비스 추가 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("agent")`: 백엔드 에이전트 서비스 앱을 .NET 프로젝트로 추가합니다. + - `.WithReference(foundry)`: 위에서 생성한 foundry 리소스를 참조하여 Microsoft Foundry 연결 정보를 백엔드 에이전트 서비스 앱으로 전달합니다. + +1. 같은 파일에서 `// Add frontend web UI` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `agents`와 `agent` 리소스를 모두 참조하는 프론트엔드 웹 UI를 정의합니다 — 에이전트 세부 정보와 백엔드 연결 정보가 모두 프론트엔드 웹 UI 앱으로 전달됩니다. + + ```csharp + // 프론트엔드 웹 UI 추가 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("webui")`: 프론트엔드 웹 UI 앱을 .NET 프로젝트로 추가합니다. + - `.WithExternalHttpEndpoints()`: 이 프론트엔드 웹 UI 앱을 인터넷에 노출하여 공개적으로 접근할 수 있게 합니다. + - `.WithReference(agents)`: 위에서 생성한 에이전트 리소스를 참조하여 에이전트 목록을 프론트엔드 웹 UI 앱으로 전달합니다. + - `.WithReference(agent)`: 백엔드 에이전트 서비스 앱을 참조하여 연결 정보를 프론트엔드 웹 UI 앱으로 전달합니다. + +## 백엔드 에이전트 서비스에서 Concurrent 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs`를 열고, `// Create AIProjectClient instance with EntraID authentication` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에 연결합니다. + + ```csharp + // EntraID 인증으로 AIProjectClient 인스턴스 생성 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + 코드를 분석해 봅시다. + + - `new DefaultAzureCredential(...)`: API 키 없이 Azure에 로그인합니다. 로컬 머신에서는 Azure CLI 또는 Azure Developer CLI 로그인 정보를 사용하고, Azure에 앱이 배포되면 Managed Identity를 사용합니다. + - `new AIProjectClient(endpoint, credential)`: 엔드포인트와 로그인 정보를 사용하여 Microsoft Foundry 프로젝트 인스턴스에 연결합니다. + +1. 같은 파일에서 `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에서 에이전트 세부 정보를 가져와 IoC 컨테이너에 싱글톤 서비스로 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 코드를 분석해 봅시다. + + - 에이전트 목록은 이미 알고 있지만 이름만 알고 있으므로, 코드는 각 에이전트에 대해 `foreach` 루프를 실행합니다. + - `new AgentReference(name, version)`: 각 에이전트의 정보를 사용하여 참조 인스턴스를 생성합니다. + - `projectClient.AsAIAgent(reference, factory)`: 참조 정보를 사용하여 실제 에이전트에 연결합니다. + - `builder.Services.AddKeyedSingleton(name, agent)`: 에이전트 인스턴스를 싱글톤 서비스로 등록합니다. + + > **참고**: `AgentRecordShimChatClient` 클래스를 발견할 수 있습니다. 이 클래스는 Microsoft Agent Framework와 Microsoft Foundry SDK 간의 버전 불일치에 대한 임시 해결 방법이며, 곧 제거될 예정입니다. + +1. 같은 파일에서 `// Build a concurrent workflow pattern with the agents registered` 주석을 찾아 바로 아래에 코드를 추가합니다. + + ```csharp + // 등록된 에이전트로 Concurrent 워크플로 패턴 구축 + var concurrentAgents = agents.Where(a => a.Name != "aggregator-agent"); + var aggregatorAgent = agents.SingleOrDefault(a => a.Name == "aggregator-agent"); + + builder.AddWorkflow("concurrent-analysis", (sp, key) => AgentWorkflowBuilder.BuildConcurrent( + workflowName: key, + agents: [.. concurrentAgents.Select(a => sp.GetRequiredKeyedService(a.Name))], + aggregator: null + )).AddAsAIAgent("concurrent-analysis"); + + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [ + sp.GetRequiredKeyedService("concurrent-analysis"), + sp.GetRequiredKeyedService(aggregatorAgent!.Name) + ] + )).AddAsAIAgent("publisher"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddWorkflow("concurrent-analysis", ...).AddAsAIAgent("concurrent-analysis")`: 멀티 에이전트 워크플로를 `concurrent-analysis`라는 또 다른 에이전트 인스턴스로 추가하고 싱글톤으로 등록합니다. + - `AgentWorkflowBuilder.BuildConcurrent(...)`: 동일한 이름 `concurrent-analysis`를 사용하는 Concurrent 워크플로 빌더입니다. + + 이전에 등록된 서비스에서 `agents` 배열에 선언된 여러 에이전트를 추가하는 점에 주목하세요. + + 또한 집계자에 `null`을 전달하여 Microsoft Foundry에서 제공하는 `aggregator-agent`를 대신 사용할 수 있도록 하는 점에도 주목하세요. + - `builder.AddWorkflow("publisher, ...).AddAsAIAgent("publisher")`: 멀티 에이전트 워크플로를 `publisher`라는 또 다른 에이전트 인스턴스로 추가하고 싱글톤으로 등록합니다. + - `AgentWorkflowBuilder.BuildSequential(...)`: 동일한 이름 `publisher`를 사용하는 Sequential 워크플로 빌더입니다. + + `concurrent-analysis` 워크플로와 `aggregator-agent`를 모두 추가하여 집계 에이전트가 Concurrent 워크플로에서 각 에이전트가 응답한 내용을 요약하도록 하는 점에 주목하세요. + +1. 같은 파일에서 `// Map AGUI to the publisher workflow agent` 주석을 찾아 바로 아래에 코드를 추가합니다. 워크플로는 `ag-ui` API 엔드포인트로 노출되어 프론트엔드 웹 UI가 이 백엔드 에이전트 서비스 앱과 통신할 수 있습니다. + + ```csharp + // publisher 워크플로 에이전트에 AGUI 매핑 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## 프론트엔드 웹 UI에서 Concurrent 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs`를 열고, `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 웹 UI가 어떤 에이전트가 응답하는지 알 수 있도록 모든 에이전트 세부 정보를 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + builder.Services.AddSingleton(agents); + ``` + +1. 같은 파일에서 `// Register the backend agent service as an HTTP client` 주석을 찾아 바로 아래에 코드를 추가합니다. Aspire가 이미 프론트엔드 웹 UI 앱에 백엔드 에이전트 서비스의 연결 정보를 제공합니다. + + ```csharp + // 백엔드 에이전트 서비스를 HTTP 클라이언트로 등록 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 같은 파일에서 `// Register AGUI client` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 AGUI 클라이언트를 사용하여 프론트엔드 웹 UI 앱이 `ag-ui` 엔드포인트를 통해 백엔드 에이전트 서비스 앱과 통신합니다. + + ```csharp + // AGUI 클라이언트 등록 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire 실행하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI와 Azure Developer CLI를 모두 사용하여 이미 Azure에 로그인했는지 확인합니다. 확실하지 않다면 [이 단계](./00-setup.md#azure에-로그인하기)를 다시 따라하세요. + +1. 다음 명령어를 실행하여 Aspire를 통해 모든 앱을 시작합니다. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 대시보드가 자동으로 열립니다. + + ![Aspire 대시보드](../../../docs/images/step-02-image-01.png) + + 백엔드 에이전트 서비스 앱을 클릭합니다. + +1. Dev UI 페이지가 열리면 에이전트를 `concurrent-analysis`로 변경하여 모든 에이전트가 동시에 실행되는 것을 확인합니다. + + ![Microsoft Agent Framework Dev UI - Concurrent 패턴](../../../docs/images/step-02-image-02.png) + + 그런 다음 에이전트를 `publisher`로 변경하여 Sequential 패턴이 `concurrent-analysis`와 `aggregator-agent`를 어떻게 결합하는지 확인합니다. + + ![Microsoft Agent Framework Dev UI - Sequential 패턴](../../../docs/images/step-02-image-03.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Dev UI - 요청 보내기](../../../docs/images/step-02-image-04.png) + + 결과를 확인하고 화면 왼쪽에서 워크플로가 어떻게 진행되는지 살펴보세요. + + ![Microsoft Agent Framework Dev UI - 워크플로 실행](../../../docs/images/step-02-image-05.png) + +1. Aspire 대시보드로 돌아가서 웹 UI 앱을 클릭합니다. + + ![Aspire 대시보드](../../../docs/images/step-02-image-06.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Chat UI - 요청 보내기](../../../docs/images/step-02-image-07.png) + + 결과를 확인합니다. + +1. `Ctrl`+`C`를 눌러 실행 중인 모든 앱을 종료합니다. + +## Azure에 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 다음 명령어를 실행하여 프론트엔드 웹 UI와 백엔드 에이전트 서비스 앱을 모두 Azure에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 완료되면 터미널 화면에 웹 UI 애플리케이션 URL이 표시됩니다. 웹 브라우저에서 열고 요청을 보내보세요. + + ![Azure Container Apps의 Microsoft Agent Framework - 요청 보내기](../../../docs/images/step-02-image-08.png) + + 결과를 확인합니다. + +1. 모든 작업이 완료되면 Azure에서 모든 앱과 에이전트를 삭제합니다. + + ```bash + # 웹 UI와 에이전트 서비스 앱을 모두 삭제합니다. + azd down --purge --force + + # 모든 에이전트와 Microsoft Foundry 리소스를 삭제합니다. + cd resources-foundry + azd down --purge --force + ``` + +--- + +축하합니다! 🎉 두 번째 멀티 에이전트 오케스트레이션 시나리오인 Concurrent 패턴을 완료했습니다. 다음 단계로 진행합시다! + +👈 [01: Sequential Pattern](./01-sequential-pattern.md) | [03: Handoff Pattern](./03-handoff-pattern.md) 👉 diff --git a/localization/ko-kr/docs/03-handoff-pattern.md b/localization/ko-kr/docs/03-handoff-pattern.md new file mode 100644 index 0000000..d11ed36 --- /dev/null +++ b/localization/ko-kr/docs/03-handoff-pattern.md @@ -0,0 +1,449 @@ +# 03 Handoff 패턴 + +Handoff 패턴에서는 에이전트가 대화 컨텍스트에 따라 동적으로 서로 제어권을 넘깁니다. 트리아지 에이전트가 초기 요청을 수신하고 이를 처리하기에 가장 적합한 전문가에게 라우팅합니다. 전문가는 문제가 여러 도메인에 걸쳐 있을 때 서로에게 리디렉션할 수도 있습니다. 이 패턴은 IT 지원, 고객 서비스 또는 단계마다 다른 전문 지식이 필요한 모든 워크플로에 적합합니다. + +## 시나리오 + +IT 지원 팀에서 에이전트를 사용하여 작업합니다 – 일반 지원 에이전트, 네트워크 전문가 에이전트, 보증 에이전트, 트리아지 에이전트. + +
+ 아키텍처 - Handoff 패턴 +
+ +## 저장소 루트 가져오기 + +1. 먼저 `$REPOSITORY_ROOT` 변수를 가져옵니다. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 시작 프로젝트 복사하기 + +1. 이미 `workshop` 디렉터리가 있다면 먼저 이름을 변경하거나 삭제합니다. + +1. 설정 스크립트를 실행하여 시작 프로젝트를 `workshop` 디렉터리에 복사합니다. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 03-handoff-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 03-handoff-pattern + ``` + +## 에이전트 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` 디렉터리로 이동합니다. + + ```bash + pushd resources-foundry + ``` + +1. 다음 명령어를 실행하여 위에서 정의한 에이전트를 Microsoft Foundry에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 프로비저닝과 배포가 완료되면 다음 명령어를 실행하여 에이전트가 성공적으로 배포되었는지 확인합니다. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 네 개의 에이전트 이름이 표시되어야 합니다. + + ```text + warranty-agent + network-specialist-agent + general-support-agent + triage-agent + ``` + +1. workshop 디렉터리로 돌아갑니다. + + ```bash + popd + ``` + +## Aspire 오케스트레이션 구성하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 필요한 모든 에이전트 정보가 기록되었는지 확인합니다. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP`, `Foundry:Project:Endpoint` 값이 표시되어야 합니다. + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs`를 열고, `// Add resource for Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트 연결 정보를 추가합니다. + + ```csharp + // Microsoft Foundry 리소스 추가 + var foundry = builder.AddFoundry("foundry"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddFoundry("foundry")`: 커스텀 리소스 `FoundryResource`를 통해 Microsoft Foundry 연결 정보를 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add resource for agents on Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 에이전트 세부 정보 목록을 참조하는 애플리케이션에 노출합니다. + + ```csharp + // Microsoft Foundry의 에이전트 리소스 추가 + var agents = builder.AddAgents("agents"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddAgents("agents")`: 커스텀 리소스 `AgentResource`를 통해 에이전트 세부 정보 목록을 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add backend agent service` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `foundry` 리소스를 참조하는 백엔드 에이전트 서비스를 정의합니다 — 모든 Microsoft Foundry 연결 정보가 백엔드 에이전트 서비스 앱으로 전달됩니다. + + ```csharp + // 백엔드 에이전트 서비스 추가 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("agent")`: 백엔드 에이전트 서비스 앱을 .NET 프로젝트로 추가합니다. + - `.WithReference(foundry)`: 위에서 생성한 foundry 리소스를 참조하여 Microsoft Foundry 연결 정보를 백엔드 에이전트 서비스 앱으로 전달합니다. + +1. 같은 파일에서 `// Add frontend web UI` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `agents`와 `agent` 리소스를 모두 참조하는 프론트엔드 웹 UI를 정의합니다 — 에이전트 세부 정보와 백엔드 연결 정보가 모두 프론트엔드 웹 UI 앱으로 전달됩니다. + + ```csharp + // 프론트엔드 웹 UI 추가 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("webui")`: 프론트엔드 웹 UI 앱을 .NET 프로젝트로 추가합니다. + - `.WithExternalHttpEndpoints()`: 이 프론트엔드 웹 UI 앱을 인터넷에 노출하여 공개적으로 접근할 수 있게 합니다. + - `.WithReference(agents)`: 위에서 생성한 에이전트 리소스를 참조하여 에이전트 목록을 프론트엔드 웹 UI 앱으로 전달합니다. + - `.WithReference(agent)`: 백엔드 에이전트 서비스 앱을 참조하여 연결 정보를 프론트엔드 웹 UI 앱으로 전달합니다. + +## 백엔드 에이전트 서비스에서 Handoff 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs`를 열고, `// Create AzureOpenAIClient instance with EntraID authentication` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에 연결합니다. + + ```csharp + // EntraID 인증으로 AzureOpenAIClient 인스턴스 생성 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + + var url = new Uri(endpoint.GetAzureOpenAIResponsesEndpoint()); + var chatClient = new AzureOpenAIClient(url, credential) + .GetResponsesClient() + .AsIChatClient(model); + ``` + + 코드를 분석해 봅시다. + + - `new DefaultAzureCredential(...)`: API 키 없이 Azure에 로그인합니다. 로컬 머신에서는 Azure CLI 또는 Azure Developer CLI 로그인 정보를 사용하고, Azure에 앱이 배포되면 Managed Identity를 사용합니다. + - `endpoint.GetAzureOpenAIResponsesEndpoint()`: Microsoft Foundry SDK가 현재 Handoff 패턴을 지원하지 않으므로 Microsoft Foundry 프로젝트 엔드포인트를 Microsoft Foundry OpenAI 엔드포인트로 변환합니다. + - `new AzureOpenAIClient(url, credential)`: 엔드포인트와 로그인 정보를 사용하여 Azure OpenAI 인스턴스에 연결하고 `IChatClient` 인스턴스로 변환합니다. + +1. 같은 파일에서 `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에서 에이전트 세부 정보를 가져와 IoC 컨테이너에 싱글톤 서비스로 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + foreach (var agentSettings in agents) + { + var instruction = await File.ReadAllTextAsync( + Path.Combine(AppContext.BaseDirectory, "Prompts", $"{agentSettings.Name}.txt")); + + var agent = new ChatClientAgent( + chatClient, + instructions: instruction, + name: agentSettings.Name); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 코드를 분석해 봅시다. + + - 에이전트 목록은 이미 알고 있지만 이름만 알고 있으므로, 코드는 각 에이전트에 대해 `foreach` 루프를 실행합니다. + - `await File.ReadAllTextAsync(...)`: 에이전트 지시 사항 파일을 가져옵니다. + - `new ChatClientAgent(chatClient, instructions, name)`: 각 에이전트의 정보, 지시 사항, `IChatClient` 인스턴스를 사용하여 에이전트 인스턴스를 생성합니다. + - `builder.Services.AddKeyedSingleton(name, agent)`: 에이전트 인스턴스를 싱글톤 서비스로 등록합니다. + +1. 같은 파일에서 `// Build a handoff workflow pattern with the agents registered` 주석을 찾아 바로 아래에 코드를 추가합니다. + + ```csharp + // 등록된 에이전트로 Handoff 워크플로 패턴 구축 + builder.AddWorkflow("publisher", (sp, key) => + { + var triage = sp.GetRequiredKeyedService("triage-agent"); + var generalSupport = sp.GetRequiredKeyedService("general-support-agent"); + var networkSpecialist = sp.GetRequiredKeyedService("network-specialist-agent"); + var warranty = sp.GetRequiredKeyedService("warranty-agent"); + + var specialists = new[] { generalSupport, networkSpecialist, warranty }; + + var workflow = AgentWorkflowBuilder.CreateHandoffBuilderWith(triage) + // 트리아지가 모든 전문가에게 핸드오프 가능 + .WithHandoffs(triage, specialists) + // 각 전문가가 다른 전문가에게 핸드오프 가능 + .WithHandoffs(generalSupport, [networkSpecialist, warranty]) + .WithHandoffs(networkSpecialist, [generalSupport, warranty]) + .WithHandoffs(warranty, [generalSupport, networkSpecialist]) + // 모든 전문가가 트리아지로 다시 핸드오프 + .WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing") + .Build(); + + // HandoffWorkflowBuilder.Build()는 워크플로 이름을 설정하지 않습니다. + // AddWorkflow의 이름 검증을 통과하기 위해 리플렉션으로 설정합니다. + typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key); + + return workflow; + }).AddAsAIAgent("publisher"); + ``` + + 코드를 분석해 봅시다. + + - `var specialists = new[] { generalSupport, networkSpecialist, warranty };`: 전문가 에이전트 목록을 정의합니다. 트리아지 에이전트는 사용자 요청을 전문가 에이전트 중 하나로 리라우팅하는 시작점입니다. + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: 멀티 에이전트 워크플로를 `publisher`라는 또 다른 에이전트 인스턴스로 추가하고 싱글톤으로 등록합니다. + - `AgentWorkflowBuilder.CreateHandoffBuilderWith(triage)`: 트리아지 에이전트를 사용한 Handoff 워크플로 빌더입니다. + - `.WithHandoffs(triage, specialists)`: 트리아지 에이전트에서 전문가 에이전트로의 핸드오프를 정의합니다. + - `.WithHandoffs(generalSupport, [networkSpecialist, warranty])`: 일반 지원 에이전트에서 다른 전문가 에이전트로의 핸드오프를 정의합니다. + - `.WithHandoffs(networkSpecialist, [generalSupport, warranty])`: 네트워크 전문가 에이전트에서 다른 전문가 에이전트로의 핸드오프를 정의합니다. + - `.WithHandoffs(warranty, [generalSupport, networkSpecialist])`: 보증 에이전트에서 다른 전문가 에이전트로의 핸드오프를 정의합니다. + - `.WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing")`: 문제가 해결되거나 추가 라우팅이 필요할 때 모든 전문가 에이전트에서 트리아지 에이전트로의 핸드오프를 정의합니다. + - `typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key);`: 워크플로 이름을 주입합니다. 이는 임시 해결 방법입니다. + +1. 같은 파일에서 `// Map AGUI to the publisher workflow agent` 주석을 찾아 바로 아래에 코드를 추가합니다. 워크플로는 `ag-ui` API 엔드포인트로 노출되어 프론트엔드 웹 UI가 이 백엔드 에이전트 서비스 앱과 통신할 수 있습니다. + + ```csharp + // publisher 워크플로 에이전트에 AGUI 매핑 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + .CreateFixedAgent() + ); + ``` + + `.CreateFixedAgent()`는 출력 스트림이 올바르게 처리될 때까지의 임시 해결 방법입니다. + +## 프론트엔드 웹 UI에서 Handoff 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs`를 열고, `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 웹 UI가 어떤 에이전트가 응답하는지 알 수 있도록 모든 에이전트 세부 정보를 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + builder.Services.AddSingleton(agents); + ``` + +1. 같은 파일에서 `// Register the backend agent service as an HTTP client` 주석을 찾아 바로 아래에 코드를 추가합니다. Aspire가 이미 프론트엔드 웹 UI 앱에 백엔드 에이전트 서비스의 연결 정보를 제공합니다. + + ```csharp + // 백엔드 에이전트 서비스를 HTTP 클라이언트로 등록 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 같은 파일에서 `// Register AGUI client` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 AGUI 클라이언트를 사용하여 프론트엔드 웹 UI 앱이 `ag-ui` 엔드포인트를 통해 백엔드 에이전트 서비스 앱과 통신합니다. + + ```csharp + // AGUI 클라이언트 등록 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire 실행하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI와 Azure Developer CLI를 모두 사용하여 이미 Azure에 로그인했는지 확인합니다. 확실하지 않다면 [이 단계](./00-setup.md#azure에-로그인하기)를 다시 따라하세요. + +1. 다음 명령어를 실행하여 Aspire를 통해 모든 앱을 시작합니다. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 대시보드가 자동으로 열립니다. + + ![Aspire 대시보드](../../../docs/images/step-03-image-01.png) + + 백엔드 에이전트 서비스 앱을 클릭합니다. + +1. Dev UI 페이지가 열리면 에이전트를 `publisher`로 변경하여 트리아지 에이전트가 요청을 다른 에이전트에게 분배하는 것을 확인합니다. + + ![Microsoft Agent Framework Dev UI - Handoff 패턴](../../../docs/images/step-03-image-02.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Dev UI - 요청 보내기](../../../docs/images/step-03-image-03.png) + + 결과를 확인하고 화면 왼쪽에서 워크플로가 어떻게 진행되는지 살펴보세요. + + ![Microsoft Agent Framework Dev UI - 워크플로 실행](../../../docs/images/step-03-image-04.png) + +1. Aspire 대시보드로 돌아가서 웹 UI 앱을 클릭합니다. + + ![Aspire 대시보드](../../../docs/images/step-03-image-05.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Chat UI - 요청 보내기](../../../docs/images/step-03-image-06.png) + + 결과를 확인합니다. + +1. `Ctrl`+`C`를 눌러 실행 중인 모든 앱을 종료합니다. + +## Azure에 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 다음 명령어를 실행하여 프론트엔드 웹 UI와 백엔드 에이전트 서비스 앱을 모두 Azure에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 완료되면 터미널 화면에 웹 UI 애플리케이션 URL이 표시됩니다. 웹 브라우저에서 열고 요청을 보내보세요. + + ![Azure Container Apps의 Microsoft Agent Framework - 요청 보내기](../../../docs/images/step-03-image-07.png) + + 결과를 확인합니다. + +1. 모든 작업이 완료되면 Azure에서 모든 앱과 에이전트를 삭제합니다. + + ```bash + # 웹 UI와 에이전트 서비스 앱을 모두 삭제합니다. + azd down --purge --force + + # 모든 에이전트와 Microsoft Foundry 리소스를 삭제합니다. + cd resources-foundry + azd down --purge --force + ``` + +--- + +축하합니다! 🎉 세 번째 멀티 에이전트 오케스트레이션 시나리오인 Handoff 패턴을 완료했습니다. 다음 단계로 진행합시다! + +👈 [02: Concurrent Pattern](./02-concurrent-pattern.md) | [04: Group Chat Pattern](./04-group-chat-pattern.md) 👉 diff --git a/localization/ko-kr/docs/04-group-chat-pattern.md b/localization/ko-kr/docs/04-group-chat-pattern.md new file mode 100644 index 0000000..5860a18 --- /dev/null +++ b/localization/ko-kr/docs/04-group-chat-pattern.md @@ -0,0 +1,421 @@ +# 04 Group Chat 패턴 + +Group Chat 패턴에서는 여러 에이전트가 공유 대화에 참여하여 차례로 자신의 전문성을 기여합니다. 오케스트레이터가 토론 흐름을 관리하고 어떤 에이전트가 다음에 발언하고 대화가 언제 끝나야 하는지 결정합니다. 이 패턴은 교차 기능 기획, 창의적 브레인스토밍 또는 다양한 관점이 반복적으로 상호 작용하고 서로를 기반으로 발전해야 하는 모든 작업에 적합합니다. + +## 시나리오 + +교차 기능 제품 팀에서 에이전트를 사용하여 신제품 출시를 계획합니다 – 제품 전략 에이전트, 사용자 경험 에이전트, 기술 에이전트, 비즈니스 에이전트. + +
+ 아키텍처 - Group Chat 패턴 +
+ +## 저장소 루트 가져오기 + +1. 먼저 `$REPOSITORY_ROOT` 변수를 가져옵니다. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 시작 프로젝트 복사하기 + +1. 이미 `workshop` 디렉터리가 있다면 먼저 이름을 변경하거나 삭제합니다. + +1. 설정 스크립트를 실행하여 시작 프로젝트를 `workshop` 디렉터리에 복사합니다. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 04-group-chat-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 04-group-chat-pattern + ``` + +## 에이전트 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.PromptAgent/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `resources-foundry` 디렉터리로 이동합니다. + + ```bash + pushd resources-foundry + ``` + +1. 다음 명령어를 실행하여 위에서 정의한 에이전트를 Microsoft Foundry에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 프로비저닝과 배포가 완료되면 다음 명령어를 실행하여 에이전트가 성공적으로 배포되었는지 확인합니다. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 네 개의 에이전트 이름이 표시되어야 합니다. + + ```text + business-agent + technical-agent + user-experience-agent + product-strategy-agent + ``` + +1. workshop 디렉터리로 돌아갑니다. + + ```bash + popd + ``` + +## Aspire 오케스트레이션 구성하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 필요한 모든 에이전트 정보가 기록되었는지 확인합니다. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP`, `Foundry:Project:Endpoint` 값이 표시되어야 합니다. + +1. `src/MultiAgentWorkshop.AppHost/appsettings.json`을 열고, `// Add agents` 주석 줄을 찾아 그 아래에 `Agents` 속성을 추가합니다. + + ```jsonc + { + ... + // 에이전트 추가 + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. `src/MultiAgentWorkshop.AppHost/AppHost.cs`를 열고, `// Add resource for Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트 연결 정보를 추가합니다. + + ```csharp + // Microsoft Foundry 리소스 추가 + var foundry = builder.AddFoundry("foundry"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddFoundry("foundry")`: 커스텀 리소스 `FoundryResource`를 통해 Microsoft Foundry 연결 정보를 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add resource for agents on Microsoft Foundry` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 에이전트 세부 정보 목록을 참조하는 애플리케이션에 노출합니다. + + ```csharp + // Microsoft Foundry의 에이전트 리소스 추가 + var agents = builder.AddAgents("agents"); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddAgents("agents")`: 커스텀 리소스 `AgentResource`를 통해 에이전트 세부 정보 목록을 추가합니다. Aspire 커스텀 리소스에 대해 자세히 알고 싶다면 [커스텀 호스팅 통합 만들기](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)를 참고하세요. + +1. 같은 파일에서 `// Add backend agent service` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `foundry` 리소스를 참조하는 백엔드 에이전트 서비스를 정의합니다 – 모든 Microsoft Foundry 연결 정보가 백엔드 에이전트 서비스 앱으로 전달됩니다. + + ```csharp + // 백엔드 에이전트 서비스 추가 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("agent")`: 백엔드 에이전트 서비스 앱을 .NET 프로젝트로 추가합니다. + - `.WithReference(foundry)`: 위에서 생성한 foundry 리소스를 참조하여 Microsoft Foundry 연결 정보를 백엔드 에이전트 서비스 앱으로 전달합니다. + +1. 같은 파일에서 `// Add frontend web UI` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 `agents`와 `agent` 리소스를 모두 참조하는 프론트엔드 웹 UI를 정의합니다 – 에이전트 세부 정보와 백엔드 연결 정보가 모두 프론트엔드 웹 UI 앱으로 전달됩니다. + + ```csharp + // 프론트엔드 웹 UI 추가 + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 코드를 분석해 봅시다. + + - `builder.AddProject("webui")`: 프론트엔드 웹 UI 앱을 .NET 프로젝트로 추가합니다. + - `.WithExternalHttpEndpoints()`: 이 프론트엔드 웹 UI 앱을 인터넷에 노출하여 공개적으로 접근할 수 있게 합니다. + - `.WithReference(agents)`: 위에서 생성한 에이전트 리소스를 참조하여 에이전트 목록을 프론트엔드 웹 UI 앱으로 전달합니다. + - `.WithReference(agent)`: 백엔드 에이전트 서비스 앱을 참조하여 연결 정보를 프론트엔드 웹 UI 앱으로 전달합니다. + +## 백엔드 에이전트 서비스에서 Group Chat 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.Agent/Program.cs`를 열고, `// Create AIProjectClient instance with EntraID authentication` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에 연결합니다. + + ```csharp + // EntraID 인증으로 AIProjectClient 인스턴스 생성 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + 코드를 분석해 봅시다. + + - `new DefaultAzureCredential(...)`: API 키 없이 Azure에 로그인합니다. 로컬 머신에서는 Azure CLI 또는 Azure Developer CLI 로그인 정보를 사용하고, Azure에 앱이 배포되면 Managed Identity를 사용합니다. + - `new AIProjectClient(endpoint, credential)`: 엔드포인트와 로그인 정보를 사용하여 Microsoft Foundry 프로젝트 인스턴스에 연결합니다. + +1. 같은 파일에서 `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 Microsoft Foundry 프로젝트에서 에이전트 세부 정보를 가져와 IoC 컨테이너에 싱글톤 서비스로 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 코드를 분석해 봅시다. + + - 에이전트 목록은 이미 알고 있지만 이름만 알고 있으므로, 코드는 각 에이전트에 대해 `foreach` 루프를 실행합니다. + - `new AgentReference(name, version)`: 각 에이전트의 정보를 사용하여 참조 인스턴스를 생성합니다. + - `projectClient.AsAIAgent(reference, factory)`: 참조 정보를 사용하여 실제 에이전트에 연결합니다. + - `builder.Services.AddKeyedSingleton(name, agent)`: 에이전트 인스턴스를 싱글톤 서비스로 등록합니다. + + > **참고**: `AgentRecordShimChatClient` 클래스를 발견할 수 있습니다. 이 클래스는 Microsoft Agent Framework와 Microsoft Foundry SDK 간의 버전 불일치에 대한 임시 해결 방법이며, 곧 제거될 예정입니다. + +1. 같은 파일에서 `// Build a group chat workflow pattern with the agents registered` 주석을 찾아 바로 아래에 코드를 추가합니다. + + ```csharp + // 등록된 에이전트로 Group Chat 워크플로 패턴 구축 + builder.AddWorkflow("publisher", (sp, key) => + { + var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name)); + + return AgentWorkflowBuilder.CreateGroupChatBuilderWith(agentList => + new RoundRobinGroupChatManager(agentList) { MaximumIterationCount = participants.Count() * 2 }) + .AddParticipants(participants) + .WithName(key) + .Build(); + }).AddAsAIAgent("publisher"); + ``` + + 코드를 분석해 봅시다. + + - `var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name));`: Group Chat에 참여하는 에이전트 목록을 식별합니다. + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: 멀티 에이전트 워크플로를 `publisher`라는 또 다른 에이전트 인스턴스로 추가하고 싱글톤으로 등록합니다. + - `AgentWorkflowBuilder.CreateGroupChatBuilderWith(...)`: 동일한 이름 `publisher`를 사용하는 Group Chat 워크플로 빌더입니다. + - `new RoundRobinGroupChatManager(...)`: Group Chat 전략을 라운드 로빈으로 설정합니다. 또한 최대 반복 횟수를 정의합니다. 이 코드에서 각 에이전트는 라운드 로빈 사이클 동안 두 번 응답합니다. + +1. 같은 파일에서 `// Map AGUI to the publisher workflow agent` 주석을 찾아 바로 아래에 코드를 추가합니다. 워크플로는 `ag-ui` API 엔드포인트로 노출되어 프론트엔드 웹 UI가 이 백엔드 에이전트 서비스 앱과 통신할 수 있습니다. + + ```csharp + // publisher 워크플로 에이전트에 AGUI 매핑 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## 프론트엔드 웹 UI에서 Group Chat 패턴 구현하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. `src/MultiAgentWorkshop.WebUI/Program.cs`를 열고, `// Register all agents passed from Aspire` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 코드는 웹 UI가 어떤 에이전트가 응답하는지 알 수 있도록 모든 에이전트 세부 정보를 등록합니다. + + ```csharp + // Aspire에서 전달된 모든 에이전트 등록 + builder.Services.AddSingleton(agents); + ``` + +1. 같은 파일에서 `// Register the backend agent service as an HTTP client` 주석을 찾아 바로 아래에 코드를 추가합니다. Aspire가 이미 프론트엔드 웹 UI 앱에 백엔드 에이전트 서비스의 연결 정보를 제공합니다. + + ```csharp + // 백엔드 에이전트 서비스를 HTTP 클라이언트로 등록 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 같은 파일에서 `// Register AGUI client` 주석을 찾아 바로 아래에 코드를 추가합니다. 이 AGUI 클라이언트를 사용하여 프론트엔드 웹 UI 앱이 `ag-ui` 엔드포인트를 통해 백엔드 에이전트 서비스 앱과 통신합니다. + + ```csharp + // AGUI 클라이언트 등록 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Aspire 실행하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Azure CLI와 Azure Developer CLI를 모두 사용하여 이미 Azure에 로그인했는지 확인합니다. 확실하지 않다면 [이 단계](./00-setup.md#azure에-로그인하기)를 다시 따라하세요. + +1. 다음 명령어를 실행하여 Aspire를 통해 모든 앱을 시작합니다. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 대시보드가 자동으로 열립니다. + + ![Aspire 대시보드](../../../docs/images/step-04-image-01.png) + + 백엔드 에이전트 서비스 앱을 클릭합니다. + +1. Dev UI 페이지가 열리면 에이전트를 `publisher`로 변경하고 "Configure & Run" 버튼을 클릭합니다. + + ![Microsoft Agent Framework Dev UI - Group Chat 패턴](../../../docs/images/step-04-image-02.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Dev UI - 요청 보내기](../../../docs/images/step-04-image-03.png) + + 결과를 확인하고 화면 왼쪽에서 워크플로가 어떻게 진행되는지 살펴보세요. + + ![Microsoft Agent Framework Dev UI - 워크플로 실행](../../../docs/images/step-04-image-04.png) + +1. Aspire 대시보드로 돌아가서 웹 UI 앱을 클릭합니다. + + ![Aspire 대시보드](../../../docs/images/step-04-image-05.png) + +1. 아무 요청이나 보내보세요. + + ![Microsoft Agent Framework Chat UI - 요청 보내기](../../../docs/images/step-04-image-06.png) + + 결과를 확인합니다. + +1. `Ctrl`+`C`를 눌러 실행 중인 모든 앱을 종료합니다. + +## Azure에 배포하기 + +1. `workshop` 디렉터리에 있는지 확인합니다. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 다음 명령어를 실행하여 프론트엔드 웹 UI와 백엔드 에이전트 서비스 앱을 모두 Azure에 프로비저닝하고 배포합니다. + + ```bash + azd up + ``` + + 프로비저닝 중에 환경 이름, Azure 구독 및 위치를 입력하라는 메시지가 표시됩니다. + +1. 완료되면 터미널 화면에 웹 UI 애플리케이션 URL이 표시됩니다. 웹 브라우저에서 열고 요청을 보내보세요. + + ![Azure Container Apps의 Microsoft Agent Framework - 요청 보내기](../../../docs/images/step-04-image-07.png) + + 결과를 확인합니다. + +1. 모든 작업이 완료되면 Azure에서 모든 앱과 에이전트를 삭제합니다. + + ```bash + # 웹 UI와 에이전트 서비스 앱을 모두 삭제합니다. + azd down --purge --force + + # 모든 에이전트와 Microsoft Foundry 리소스를 삭제합니다. + cd resources-foundry + azd down --purge --force + ``` + +--- + +축하합니다! 🎉 네 번째 멀티 에이전트 오케스트레이션 시나리오인 Group Chat 패턴을 완료했습니다. 모든 과정을 완료하셨습니다! + +👈 [03: Handoff Pattern](./03-handoff-pattern.md) | [README](../README.md) 👉 diff --git a/localization/ko-kr/docs/README.md b/localization/ko-kr/docs/README.md new file mode 100644 index 0000000..9d2b6fe --- /dev/null +++ b/localization/ko-kr/docs/README.md @@ -0,0 +1,10 @@ +# 멀티 에이전트 워크숍 자료 + +멀티 에이전트 오케스트레이션 패턴을 구축하기 위한 워크숍 자료 목록과 코드 샘플입니다. + +| 문서 | 코드 샘플 | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](./01-sequential-pattern.md) | [01-sequential-pattern](../samples/01-sequential-pattern) | +| [02-concurrent-pattern.md](./02-concurrent-pattern.md) | [02-concurrent-pattern](../samples/02-concurrent-pattern) | +| [03-handoff-pattern.md](./03-handoff-pattern.md) | [03-handoff-pattern](../samples/03-handoff-pattern) | +| [04-group-chat-pattern.md](./04-group-chat-pattern.md) | [04-group-chat-pattern](../samples/04-group-chat-pattern) | diff --git a/localization/ko-kr/samples/01-sequential-pattern/README.md b/localization/ko-kr/samples/01-sequential-pattern/README.md new file mode 100644 index 0000000..3be0ee3 --- /dev/null +++ b/localization/ko-kr/samples/01-sequential-pattern/README.md @@ -0,0 +1,13 @@ +# 01 순차 패턴 + +순차 패턴에서는 에이전트들이 정의된 파이프라인에 따라 순서대로 작업하며, 각 에이전트의 출력이 다음 에이전트의 입력으로 전달됩니다. 이 접근 방식은 콘텐츠 생성 워크플로우, 단계별 데이터 변환 또는 단계적 분석과 같이 자연스러운 진행 순서를 따르는 작업에 적합합니다. + +
+ 아키텍처 - 순차 패턴 +
+ +## 안내 + +[start](../../../../samples/01-sequential-pattern/start) 프로젝트와 함께 [01-sequential-pattern.md](../../docs/01-sequential-pattern.md) 안내를 따라 진행합니다. + +완료한 후, [complete](../../../../samples/01-sequential-pattern/complete) 프로젝트와 비교해 보세요. diff --git a/localization/ko-kr/samples/02-concurrent-pattern/README.md b/localization/ko-kr/samples/02-concurrent-pattern/README.md new file mode 100644 index 0000000..6a998ab --- /dev/null +++ b/localization/ko-kr/samples/02-concurrent-pattern/README.md @@ -0,0 +1,13 @@ +# 02 동시 실행 패턴 + +동시 실행 패턴에서는 여러 에이전트가 동일한 입력을 동시에 분석하며, 각 에이전트가 자신만의 전문 지식을 활용합니다. 모든 에이전트의 작업이 완료되면 출력이 하나의 통합된 결과로 결합됩니다. 이 패턴은 다중 관점 분석, 앙상블 평가 또는 협업 의사 결정과 같이 여러 관점에서 동시에 작업하는 것이 유리한 작업에 이상적입니다. + +
+ 아키텍처 - 동시 실행 패턴 +
+ +## 안내 + +[start](../../../../samples/02-concurrent-pattern/start) 프로젝트와 함께 [02-concurrent-pattern.md](../../docs/02-concurrent-pattern.md) 안내를 따라 진행합니다. + +완료한 후, [complete](../../../../samples/02-concurrent-pattern/complete) 프로젝트와 비교해 보세요. diff --git a/localization/ko-kr/samples/03-handoff-pattern/README.md b/localization/ko-kr/samples/03-handoff-pattern/README.md new file mode 100644 index 0000000..a629413 --- /dev/null +++ b/localization/ko-kr/samples/03-handoff-pattern/README.md @@ -0,0 +1,13 @@ +# 03 핸드오프 패턴 + +핸드오프 패턴에서는 에이전트들이 대화 컨텍스트에 따라 동적으로 제어를 서로 전달합니다. 트리아지 에이전트가 초기 요청을 수신하고 이를 처리하기에 가장 적합한 전문 에이전트에게 라우팅합니다. 전문 에이전트들은 문제가 다른 도메인에 걸쳐 있을 때 서로에게 리디렉션할 수도 있습니다. 이 패턴은 IT 지원, 고객 서비스 또는 각 단계에서 서로 다른 전문 지식이 필요한 워크플로우와 같은 시나리오에 적합합니다. + +
+ 아키텍처 - 핸드오프 패턴 +
+ +## 안내 + +[start](../../../../samples/03-handoff-pattern/start) 프로젝트와 함께 [03-handoff-pattern.md](../../docs/03-handoff-pattern.md) 안내를 따라 진행합니다. + +완료한 후, [complete](../../../../samples/03-handoff-pattern/complete) 프로젝트와 비교해 보세요. diff --git a/localization/ko-kr/samples/04-group-chat-pattern/README.md b/localization/ko-kr/samples/04-group-chat-pattern/README.md new file mode 100644 index 0000000..f7d5afe --- /dev/null +++ b/localization/ko-kr/samples/04-group-chat-pattern/README.md @@ -0,0 +1,13 @@ +# 04 그룹 채팅 패턴 + +그룹 채팅 패턴에서는 여러 에이전트가 공유 대화에 참여하여 순서대로 자신의 전문 지식을 제공합니다. 오케스트레이터가 토론 흐름을 관리하며, 다음에 어떤 에이전트가 발언할지와 대화를 종료할 시점을 결정합니다. 이 패턴은 교차 기능 계획, 창의적 브레인스토밍 또는 다양한 관점이 반복적으로 상호작용하며 서로의 의견을 발전시켜야 하는 작업에 적합합니다. + +
+ 아키텍처 - 그룹 채팅 패턴 +
+ +## 안내 + +[start](../../../../samples/04-group-chat-pattern/start) 프로젝트와 함께 [04-group-chat-pattern.md](../../docs/04-group-chat-pattern.md) 안내를 따라 진행합니다. + +완료한 후, [complete](../../../../samples/04-group-chat-pattern/complete) 프로젝트와 비교해 보세요. diff --git a/localization/ko-kr/samples/README.md b/localization/ko-kr/samples/README.md new file mode 100644 index 0000000..5778d19 --- /dev/null +++ b/localization/ko-kr/samples/README.md @@ -0,0 +1,10 @@ +# 멀티 에이전트 오케스트레이션 코드 샘플 + +멀티 에이전트 오케스트레이션 패턴과 코드 샘플 목록입니다. + +| 문서 | 코드 샘플 | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](../docs/01-sequential-pattern.md) | [01-sequential-pattern](./01-sequential-pattern) | +| [02-concurrent-pattern.md](../docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./02-concurrent-pattern) | +| [03-handoff-pattern.md](../docs/03-handoff-pattern.md) | [03-handoff-pattern](./03-handoff-pattern) | +| [04-group-chat-pattern.md](../docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./04-group-chat-pattern) | diff --git a/localization/pt-br/README.md b/localization/pt-br/README.md new file mode 100644 index 0000000..c5fcecf --- /dev/null +++ b/localization/pt-br/README.md @@ -0,0 +1,65 @@ +# Multi-Agent Orchestration Workshop + +Este é o material de workshop para construir aplicações multi-agente baseadas em .NET usando [Microsoft Agent Framework](https://aka.ms/agent-framework), [Microsoft Foundry](https://aka.ms/microsoft-foundry) e [Aspire](https://aspire.dev). + +![Workshop MAF + Foundry](../../images/hero.jpg) + +## Para que serve este workshop? + +Construir uma aplicação com um único agente é fácil. Mas existem muitos casos de uso reais que exigem múltiplos agentes trabalhando juntos, e construir uma aplicação multi-agente não é tão simples quanto construir uma com um único agente. O [Microsoft Agent Framework](https://aka.ms/agent-framework) oferece cinco padrões de orquestração multi-agente: + +| Padrão | Descrição | +|----------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------| +| [Sequential](https://learn.microsoft.com/agent-framework/workflows/orchestrations/sequential?pivots=programming-language-csharp) | Os agentes executam um após o outro em uma ordem definida | +| [Concurrent](https://learn.microsoft.com/agent-framework/workflows/orchestrations/concurrent?pivots=programming-language-csharp) | Os agentes executam em paralelo | +| [Handoff](https://learn.microsoft.com/agent-framework/workflows/orchestrations/handoff?pivots=programming-language-csharp) | Os agentes transferem o controle entre si com base no contexto | +| [Group Chat](https://learn.microsoft.com/agent-framework/workflows/orchestrations/group-chat?pivots=programming-language-csharp) | Os agentes colaboram em uma conversa compartilhada | +| [Magentic](https://learn.microsoft.com/agent-framework/workflows/orchestrations/magentic?pivots=programming-language-python) | Um agente gerente coordena dinamicamente agentes especializados | + +## Funcionalidades + +Neste workshop, construímos todos os padrões de orquestração multi-agente, exceto o padrão Magentic. Ao concluir cada padrão, você terá a seguinte arquitetura: + +- Frontend [Blazor](https://blazor.net) para a interface de chat +- Backend [ASP.NET](https://asp.net) com [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) para hospedagem de agentes +- [Aspire](https://aspire.dev) para orquestração de aplicações cloud-native + +> [!NOTE] +> A versão .NET do SDK do Microsoft Agent Framework suportará o padrão Magentic em uma versão futura. + +## Pré-requisitos + +- [Assinatura Azure (gratuita)](http://azure.microsoft.com/free) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) ou superior +- [Visual Studio 2026](https://visualstudio.microsoft.com/downloads/) ou [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) +- [Docker Desktop](https://docs.docker.com/desktop/) ou equivalente +- [GitHub CLI](https://cli.github.com) +- [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) +- [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) +- [Aspire CLI](https://aspire.dev/get-started/install-cli/) + +## Sessões do workshop + +| Sessão | Documento | Exemplo de Código | +|-----------------------------|-------------------------------------------------------------|----------------------------------------------------------| +| 00 Configuração | [00-setup.md](./docs/00-setup.md) | | +| 01 Padrão Sequential | [01-sequential-pattern.md](./docs/01-sequential-pattern.md) | [01-sequential-pattern](./samples/01-sequential-pattern) | +| 02 Padrão Concurrent | [02-concurrent-pattern.md](./docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./samples/02-concurrent-pattern) | +| 03 Padrão Handoff | [03-handoff-pattern.md](./docs/03-handoff-pattern.md) | [03-handoff-pattern](./samples/03-handoff-pattern) | +| 04 Padrão Group Chat | [04-group-chat-pattern.md](./docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./samples/04-group-chat-pattern) | + +## Use seu idioma preferido! + +Este material de workshop está disponível nos seguintes idiomas. + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](../ja-jp/README.md) | [한국어](../ko-kr/README.md) | [Português](./README.md) | [中文(简体)](../zh-cn/README.md) + +## Recursos + +- [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Agent Framework - Workflow Orchestrations](https://learn.microsoft.com/agent-framework/workflows/orchestrations) +- [Microsoft Foundry](https://aka.ms/microsoft-foundry) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) +- [Model Context Protocol (MCP)](https://modelcontextprotocol.io) +- [Aspire](https://aspire.dev) diff --git a/localization/pt-br/docs/00-setup.md b/localization/pt-br/docs/00-setup.md new file mode 100644 index 0000000..ceb3734 --- /dev/null +++ b/localization/pt-br/docs/00-setup.md @@ -0,0 +1,215 @@ +# 00 Configuração + +Nesta sessão, vamos configurar o ambiente de desenvolvimento na sua máquina ou no GitHub Codespaces. + +## Pré-requisitos + +- Navegador web: [Microsoft Edge](https://microsoft.com/edge) ou [Google Chrome](http://chrome.google.com) +- [Assinatura Azure](https://azure.microsoft.com/free) + +## Configuração no GitHub Codespaces + +Para o workshop, recomendamos fortemente o uso do GitHub Codespaces para economizar tempo na configuração do ambiente de desenvolvimento. Se você preferir configurar o ambiente na sua máquina local, pule esta seção e vá para a seção [Configuração no VS Code](#configuração-no-vs-code). + +1. Clique no botão abaixo para criar uma nova instância do GitHub Codespaces. + + [![Criar uma nova instância do GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/multi-agent-orchestration-workshop) + +1. Após a criação, execute os seguintes comandos para verificar se as ferramentas necessárias estão instaladas corretamente. + + ```bash + # .NET SDK + dotnet --list-sdks + + # node.js + node --version + npm --version + + # PowerShell + pwsh --version + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +1. Verifique o status do seu login no GitHub. + + ```bash + gh auth status + ``` + +1. Obtenha os detalhes do repositório remoto. + + ```bash + git remote -v + ``` + + Você deverá ver o seguinte. + + ```text + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (push) + ``` + + Se você não vir essas duas linhas, exclua a instância atual do GitHub Codespaces e crie-a novamente. + +1. Como a instância do GitHub Codespaces NÃO está sob a sua conta, faça um fork do repositório para transferir a propriedade usando os seguintes comandos. + + ```bash + git remote -v > remote.txt + git add . && git commit -m "Add remote.txt for forking" + ``` + + Você pode ver uma mensagem como a seguinte: + + ```text + You don't have write access to the Azure-Samples/multi-agent-orchestration-workshop repository, so you cannot push changes to it. + To obtain write access we will point this codespace at your fork of Azure-Samples/multi-agent-orchestration-workshop, creating that fork if it doesn't exist. + + Would you like to proceed? + ``` + + Digite `y` para continuar. Isso fará automaticamente o fork do repositório na sua conta. + +1. Verifique o status do repositório remoto. + + ```bash + git remote -v + ``` + + Desta vez, você deverá ver as seguintes quatro linhas. + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + + Se você não vir essas quatro linhas, exclua e recrie a instância do GitHub Codespaces. + +## Configuração no VS Code + +Se você já tem uma instância do GitHub Codespaces, pule esta seção e vá diretamente para a seção [Fazer login no Azure](#fazer-login-no-azure). + +1. Instale as seguintes ferramentas na sua máquina. + + - [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) + - [Docker Desktop](https://docs.docker.com/desktop/) ou equivalente + - [GitHub CLI](https://cli.github.com) + - [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) + - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) + - [Aspire CLI](https://aspire.dev/get-started/install-cli/) + + Em seguida, execute os seguintes comandos para verificar se estão instalados corretamente. + + ```bash + # .NET SDK + dotnet --list-sdks + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +### Fazer login no GitHub + +1. Faça login no GitHub. + + ```bash + gh auth login + ``` + + Após fazer login, execute o seguinte comando para verificar o status do login. + + ```bash + gh auth status + ``` + +### Clonar o projeto + +1. Faça fork deste repositório para a sua máquina local. + + ```bash + gh repo fork Azure-Samples/multi-agent-orchestration-workshop --clone + ``` + +1. Navegue até o diretório clonado. + + ```bash + cd multi-agent-orchestration-workshop + ``` + +1. Verifique o status do repositório remoto. + + ```bash + git remote -v + ``` + + Você deverá ver as seguintes quatro linhas. + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + +1. Abra o repositório no VS Code. + + ```bash + code . + ``` + +## Fazer login no Azure + +1. Faça login no Azure. + + ```bash + # Azure Developer CLI + azd auth login + + # Azure CLI + az login + ``` + + Após fazer login, execute o seguinte comando para verificar o status do login. + + ```bash + # Azure Developer CLI + azd auth login --check-status + + # Azure Login + az account show + ``` + +--- + +Parabéns! 🎉 Você acabou de concluir a configuração do ambiente de desenvolvimento. Vamos prosseguir! + +👈 [README](../README.md) | [01: Sequential Pattern](./01-sequential-pattern.md) 👉 diff --git a/localization/pt-br/docs/01-sequential-pattern.md b/localization/pt-br/docs/01-sequential-pattern.md new file mode 100644 index 0000000..42dd744 --- /dev/null +++ b/localization/pt-br/docs/01-sequential-pattern.md @@ -0,0 +1,415 @@ +# 01 Padrão Sequential + +No padrão sequential, os agentes trabalham um após o outro em um pipeline definido, onde a saída de cada agente alimenta o próximo. Essa abordagem funciona bem para tarefas que seguem uma progressão natural, como fluxos de criação de conteúdo, transformações de dados em etapas ou análises passo a passo. + +## Cenário + +Você está escrevendo um post técnico para blog com agentes – agente de pesquisa, agente de estruturação, agente escritor e agente editor. + +
+ Arquitetura - Padrão Sequential +
+ +## Obter a raiz do repositório + +1. Obtenha a variável `$REPOSITORY_ROOT` primeiro. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar o projeto inicial + +1. Se você já tem o diretório `workshop`, renomeie ou remova-o primeiro. + +1. Execute o script de configuração para copiar o projeto inicial para o diretório `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 01-sequential-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 01-sequential-pattern + ``` + +## Implantar os agentes + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue até o diretório `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Execute o seguinte comando para provisionar e implantar os agentes definidos acima no Microsoft Foundry. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após o provisionamento e a implantação serem concluídos, execute o seguinte comando para confirmar que os agentes foram implantados com sucesso. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Você deverá ver os quatro nomes dos agentes. + + ```text + editor-agent + writer-agent + outliner-agent + research-agent + ``` + +1. Navegue de volta ao diretório do workshop. + + ```bash + popd + ``` + +## Configurar a orquestração do Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique se todas as informações necessárias dos agentes foram registradas. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Você deverá ver os valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` e `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, encontre o comentário `// Add resource for Microsoft Foundry` e adicione o código logo abaixo dele. Isso adiciona os detalhes de conexão do projeto Microsoft Foundry. + + ```csharp + // Adicionar recurso para Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Vamos analisar o código. + + - `builder.AddFoundry("foundry")`: Isso adiciona os detalhes de conexão do Microsoft Foundry por meio de um recurso personalizado, `FoundryResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add resource for agents on Microsoft Foundry` e adicione o código logo abaixo dele. Isso expõe a lista de detalhes dos agentes para a aplicação que o referencia. + + ```csharp + // Adicionar recurso para agentes no Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Vamos analisar o código. + + - `builder.AddAgents("agents")`: Isso adiciona a lista de detalhes dos agentes por meio de um recurso personalizado, `AgentResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add backend agent service` e adicione o código logo abaixo dele. Isso define o serviço de agente backend que referencia o recurso `foundry` – todos os detalhes de conexão do Microsoft Foundry são passados para o aplicativo de serviço de agente backend. + + ```csharp + // Adicionar serviço de agente backend + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Vamos analisar o código. + + - `builder.AddProject("agent")`: Isso adiciona o aplicativo de serviço de agente backend como um projeto .NET. + - `.WithReference(foundry)`: Isso referencia o recurso foundry criado acima, que passa os detalhes de conexão do Microsoft Foundry para o aplicativo de serviço de agente backend. + +1. No mesmo arquivo, encontre o comentário `// Add frontend web UI` e adicione o código logo abaixo dele. Isso define a interface web frontend que referencia os recursos `agents` e `agent` – os detalhes dos agentes e os detalhes de conexão do backend são passados para o aplicativo de interface web frontend. + + ```csharp + // Adicionar interface web frontend + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Vamos analisar o código. + + - `builder.AddProject("webui")`: Isso adiciona o aplicativo de interface web frontend como um projeto .NET. + - `.WithExternalHttpEndpoints()`: Isso expõe o aplicativo de interface web frontend para a Internet, tornando-o acessível publicamente. + - `.WithReference(agents)`: Isso referencia o recurso de agentes criado acima, que passa a lista de agentes para o aplicativo de interface web frontend. + - `.WithReference(agent)`: Isso referencia o aplicativo de serviço de agente backend, que passa os detalhes de conexão para o aplicativo de interface web frontend. + +## Implementar o padrão sequential no serviço de agente backend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, encontre o comentário `// Create AIProjectClient instance with EntraID authentication` e adicione o código logo abaixo dele. Isso conecta ao projeto Microsoft Foundry. + + ```csharp + // Criar instância do AIProjectClient com autenticação EntraID + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + Vamos analisar o código. + + - `new DefaultAzureCredential(...)`: Isso faz login no Azure sem uma chave de API. Usa os detalhes de login do Azure CLI ou Azure Developer CLI na sua máquina local, e Managed Identity quando o aplicativo é implantado no Azure. + - `new AIProjectClient(endpoint, credential)`: Isso conecta à instância do projeto Microsoft Foundry usando o endpoint e os detalhes de login. + +1. No mesmo arquivo, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso obtém os detalhes dos agentes do projeto Microsoft Foundry e os registra no contêiner IoC como serviços singleton. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Vamos analisar o código. + + - Já conhecemos a lista de agentes, mas sabemos apenas seus nomes. Portanto, o código executa o loop `foreach` para cada agente. + - `new AgentReference(name, version)`: Usando as informações de cada agente, isso cria uma instância de referência. + - `projectClient.AsAIAgent(reference, factory)`: Isso conecta ao agente real usando os detalhes de referência. + - `builder.Services.AddKeyedSingleton(name, agent)`: Isso registra a instância do agente como um serviço singleton. + + > **NOTA**: Você pode notar a classe `AgentRecordShimChatClient`. É uma solução temporária para uma incompatibilidade de versão entre o Microsoft Agent Framework e o SDK do Microsoft Foundry, que será removida em breve. + +1. No mesmo arquivo, encontre o comentário `// Build a sequential workflow pattern with the agents registered` e adicione o código logo abaixo dele. + + ```csharp + // Construir um padrão de fluxo de trabalho sequential com os agentes registrados + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [.. agents.Select(a => sp.GetRequiredKeyedService(a.Name))] + )).AddAsAIAgent("publisher"); + ``` + + Vamos analisar o código. + + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: Isso adiciona o fluxo de trabalho multi-agente como outra instância de agente chamada `publisher` e o registra como singleton. + - `AgentWorkflowBuilder.BuildSequential(...)`: Este é o construtor de fluxo de trabalho sequential que usa o mesmo nome, `publisher`. + + Note que ele adiciona múltiplos agentes dos serviços registrados anteriormente na ordem declarada pelo array `agents`. + +1. No mesmo arquivo, encontre o comentário `// Map AGUI to the publisher workflow agent` e adicione o código logo abaixo dele. O fluxo de trabalho é exposto como um endpoint de API em `ag-ui` para que a interface web frontend possa se comunicar com este aplicativo de serviço de agente backend. + + ```csharp + // Mapear AGUI para o agente de fluxo de trabalho publisher + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## Implementar o padrão sequential na interface web frontend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso registra todos os detalhes dos agentes para que a interface web saiba qual agente está respondendo. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + builder.Services.AddSingleton(agents); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register the backend agent service as an HTTP client` e adicione o código logo abaixo dele. O Aspire já fornece ao aplicativo de interface web frontend os detalhes de conexão para o serviço de agente backend. + + ```csharp + // Registrar o serviço de agente backend como um cliente HTTP + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register AGUI client` e adicione o código logo abaixo dele. Usando este cliente AGUI, o aplicativo de interface web frontend se comunica com o aplicativo de serviço de agente backend via o endpoint `ag-ui`. + + ```csharp + // Registrar cliente AGUI + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Executar o Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Certifique-se de que você já fez login no Azure usando tanto o Azure CLI quanto o Azure Developer CLI. Se não tiver certeza, siga [este passo](./00-setup.md#fazer-login-no-azure) novamente. + +1. Execute o seguinte comando para iniciar todos os aplicativos através do Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. O painel do Aspire abre automaticamente. + + ![Painel do Aspire](../../../docs/images/step-01-image-01.png) + + Clique no aplicativo de serviço de agente backend. + +1. Quando a página Dev UI abrir, altere o agente para `publisher` e clique no botão "Configure & Run". + + ![Microsoft Agent Framework Dev UI - Padrão sequential](../../../docs/images/step-01-image-02.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Dev UI - Enviar solicitação](../../../docs/images/step-01-image-03.png) + + Veja o resultado e como o fluxo de trabalho progride no lado esquerdo da tela. + + ![Microsoft Agent Framework Dev UI - Execução do fluxo de trabalho](../../../docs/images/step-01-image-04.png) + +1. Volte ao painel do Aspire e clique no aplicativo de interface web. + + ![Painel do Aspire](../../../docs/images/step-01-image-05.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Chat UI - Enviar solicitação](../../../docs/images/step-01-image-06.png) + + Veja o resultado. + +1. Pressione `Ctrl`+`C` para encerrar todos os aplicativos em execução. + +## Implantar no Azure + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Execute o seguinte comando para provisionar e implantar tanto a interface web frontend quanto o serviço de agente backend no Azure. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após concluído, você verá a URL do aplicativo de interface web na tela do terminal. Abra-a no seu navegador e envie uma solicitação. + + ![Microsoft Agent Framework no Azure Container Apps - Enviar solicitação](../../../docs/images/step-01-image-07.png) + + Veja o resultado. + +1. Quando tudo estiver pronto, remova todos os aplicativos e agentes do Azure. + + ```bash + # Excluir tanto o aplicativo de interface web quanto o de serviço de agente. + azd down --purge --force + + # Excluir todos os agentes e o recurso Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +Parabéns! 🎉 Você acabou de concluir o primeiro cenário de orquestração multi-agente - o padrão sequential. Vamos prosseguir! + +👈 [00: Setup](./00-setup.md) | [02: Concurrent Pattern](./02-concurrent-pattern.md) 👉 diff --git a/localization/pt-br/docs/02-concurrent-pattern.md b/localization/pt-br/docs/02-concurrent-pattern.md new file mode 100644 index 0000000..14d554a --- /dev/null +++ b/localization/pt-br/docs/02-concurrent-pattern.md @@ -0,0 +1,446 @@ +# 02 Padrão Concurrent + +No padrão concurrent, múltiplos agentes analisam a mesma entrada simultaneamente, cada um trazendo sua própria expertise. Quando todos os agentes terminam, suas saídas são combinadas em um resultado unificado. Isso é ideal para tarefas que se beneficiam de múltiplos pontos de vista trabalhando ao mesmo tempo, como análise com múltiplas perspectivas, avaliação em conjunto ou tomada de decisão colaborativa. + +## Cenário + +Você trabalha para uma empresa de capital de risco e está analisando uma proposta de startup com agentes – agente de análise de mercado, agente de viabilidade tecnológica, agente de modelo financeiro, agente de avaliação de riscos e agente agregador. + +
+ Arquitetura - Padrão Concurrent +
+ +## Obter a raiz do repositório + +1. Obtenha a variável `$REPOSITORY_ROOT` primeiro. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar o projeto inicial + +1. Se você já tem o diretório `workshop`, renomeie ou remova-o primeiro. + +1. Execute o script de configuração para copiar o projeto inicial para o diretório `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 02-concurrent-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 02-concurrent-pattern + ``` + +## Implantar os agentes + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue até o diretório `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Execute o seguinte comando para provisionar e implantar os agentes definidos acima no Microsoft Foundry. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após o provisionamento e a implantação serem concluídos, execute o seguinte comando para confirmar que os agentes foram implantados com sucesso. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Você deverá ver os cinco nomes dos agentes. + + ```text + aggregator-agent + risk-assessment-agent + financial-model-agent + technology-feasibility-agent + market-analysis-agent + ``` + +1. Navegue de volta ao diretório do workshop. + + ```bash + popd + ``` + +## Configurar a orquestração do Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique se todas as informações necessárias dos agentes foram registradas. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Você deverá ver os valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` e `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, encontre o comentário `// Add resource for Microsoft Foundry` e adicione o código logo abaixo dele. Isso adiciona os detalhes de conexão do projeto Microsoft Foundry. + + ```csharp + // Adicionar recurso para Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Vamos analisar o código. + + - `builder.AddFoundry("foundry")`: Isso adiciona os detalhes de conexão do Microsoft Foundry por meio de um recurso personalizado, `FoundryResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add resource for agents on Microsoft Foundry` e adicione o código logo abaixo dele. Isso expõe a lista de detalhes dos agentes para a aplicação que o referencia. + + ```csharp + // Adicionar recurso para agentes no Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Vamos analisar o código. + + - `builder.AddAgents("agents")`: Isso adiciona a lista de detalhes dos agentes por meio de um recurso personalizado, `AgentResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add backend agent service` e adicione o código logo abaixo dele. Isso define o serviço de agente backend que referencia o recurso `foundry` — todos os detalhes de conexão do Microsoft Foundry são passados para o aplicativo de serviço de agente backend. + + ```csharp + // Adicionar serviço de agente backend + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Vamos analisar o código. + + - `builder.AddProject("agent")`: Isso adiciona o aplicativo de serviço de agente backend como um projeto .NET. + - `.WithReference(foundry)`: Isso referencia o recurso foundry criado acima, que passa os detalhes de conexão do Microsoft Foundry para o aplicativo de serviço de agente backend. + +1. No mesmo arquivo, encontre o comentário `// Add frontend web UI` e adicione o código logo abaixo dele. Isso define a interface web frontend que referencia os recursos `agents` e `agent` — os detalhes dos agentes e os detalhes de conexão do backend são passados para o aplicativo de interface web frontend. + + ```csharp + // Adicionar interface web frontend + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Vamos analisar o código. + + - `builder.AddProject("webui")`: Isso adiciona o aplicativo de interface web frontend como um projeto .NET. + - `.WithExternalHttpEndpoints()`: Isso expõe o aplicativo de interface web frontend para a Internet, tornando-o acessível publicamente. + - `.WithReference(agents)`: Isso referencia o recurso de agentes criado acima, que passa a lista de agentes para o aplicativo de interface web frontend. + - `.WithReference(agent)`: Isso referencia o aplicativo de serviço de agente backend, que passa os detalhes de conexão para o aplicativo de interface web frontend. + +## Implementar o padrão concurrent no serviço de agente backend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, encontre o comentário `// Create AIProjectClient instance with EntraID authentication` e adicione o código logo abaixo dele. Isso conecta ao projeto Microsoft Foundry. + + ```csharp + // Criar instância do AIProjectClient com autenticação EntraID + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + Vamos analisar o código. + + - `new DefaultAzureCredential(...)`: Isso faz login no Azure sem uma chave de API. Usa os detalhes de login do Azure CLI ou Azure Developer CLI na sua máquina local, e Managed Identity quando o aplicativo é implantado no Azure. + - `new AIProjectClient(endpoint, credential)`: Isso conecta à instância do projeto Microsoft Foundry usando o endpoint e os detalhes de login. + +1. No mesmo arquivo, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso obtém os detalhes dos agentes do projeto Microsoft Foundry e os registra no contêiner IoC como serviços singleton. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Vamos analisar o código. + + - Já conhecemos a lista de agentes, mas sabemos apenas seus nomes. Portanto, o código executa o loop `foreach` para cada agente. + - `new AgentReference(name, version)`: Usando as informações de cada agente, isso cria uma instância de referência. + - `projectClient.AsAIAgent(reference, factory)`: Isso conecta ao agente real usando os detalhes de referência. + - `builder.Services.AddKeyedSingleton(name, agent)`: Isso registra a instância do agente como um serviço singleton. + + > **NOTA**: Você pode notar a classe `AgentRecordShimChatClient`. É uma solução temporária para uma incompatibilidade de versão entre o Microsoft Agent Framework e o SDK do Microsoft Foundry, que será removida em breve. + +1. No mesmo arquivo, encontre o comentário `// Build a concurrent workflow pattern with the agents registered` e adicione o código logo abaixo dele. + + ```csharp + // Construir um padrão de fluxo de trabalho concurrent com os agentes registrados + var concurrentAgents = agents.Where(a => a.Name != "aggregator-agent"); + var aggregatorAgent = agents.SingleOrDefault(a => a.Name == "aggregator-agent"); + + builder.AddWorkflow("concurrent-analysis", (sp, key) => AgentWorkflowBuilder.BuildConcurrent( + workflowName: key, + agents: [.. concurrentAgents.Select(a => sp.GetRequiredKeyedService(a.Name))], + aggregator: null + )).AddAsAIAgent("concurrent-analysis"); + + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [ + sp.GetRequiredKeyedService("concurrent-analysis"), + sp.GetRequiredKeyedService(aggregatorAgent!.Name) + ] + )).AddAsAIAgent("publisher"); + ``` + + Vamos analisar o código. + + - `builder.AddWorkflow("concurrent-analysis", ...).AddAsAIAgent("concurrent-analysis")`: Isso adiciona o fluxo de trabalho multi-agente como outra instância de agente chamada `concurrent-analysis` e o registra como singleton. + - `AgentWorkflowBuilder.BuildConcurrent(...)`: Este é o construtor de fluxo de trabalho concurrent que usa o mesmo nome, `concurrent-analysis`. + + Note que ele adiciona múltiplos agentes dos serviços registrados anteriormente declarados pelo array `agents`. + + Note também que ele passa `null` para o agregador para que possamos usar o `aggregator-agent` fornecido pelo Microsoft Foundry. + - `builder.AddWorkflow("publisher, ...).AddAsAIAgent("publisher")`: Isso adiciona o fluxo de trabalho multi-agente como outra instância de agente chamada `publisher` e o registra como singleton. + - `AgentWorkflowBuilder.BuildSequential(...)`: Este é o construtor de fluxo de trabalho sequential que usa o mesmo nome, `publisher`. + + Note que ele adiciona tanto o fluxo de trabalho `concurrent-analysis` quanto o `aggregator-agent` para que o agente agregador resuma o que cada agente respondeu no fluxo de trabalho concurrent. + +1. No mesmo arquivo, encontre o comentário `// Map AGUI to the publisher workflow agent` e adicione o código logo abaixo dele. O fluxo de trabalho é exposto como um endpoint de API em `ag-ui` para que a interface web frontend possa se comunicar com este aplicativo de serviço de agente backend. + + ```csharp + // Mapear AGUI para o agente de fluxo de trabalho publisher + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## Implementar o padrão concurrent na interface web frontend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso registra todos os detalhes dos agentes para que a interface web saiba qual agente está respondendo. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + builder.Services.AddSingleton(agents); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register the backend agent service as an HTTP client` e adicione o código logo abaixo dele. O Aspire já fornece ao aplicativo de interface web frontend os detalhes de conexão para o serviço de agente backend. + + ```csharp + // Registrar o serviço de agente backend como um cliente HTTP + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register AGUI client` e adicione o código logo abaixo dele. Usando este cliente AGUI, o aplicativo de interface web frontend se comunica com o aplicativo de serviço de agente backend via o endpoint `ag-ui`. + + ```csharp + // Registrar cliente AGUI + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Executar o Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Certifique-se de que você já fez login no Azure usando tanto o Azure CLI quanto o Azure Developer CLI. Se não tiver certeza, siga [este passo](./00-setup.md#fazer-login-no-azure) novamente. + +1. Execute o seguinte comando para iniciar todos os aplicativos através do Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. O painel do Aspire abre automaticamente. + + ![Painel do Aspire](../../../docs/images/step-02-image-01.png) + + Clique no aplicativo de serviço de agente backend. + +1. Quando a página Dev UI abrir, altere o agente para `concurrent-analysis` e veja que todos os agentes executam concorrentemente. + + ![Microsoft Agent Framework Dev UI - Padrão concurrent](../../../docs/images/step-02-image-02.png) + + Em seguida, altere o agente para `publisher` e veja como o padrão sequential combina o `concurrent-analysis` com o `aggregator-agent`. + + ![Microsoft Agent Framework Dev UI - Padrão sequential](../../../docs/images/step-02-image-03.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Dev UI - Enviar solicitação](../../../docs/images/step-02-image-04.png) + + Veja o resultado e como o fluxo de trabalho progride no lado esquerdo da tela. + + ![Microsoft Agent Framework Dev UI - Execução do fluxo de trabalho](../../../docs/images/step-02-image-05.png) + +1. Volte ao painel do Aspire e clique no aplicativo de interface web. + + ![Painel do Aspire](../../../docs/images/step-02-image-06.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Chat UI - Enviar solicitação](../../../docs/images/step-02-image-07.png) + + Veja o resultado. + +1. Pressione `Ctrl`+`C` para encerrar todos os aplicativos em execução. + +## Implantar no Azure + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Execute o seguinte comando para provisionar e implantar tanto a interface web frontend quanto o serviço de agente backend no Azure. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após concluído, você verá a URL do aplicativo de interface web na tela do terminal. Abra-a no seu navegador e envie uma solicitação. + + ![Microsoft Agent Framework no Azure Container Apps - Enviar solicitação](../../../docs/images/step-02-image-08.png) + + Veja o resultado. + +1. Quando tudo estiver pronto, remova todos os aplicativos e agentes do Azure. + + ```bash + # Excluir tanto o aplicativo de interface web quanto o de serviço de agente. + azd down --purge --force + + # Excluir todos os agentes e o recurso Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +Parabéns! 🎉 Você acabou de concluir o segundo cenário de orquestração multi-agente - o padrão concurrent. Vamos prosseguir! + +👈 [01: Sequential Pattern](./01-sequential-pattern.md) | [03: Handoff Pattern](./03-handoff-pattern.md) 👉 diff --git a/localization/pt-br/docs/03-handoff-pattern.md b/localization/pt-br/docs/03-handoff-pattern.md new file mode 100644 index 0000000..4bf2a70 --- /dev/null +++ b/localization/pt-br/docs/03-handoff-pattern.md @@ -0,0 +1,449 @@ +# 03 Padrão Handoff + +No padrão handoff, os agentes passam dinamicamente o controle uns aos outros com base no contexto da conversa. Um agente de triagem recebe a solicitação inicial e a encaminha para o especialista mais adequado para tratá-la. Os especialistas também podem redirecionar entre si quando o problema abrange diferentes domínios. Isso funciona bem para cenários como suporte de TI, atendimento ao cliente ou qualquer fluxo de trabalho onde diferentes especialidades são necessárias em diferentes estágios. + +## Cenário + +Você trabalha em uma equipe de suporte de TI com agentes – agente de suporte geral, agente especialista em rede, agente de garantia e agente de triagem. + +
+ Arquitetura - Padrão Handoff +
+ +## Obter a raiz do repositório + +1. Obtenha a variável `$REPOSITORY_ROOT` primeiro. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar o projeto inicial + +1. Se você já tem o diretório `workshop`, renomeie ou remova-o primeiro. + +1. Execute o script de configuração para copiar o projeto inicial para o diretório `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 03-handoff-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 03-handoff-pattern + ``` + +## Implantar os agentes + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue até o diretório `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Execute o seguinte comando para provisionar e implantar os agentes definidos acima no Microsoft Foundry. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após o provisionamento e a implantação serem concluídos, execute o seguinte comando para confirmar que os agentes foram implantados com sucesso. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Você deverá ver os quatro nomes dos agentes. + + ```text + warranty-agent + network-specialist-agent + general-support-agent + triage-agent + ``` + +1. Navegue de volta ao diretório do workshop. + + ```bash + popd + ``` + +## Configurar a orquestração do Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique se todas as informações necessárias dos agentes foram registradas. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Você deverá ver os valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` e `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, encontre o comentário `// Add resource for Microsoft Foundry` e adicione o código logo abaixo dele. Isso adiciona os detalhes de conexão do projeto Microsoft Foundry. + + ```csharp + // Adicionar recurso para Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Vamos analisar o código. + + - `builder.AddFoundry("foundry")`: Isso adiciona os detalhes de conexão do Microsoft Foundry por meio de um recurso personalizado, `FoundryResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add resource for agents on Microsoft Foundry` e adicione o código logo abaixo dele. Isso expõe a lista de detalhes dos agentes para a aplicação que o referencia. + + ```csharp + // Adicionar recurso para agentes no Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Vamos analisar o código. + + - `builder.AddAgents("agents")`: Isso adiciona a lista de detalhes dos agentes por meio de um recurso personalizado, `AgentResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add backend agent service` e adicione o código logo abaixo dele. Isso define o serviço de agente backend que referencia o recurso `foundry` — todos os detalhes de conexão do Microsoft Foundry são passados para o aplicativo de serviço de agente backend. + + ```csharp + // Adicionar serviço de agente backend + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Vamos analisar o código. + + - `builder.AddProject("agent")`: Isso adiciona o aplicativo de serviço de agente backend como um projeto .NET. + - `.WithReference(foundry)`: Isso referencia o recurso foundry criado acima, que passa os detalhes de conexão do Microsoft Foundry para o aplicativo de serviço de agente backend. + +1. No mesmo arquivo, encontre o comentário `// Add frontend web UI` e adicione o código logo abaixo dele. Isso define a interface web frontend que referencia os recursos `agents` e `agent` — os detalhes dos agentes e os detalhes de conexão do backend são passados para o aplicativo de interface web frontend. + + ```csharp + // Adicionar interface web frontend + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Vamos analisar o código. + + - `builder.AddProject("webui")`: Isso adiciona o aplicativo de interface web frontend como um projeto .NET. + - `.WithExternalHttpEndpoints()`: Isso expõe o aplicativo de interface web frontend para a Internet, tornando-o acessível publicamente. + - `.WithReference(agents)`: Isso referencia o recurso de agentes criado acima, que passa a lista de agentes para o aplicativo de interface web frontend. + - `.WithReference(agent)`: Isso referencia o aplicativo de serviço de agente backend, que passa os detalhes de conexão para o aplicativo de interface web frontend. + +## Implementar o padrão handoff no serviço de agente backend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, encontre o comentário `// Create AzureOpenAIClient instance with EntraID authentication` e adicione o código logo abaixo dele. Isso conecta ao projeto Microsoft Foundry. + + ```csharp + // Criar instância do AzureOpenAIClient com autenticação EntraID + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + + var url = new Uri(endpoint.GetAzureOpenAIResponsesEndpoint()); + var chatClient = new AzureOpenAIClient(url, credential) + .GetResponsesClient() + .AsIChatClient(model); + ``` + + Vamos analisar o código. + + - `new DefaultAzureCredential(...)`: Isso faz login no Azure sem uma chave de API. Usa os detalhes de login do Azure CLI ou Azure Developer CLI na sua máquina local, e Managed Identity quando o aplicativo é implantado no Azure. + - `endpoint.GetAzureOpenAIResponsesEndpoint()`: Isso converte o endpoint do projeto Microsoft Foundry para o endpoint OpenAI do Microsoft Foundry porque o SDK do Microsoft Foundry atualmente não suporta o padrão handoff. + - `new AzureOpenAIClient(url, credential)`: Isso conecta à instância do Azure OpenAI usando o endpoint e os detalhes de login e o converte em uma instância `IChatClient`. + +1. No mesmo arquivo, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso obtém os detalhes dos agentes do projeto Microsoft Foundry e os registra no contêiner IoC como serviços singleton. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + foreach (var agentSettings in agents) + { + var instruction = await File.ReadAllTextAsync( + Path.Combine(AppContext.BaseDirectory, "Prompts", $"{agentSettings.Name}.txt")); + + var agent = new ChatClientAgent( + chatClient, + instructions: instruction, + name: agentSettings.Name); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Vamos analisar o código. + + - Já conhecemos a lista de agentes, mas sabemos apenas seus nomes. Portanto, o código executa o loop `foreach` para cada agente. + - `await File.ReadAllTextAsync(...)`: Isso importa o arquivo de instrução do agente. + - `new ChatClientAgent(chatClient, instructions, name)`: Usando as informações de cada agente, a instrução e a instância `IChatClient`, isso cria uma instância de agente. + - `builder.Services.AddKeyedSingleton(name, agent)`: Isso registra a instância do agente como um serviço singleton. + +1. No mesmo arquivo, encontre o comentário `// Build a handoff workflow pattern with the agents registered` e adicione o código logo abaixo dele. + + ```csharp + // Construir um padrão de fluxo de trabalho handoff com os agentes registrados + builder.AddWorkflow("publisher", (sp, key) => + { + var triage = sp.GetRequiredKeyedService("triage-agent"); + var generalSupport = sp.GetRequiredKeyedService("general-support-agent"); + var networkSpecialist = sp.GetRequiredKeyedService("network-specialist-agent"); + var warranty = sp.GetRequiredKeyedService("warranty-agent"); + + var specialists = new[] { generalSupport, networkSpecialist, warranty }; + + var workflow = AgentWorkflowBuilder.CreateHandoffBuilderWith(triage) + // A triagem pode transferir para qualquer especialista + .WithHandoffs(triage, specialists) + // Cada especialista pode transferir para outros especialistas + .WithHandoffs(generalSupport, [networkSpecialist, warranty]) + .WithHandoffs(networkSpecialist, [generalSupport, warranty]) + .WithHandoffs(warranty, [generalSupport, networkSpecialist]) + // Todos os especialistas retornam para a triagem + .WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing") + .Build(); + + // HandoffWorkflowBuilder.Build() não define o nome do fluxo de trabalho. + // Define via reflexão para que a validação de nome do AddWorkflow funcione. + typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key); + + return workflow; + }).AddAsAIAgent("publisher"); + ``` + + Vamos analisar o código. + + - `var specialists = new[] { generalSupport, networkSpecialist, warranty };`: Isso define a lista de agentes especialistas. O agente de triagem é o ponto de partida que redireciona a solicitação do usuário para um dos agentes especialistas. + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: Isso adiciona o fluxo de trabalho multi-agente como outra instância de agente chamada `publisher` e o registra como singleton. + - `AgentWorkflowBuilder.CreateHandoffBuilderWith(triage)`: Este é o construtor de fluxo de trabalho handoff com o agente de triagem. + - `.WithHandoffs(triage, specialists)`: Isso define a transferência do agente de triagem para os agentes especialistas. + - `.WithHandoffs(generalSupport, [networkSpecialist, warranty])`: Isso define a transferência do agente de suporte geral para os outros agentes especialistas. + - `.WithHandoffs(networkSpecialist, [generalSupport, warranty])`: Isso define a transferência do agente especialista em rede para os outros agentes especialistas. + - `.WithHandoffs(warranty, [generalSupport, networkSpecialist])`: Isso define a transferência do agente de garantia para os outros agentes especialistas. + - `.WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing")`: Isso define a transferência de todos os agentes especialistas de volta para o agente de triagem quando o problema é resolvido ou precisa de encaminhamento adicional. + - `typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key);`: Isso injeta o nome do fluxo de trabalho, que é uma solução temporária. + +1. No mesmo arquivo, encontre o comentário `// Map AGUI to the publisher workflow agent` e adicione o código logo abaixo dele. O fluxo de trabalho é exposto como um endpoint de API em `ag-ui` para que a interface web frontend possa se comunicar com este aplicativo de serviço de agente backend. + + ```csharp + // Mapear AGUI para o agente de fluxo de trabalho publisher + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + .CreateFixedAgent() + ); + ``` + + Note que `.CreateFixedAgent()` é uma solução temporária até que o fluxo de saída seja tratado corretamente. + +## Implementar o padrão handoff na interface web frontend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso registra todos os detalhes dos agentes para que a interface web saiba qual agente está respondendo. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + builder.Services.AddSingleton(agents); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register the backend agent service as an HTTP client` e adicione o código logo abaixo dele. O Aspire já fornece ao aplicativo de interface web frontend os detalhes de conexão para o serviço de agente backend. + + ```csharp + // Registrar o serviço de agente backend como um cliente HTTP + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register AGUI client` e adicione o código logo abaixo dele. Usando este cliente AGUI, o aplicativo de interface web frontend se comunica com o aplicativo de serviço de agente backend via o endpoint `ag-ui`. + + ```csharp + // Registrar cliente AGUI + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Executar o Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Certifique-se de que você já fez login no Azure usando tanto o Azure CLI quanto o Azure Developer CLI. Se não tiver certeza, siga [este passo](./00-setup.md#fazer-login-no-azure) novamente. + +1. Execute o seguinte comando para iniciar todos os aplicativos através do Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. O painel do Aspire abre automaticamente. + + ![Painel do Aspire](../../../docs/images/step-03-image-01.png) + + Clique no aplicativo de serviço de agente backend. + +1. Quando a página Dev UI abrir, altere o agente para `publisher` e veja que o agente de triagem distribui a solicitação para os outros agentes. + + ![Microsoft Agent Framework Dev UI - Padrão handoff](../../../docs/images/step-03-image-02.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Dev UI - Enviar solicitação](../../../docs/images/step-03-image-03.png) + + Veja o resultado e como o fluxo de trabalho progride no lado esquerdo da tela. + + ![Microsoft Agent Framework Dev UI - Execução do fluxo de trabalho](../../../docs/images/step-03-image-04.png) + +1. Volte ao painel do Aspire e clique no aplicativo de interface web. + + ![Painel do Aspire](../../../docs/images/step-03-image-05.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Chat UI - Enviar solicitação](../../../docs/images/step-03-image-06.png) + + Veja o resultado. + +1. Pressione `Ctrl`+`C` para encerrar todos os aplicativos em execução. + +## Implantar no Azure + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Execute o seguinte comando para provisionar e implantar tanto a interface web frontend quanto o serviço de agente backend no Azure. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após concluído, você verá a URL do aplicativo de interface web na tela do terminal. Abra-a no seu navegador e envie uma solicitação. + + ![Microsoft Agent Framework no Azure Container Apps - Enviar solicitação](../../../docs/images/step-03-image-07.png) + + Veja o resultado. + +1. Quando tudo estiver pronto, remova todos os aplicativos e agentes do Azure. + + ```bash + # Excluir tanto o aplicativo de interface web quanto o de serviço de agente. + azd down --purge --force + + # Excluir todos os agentes e o recurso Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +Parabéns! 🎉 Você acabou de concluir o terceiro cenário de orquestração multi-agente – o padrão handoff. Vamos prosseguir! + +👈 [02: Concurrent Pattern](./02-concurrent-pattern.md) | [04: Group Chat Pattern](./04-group-chat-pattern.md) 👉 diff --git a/localization/pt-br/docs/04-group-chat-pattern.md b/localization/pt-br/docs/04-group-chat-pattern.md new file mode 100644 index 0000000..0258423 --- /dev/null +++ b/localization/pt-br/docs/04-group-chat-pattern.md @@ -0,0 +1,421 @@ +# 04 Padrão Group Chat + +No padrão group chat, múltiplos agentes participam de uma conversa compartilhada, alternando para contribuir com suas especialidades. Um orquestrador gerencia o fluxo da discussão, decidindo qual agente fala a seguir e quando a conversa deve terminar. Isso é adequado para planejamento multifuncional, brainstorming criativo ou qualquer tarefa onde perspectivas diversas precisam interagir e se complementar iterativamente. + +## Cenário + +Você faz parte de uma equipe multifuncional de produto planejando o lançamento de um novo produto com agentes – agente de estratégia de produto, agente de experiência do usuário, agente técnico e agente de negócios. + +
+ Arquitetura - Padrão Group Chat +
+ +## Obter a raiz do repositório + +1. Obtenha a variável `$REPOSITORY_ROOT` primeiro. + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## Copiar o projeto inicial + +1. Se você já tem o diretório `workshop`, renomeie ou remova-o primeiro. + +1. Execute o script de configuração para copiar o projeto inicial para o diretório `workshop`. + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 04-group-chat-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 04-group-chat-pattern + ``` + +## Implantar os agentes + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.PromptAgent/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Navegue até o diretório `resources-foundry`. + + ```bash + pushd resources-foundry + ``` + +1. Execute o seguinte comando para provisionar e implantar os agentes definidos acima no Microsoft Foundry. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após o provisionamento e a implantação serem concluídos, execute o seguinte comando para confirmar que os agentes foram implantados com sucesso. + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + Você deverá ver os quatro nomes dos agentes. + + ```text + business-agent + technical-agent + user-experience-agent + product-strategy-agent + ``` + +1. Navegue de volta ao diretório do workshop. + + ```bash + popd + ``` + +## Configurar a orquestração do Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Verifique se todas as informações necessárias dos agentes foram registradas. + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + Você deverá ver os valores de `AZURE_TENANT_ID`, `FOUNDRY_NAME`, `FOUNDRY_PROJECT_NAME`, `FOUNDRY_RESOURCE_GROUP` e `Foundry:Project:Endpoint`. + +1. Abra `src/MultiAgentWorkshop.AppHost/appsettings.json`, encontre a linha de comentário `// Add agents` e adicione a propriedade `Agents` logo abaixo dela. + + ```jsonc + { + ... + // Adicionar agentes + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. Abra `src/MultiAgentWorkshop.AppHost/AppHost.cs`, encontre o comentário `// Add resource for Microsoft Foundry` e adicione o código logo abaixo dele. Isso adiciona os detalhes de conexão do projeto Microsoft Foundry. + + ```csharp + // Adicionar recurso para Microsoft Foundry + var foundry = builder.AddFoundry("foundry"); + ``` + + Vamos analisar o código. + + - `builder.AddFoundry("foundry")`: Isso adiciona os detalhes de conexão do Microsoft Foundry por meio de um recurso personalizado, `FoundryResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add resource for agents on Microsoft Foundry` e adicione o código logo abaixo dele. Isso expõe a lista de detalhes dos agentes para a aplicação que o referencia. + + ```csharp + // Adicionar recurso para agentes no Microsoft Foundry + var agents = builder.AddAgents("agents"); + ``` + + Vamos analisar o código. + + - `builder.AddAgents("agents")`: Isso adiciona a lista de detalhes dos agentes por meio de um recurso personalizado, `AgentResource`. Se você quiser saber mais sobre o recurso personalizado do Aspire, visite [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/). + +1. No mesmo arquivo, encontre o comentário `// Add backend agent service` e adicione o código logo abaixo dele. Isso define o serviço de agente backend que referencia o recurso `foundry` – todos os detalhes de conexão do Microsoft Foundry são passados para o aplicativo de serviço de agente backend. + + ```csharp + // Adicionar serviço de agente backend + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + Vamos analisar o código. + + - `builder.AddProject("agent")`: Isso adiciona o aplicativo de serviço de agente backend como um projeto .NET. + - `.WithReference(foundry)`: Isso referencia o recurso foundry criado acima, que passa os detalhes de conexão do Microsoft Foundry para o aplicativo de serviço de agente backend. + +1. No mesmo arquivo, encontre o comentário `// Add frontend web UI` e adicione o código logo abaixo dele. Isso define a interface web frontend que referencia os recursos `agents` e `agent` – os detalhes dos agentes e os detalhes de conexão do backend são passados para o aplicativo de interface web frontend. + + ```csharp + // Adicionar interface web frontend + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + Vamos analisar o código. + + - `builder.AddProject("webui")`: Isso adiciona o aplicativo de interface web frontend como um projeto .NET. + - `.WithExternalHttpEndpoints()`: Isso expõe o aplicativo de interface web frontend para a Internet, tornando-o acessível publicamente. + - `.WithReference(agents)`: Isso referencia o recurso de agentes criado acima, que passa a lista de agentes para o aplicativo de interface web frontend. + - `.WithReference(agent)`: Isso referencia o aplicativo de serviço de agente backend, que passa os detalhes de conexão para o aplicativo de interface web frontend. + +## Implementar o padrão group chat no serviço de agente backend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.Agent/Program.cs`, encontre o comentário `// Create AIProjectClient instance with EntraID authentication` e adicione o código logo abaixo dele. Isso conecta ao projeto Microsoft Foundry. + + ```csharp + // Criar instância do AIProjectClient com autenticação EntraID + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + Vamos analisar o código. + + - `new DefaultAzureCredential(...)`: Isso faz login no Azure sem uma chave de API. Usa os detalhes de login do Azure CLI ou Azure Developer CLI na sua máquina local, e Managed Identity quando o aplicativo é implantado no Azure. + - `new AIProjectClient(endpoint, credential)`: Isso conecta à instância do projeto Microsoft Foundry usando o endpoint e os detalhes de login. + +1. No mesmo arquivo, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso obtém os detalhes dos agentes do projeto Microsoft Foundry e os registra no contêiner IoC como serviços singleton. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + Vamos analisar o código. + + - Já conhecemos a lista de agentes, mas sabemos apenas seus nomes. Portanto, o código executa o loop `foreach` para cada agente. + - `new AgentReference(name, version)`: Usando as informações de cada agente, isso cria uma instância de referência. + - `projectClient.AsAIAgent(reference, factory)`: Isso conecta ao agente real usando os detalhes de referência. + - `builder.Services.AddKeyedSingleton(name, agent)`: Isso registra a instância do agente como um serviço singleton. + + > **NOTA**: Você pode notar a classe `AgentRecordShimChatClient`. É uma solução temporária para uma incompatibilidade de versão entre o Microsoft Agent Framework e o SDK do Microsoft Foundry, que será removida em breve. + +1. No mesmo arquivo, encontre o comentário `// Build a group chat workflow pattern with the agents registered` e adicione o código logo abaixo dele. + + ```csharp + // Construir um padrão de fluxo de trabalho group chat com os agentes registrados + builder.AddWorkflow("publisher", (sp, key) => + { + var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name)); + + return AgentWorkflowBuilder.CreateGroupChatBuilderWith(agentList => + new RoundRobinGroupChatManager(agentList) { MaximumIterationCount = participants.Count() * 2 }) + .AddParticipants(participants) + .WithName(key) + .Build(); + }).AddAsAIAgent("publisher"); + ``` + + Vamos analisar o código. + + - `var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name));`: Isso identifica a lista de agentes participantes no group chat. + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`: Isso adiciona o fluxo de trabalho multi-agente como outra instância de agente chamada `publisher` e o registra como singleton. + - `AgentWorkflowBuilder.CreateGroupChatBuilderWith(...)`: Este é o construtor de fluxo de trabalho group chat que usa o mesmo nome, `publisher`. + - `new RoundRobinGroupChatManager(...)`: Isso define a estratégia do group chat como round-robin. Também define o número máximo de iterações. Neste código, cada agente responde duas vezes durante o ciclo round-robin. + +1. No mesmo arquivo, encontre o comentário `// Map AGUI to the publisher workflow agent` e adicione o código logo abaixo dele. O fluxo de trabalho é exposto como um endpoint de API em `ag-ui` para que a interface web frontend possa se comunicar com este aplicativo de serviço de agente backend. + + ```csharp + // Mapear AGUI para o agente de fluxo de trabalho publisher + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## Implementar o padrão group chat na interface web frontend + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Abra `src/MultiAgentWorkshop.WebUI/Program.cs`, encontre o comentário `// Register all agents passed from Aspire` e adicione o código logo abaixo dele. Isso registra todos os detalhes dos agentes para que a interface web saiba qual agente está respondendo. + + ```csharp + // Registrar todos os agentes passados pelo Aspire + builder.Services.AddSingleton(agents); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register the backend agent service as an HTTP client` e adicione o código logo abaixo dele. O Aspire já fornece ao aplicativo de interface web frontend os detalhes de conexão para o serviço de agente backend. + + ```csharp + // Registrar o serviço de agente backend como um cliente HTTP + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. No mesmo arquivo, encontre o comentário `// Register AGUI client` e adicione o código logo abaixo dele. Usando este cliente AGUI, o aplicativo de interface web frontend se comunica com o aplicativo de serviço de agente backend via o endpoint `ag-ui`. + + ```csharp + // Registrar cliente AGUI + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## Executar o Aspire + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Certifique-se de que você já fez login no Azure usando tanto o Azure CLI quanto o Azure Developer CLI. Se não tiver certeza, siga [este passo](./00-setup.md#fazer-login-no-azure) novamente. + +1. Execute o seguinte comando para iniciar todos os aplicativos através do Aspire. + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. O painel do Aspire abre automaticamente. + + ![Painel do Aspire](../../../docs/images/step-04-image-01.png) + + Clique no aplicativo de serviço de agente backend. + +1. Quando a página Dev UI abrir, altere o agente para `publisher` e clique no botão "Configure & Run". + + ![Microsoft Agent Framework Dev UI - Padrão group chat](../../../docs/images/step-04-image-02.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Dev UI - Enviar solicitação](../../../docs/images/step-04-image-03.png) + + Veja o resultado e como o fluxo de trabalho progride no lado esquerdo da tela. + + ![Microsoft Agent Framework Dev UI - Execução do fluxo de trabalho](../../../docs/images/step-04-image-04.png) + +1. Volte ao painel do Aspire e clique no aplicativo de interface web. + + ![Painel do Aspire](../../../docs/images/step-04-image-05.png) + +1. Envie qualquer solicitação. + + ![Microsoft Agent Framework Chat UI - Enviar solicitação](../../../docs/images/step-04-image-06.png) + + Veja o resultado. + +1. Pressione `Ctrl`+`C` para encerrar todos os aplicativos em execução. + +## Implantar no Azure + +1. Certifique-se de que você está no diretório `workshop`. + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. Execute o seguinte comando para provisionar e implantar tanto a interface web frontend quanto o serviço de agente backend no Azure. + + ```bash + azd up + ``` + + Durante o provisionamento, será solicitado que você informe um nome de ambiente, assinatura Azure e localização. + +1. Após concluído, você verá a URL do aplicativo de interface web na tela do terminal. Abra-a no seu navegador e envie uma solicitação. + + ![Microsoft Agent Framework no Azure Container Apps - Enviar solicitação](../../../docs/images/step-04-image-07.png) + + Veja o resultado. + +1. Quando tudo estiver pronto, remova todos os aplicativos e agentes do Azure. + + ```bash + # Excluir tanto o aplicativo de interface web quanto o de serviço de agente. + azd down --purge --force + + # Excluir todos os agentes e o recurso Microsoft Foundry. + cd resources-foundry + azd down --purge --force + ``` + +--- + +Parabéns! 🎉 Você acabou de concluir o quarto cenário de orquestração multi-agente – o padrão group chat. Você concluiu tudo! + +👈 [03: Handoff Pattern](./03-handoff-pattern.md) | [README](../README.md) 👉 diff --git a/localization/pt-br/docs/README.md b/localization/pt-br/docs/README.md new file mode 100644 index 0000000..6591077 --- /dev/null +++ b/localization/pt-br/docs/README.md @@ -0,0 +1,10 @@ +# Materiais do Workshop Multi-Agent + +Aqui está a lista de materiais do workshop para construir padrões de orquestração multi-agente, junto com seus exemplos de código. + +| Documento | Exemplo de Código | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](./01-sequential-pattern.md) | [01-sequential-pattern](../samples/01-sequential-pattern) | +| [02-concurrent-pattern.md](./02-concurrent-pattern.md) | [02-concurrent-pattern](../samples/02-concurrent-pattern) | +| [03-handoff-pattern.md](./03-handoff-pattern.md) | [03-handoff-pattern](../samples/03-handoff-pattern) | +| [04-group-chat-pattern.md](./04-group-chat-pattern.md) | [04-group-chat-pattern](../samples/04-group-chat-pattern) | diff --git a/localization/pt-br/samples/01-sequential-pattern/README.md b/localization/pt-br/samples/01-sequential-pattern/README.md new file mode 100644 index 0000000..017076b --- /dev/null +++ b/localization/pt-br/samples/01-sequential-pattern/README.md @@ -0,0 +1,13 @@ +# 01 Padrão Sequencial + +No padrão sequencial, os agentes trabalham um após o outro em um pipeline definido, onde a saída de cada agente alimenta o próximo. Essa abordagem funciona bem para tarefas que seguem uma progressão natural, como fluxos de trabalho de criação de conteúdo, transformações de dados em etapas ou análises passo a passo. + +
+ Arquitetura - Padrão Sequencial +
+ +## Instruções + +Siga as instruções em [01-sequential-pattern.md](../../docs/01-sequential-pattern.md) com o projeto [start](../../../../samples/01-sequential-pattern/start). + +Após concluir, compare o seu resultado com o projeto [complete](../../../../samples/01-sequential-pattern/complete). diff --git a/localization/pt-br/samples/02-concurrent-pattern/README.md b/localization/pt-br/samples/02-concurrent-pattern/README.md new file mode 100644 index 0000000..897ccdb --- /dev/null +++ b/localization/pt-br/samples/02-concurrent-pattern/README.md @@ -0,0 +1,13 @@ +# 02 Padrão Concorrente + +No padrão concorrente, múltiplos agentes analisam a mesma entrada simultaneamente, cada um trazendo sua própria especialidade. Quando todos os agentes terminam, suas saídas são combinadas em um resultado unificado. Isso é ideal para tarefas que se beneficiam de múltiplos pontos de vista trabalhando ao mesmo tempo, como análise de múltiplas perspectivas, avaliação em conjunto ou tomada de decisão colaborativa. + +
+ Arquitetura - Padrão Concorrente +
+ +## Instruções + +Siga as instruções em [02-concurrent-pattern.md](../../docs/02-concurrent-pattern.md) com o projeto [start](../../../../samples/02-concurrent-pattern/start). + +Após concluir, compare o seu resultado com o projeto [complete](../../../../samples/02-concurrent-pattern/complete). diff --git a/localization/pt-br/samples/03-handoff-pattern/README.md b/localization/pt-br/samples/03-handoff-pattern/README.md new file mode 100644 index 0000000..4dd020a --- /dev/null +++ b/localization/pt-br/samples/03-handoff-pattern/README.md @@ -0,0 +1,13 @@ +# 03 Padrão de Transferência + +No padrão de transferência, os agentes passam o controle dinamicamente uns para os outros com base no contexto da conversa. Um agente de triagem recebe a solicitação inicial e a encaminha para o especialista mais adequado para lidar com ela. Os especialistas também podem redirecionar entre si quando o problema envolve diferentes domínios. Isso funciona bem para cenários como suporte de TI, atendimento ao cliente ou qualquer fluxo de trabalho onde diferentes especialidades são necessárias em diferentes etapas. + +
+ Arquitetura - Padrão de Transferência +
+ +## Instruções + +Siga as instruções em [03-handoff-pattern.md](../../docs/03-handoff-pattern.md) com o projeto [start](../../../../samples/03-handoff-pattern/start). + +Após concluir, compare o seu resultado com o projeto [complete](../../../../samples/03-handoff-pattern/complete). diff --git a/localization/pt-br/samples/04-group-chat-pattern/README.md b/localization/pt-br/samples/04-group-chat-pattern/README.md new file mode 100644 index 0000000..7f20e2f --- /dev/null +++ b/localization/pt-br/samples/04-group-chat-pattern/README.md @@ -0,0 +1,13 @@ +# 04 Padrão de Chat em Grupo + +No padrão de chat em grupo, múltiplos agentes participam de uma conversa compartilhada, contribuindo com sua especialidade em turnos. Um orquestrador gerencia o fluxo da discussão, decidindo qual agente fala em seguida e quando a conversa deve terminar. Isso é adequado para planejamento multifuncional, brainstorming criativo ou qualquer tarefa onde perspectivas diversas precisam interagir e construir umas sobre as outras de forma iterativa. + +
+ Arquitetura - Padrão de Chat em Grupo +
+ +## Instruções + +Siga as instruções em [04-group-chat-pattern.md](../../docs/04-group-chat-pattern.md) com o projeto [start](../../../../samples/04-group-chat-pattern/start). + +Após concluir, compare o seu resultado com o projeto [complete](../../../../samples/04-group-chat-pattern/complete). diff --git a/localization/pt-br/samples/README.md b/localization/pt-br/samples/README.md new file mode 100644 index 0000000..8309882 --- /dev/null +++ b/localization/pt-br/samples/README.md @@ -0,0 +1,10 @@ +# Exemplos de Código de Orquestração Multi-Agente + +Aqui está a lista de padrões de orquestração multi-agente e seus exemplos de código. + +| Documento | Exemplo de Código | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](../docs/01-sequential-pattern.md) | [01-sequential-pattern](./01-sequential-pattern) | +| [02-concurrent-pattern.md](../docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./02-concurrent-pattern) | +| [03-handoff-pattern.md](../docs/03-handoff-pattern.md) | [03-handoff-pattern](./03-handoff-pattern) | +| [04-group-chat-pattern.md](../docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./04-group-chat-pattern) | diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md new file mode 100644 index 0000000..95153da --- /dev/null +++ b/localization/zh-cn/README.md @@ -0,0 +1,65 @@ +# Multi-Agent Orchestration Workshop + +这是一份使用 [Microsoft Agent Framework](https://aka.ms/agent-framework)、[Microsoft Foundry](https://aka.ms/microsoft-foundry) 和 [Aspire](https://aspire.dev) 构建基于 .NET 的多智能体应用的工作坊教材。 + +![MAF + Foundry 工作坊](../../images/hero.jpg) + +## 这个工作坊是做什么的? + +构建单智能体应用很简单。但在许多真实场景中,需要多个智能体协同工作,而构建多智能体应用远不如构建单智能体那么简单。[Microsoft Agent Framework](https://aka.ms/agent-framework) 提供了五种多智能体编排模式: + +| 模式 | 描述 | +|----------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| +| [顺序模式(Sequential)](https://learn.microsoft.com/agent-framework/workflows/orchestrations/sequential?pivots=programming-language-csharp) | 智能体按预定义的顺序依次执行 | +| [并发模式(Concurrent)](https://learn.microsoft.com/agent-framework/workflows/orchestrations/concurrent?pivots=programming-language-csharp) | 智能体并行执行 | +| [交接模式(Handoff)](https://learn.microsoft.com/agent-framework/workflows/orchestrations/handoff?pivots=programming-language-csharp) | 智能体根据上下文将控制权传递给彼此 | +| [群聊模式(Group Chat)](https://learn.microsoft.com/agent-framework/workflows/orchestrations/group-chat?pivots=programming-language-csharp) | 智能体在共享对话中协作 | +| [Magentic](https://learn.microsoft.com/agent-framework/workflows/orchestrations/magentic?pivots=programming-language-python) | 管理者智能体动态协调专业智能体 | + +## 功能特性 + +在本工作坊中,我们将构建除 Magentic 模式以外的所有多智能体编排模式。完成每个模式后,您将获得以下架构: + +- [Blazor](https://blazor.net) 前端聊天界面 +- [ASP.NET](https://asp.net) 后端搭配 [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) 用于智能体托管 +- [Aspire](https://aspire.dev) 用于云原生应用编排 + +> [!NOTE] +> Microsoft Agent Framework SDK 的 .NET 版本将在后续版本中支持 Magentic 模式。 + +## 前提条件 + +- [Azure 订阅(免费)](http://azure.microsoft.com/free) +- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) 或更高版本 +- [Visual Studio 2026](https://visualstudio.microsoft.com/downloads/) 或 [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) +- [Docker Desktop](https://docs.docker.com/desktop/) 或等效工具 +- [GitHub CLI](https://cli.github.com) +- [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) +- [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) +- [Aspire CLI](https://aspire.dev/get-started/install-cli/) + +## 工作坊课程 + +| 课程 | 文档 | 代码示例 | +|-----------------------|-------------------------------------------------------------|----------------------------------------------------------| +| 00 环境搭建 | [00-setup.md](./docs/00-setup.md) | | +| 01 顺序模式 | [01-sequential-pattern.md](./docs/01-sequential-pattern.md) | [01-sequential-pattern](./samples/01-sequential-pattern) | +| 02 并发模式 | [02-concurrent-pattern.md](./docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./samples/02-concurrent-pattern) | +| 03 交接模式 | [03-handoff-pattern.md](./docs/03-handoff-pattern.md) | [03-handoff-pattern](./samples/03-handoff-pattern) | +| 04 群聊模式 | [04-group-chat-pattern.md](./docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./samples/04-group-chat-pattern) | + +## 选择您的首选语言! + +本工作坊教材提供以下语言版本。 + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](../ja-jp/README.md) | [한국어](../ko-kr/README.md) | [Português](../pt-br/README.md) | [中文(简体)](./README.md) + +## 资源 + +- [Microsoft Agent Framework](https://aka.ms/agent-framework) +- [Microsoft Agent Framework - 工作流编排](https://learn.microsoft.com/agent-framework/workflows/orchestrations) +- [Microsoft Foundry](https://aka.ms/microsoft-foundry) +- [Microsoft Foundry Agent Service](https://aka.ms/microsoft-foundry/agent-service) +- [Model Context Protocol (MCP)](https://modelcontextprotocol.io) +- [Aspire](https://aspire.dev) diff --git a/localization/zh-cn/docs/00-setup.md b/localization/zh-cn/docs/00-setup.md new file mode 100644 index 0000000..831aa8c --- /dev/null +++ b/localization/zh-cn/docs/00-setup.md @@ -0,0 +1,215 @@ +# 00 环境搭建 + +在本课程中,我们将在您的本地机器或 GitHub Codespaces 中搭建开发环境。 + +## 前提条件 + +- Web 浏览器:[Microsoft Edge](https://microsoft.com/edge) 或 [Google Chrome](http://chrome.google.com) +- [Azure 订阅](https://azure.microsoft.com/free) + +## 在 GitHub Codespaces 中搭建 + +对于本工作坊,我们强烈建议使用 GitHub Codespaces 以节省搭建开发环境的时间。如果您更倾向于在本地机器上搭建开发环境,请跳过本节,直接前往[在 VS Code 中搭建](#在-vs-code-中搭建)部分。 + +1. 点击下方按钮创建一个新的 GitHub Codespaces 实例。 + + [![创建新的 GitHub Codespaces 实例](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/multi-agent-orchestration-workshop) + +1. 创建完成后,运行以下命令验证必要工具是否已正确安装。 + + ```bash + # .NET SDK + dotnet --list-sdks + + # node.js + node --version + npm --version + + # PowerShell + pwsh --version + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +1. 检查您的 GitHub 登录状态。 + + ```bash + gh auth status + ``` + +1. 获取远程仓库详情。 + + ```bash + git remote -v + ``` + + 您应该看到以下内容。 + + ```text + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/Azure-Samples/multi-agent-orchestration-workshop.git (push) + ``` + + 如果没有看到这两行,请删除当前的 GitHub Codespaces 实例并重新创建。 + +1. 由于 GitHub Codespaces 实例不在您的账户下,请使用以下命令 fork 仓库以转移所有权。 + + ```bash + git remote -v > remote.txt + git add . && git commit -m "Add remote.txt for forking" + ``` + + 您可能会看到类似以下的提示信息: + + ```text + You don't have write access to the Azure-Samples/multi-agent-orchestration-workshop repository, so you cannot push changes to it. + To obtain write access we will point this codespace at your fork of Azure-Samples/multi-agent-orchestration-workshop, creating that fork if it doesn't exist. + + Would you like to proceed? + ``` + + 输入 `y` 继续。它将自动在您的账户下 fork 该仓库。 + +1. 检查远程仓库状态。 + + ```bash + git remote -v + ``` + + 这次,您应该看到以下四行。 + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + + 如果没有看到这四行,请删除并重新创建 GitHub Codespaces 实例。 + +## 在 VS Code 中搭建 + +如果您已经创建了 GitHub Codespaces 实例,请跳过本节,直接前往[登录 Azure](#登录-azure)部分。 + +1. 在您的机器上安装以下工具。 + + - [VS Code](https://code.visualstudio.com/download) + [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) + - [Docker Desktop](https://docs.docker.com/desktop/) 或等效工具 + - [GitHub CLI](https://cli.github.com) + - [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) + - [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) + - [Aspire CLI](https://aspire.dev/get-started/install-cli/) + + 然后,运行以下命令验证它们是否已正确安装。 + + ```bash + # .NET SDK + dotnet --list-sdks + + # Docker + docker info + + # GitHub CLI + gh --version + + # azd CLI + azd version + + # az CLI + az --version + az bicep version + + # Aspire CLI + aspire --version + ``` + +### 登录 GitHub + +1. 登录 GitHub。 + + ```bash + gh auth login + ``` + + 登录成功后,运行以下命令验证登录状态。 + + ```bash + gh auth status + ``` + +### 克隆项目 + +1. 将此仓库 fork 到您的本地机器。 + + ```bash + gh repo fork Azure-Samples/multi-agent-orchestration-workshop --clone + ``` + +1. 导航到克隆的目录。 + + ```bash + cd multi-agent-orchestration-workshop + ``` + +1. 检查远程仓库状态。 + + ```bash + git remote -v + ``` + + 您应该看到以下四行。 + + ```text + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (fetch) + origin https://github.com/{{YOUR_GITHUB_ID}}/multi-agent-orchestration-workshop.git (push) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (fetch) + upstream https://github.com/Azure-Samples/multi-agent-orchestration-workshop (push) + ``` + +1. 在 VS Code 中打开仓库。 + + ```bash + code . + ``` + +## 登录 Azure + +1. 登录 Azure。 + + ```bash + # Azure Developer CLI + azd auth login + + # Azure CLI + az login + ``` + + 登录成功后,运行以下命令验证登录状态。 + + ```bash + # Azure Developer CLI + azd auth login --check-status + + # Azure CLI + az account show + ``` + +--- + +恭喜!🎉 您已完成开发环境搭建。让我们继续吧! + +👈 [README](../README.md) | [01: 顺序模式](./01-sequential-pattern.md) 👉 diff --git a/localization/zh-cn/docs/01-sequential-pattern.md b/localization/zh-cn/docs/01-sequential-pattern.md new file mode 100644 index 0000000..27820e0 --- /dev/null +++ b/localization/zh-cn/docs/01-sequential-pattern.md @@ -0,0 +1,415 @@ +# 01 顺序模式 + +在顺序模式中,智能体按预定义的流水线依次工作,每个智能体的输出作为下一个智能体的输入。这种方式非常适合具有自然推进过程的任务,例如内容创作工作流、分阶段的数据转换或逐步分析。 + +## 场景 + +您正在使用智能体编写一篇技术博客文章——包括研究智能体、大纲智能体、写作智能体和编辑智能体。 + +
+ 架构图 - 顺序模式 +
+ +## 获取仓库根目录 + +1. 首先获取 `$REPOSITORY_ROOT` 变量。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 复制起始项目 + +1. 如果您已经有 `workshop` 目录,请先重命名或删除它。 + +1. 运行安装脚本将起始项目复制到 `workshop` 目录。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 01-sequential-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 01-sequential-pattern + ``` + +## 部署智能体 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.PromptAgent/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 导航到 `resources-foundry` 目录。 + + ```bash + pushd resources-foundry + ``` + +1. 运行以下命令将上面定义的智能体预配并部署到 Microsoft Foundry。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 预配和部署完成后,运行以下命令确认智能体已成功部署。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 您应该看到四个智能体名称。 + + ```text + editor-agent + writer-agent + outliner-agent + research-agent + ``` + +1. 导航回 workshop 目录。 + + ```bash + popd + ``` + +## 配置 Aspire 编排 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 验证所有必要的智能体信息已被记录。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + 您应该看到 `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP` 和 `Foundry:Project:Endpoint` 的值。 + +1. 打开 `src/MultiAgentWorkshop.AppHost/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "research-agent", + "Version": "1" + }, + { + "Name": "outliner-agent", + "Version": "1" + }, + { + "Name": "writer-agent", + "Version": "1" + }, + { + "Name": "editor-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 打开 `src/MultiAgentWorkshop.AppHost/AppHost.cs`,找到注释 `// Add resource for Microsoft Foundry`,在其正下方添加代码。这将添加 Microsoft Foundry 项目的连接详情。 + + ```csharp + // 添加 Microsoft Foundry 资源 + var foundry = builder.AddFoundry("foundry"); + ``` + + 让我们分解这段代码。 + + - `builder.AddFoundry("foundry")`:这通过自定义资源 `FoundryResource` 添加 Microsoft Foundry 连接详情。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add resource for agents on Microsoft Foundry`,在其正下方添加代码。这将向引用的应用公开智能体详情列表。 + + ```csharp + // 添加 Microsoft Foundry 上的智能体资源 + var agents = builder.AddAgents("agents"); + ``` + + 让我们分解这段代码。 + + - `builder.AddAgents("agents")`:这通过自定义资源 `AgentResource` 添加智能体详情列表。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add backend agent service`,在其正下方添加代码。这将定义引用 `foundry` 资源的后端智能体服务——所有 Microsoft Foundry 连接详情将传递给后端智能体服务应用。 + + ```csharp + // 添加后端智能体服务 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("agent")`:这将后端智能体服务应用作为 .NET 项目添加。 + - `.WithReference(foundry)`:这引用了上面创建的 foundry 资源,将 Microsoft Foundry 连接详情传递给后端智能体服务应用。 + +1. 在同一文件中,找到注释 `// Add frontend web UI`,在其正下方添加代码。这将定义引用 `agents` 和 `agent` 两个资源的前端 Web UI——智能体详情和后端连接详情都将传递给前端 Web UI 应用。 + + ```csharp + // 添加前端 Web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("webui")`:这将前端 Web UI 应用作为 .NET 项目添加。 + - `.WithExternalHttpEndpoints()`:这将前端 Web UI 应用暴露到互联网,使其可公开访问。 + - `.WithReference(agents)`:这引用了上面创建的 agents 资源,将智能体列表传递给前端 Web UI 应用。 + - `.WithReference(agent)`:这引用了后端智能体服务应用,将连接详情传递给前端 Web UI 应用。 + +## 在后端智能体服务中实现顺序模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.Agent/Program.cs`,找到注释 `// Create AIProjectClient instance with EntraID authentication`,在其正下方添加代码。这将连接到 Microsoft Foundry 项目。 + + ```csharp + // 使用 EntraID 身份验证创建 AIProjectClient 实例 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + 让我们分解这段代码。 + + - `new DefaultAzureCredential(...)`:这无需 API 密钥即可登录 Azure。在本地机器上使用您的 Azure CLI 登录或 Azure Developer CLI 登录详情,在部署到 Azure 时使用托管标识。 + - `new AIProjectClient(endpoint, credential)`:这使用端点和登录详情连接到 Microsoft Foundry 项目实例。 + +1. 在同一文件中,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将从 Microsoft Foundry 项目中拉取智能体详情,并将它们作为单例服务注册到 IoC 容器中。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 让我们分解这段代码。 + + - 我们已经知道智能体列表,但只知道它们的名称。因此,代码对每个智能体运行 `foreach` 循环。 + - `new AgentReference(name, version)`:使用每个智能体的信息创建引用实例。 + - `projectClient.AsAIAgent(reference, factory)`:使用引用详情连接到实际的智能体。 + - `builder.Services.AddKeyedSingleton(name, agent)`:将智能体实例注册为单例服务。 + + > **注意**:您可能会注意到 `AgentRecordShimChatClient` 类。这是 Microsoft Agent Framework 和 Microsoft Foundry SDK 之间版本不匹配的临时解决方案,将很快被移除。 + +1. 在同一文件中,找到注释 `// Build a sequential workflow pattern with the agents registered`,在其正下方添加代码。 + + ```csharp + // 使用已注册的智能体构建顺序工作流模式 + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [.. agents.Select(a => sp.GetRequiredKeyedService(a.Name))] + )).AddAsAIAgent("publisher"); + ``` + + 让我们分解这段代码。 + + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`:这将多智能体工作流作为另一个名为 `publisher` 的智能体实例添加,并将其注册为单例。 + - `AgentWorkflowBuilder.BuildSequential(...)`:这是使用相同名称 `publisher` 的顺序工作流构建器。 + + 请注意,它按照 `agents` 数组声明的顺序从之前注册的服务中添加多个智能体。 + +1. 在同一文件中,找到注释 `// Map AGUI to the publisher workflow agent`,在其正下方添加代码。工作流通过 `ag-ui` 端点作为 API 暴露,以便前端 Web UI 可以与此后端智能体服务应用通信。 + + ```csharp + // 将 AGUI 映射到 publisher 工作流智能体 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## 在前端 Web UI 中实现顺序模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.WebUI/Program.cs`,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将注册所有智能体详情,以便 Web UI 知道哪个智能体在响应。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + builder.Services.AddSingleton(agents); + ``` + +1. 在同一文件中,找到注释 `// Register the backend agent service as an HTTP client`,在其正下方添加代码。Aspire 已经为前端 Web UI 应用提供了后端智能体服务的连接详情。 + + ```csharp + // 将后端智能体服务注册为 HTTP 客户端 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 在同一文件中,找到注释 `// Register AGUI client`,在其正下方添加代码。使用此 AGUI 客户端,前端 Web UI 应用通过 `ag-ui` 端点与后端智能体服务应用通信。 + + ```csharp + // 注册 AGUI 客户端 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## 运行 Aspire + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 确保您已经使用 Azure CLI 和 Azure Developer CLI 登录了 Azure。如果不确定,请再次按照[此步骤](./00-setup.md#登录-azure)操作。 + +1. 运行以下命令通过 Aspire 启动所有应用。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 仪表板会自动打开。 + + ![Aspire 仪表板](../../../docs/images/step-01-image-01.png) + + 点击后端智能体服务应用。 + +1. 当 Dev UI 页面打开后,将智能体切换为 `publisher` 并点击 "Configure & Run" 按钮。 + + ![Microsoft Agent Framework Dev UI - 顺序模式](../../../docs/images/step-01-image-02.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Dev UI - 发送请求](../../../docs/images/step-01-image-03.png) + + 查看结果以及屏幕左侧的工作流进度。 + + ![Microsoft Agent Framework Dev UI - 工作流运行](../../../docs/images/step-01-image-04.png) + +1. 返回 Aspire 仪表板,点击 Web UI 应用。 + + ![Aspire 仪表板](../../../docs/images/step-01-image-05.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Chat UI - 发送请求](../../../docs/images/step-01-image-06.png) + + 查看结果。 + +1. 按 `Ctrl`+`C` 终止所有运行中的应用。 + +## 部署到 Azure + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 运行以下命令将前端 Web UI 和后端智能体服务应用预配并部署到 Azure。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 完成后,您将在终端屏幕上看到 Web UI 应用的 URL。在浏览器中打开它并发送请求。 + + ![Microsoft Agent Framework on Azure Container Apps - 发送请求](../../../docs/images/step-01-image-07.png) + + 查看结果。 + +1. 一切完成后,从 Azure 中删除所有应用和智能体。 + + ```bash + # 删除 Web UI 和智能体服务应用。 + azd down --purge --force + + # 删除所有智能体和 Microsoft Foundry 资源。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +恭喜!🎉 您已完成第一个多智能体编排场景——顺序模式。让我们继续吧! + +👈 [00: 环境搭建](./00-setup.md) | [02: 并发模式](./02-concurrent-pattern.md) 👉 diff --git a/localization/zh-cn/docs/02-concurrent-pattern.md b/localization/zh-cn/docs/02-concurrent-pattern.md new file mode 100644 index 0000000..0f3e722 --- /dev/null +++ b/localization/zh-cn/docs/02-concurrent-pattern.md @@ -0,0 +1,446 @@ +# 02 并发模式 + +在并发模式中,多个智能体同时分析相同的输入,每个智能体贡献其专业知识。当所有智能体完成后,它们的输出将被合并为统一的结果。这非常适合需要多个视角同时工作的任务,例如多角度分析、集成评估或协作决策。 + +## 场景 + +您在一家风险投资公司工作,使用智能体分析创业公司的商业计划书——包括市场分析智能体、技术可行性智能体、财务模型智能体、风险评估智能体和聚合智能体。 + +
+ 架构图 - 并发模式 +
+ +## 获取仓库根目录 + +1. 首先获取 `$REPOSITORY_ROOT` 变量。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 复制起始项目 + +1. 如果您已经有 `workshop` 目录,请先重命名或删除它。 + +1. 运行安装脚本将起始项目复制到 `workshop` 目录。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 02-concurrent-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 02-concurrent-pattern + ``` + +## 部署智能体 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.PromptAgent/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 导航到 `resources-foundry` 目录。 + + ```bash + pushd resources-foundry + ``` + +1. 运行以下命令将上面定义的智能体预配并部署到 Microsoft Foundry。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 预配和部署完成后,运行以下命令确认智能体已成功部署。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 您应该看到五个智能体名称。 + + ```text + aggregator-agent + risk-assessment-agent + financial-model-agent + technology-feasibility-agent + market-analysis-agent + ``` + +1. 导航回 workshop 目录。 + + ```bash + popd + ``` + +## 配置 Aspire 编排 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 验证所有必要的智能体信息已被记录。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + 您应该看到 `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP` 和 `Foundry:Project:Endpoint` 的值。 + +1. 打开 `src/MultiAgentWorkshop.AppHost/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "market-analysis-agent", + "Version": "1" + }, + { + "Name": "technology-feasibility-agent", + "Version": "1" + }, + { + "Name": "financial-model-agent", + "Version": "1" + }, + { + "Name": "risk-assessment-agent", + "Version": "1" + }, + { + "Name": "aggregator-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 打开 `src/MultiAgentWorkshop.AppHost/AppHost.cs`,找到注释 `// Add resource for Microsoft Foundry`,在其正下方添加代码。这将添加 Microsoft Foundry 项目的连接详情。 + + ```csharp + // 添加 Microsoft Foundry 资源 + var foundry = builder.AddFoundry("foundry"); + ``` + + 让我们分解这段代码。 + + - `builder.AddFoundry("foundry")`:这通过自定义资源 `FoundryResource` 添加 Microsoft Foundry 连接详情。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add resource for agents on Microsoft Foundry`,在其正下方添加代码。这将向引用的应用公开智能体详情列表。 + + ```csharp + // 添加 Microsoft Foundry 上的智能体资源 + var agents = builder.AddAgents("agents"); + ``` + + 让我们分解这段代码。 + + - `builder.AddAgents("agents")`:这通过自定义资源 `AgentResource` 添加智能体详情列表。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add backend agent service`,在其正下方添加代码。这将定义引用 `foundry` 资源的后端智能体服务——所有 Microsoft Foundry 连接详情将传递给后端智能体服务应用。 + + ```csharp + // 添加后端智能体服务 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("agent")`:这将后端智能体服务应用作为 .NET 项目添加。 + - `.WithReference(foundry)`:这引用了上面创建的 foundry 资源,将 Microsoft Foundry 连接详情传递给后端智能体服务应用。 + +1. 在同一文件中,找到注释 `// Add frontend web UI`,在其正下方添加代码。这将定义引用 `agents` 和 `agent` 两个资源的前端 Web UI——智能体详情和后端连接详情都将传递给前端 Web UI 应用。 + + ```csharp + // 添加前端 Web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("webui")`:这将前端 Web UI 应用作为 .NET 项目添加。 + - `.WithExternalHttpEndpoints()`:这将前端 Web UI 应用暴露到互联网,使其可公开访问。 + - `.WithReference(agents)`:这引用了上面创建的 agents 资源,将智能体列表传递给前端 Web UI 应用。 + - `.WithReference(agent)`:这引用了后端智能体服务应用,将连接详情传递给前端 Web UI 应用。 + +## 在后端智能体服务中实现并发模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.Agent/Program.cs`,找到注释 `// Create AIProjectClient instance with EntraID authentication`,在其正下方添加代码。这将连接到 Microsoft Foundry 项目。 + + ```csharp + // 使用 EntraID 身份验证创建 AIProjectClient 实例 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + 让我们分解这段代码。 + + - `new DefaultAzureCredential(...)`:这无需 API 密钥即可登录 Azure。在本地机器上使用您的 Azure CLI 登录或 Azure Developer CLI 登录详情,在部署到 Azure 时使用托管标识。 + - `new AIProjectClient(endpoint, credential)`:这使用端点和登录详情连接到 Microsoft Foundry 项目实例。 + +1. 在同一文件中,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将从 Microsoft Foundry 项目中拉取智能体详情,并将它们作为单例服务注册到 IoC 容器中。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 让我们分解这段代码。 + + - 我们已经知道智能体列表,但只知道它们的名称。因此,代码对每个智能体运行 `foreach` 循环。 + - `new AgentReference(name, version)`:使用每个智能体的信息创建引用实例。 + - `projectClient.AsAIAgent(reference, factory)`:使用引用详情连接到实际的智能体。 + - `builder.Services.AddKeyedSingleton(name, agent)`:将智能体实例注册为单例服务。 + + > **注意**:您可能会注意到 `AgentRecordShimChatClient` 类。这是 Microsoft Agent Framework 和 Microsoft Foundry SDK 之间版本不匹配的临时解决方案,将很快被移除。 + +1. 在同一文件中,找到注释 `// Build a concurrent workflow pattern with the agents registered`,在其正下方添加代码。 + + ```csharp + // 使用已注册的智能体构建并发工作流模式 + var concurrentAgents = agents.Where(a => a.Name != "aggregator-agent"); + var aggregatorAgent = agents.SingleOrDefault(a => a.Name == "aggregator-agent"); + + builder.AddWorkflow("concurrent-analysis", (sp, key) => AgentWorkflowBuilder.BuildConcurrent( + workflowName: key, + agents: [.. concurrentAgents.Select(a => sp.GetRequiredKeyedService(a.Name))], + aggregator: null + )).AddAsAIAgent("concurrent-analysis"); + + builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential( + workflowName: key, + agents: [ + sp.GetRequiredKeyedService("concurrent-analysis"), + sp.GetRequiredKeyedService(aggregatorAgent!.Name) + ] + )).AddAsAIAgent("publisher"); + ``` + + 让我们分解这段代码。 + + - `builder.AddWorkflow("concurrent-analysis", ...).AddAsAIAgent("concurrent-analysis")`:这将多智能体工作流作为另一个名为 `concurrent-analysis` 的智能体实例添加,并将其注册为单例。 + - `AgentWorkflowBuilder.BuildConcurrent(...)`:这是使用相同名称 `concurrent-analysis` 的并发工作流构建器。 + + 请注意,它从之前注册的服务中添加了 `agents` 数组声明的多个智能体。 + + 还请注意,聚合器传递了 `null`,这样我们可以使用 Microsoft Foundry 提供的 `aggregator-agent` 来代替。 + - `builder.AddWorkflow("publisher, ...).AddAsAIAgent("publisher")`:这将多智能体工作流作为另一个名为 `publisher` 的智能体实例添加,并将其注册为单例。 + - `AgentWorkflowBuilder.BuildSequential(...)`:这是使用相同名称 `publisher` 的顺序工作流构建器。 + + 请注意,它同时添加了 `concurrent-analysis` 工作流和 `aggregator-agent`,以便聚合智能体汇总并发工作流中每个智能体的响应。 + +1. 在同一文件中,找到注释 `// Map AGUI to the publisher workflow agent`,在其正下方添加代码。工作流通过 `ag-ui` 端点作为 API 暴露,以便前端 Web UI 可以与此后端智能体服务应用通信。 + + ```csharp + // 将 AGUI 映射到 publisher 工作流智能体 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## 在前端 Web UI 中实现并发模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.WebUI/Program.cs`,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将注册所有智能体详情,以便 Web UI 知道哪个智能体在响应。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + builder.Services.AddSingleton(agents); + ``` + +1. 在同一文件中,找到注释 `// Register the backend agent service as an HTTP client`,在其正下方添加代码。Aspire 已经为前端 Web UI 应用提供了后端智能体服务的连接详情。 + + ```csharp + // 将后端智能体服务注册为 HTTP 客户端 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 在同一文件中,找到注释 `// Register AGUI client`,在其正下方添加代码。使用此 AGUI 客户端,前端 Web UI 应用通过 `ag-ui` 端点与后端智能体服务应用通信。 + + ```csharp + // 注册 AGUI 客户端 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## 运行 Aspire + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 确保您已经使用 Azure CLI 和 Azure Developer CLI 登录了 Azure。如果不确定,请再次按照[此步骤](./00-setup.md#登录-azure)操作。 + +1. 运行以下命令通过 Aspire 启动所有应用。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 仪表板会自动打开。 + + ![Aspire 仪表板](../../../docs/images/step-02-image-01.png) + + 点击后端智能体服务应用。 + +1. 当 Dev UI 页面打开后,将智能体切换为 `concurrent-analysis`,查看所有智能体并发运行的效果。 + + ![Microsoft Agent Framework Dev UI - 并发模式](../../../docs/images/step-02-image-02.png) + + 然后,将智能体切换为 `publisher`,查看顺序模式如何将 `concurrent-analysis` 与 `aggregator-agent` 组合。 + + ![Microsoft Agent Framework Dev UI - 顺序模式](../../../docs/images/step-02-image-03.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Dev UI - 发送请求](../../../docs/images/step-02-image-04.png) + + 查看结果以及屏幕左侧的工作流进度。 + + ![Microsoft Agent Framework Dev UI - 工作流运行](../../../docs/images/step-02-image-05.png) + +1. 返回 Aspire 仪表板,点击 Web UI 应用。 + + ![Aspire 仪表板](../../../docs/images/step-02-image-06.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Chat UI - 发送请求](../../../docs/images/step-02-image-07.png) + + 查看结果。 + +1. 按 `Ctrl`+`C` 终止所有运行中的应用。 + +## 部署到 Azure + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 运行以下命令将前端 Web UI 和后端智能体服务应用预配并部署到 Azure。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 完成后,您将在终端屏幕上看到 Web UI 应用的 URL。在浏览器中打开它并发送请求。 + + ![Microsoft Agent Framework on Azure Container Apps - 发送请求](../../../docs/images/step-02-image-08.png) + + 查看结果。 + +1. 一切完成后,从 Azure 中删除所有应用和智能体。 + + ```bash + # 删除 Web UI 和智能体服务应用。 + azd down --purge --force + + # 删除所有智能体和 Microsoft Foundry 资源。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +恭喜!🎉 您已完成第二个多智能体编排场景——并发模式。让我们继续吧! + +👈 [01: 顺序模式](./01-sequential-pattern.md) | [03: 交接模式](./03-handoff-pattern.md) 👉 diff --git a/localization/zh-cn/docs/03-handoff-pattern.md b/localization/zh-cn/docs/03-handoff-pattern.md new file mode 100644 index 0000000..9ff0bbf --- /dev/null +++ b/localization/zh-cn/docs/03-handoff-pattern.md @@ -0,0 +1,449 @@ +# 03 交接模式 + +在交接模式中,智能体根据对话上下文动态地将控制权传递给彼此。分诊智能体接收初始请求,并将其路由到最适合处理该请求的专家。专家之间也可以在问题跨领域时互相重定向。这非常适合 IT 支持、客户服务或任何在不同阶段需要不同专业知识的工作流场景。 + +## 场景 + +您在一个 IT 支持团队中工作,使用智能体——包括通用支持智能体、网络专家智能体、保修智能体和分诊智能体。 + +
+ 架构图 - 交接模式 +
+ +## 获取仓库根目录 + +1. 首先获取 `$REPOSITORY_ROOT` 变量。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 复制起始项目 + +1. 如果您已经有 `workshop` 目录,请先重命名或删除它。 + +1. 运行安装脚本将起始项目复制到 `workshop` 目录。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 03-handoff-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 03-handoff-pattern + ``` + +## 部署智能体 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.PromptAgent/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 导航到 `resources-foundry` 目录。 + + ```bash + pushd resources-foundry + ``` + +1. 运行以下命令将上面定义的智能体预配并部署到 Microsoft Foundry。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 预配和部署完成后,运行以下命令确认智能体已成功部署。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 您应该看到四个智能体名称。 + + ```text + warranty-agent + network-specialist-agent + general-support-agent + triage-agent + ``` + +1. 导航回 workshop 目录。 + + ```bash + popd + ``` + +## 配置 Aspire 编排 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 验证所有必要的智能体信息已被记录。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + 您应该看到 `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP` 和 `Foundry:Project:Endpoint` 的值。 + +1. 打开 `src/MultiAgentWorkshop.AppHost/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "triage-agent", + "Version": "1" + }, + { + "Name": "general-support-agent", + "Version": "1" + }, + { + "Name": "network-specialist-agent", + "Version": "1" + }, + { + "Name": "warranty-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 打开 `src/MultiAgentWorkshop.AppHost/AppHost.cs`,找到注释 `// Add resource for Microsoft Foundry`,在其正下方添加代码。这将添加 Microsoft Foundry 项目的连接详情。 + + ```csharp + // 添加 Microsoft Foundry 资源 + var foundry = builder.AddFoundry("foundry"); + ``` + + 让我们分解这段代码。 + + - `builder.AddFoundry("foundry")`:这通过自定义资源 `FoundryResource` 添加 Microsoft Foundry 连接详情。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add resource for agents on Microsoft Foundry`,在其正下方添加代码。这将向引用的应用公开智能体详情列表。 + + ```csharp + // 添加 Microsoft Foundry 上的智能体资源 + var agents = builder.AddAgents("agents"); + ``` + + 让我们分解这段代码。 + + - `builder.AddAgents("agents")`:这通过自定义资源 `AgentResource` 添加智能体详情列表。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add backend agent service`,在其正下方添加代码。这将定义引用 `foundry` 资源的后端智能体服务——所有 Microsoft Foundry 连接详情将传递给后端智能体服务应用。 + + ```csharp + // 添加后端智能体服务 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("agent")`:这将后端智能体服务应用作为 .NET 项目添加。 + - `.WithReference(foundry)`:这引用了上面创建的 foundry 资源,将 Microsoft Foundry 连接详情传递给后端智能体服务应用。 + +1. 在同一文件中,找到注释 `// Add frontend web UI`,在其正下方添加代码。这将定义引用 `agents` 和 `agent` 两个资源的前端 Web UI——智能体详情和后端连接详情都将传递给前端 Web UI 应用。 + + ```csharp + // 添加前端 Web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("webui")`:这将前端 Web UI 应用作为 .NET 项目添加。 + - `.WithExternalHttpEndpoints()`:这将前端 Web UI 应用暴露到互联网,使其可公开访问。 + - `.WithReference(agents)`:这引用了上面创建的 agents 资源,将智能体列表传递给前端 Web UI 应用。 + - `.WithReference(agent)`:这引用了后端智能体服务应用,将连接详情传递给前端 Web UI 应用。 + +## 在后端智能体服务中实现交接模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.Agent/Program.cs`,找到注释 `// Create AzureOpenAIClient instance with EntraID authentication`,在其正下方添加代码。这将连接到 Microsoft Foundry 项目。 + + ```csharp + // 使用 EntraID 身份验证创建 AzureOpenAIClient 实例 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + + var url = new Uri(endpoint.GetAzureOpenAIResponsesEndpoint()); + var chatClient = new AzureOpenAIClient(url, credential) + .GetResponsesClient() + .AsIChatClient(model); + ``` + + 让我们分解这段代码。 + + - `new DefaultAzureCredential(...)`:这无需 API 密钥即可登录 Azure。在本地机器上使用您的 Azure CLI 登录或 Azure Developer CLI 登录详情,在部署到 Azure 时使用托管标识。 + - `endpoint.GetAzureOpenAIResponsesEndpoint()`:这将 Microsoft Foundry 项目端点转换为 Microsoft Foundry OpenAI 端点,因为 Microsoft Foundry SDK 目前不支持交接模式。 + - `new AzureOpenAIClient(url, credential)`:这使用端点和登录详情连接到 Azure OpenAI 实例,并将其转换为 `IChatClient` 实例。 + +1. 在同一文件中,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将从 Microsoft Foundry 项目中拉取智能体详情,并将它们作为单例服务注册到 IoC 容器中。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + foreach (var agentSettings in agents) + { + var instruction = await File.ReadAllTextAsync( + Path.Combine(AppContext.BaseDirectory, "Prompts", $"{agentSettings.Name}.txt")); + + var agent = new ChatClientAgent( + chatClient, + instructions: instruction, + name: agentSettings.Name); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 让我们分解这段代码。 + + - 我们已经知道智能体列表,但只知道它们的名称。因此,代码对每个智能体运行 `foreach` 循环。 + - `await File.ReadAllTextAsync(...)`:这导入智能体指令文件。 + - `new ChatClientAgent(chatClient, instructions, name)`:使用每个智能体的信息、指令和 `IChatClient` 实例创建智能体实例。 + - `builder.Services.AddKeyedSingleton(name, agent)`:将智能体实例注册为单例服务。 + +1. 在同一文件中,找到注释 `// Build a handoff workflow pattern with the agents registered`,在其正下方添加代码。 + + ```csharp + // 使用已注册的智能体构建交接工作流模式 + builder.AddWorkflow("publisher", (sp, key) => + { + var triage = sp.GetRequiredKeyedService("triage-agent"); + var generalSupport = sp.GetRequiredKeyedService("general-support-agent"); + var networkSpecialist = sp.GetRequiredKeyedService("network-specialist-agent"); + var warranty = sp.GetRequiredKeyedService("warranty-agent"); + + var specialists = new[] { generalSupport, networkSpecialist, warranty }; + + var workflow = AgentWorkflowBuilder.CreateHandoffBuilderWith(triage) + // 分诊智能体可以交接给任何专家 + .WithHandoffs(triage, specialists) + // 每个专家可以交接给其他专家 + .WithHandoffs(generalSupport, [networkSpecialist, warranty]) + .WithHandoffs(networkSpecialist, [generalSupport, warranty]) + .WithHandoffs(warranty, [generalSupport, networkSpecialist]) + // 所有专家交接回分诊智能体 + .WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing") + .Build(); + + // HandoffWorkflowBuilder.Build() 不会设置工作流名称。 + // 通过反射设置名称以通过 AddWorkflow 的名称验证。 + typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key); + + return workflow; + }).AddAsAIAgent("publisher"); + ``` + + 让我们分解这段代码。 + + - `var specialists = new[] { generalSupport, networkSpecialist, warranty };`:这定义了专家智能体列表。分诊智能体是起始点,将用户请求重新路由到其中一个专家智能体。 + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`:这将多智能体工作流作为另一个名为 `publisher` 的智能体实例添加,并将其注册为单例。 + - `AgentWorkflowBuilder.CreateHandoffBuilderWith(triage)`:这是带有分诊智能体的交接工作流构建器。 + - `.WithHandoffs(triage, specialists)`:这定义了从分诊智能体到专家智能体的交接。 + - `.WithHandoffs(generalSupport, [networkSpecialist, warranty])`:这定义了从通用支持智能体到其他专家智能体的交接。 + - `.WithHandoffs(networkSpecialist, [generalSupport, warranty])`:这定义了从网络专家智能体到其他专家智能体的交接。 + - `.WithHandoffs(warranty, [generalSupport, networkSpecialist])`:这定义了从保修智能体到其他专家智能体的交接。 + - `.WithHandoffs(specialists, triage, "Hand back to triage when the issue is resolved or needs further routing")`:这定义了当问题解决或需要进一步路由时,所有专家智能体交接回分诊智能体。 + - `typeof(Workflow).GetProperty("Name")!.SetValue(workflow, key);`:这注入工作流名称,是一个临时的解决方案。 + +1. 在同一文件中,找到注释 `// Map AGUI to the publisher workflow agent`,在其正下方添加代码。工作流通过 `ag-ui` 端点作为 API 暴露,以便前端 Web UI 可以与此后端智能体服务应用通信。 + + ```csharp + // 将 AGUI 映射到 publisher 工作流智能体 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + .CreateFixedAgent() + ); + ``` + + 请注意,`.CreateFixedAgent()` 是一个临时的解决方案,直到输出流被正确处理。 + +## 在前端 Web UI 中实现交接模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.WebUI/Program.cs`,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将注册所有智能体详情,以便 Web UI 知道哪个智能体在响应。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + builder.Services.AddSingleton(agents); + ``` + +1. 在同一文件中,找到注释 `// Register the backend agent service as an HTTP client`,在其正下方添加代码。Aspire 已经为前端 Web UI 应用提供了后端智能体服务的连接详情。 + + ```csharp + // 将后端智能体服务注册为 HTTP 客户端 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 在同一文件中,找到注释 `// Register AGUI client`,在其正下方添加代码。使用此 AGUI 客户端,前端 Web UI 应用通过 `ag-ui` 端点与后端智能体服务应用通信。 + + ```csharp + // 注册 AGUI 客户端 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## 运行 Aspire + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 确保您已经使用 Azure CLI 和 Azure Developer CLI 登录了 Azure。如果不确定,请再次按照[此步骤](./00-setup.md#登录-azure)操作。 + +1. 运行以下命令通过 Aspire 启动所有应用。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 仪表板会自动打开。 + + ![Aspire 仪表板](../../../docs/images/step-03-image-01.png) + + 点击后端智能体服务应用。 + +1. 当 Dev UI 页面打开后,将智能体切换为 `publisher`,查看分诊智能体如何将请求分发给其他智能体。 + + ![Microsoft Agent Framework Dev UI - 交接模式](../../../docs/images/step-03-image-02.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Dev UI - 发送请求](../../../docs/images/step-03-image-03.png) + + 查看结果以及屏幕左侧的工作流进度。 + + ![Microsoft Agent Framework Dev UI - 工作流运行](../../../docs/images/step-03-image-04.png) + +1. 返回 Aspire 仪表板,点击 Web UI 应用。 + + ![Aspire 仪表板](../../../docs/images/step-03-image-05.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Chat UI - 发送请求](../../../docs/images/step-03-image-06.png) + + 查看结果。 + +1. 按 `Ctrl`+`C` 终止所有运行中的应用。 + +## 部署到 Azure + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 运行以下命令将前端 Web UI 和后端智能体服务应用预配并部署到 Azure。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 完成后,您将在终端屏幕上看到 Web UI 应用的 URL。在浏览器中打开它并发送请求。 + + ![Microsoft Agent Framework on Azure Container Apps - 发送请求](../../../docs/images/step-03-image-07.png) + + 查看结果。 + +1. 一切完成后,从 Azure 中删除所有应用和智能体。 + + ```bash + # 删除 Web UI 和智能体服务应用。 + azd down --purge --force + + # 删除所有智能体和 Microsoft Foundry 资源。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +恭喜!🎉 您已完成第三个多智能体编排场景——交接模式。让我们继续吧! + +👈 [02: 并发模式](./02-concurrent-pattern.md) | [04: 群聊模式](./04-group-chat-pattern.md) 👉 diff --git a/localization/zh-cn/docs/04-group-chat-pattern.md b/localization/zh-cn/docs/04-group-chat-pattern.md new file mode 100644 index 0000000..dce04be --- /dev/null +++ b/localization/zh-cn/docs/04-group-chat-pattern.md @@ -0,0 +1,421 @@ +# 04 群聊模式 + +在群聊模式中,多个智能体参与共享对话,轮流贡献其专业知识。编排器管理讨论流程,决定下一个发言的智能体以及对话何时结束。这非常适合跨职能规划、创意头脑风暴或任何需要多元视角相互交流并迭代构建的任务。 + +## 场景 + +您在一个跨职能产品团队中,计划使用智能体推出新产品——包括产品策略智能体、用户体验智能体、技术智能体和商务智能体。 + +
+ 架构图 - 群聊模式 +
+ +## 获取仓库根目录 + +1. 首先获取 `$REPOSITORY_ROOT` 变量。 + + ```bash + # zsh/bash + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` + + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` + +## 复制起始项目 + +1. 如果您已经有 `workshop` 目录,请先重命名或删除它。 + +1. 运行安装脚本将起始项目复制到 `workshop` 目录。 + + ```bash + # zsh/bash + bash $REPOSITORY_ROOT/scripts/setup.sh --session 04-group-chat-pattern + ``` + + ```powershell + # PowerShell + & $REPOSITORY_ROOT/scripts/setup.ps1 -Session 04-group-chat-pattern + ``` + +## 部署智能体 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.PromptAgent/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 导航到 `resources-foundry` 目录。 + + ```bash + pushd resources-foundry + ``` + +1. 运行以下命令将上面定义的智能体预配并部署到 Microsoft Foundry。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 预配和部署完成后,运行以下命令确认智能体已成功部署。 + + ```bash + # zsh/bash + az cognitiveservices agent list \ + -a $(azd env get-value FOUNDRY_NAME) \ + -p $(azd env get-value FOUNDRY_PROJECT_NAME) \ + --query "[].id" -o tsv + ``` + + ```bash + # PowerShell + az cognitiveservices agent list ` + -a $(azd env get-value FOUNDRY_NAME) ` + -p $(azd env get-value FOUNDRY_PROJECT_NAME) ` + --query "[].id" -o tsv + ``` + + 您应该看到四个智能体名称。 + + ```text + business-agent + technical-agent + user-experience-agent + product-strategy-agent + ``` + +1. 导航回 workshop 目录。 + + ```bash + popd + ``` + +## 配置 Aspire 编排 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 验证所有必要的智能体信息已被记录。 + + ```bash + dotnet user-secrets --project ./src/MultiAgentWorkshop.AppHost list + ``` + + 您应该看到 `AZURE_TENANT_ID`、`FOUNDRY_NAME`、`FOUNDRY_PROJECT_NAME`、`FOUNDRY_RESOURCE_GROUP` 和 `Foundry:Project:Endpoint` 的值。 + +1. 打开 `src/MultiAgentWorkshop.AppHost/appsettings.json`,找到注释行 `// Add agents`,在其下方添加 `Agents` 属性。 + + ```jsonc + { + ... + // 添加智能体 + "Agents": [ + { + "Name": "product-strategy-agent", + "Version": "1" + }, + { + "Name": "user-experience-agent", + "Version": "1" + }, + { + "Name": "technical-agent", + "Version": "1" + }, + { + "Name": "business-agent", + "Version": "1" + } + ] + ... + } + ``` + +1. 打开 `src/MultiAgentWorkshop.AppHost/AppHost.cs`,找到注释 `// Add resource for Microsoft Foundry`,在其正下方添加代码。这将添加 Microsoft Foundry 项目的连接详情。 + + ```csharp + // 添加 Microsoft Foundry 资源 + var foundry = builder.AddFoundry("foundry"); + ``` + + 让我们分解这段代码。 + + - `builder.AddFoundry("foundry")`:这通过自定义资源 `FoundryResource` 添加 Microsoft Foundry 连接详情。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add resource for agents on Microsoft Foundry`,在其正下方添加代码。这将向引用的应用公开智能体详情列表。 + + ```csharp + // 添加 Microsoft Foundry 上的智能体资源 + var agents = builder.AddAgents("agents"); + ``` + + 让我们分解这段代码。 + + - `builder.AddAgents("agents")`:这通过自定义资源 `AgentResource` 添加智能体详情列表。如果您想了解更多关于 Aspire 自定义资源的信息,请访问 [Create custom hosting integrations](https://aspire.dev/integrations/custom-integrations/hosting-integrations/)。 + +1. 在同一文件中,找到注释 `// Add backend agent service`,在其正下方添加代码。这将定义引用 `foundry` 资源的后端智能体服务——所有 Microsoft Foundry 连接详情将传递给后端智能体服务应用。 + + ```csharp + // 添加后端智能体服务 + var agent = builder.AddProject("agent") + .WithReference(foundry); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("agent")`:这将后端智能体服务应用作为 .NET 项目添加。 + - `.WithReference(foundry)`:这引用了上面创建的 foundry 资源,将 Microsoft Foundry 连接详情传递给后端智能体服务应用。 + +1. 在同一文件中,找到注释 `// Add frontend web UI`,在其正下方添加代码。这将定义引用 `agents` 和 `agent` 两个资源的前端 Web UI——智能体详情和后端连接详情都将传递给前端 Web UI 应用。 + + ```csharp + // 添加前端 Web UI + var webUI = builder.AddProject("webui") + .WithExternalHttpEndpoints() + .WithReference(agents) + .WithReference(agent) + .WaitFor(agent); + ``` + + 让我们分解这段代码。 + + - `builder.AddProject("webui")`:这将前端 Web UI 应用作为 .NET 项目添加。 + - `.WithExternalHttpEndpoints()`:这将前端 Web UI 应用暴露到互联网,使其可公开访问。 + - `.WithReference(agents)`:这引用了上面创建的 agents 资源,将智能体列表传递给前端 Web UI 应用。 + - `.WithReference(agent)`:这引用了后端智能体服务应用,将连接详情传递给前端 Web UI 应用。 + +## 在后端智能体服务中实现群聊模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.Agent/Program.cs`,找到注释 `// Create AIProjectClient instance with EntraID authentication`,在其正下方添加代码。这将连接到 Microsoft Foundry 项目。 + + ```csharp + // 使用 EntraID 身份验证创建 AIProjectClient 实例 + var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = config["AZURE_TENANT_ID"] }); + var projectClient = new AIProjectClient(endpoint: new Uri(endpoint), tokenProvider: credential); + ``` + + 让我们分解这段代码。 + + - `new DefaultAzureCredential(...)`:这无需 API 密钥即可登录 Azure。在本地机器上使用您的 Azure CLI 登录或 Azure Developer CLI 登录详情,在部署到 Azure 时使用托管标识。 + - `new AIProjectClient(endpoint, credential)`:这使用端点和登录详情连接到 Microsoft Foundry 项目实例。 + +1. 在同一文件中,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将从 Microsoft Foundry 项目中拉取智能体详情,并将它们作为单例服务注册到 IoC 容器中。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + foreach (var agentSettings in agents) + { + var agentReference = new AgentReference(agentSettings.Name, agentSettings.Version); + + var agent = projectClient.AsAIAgent( + agentReference: agentReference, + clientFactory: inner => new AgentRecordShimChatClient(inner) + ); + + builder.Services.AddKeyedSingleton(agentSettings.Name, agent); + } + ``` + + 让我们分解这段代码。 + + - 我们已经知道智能体列表,但只知道它们的名称。因此,代码对每个智能体运行 `foreach` 循环。 + - `new AgentReference(name, version)`:使用每个智能体的信息创建引用实例。 + - `projectClient.AsAIAgent(reference, factory)`:使用引用详情连接到实际的智能体。 + - `builder.Services.AddKeyedSingleton(name, agent)`:将智能体实例注册为单例服务。 + + > **注意**:您可能会注意到 `AgentRecordShimChatClient` 类。这是 Microsoft Agent Framework 和 Microsoft Foundry SDK 之间版本不匹配的临时解决方案,将很快被移除。 + +1. 在同一文件中,找到注释 `// Build a group chat workflow pattern with the agents registered`,在其正下方添加代码。 + + ```csharp + // 使用已注册的智能体构建群聊工作流模式 + builder.AddWorkflow("publisher", (sp, key) => + { + var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name)); + + return AgentWorkflowBuilder.CreateGroupChatBuilderWith(agentList => + new RoundRobinGroupChatManager(agentList) { MaximumIterationCount = participants.Count() * 2 }) + .AddParticipants(participants) + .WithName(key) + .Build(); + }).AddAsAIAgent("publisher"); + ``` + + 让我们分解这段代码。 + + - `var participants = agents.Select(a => sp.GetRequiredKeyedService(a.Name));`:这确定群聊中参与的智能体列表。 + - `builder.AddWorkflow("publisher", ...).AddAsAIAgent("publisher")`:这将多智能体工作流作为另一个名为 `publisher` 的智能体实例添加,并将其注册为单例。 + - `AgentWorkflowBuilder.CreateGroupChatBuilderWith(...)`:这是使用相同名称 `publisher` 的群聊工作流构建器。 + - `new RoundRobinGroupChatManager(...)`:这将群聊策略设置为轮询。它还定义了最大迭代次数。在此代码中,每个智能体在轮询周期中响应两次。 + +1. 在同一文件中,找到注释 `// Map AGUI to the publisher workflow agent`,在其正下方添加代码。工作流通过 `ag-ui` 端点作为 API 暴露,以便前端 Web UI 可以与此后端智能体服务应用通信。 + + ```csharp + // 将 AGUI 映射到 publisher 工作流智能体 + app.MapAGUI( + pattern: "ag-ui", + aiAgent: app.Services.GetRequiredKeyedService("publisher") + ); + ``` + +## 在前端 Web UI 中实现群聊模式 + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 打开 `src/MultiAgentWorkshop.WebUI/Program.cs`,找到注释 `// Register all agents passed from Aspire`,在其正下方添加代码。这将注册所有智能体详情,以便 Web UI 知道哪个智能体在响应。 + + ```csharp + // 注册所有从 Aspire 传递的智能体 + builder.Services.AddSingleton(agents); + ``` + +1. 在同一文件中,找到注释 `// Register the backend agent service as an HTTP client`,在其正下方添加代码。Aspire 已经为前端 Web UI 应用提供了后端智能体服务的连接详情。 + + ```csharp + // 将后端智能体服务注册为 HTTP 客户端 + builder.Services.AddHttpClient("agent", client => + { + client.BaseAddress = new Uri("https+http://agent"); + }); + ``` + +1. 在同一文件中,找到注释 `// Register AGUI client`,在其正下方添加代码。使用此 AGUI 客户端,前端 Web UI 应用通过 `ag-ui` 端点与后端智能体服务应用通信。 + + ```csharp + // 注册 AGUI 客户端 + builder.Services.AddChatClient(sp => new AGUIChatClient( + httpClient: sp.GetRequiredService().CreateClient("agent"), + endpoint: "ag-ui") + ); + ``` + +## 运行 Aspire + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 确保您已经使用 Azure CLI 和 Azure Developer CLI 登录了 Azure。如果不确定,请再次按照[此步骤](./00-setup.md#登录-azure)操作。 + +1. 运行以下命令通过 Aspire 启动所有应用。 + + ```bash + dotnet watch run --project ./src/MultiAgentWorkshop.AppHost + ``` + +1. Aspire 仪表板会自动打开。 + + ![Aspire 仪表板](../../../docs/images/step-04-image-01.png) + + 点击后端智能体服务应用。 + +1. 当 Dev UI 页面打开后,将智能体切换为 `publisher` 并点击 "Configure & Run" 按钮。 + + ![Microsoft Agent Framework Dev UI - 群聊模式](../../../docs/images/step-04-image-02.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Dev UI - 发送请求](../../../docs/images/step-04-image-03.png) + + 查看结果以及屏幕左侧的工作流进度。 + + ![Microsoft Agent Framework Dev UI - 工作流运行](../../../docs/images/step-04-image-04.png) + +1. 返回 Aspire 仪表板,点击 Web UI 应用。 + + ![Aspire 仪表板](../../../docs/images/step-04-image-05.png) + +1. 发送任意请求。 + + ![Microsoft Agent Framework Chat UI - 发送请求](../../../docs/images/step-04-image-06.png) + + 查看结果。 + +1. 按 `Ctrl`+`C` 终止所有运行中的应用。 + +## 部署到 Azure + +1. 确保您在 `workshop` 目录中。 + + ```bash + cd $REPOSITORY_ROOT/workshop + ``` + +1. 运行以下命令将前端 Web UI 和后端智能体服务应用预配并部署到 Azure。 + + ```bash + azd up + ``` + + 在预配过程中,系统会要求您输入环境名称、Azure 订阅和位置。 + +1. 完成后,您将在终端屏幕上看到 Web UI 应用的 URL。在浏览器中打开它并发送请求。 + + ![Microsoft Agent Framework on Azure Container Apps - 发送请求](../../../docs/images/step-04-image-07.png) + + 查看结果。 + +1. 一切完成后,从 Azure 中删除所有应用和智能体。 + + ```bash + # 删除 Web UI 和智能体服务应用。 + azd down --purge --force + + # 删除所有智能体和 Microsoft Foundry 资源。 + cd resources-foundry + azd down --purge --force + ``` + +--- + +恭喜!🎉 您已完成第四个多智能体编排场景——群聊模式。您已完成所有内容! + +👈 [03: 交接模式](./03-handoff-pattern.md) | [README](../README.md) 👉 diff --git a/localization/zh-cn/docs/README.md b/localization/zh-cn/docs/README.md new file mode 100644 index 0000000..055d519 --- /dev/null +++ b/localization/zh-cn/docs/README.md @@ -0,0 +1,10 @@ +# Multi-Agent Workshop 教材 + +以下是构建多智能体编排模式的工作坊教材列表及其代码示例。 + +| 文档 | 代码示例 | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](./01-sequential-pattern.md) | [01-sequential-pattern](../samples/01-sequential-pattern) | +| [02-concurrent-pattern.md](./02-concurrent-pattern.md) | [02-concurrent-pattern](../samples/02-concurrent-pattern) | +| [03-handoff-pattern.md](./03-handoff-pattern.md) | [03-handoff-pattern](../samples/03-handoff-pattern) | +| [04-group-chat-pattern.md](./04-group-chat-pattern.md) | [04-group-chat-pattern](../samples/04-group-chat-pattern) | diff --git a/localization/zh-cn/samples/01-sequential-pattern/README.md b/localization/zh-cn/samples/01-sequential-pattern/README.md new file mode 100644 index 0000000..eff27cf --- /dev/null +++ b/localization/zh-cn/samples/01-sequential-pattern/README.md @@ -0,0 +1,13 @@ +# 01 顺序模式 + +在顺序模式中,智能体按照预定义的流水线依次工作,每个智能体的输出作为下一个智能体的输入。这种方法非常适合遵循自然递进关系的任务,例如内容创作工作流、分阶段数据转换或逐步分析。 + +
+ 架构 - 顺序模式 +
+ +## 操作说明 + +按照 [01-sequential-pattern.md](../../docs/01-sequential-pattern.md) 中的说明,使用 [start](../../../../samples/01-sequential-pattern/start) 项目进行操作。 + +完成后,将您的成果与 [complete](../../../../samples/01-sequential-pattern/complete) 项目进行对比。 diff --git a/localization/zh-cn/samples/02-concurrent-pattern/README.md b/localization/zh-cn/samples/02-concurrent-pattern/README.md new file mode 100644 index 0000000..877f980 --- /dev/null +++ b/localization/zh-cn/samples/02-concurrent-pattern/README.md @@ -0,0 +1,13 @@ +# 02 并发模式 + +在并发模式中,多个智能体同时分析相同的输入,每个智能体发挥各自的专业能力。当所有智能体完成后,它们的输出会合并为一个统一的结果。这非常适合需要多个视角同时工作的任务,例如多角度分析、集成评估或协作决策。 + +
+ 架构 - 并发模式 +
+ +## 操作说明 + +按照 [02-concurrent-pattern.md](../../docs/02-concurrent-pattern.md) 中的说明,使用 [start](../../../../samples/02-concurrent-pattern/start) 项目进行操作。 + +完成后,将您的成果与 [complete](../../../../samples/02-concurrent-pattern/complete) 项目进行对比。 diff --git a/localization/zh-cn/samples/03-handoff-pattern/README.md b/localization/zh-cn/samples/03-handoff-pattern/README.md new file mode 100644 index 0000000..4965201 --- /dev/null +++ b/localization/zh-cn/samples/03-handoff-pattern/README.md @@ -0,0 +1,13 @@ +# 03 交接模式 + +在交接模式中,智能体根据对话上下文动态地将控制权传递给另一个智能体。分诊智能体接收初始请求,并将其路由到最适合处理该请求的专家智能体。专家智能体之间也可以在问题跨领域时相互重定向。这非常适合 IT 支持、客户服务等场景,或任何在不同阶段需要不同专业知识的工作流。 + +
+ 架构 - 交接模式 +
+ +## 操作说明 + +按照 [03-handoff-pattern.md](../../docs/03-handoff-pattern.md) 中的说明,使用 [start](../../../../samples/03-handoff-pattern/start) 项目进行操作。 + +完成后,将您的成果与 [complete](../../../../samples/03-handoff-pattern/complete) 项目进行对比。 diff --git a/localization/zh-cn/samples/04-group-chat-pattern/README.md b/localization/zh-cn/samples/04-group-chat-pattern/README.md new file mode 100644 index 0000000..cc236a0 --- /dev/null +++ b/localization/zh-cn/samples/04-group-chat-pattern/README.md @@ -0,0 +1,13 @@ +# 04 群聊模式 + +在群聊模式中,多个智能体参与共享对话,轮流贡献各自的专业知识。编排器管理讨论流程,决定下一个发言的智能体以及对话何时结束。这非常适合跨职能规划、创意头脑风暴,或任何需要多元视角相互交流并迭代构建的任务。 + +
+ 架构 - 群聊模式 +
+ +## 操作说明 + +按照 [04-group-chat-pattern.md](../../docs/04-group-chat-pattern.md) 中的说明,使用 [start](../../../../samples/04-group-chat-pattern/start) 项目进行操作。 + +完成后,将您的成果与 [complete](../../../../samples/04-group-chat-pattern/complete) 项目进行对比。 diff --git a/localization/zh-cn/samples/README.md b/localization/zh-cn/samples/README.md new file mode 100644 index 0000000..1e09493 --- /dev/null +++ b/localization/zh-cn/samples/README.md @@ -0,0 +1,10 @@ +# 多智能体编排代码示例 + +以下是多智能体编排模式及其代码示例的列表。 + +| 文档 | 代码示例 | +|--------------------------------------------------------------|--------------------------------------------------| +| [01-sequential-pattern.md](../docs/01-sequential-pattern.md) | [01-sequential-pattern](./01-sequential-pattern) | +| [02-concurrent-pattern.md](../docs/02-concurrent-pattern.md) | [02-concurrent-pattern](./02-concurrent-pattern) | +| [03-handoff-pattern.md](../docs/03-handoff-pattern.md) | [03-handoff-pattern](./03-handoff-pattern) | +| [04-group-chat-pattern.md](../docs/04-group-chat-pattern.md) | [04-group-chat-pattern](./04-group-chat-pattern) |