跳转到内容

实现和配置 Story 代理

Story 代理是一个在模块 1中使用 --protocol=ag-ui 生成的 Strands 代理,因此 UI 可以通过 CopilotKit 使用 Agent-User Interaction 协议从中流式传输数据。它使用 Inventory MCP Server 来管理玩家的物品,并且已经通过模块 1 中生成器提供的 session.py 持久化对话历史——部署后,这就是 Strands 内置的 S3SessionManager 写入到 Game API 的 queryActions 读取的同一个 S3 存储桶中,这样浏览器可以在重新访问时重建对话记录。

更新 packages/story/dungeon_adventure_story/agent 中的 agent.py

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 删除了示例 subtract 工具,并将系统提示替换为地牢主持人提示,该提示邀请第一条用户消息说明玩家的姓名和类型,并使用 Inventory MCP Server 的工具。main.py 在这里不需要更改——会话管理在生成代理时已经连接好了。

要构建代码:

Terminal window
pnpm build

生成的 agent-chat 目标会打开一个针对您的代理的交互式 REPL。它独立运行并连接到您本地运行的代理,因此首先在一个终端中启动代理的本地服务器:

Terminal window
pnpm nx agent-dev story

然后,在第二个终端中启动聊天:

Terminal window
pnpm nx agent-chat story

您的第一条消息应该告诉代理您的英雄的名字和类型(例如:My name is Alice. Start my zombie adventure.),故事将流式返回。

恭喜。您已经在本地构建并测试了您的第一个 Strands 代理!🎉🎉🎉