Pular para o conteúdo

Implementar e configurar o agente Story

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.

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_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 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.

Para compilar o código:

Terminal window
pnpm build

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:

Terminal window
pnpm nx agent-dev story

Em seguida, em um segundo terminal, inicie o chat:

Terminal window
pnpm nx agent-chat story

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