Skip to content

Storyエージェントの実装と設定

タスク1: Storyエージェントの実装

Section titled “タスク1: 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/agentagent.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はここでは変更不要です。エージェントが生成された時点でセッション管理は既に配線されています。

タスク2: エージェントをローカルでテストする

Section titled “タスク2: エージェントをローカルでテストする”

コードをビルドするには:

Terminal window
pnpm build

生成されたagent-chatターゲットは、エージェントに対してインタラクティブなREPLを開きます。これはスタンドアロンで実行され、ローカルで実行中のエージェントに接続するため、まず1つのターミナルでエージェントのローカルサーバーを起動します:

Terminal window
pnpm nx agent-dev story

次に、2つ目のターミナルでチャットを開始します:

Terminal window
pnpm nx agent-chat story

最初のメッセージでは、エージェントにヒーローの名前とジャンルを伝える必要があります(例: My name is Alice. Start my zombie adventure.)。ストーリーがストリーミングで返されます。

おめでとうございます。最初のStrandsエージェントをローカルでビルドしてテストしました!🎉🎉🎉