Ir al contenido

Implementar y configurar el agente Story

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.

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_errors
from strands import Agent
from strands.hooks import HookCallback, HookProvider
AGENT_HOOKS: list[HookProvider | HookCallback] = [log_model_errors, log_tool_errors]
@contextmanager
def 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 story
begins, 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 the
scene in the chosen genre, and populate their inventory with a few starting
items. On subsequent turns, advance the story in response to the player's
actions 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,
)

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.

Para construir el código:

Terminal window
pnpm build

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:

Terminal window
pnpm nx agent-dev story

Luego, en una segunda terminal, inicia el chat:

Terminal window
pnpm nx agent-chat story

Tu 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! 🎉🎉🎉