Implementar y configurar el agente Story
Tarea 1: Implementar el Story Agent
Sección titulada «Tarea 1: Implementar el Story Agent»El Story Agent es un agente Strands generado con --protocol=ag-ui en el Módulo 1, por lo que la interfaz de usuario puede transmitir desde él a través del protocolo Agent-User Interaction mediante CopilotKit. Utiliza el Inventory MCP Server para gestionar los objetos del jugador, y ya persiste el historial de conversación a través del session.py que el generador provisionó en el Módulo 1 — desplegado, eso es el S3SessionManager integrado de Strands escribiendo en el mismo bucket de S3 del que lee el queryActions del Game API, para que el navegador pueda reconstruir las transcripciones al volver a visitar.
Implementación del agente
Sección titulada «Implementación del agente»Actualiza agent.py en packages/story/dungeon_adventure_story/agent:
from contextlib import contextmanager
from dungeon_adventure_agent_connection import InventoryMcpServerClientStrands, log_model_errors, log_tool_errorsfrom strands import Agentfrom strands.hooks import HookCallback, HookProvider
AGENT_HOOKS: list[HookProvider | HookCallback] = [log_model_errors, log_tool_errors]
@contextmanagerdef get_agent(): inventory_mcp_server = InventoryMcpServerClientStrands.create() with ( inventory_mcp_server, ): yield Agent( system_prompt="""You are running a text adventure game for a lone adventurer. When a new storybegins, the first user message will tell you the player's name and the genre(one of 'medieval', 'zombie', 'superhero'). Greet the player by name, set thescene in the chosen genre, and populate their inventory with a few startingitems. On subsequent turns, advance the story in response to the player'sactions and keep item state in sync with the narrative.Use the tools to manage the player's inventory as items are obtained or lost.Item names in the inventory must be Title Case — match them exactly.Only use list-inventory-items if you are unsure of the exact item name before modifying it.IMPORTANT: Only call ONE tool per response turn. Never batch multiple tool calls in a single turn.Ensure you specify a suitable emoji when adding items if available.Items should be a key part of the narrative.Keep responses under 100 words.""", tools=[*inventory_mcp_server.list_tools_sync()], hooks=AGENT_HOOKS, )from contextlib import contextmanager
from dungeon_adventure_agent_connection import InventoryMcpServerClientStrands, log_model_errors, log_tool_errorsfrom strands import Agent, toolfrom strands import Agentfrom strands.hooks import HookCallback, HookProviderfrom strands_tools import current_time
@tooldef subtract(a: int, b: int) -> int: return a - b
AGENT_HOOKS: list[HookProvider | HookCallback] = [log_model_errors, log_tool_errors]
@contextmanagerdef get_agent(): inventory_mcp_server = InventoryMcpServerClientStrands.create() with ( inventory_mcp_server, ): yield Agent( name="StoryAgent", description="StoryAgent Strands Agent", system_prompt="""You are a mathematical wizard.Use your tools for mathematical tasks.Refer to tools as your 'spellbook'.You are running a text adventure game for a lone adventurer. When a new storybegins, the first user message will tell you the player's name and the genre(one of 'medieval', 'zombie', 'superhero'). Greet the player by name, set thescene in the chosen genre, and populate their inventory with a few startingitems. On subsequent turns, advance the story in response to the player'sactions and keep item state in sync with the narrative.Use the tools to manage the player's inventory as items are obtained or lost.Item names in the inventory must be Title Case — match them exactly.Only use list-inventory-items if you are unsure of the exact item name before modifying it.IMPORTANT: Only call ONE tool per response turn. Never batch multiple tool calls in a single turn.Ensure you specify a suitable emoji when adding items if available.Items should be a key part of the narrative.Keep responses under 100 words.""", tools=[subtract, current_time, *inventory_mcp_server.list_tools_sync()], tools=[*inventory_mcp_server.list_tools_sync()], hooks=AGENT_HOOKS, )agent.py elimina la herramienta de ejemplo subtract e intercambia el prompt del sistema por uno de dungeon-master que invita al primer mensaje del usuario a indicar el nombre del jugador y el género, y utiliza las herramientas del Inventory MCP Server. main.py no necesita cambios aquí — la gestión de sesiones ya estaba configurada cuando se generó el agente.
Tarea 2: Probar tu agente localmente
Sección titulada «Tarea 2: Probar tu agente localmente»Construir el código
Sección titulada «Construir el código»Para construir el código:
pnpm buildyarn buildnpm run buildbun buildChatear con tu agente
Sección titulada «Chatear con tu agente»El target generado agent-chat abre un REPL interactivo contra tu agente. Se ejecuta de forma independiente y se conecta a tu agente ejecutándose localmente, así que primero inicia el servidor local del agente en una terminal:
pnpm nx agent-dev storyyarn nx agent-dev storynpx nx agent-dev storybunx nx agent-dev storyLuego, en una segunda terminal, inicia el chat:
pnpm nx agent-chat storyyarn nx agent-chat storynpx nx agent-chat storybunx nx agent-chat storyTu primer mensaje debe indicarle al agente el nombre de tu héroe y el género (por ejemplo: My name is Alice. Start my zombie adventure.) y la historia se transmitirá de vuelta.
¡Felicitaciones! ¡Has construido y probado tu primer Strands Agent localmente! 🎉🎉🎉