Implementar e configurar o agente Story
Tarefa 1: Implementar o Story Agent
Seção intitulada “Tarefa 1: Implementar o Story Agent”O Story Agent é um agente Strands gerado com --protocol=ag-ui no Módulo 1, para que a UI possa transmitir a partir dele através do protocolo Agent-User Interaction via CopilotKit. Ele usa o Inventory MCP Server para gerenciar os itens do jogador e já persiste o histórico de conversação através do session.py que o gerador provisionou no Módulo 1 — quando implantado, isso é o S3SessionManager integrado do Strands escrevendo no mesmo bucket S3 do qual o queryActions da Game API lê, para que o navegador possa reconstruir transcrições em revisitas.
Implementação do agente
Seção intitulada “Implementação do agente”Atualize agent.py em 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 remove a ferramenta de exemplo subtract e troca o prompt do sistema por um de mestre de masmorra que convida a primeira mensagem do usuário a declarar o nome e o gênero do jogador, e usa as ferramentas do Inventory MCP Server. main.py não precisa de alterações aqui — o gerenciamento de sessão já foi configurado quando o agente foi gerado.
Tarefa 2: Testar seu Agent localmente
Seção intitulada “Tarefa 2: Testar seu Agent localmente”Compilar o código
Seção intitulada “Compilar o código”Para compilar o código:
pnpm buildyarn buildnpm run buildbun buildConversar com seu Agent
Seção intitulada “Conversar com seu Agent”O target agent-chat gerado abre um REPL interativo contra seu agente. Ele é executado de forma independente e se conecta ao seu agente em execução local, então primeiro inicie o servidor local do agente em um terminal:
pnpm nx agent-dev storyyarn nx agent-dev storynpx nx agent-dev storybunx nx agent-dev storyEm seguida, em um segundo terminal, inicie o chat:
pnpm nx agent-chat storyyarn nx agent-chat storynpx nx agent-chat storybunx nx agent-chat storySua primeira mensagem deve informar ao agente o nome do seu herói e o gênero (por exemplo: Meu nome é Alice. Comece minha aventura zumbi.) e a história será transmitida de volta.
Parabéns. Você construiu e testou seu primeiro Strands Agent localmente! 🎉🎉🎉