

# AI エージェントの構築
<a name="building-ai-agents"></a>

Amazon Nova モデルは、Amazon Nova Act を使用して AI エージェントを構築するために最適化されています。このモデルは、ツールの使用の向上、複数ステップタスクの推論の向上、複雑なエージェントワークフロー全体でコンテキストを維持する機能の強化、リモート MCP ツールのサポートを提供します。

## エージェントを作成する
<a name="create-agent"></a>

Nova で構築された AI エージェントは、複数のツールコールをオーケストレーションし、広範なインタラクションにわたってコンテキストを維持し、必要に応じてコースを修正できます。拡張思考は、複雑な目標を通じて体系的な推論を可能にすることで、エージェントワークフローを変換します。Strands Agents などの計画フレームワーク SDK を使用して、エージェントシステムの計画と実行プロセスをより堅牢にすることを検討してください。

### エージェント設計パターン
<a name="agent-design-patterns"></a>

Nova でエージェントを設計する場合:
+ 計画と検証が必要な複雑なマルチステップワークフローで最良の結果を得るために、中程度または高い推論を有効にします
+ エージェントとのやり取り全体で柔軟なツール選択を可能にするツール選択 `auto` を実装します
+ エージェントが変更されたアプローチで復旧して再試行できるようなエラー処理を設計します
+ 会話履歴を維持し、エージェントとのやり取り全体のコンテキストを保持します
+ エージェントシステムが消費する制御されていないコンテンツに、堅牢なコンテンツフィルタリングとモデレーションメカニズムを実装します。例えば、Amazon は Amazon Bedrock ガードレールを提供しています。これは、複数の基盤モデル、ナレッジベース、エージェントに保護を適用するように設計された機能です。これらのガードレールは、有害なコンテンツをフィルタリングしたり、拒否されたトピックをブロックしたり、個人を特定できる情報などの機密情報を編集したりできます。

### マルチツールエージェントの例
<a name="multi-tool-agent-example"></a>

```
tool_config = { 
    "tools": [ 
        { 
            "toolSpec": { 
                "name": "calculator", 
                "description": "Perform mathematical calculations", 
                "inputSchema": { 
                    "json": { 
                        "type": "object", 
                        "properties": { 
                            "expression": { 
                                "type": "string", 
                                "description": "Mathematical expression to evaluate" 
                            } 
                        }, 
                        "required": ["expression"] 
                    } 
                } 
            } 
        }, 
        { 
            "toolSpec": { 
                "name": "database_query", 
                "description": "Query financial database for historical data", 
                "inputSchema": { 
                    "json": { 
                        "type": "object", 
                        "properties": { 
                            "query": { 
                                "type": "string", 
                                "description": "SQL query to execute" 
                            } 
                        }, 
                        "required": ["query"] 
                    } 
                } 
            } 
        } 
    ] 
} 
 
response = client.converse( 
    modelId=" us.amazon.nova-2-lite-v1:0", 
    messages=[{ 
        "role": "user", 
        "content": [{ 
            "text": "Analyze our Q3 financial performance across all business units, calculate year-over-year growth rates with statistical significance testing, and recommend budget allocation strategies for Q4." 
        }] 
    }], 
    toolConfig=tool_config, 
    inferenceConfig={"maxTokens": 10000, "temperature": 1, “topP”: 0.9}, 
    additionalModelRequestFields={ 
        "reasoningConfig": { 
            "type": "enabled", 
            "maxReasoningEffort": "low" 
        } 
    } 
)
```

## エージェントを呼び出す
<a name="invoke-agent"></a>

エージェント呼び出しには、会話フローの管理、ツール呼び出しの処理、複数のインタラクションにわたる状態の維持が含まれます。

### エージェントレスポンスをストリーミング
<a name="stream-agent-responses"></a>

レスポンスをストリーミングして、エージェントの推論とアクションをリアルタイムで可視化します。

```
import boto3
response = client.converse_stream( 
    modelId=" us.amazon.nova-2-lite-v1:0", 
    messages=[{ 
        "role": "user", 
        "content": [{ 
            "text": "Design a scalable microservices architecture for an e-commerce platform handling 1M+ daily transactions. Consider data consistency, fault tolerance, performance, security, and cost optimization." 
        }] 
    }], 
    inferenceConfig={"maxTokens": 10000, "temperature": 10}, 
    additionalModelRequestFields={ 
        "reasoningConfig": { 
            "type": "enabled", 
            "maxReasoningEffort": "low" 
        } 
    } 
) 
 
# Process the streaming response 
reasoning_complete = False 
for event in response["stream"]: 
    if "contentBlockDelta" in event: 
        delta = event["contentBlockDelta"]["delta"] 
         
        if "reasoningContent" in delta: 
            reasoning_text = delta["reasoningContent"]["reasoningText"]["text"] 
            print(f"{reasoning_text}", end="", flush=True) 
        elif "text" in delta: 
            if not reasoning_complete: 
                print(f" 
 
Final Architecture Design: 
") 
                reasoning_complete = True 
            print(f"{delta['text']}", end="", flush=True)
```

### エージェント状態管理
<a name="manage-agent-state"></a>

会話履歴とツールの結果を維持し、コンテキストを保持します。以下の例では、これを 1 ターンで示していますが、デベロッパーはワークフロー要件に基づいてエージェントシステム全体のオーケストレーション方法を決定できます。さらに、Strands などの Amazon Web Services ツールは、デベロッパーに代わってエージェントのコンテキストとツールの状態を管理します。

```
messages = []

messages = [] 
 
# Initial user query 
messages.append({ 
    "role": "user", 
    "content": [{"text": user_query}] 
}) 
 
# Get agent response 
response = client.converse( 
    modelId=" us.amazon.nova-2-lite-v1:0", 
    messages=messages, 
    toolConfig=tool_config, 
    inferenceConfig=inf_params 
) 
 
# Add assistant response to history 
messages.append(response["output"]["message"]) 
 
# Process tool calls and add results 
if response["stopReason"] == "tool_use": 
    tool = next( 
        block["toolUse"] 
        for block in response["output"]["message"]["content"] 
        if "toolUse" in block 
    ) 
     
    # Execute tool 
    result = execute_tool(tool["name"], tool["input"]) 
     
    # Add tool result to conversation 
    messages.append({ 
        "role": "user", 
        "content": [{ 
            "toolResult": { 
                "toolUseId": tool["toolUseId"], 
                "content": [{"json": result}], 
                "status": "success" 
            } 
        }] 
    }) 
     
    # Continue conversation 
    response = client.converse( 
        modelId=" us.amazon.nova-2-lite-v1:0", 
        messages=messages, 
        toolConfig=tool_config, 
        inferenceConfig=inf_params 
    )
```

### エージェントのベストプラクティス
<a name="agent-best-practices"></a>

エージェントのベストプラクティスの詳細については、「[一般的なベストプラクティス](prompting-best-practices.md)」を参照してください。

対話型 AI エージェントの開発に関するガイダンスについては、「[音声変換 (Amazon Nova 2 Sonic)](using-conversational-speech.md)」を参照してください。