Implémenter et configurer l'agent Story
Tâche 1 : Implémenter l’agent Story
Section intitulée « Tâche 1 : Implémenter l’agent Story »L’agent Story est un agent Strands généré avec --protocol=ag-ui dans le Module 1, afin que l’interface utilisateur puisse diffuser depuis celui-ci via le protocole Agent-User Interaction via CopilotKit. Il utilise le serveur MCP Inventory pour gérer les objets du joueur, et persiste déjà l’historique des conversations via le session.py que le générateur a provisionné dans le Module 1 — une fois déployé, c’est le S3SessionManager intégré de Strands qui écrit dans le même bucket S3 que celui depuis lequel le queryActions de l’API Game lit, afin que le navigateur puisse reconstruire les transcriptions lors d’une nouvelle visite.
Implémentation de l’agent
Section intitulée « Implémentation de l’agent »Mettez à jour agent.py dans 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 supprime l’outil d’exemple subtract et remplace le prompt système par un prompt de maître de donjon qui invite le premier message de l’utilisateur à indiquer le nom et le genre du joueur, et utilise les outils du serveur MCP Inventory. main.py n’a besoin d’aucune modification ici — la gestion des sessions était déjà configurée lors de la génération de l’agent.
Tâche 2 : Tester votre agent localement
Section intitulée « Tâche 2 : Tester votre agent localement »Compiler le code
Section intitulée « Compiler le code »Pour compiler le code :
pnpm buildyarn buildnpm run buildbun buildDiscuter avec votre agent
Section intitulée « Discuter avec votre agent »La cible agent-chat générée ouvre un REPL interactif contre votre agent. Il s’exécute de manière autonome et se connecte à votre agent s’exécutant localement, donc démarrez d’abord le serveur local de l’agent dans un terminal :
pnpm nx agent-dev storyyarn nx agent-dev storynpx nx agent-dev storybunx nx agent-dev storyEnsuite, dans un second terminal, démarrez le chat :
pnpm nx agent-chat storyyarn nx agent-chat storynpx nx agent-chat storybunx nx agent-chat storyVotre premier message devrait indiquer à l’agent le nom de votre héros et le genre (par exemple : My name is Alice. Start my zombie adventure.) et l’histoire sera diffusée en retour.
Félicitations. Vous avez construit et testé votre premier agent Strands localement ! 🎉🎉🎉