

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 建置 AI 代理程式
<a name="building-ai-agents"></a>

Amazon Nova 模型已針對使用 Amazon Nova Act 建置 AI 代理器進行最佳化。這些模型提供改善的工具使用、改善多步驟任務的推理、增強在複雜客服人員工作流程之間維護內容的能力，以及支援遠端 MCP 工具。

## 建立代理程式
<a name="create-agent"></a>

使用 Nova 建置的 AI 代理器可以協調多個工具呼叫、維持延伸互動的內容，並在需要時更正課程。延伸思考透過透過複雜目標啟用系統推理來轉換代理程式工作流程。考慮使用規劃架構 SDK，例如 Strands Agents，讓您的代理系統的規劃和執行程序更強大。

### 代理程式設計模式
<a name="agent-design-patterns"></a>

使用 Nova 設計代理程式時：
+ 針對需要規劃和驗證的複雜多步驟工作流程，在中等或高層級上啟用推理，以獲得最佳結果
+ 實作工具選擇`auto`，以允許跨客服人員互動的彈性工具選擇
+ 設計錯誤處理，允許代理程式使用修改過的方法來復原和重試
+ 維護對話歷史記錄，以保留客服人員互動的內容
+ 在代理程式系統使用的未受控制內容中，實作強大的內容篩選和管制機制。例如，Amazon 提供 Amazon Bedrock Guardrails，這項功能旨在跨多個基礎模型、知識庫和代理程式套用保護措施。這些護欄可以篩選有害內容、封鎖拒絕的主題，以及修訂敏感資訊，例如個人身分識別資訊。

### 多工具代理程式範例
<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>

維護對話歷史記錄和工具結果以保留內容；以下範例示範一次，但開發人員可以根據工作流程需求判斷如何協調整體客服人員系統。此外，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 代理器的指引，請參閱 [Speech-to-Speech(Amazon Nova 2 Sonic)](using-conversational-speech.md)。