

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

# 使用工具 （函數呼叫）
<a name="using-tools"></a>

工具透過將模型連接到 APIs、資料庫和程式碼執行環境等外部功能來擴展 Amazon Nova 功能。工具使用可讓 Amazon Nova 存取即時資訊、執行計算並與外部系統互動。

## 了解工具使用工作流程
<a name="tool-workflow"></a>

搭配 Amazon Nova 使用工具涉及三個關鍵階段：

使用者查詢和工具定義  
透過提供描述每個工具的功能和輸入要求的 JSON 結構描述來定義工具。工具組態必須包含有關何時及如何使用每個工具的明確詳細資訊。

工具選擇  
當使用者傳送訊息時，Amazon Nova 會對其進行分析，以判斷是否需要工具。此自動工具選擇會檢查內容，並決定要叫用哪個工具 （如果有的話）。如果 Amazon Nova 識別合適的工具，則會傳回工具名稱和必要的參數。  
您有責任根據模型的請求執行工具。這表示編寫程式碼來叫用工具的功能，並處理模型提供的輸入參數。

傳回結果  
執行工具後，請使用 JSON 或文字和影像的組合，以結構化格式將結果傳回 Amazon Nova。Amazon Nova 會將工具的輸出納入最終回應。如果在執行期間發生錯誤，請在工具回應中指出這一點，以允許 Amazon Nova 相應地調整。

## 建立工具
<a name="create-tool"></a>

使用工具組態來定義工具，其中包含一系列工具和選用的工具選擇參數。每個工具規格必須包含：
+ **名稱：**清除工具的識別符
+ **描述：**工具功能的簡要說明
+ **輸入結構描述：**定義必要和選用參數的 JSON 結構描述

**Example 工具組態範例**  

```
tool_config = {
    "tools": [
        {
            "toolSpec": {
                "name": "calculator",
                "description": "A calculator tool that can execute a math equation",
                "inputSchema": {
                    "json": {
                        "type": "object",
                        "properties": {
                            "equation": {
                                "type": "string",
                                "description": "The full equation to evaluate"
                            }
                        },
                        "required": ["equation"]
                    }
                }
            }
        }
    ]
}
```

### 工具定義的最佳實務
<a name="tool-best-practices"></a>
+ 確保名稱和描述明確傳達工具的確切功能；避免過於相似的語彙工具
+ 在描述中包含關鍵差異點，以協助模型區分類似的工具
+ 將 JSON 結構描述限制為兩層巢狀，以獲得最佳效能
+ 使用結構描述類型 （例如列舉、整數、浮點數） 來限制輸入，而不是以純文字描述結構
+ 使用 JSON 結構描述表示法 （例如，「必要」：【「param1」、「param2」】) 來表示必要參數與選用參數
+ 在提交之前，使用標準驗證器驗證您的 JSON 結構描述
+ 將長字串引數最後放在結構描述中，並避免將其巢狀化

### 具有限制解碼的結構式輸出
<a name="structured-output"></a>

Amazon Nova 模型會利用限制解碼，以確保產生輸出中的高可靠性。此技術使用文法來限制每個產生步驟的可能字符，防止無效的金鑰，並根據您定義的結構描述強制執行正確的資料類型。

**Example 結構化輸出範例**  

```
tool_config = {
    "tools": [
        {
            "toolSpec": {
                "name": "ProductAnalysis",
                "description": "Analyze product information from text.",
                "inputSchema": {
                    "json": {
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                "description": "Product name"
                            },
                            "rating": {
                                "maximum": 5,
                                "description": "Customer rating 1-5",
                                "type": ["number", "null"],
                                "minimum": 1
                            },
                            "features": {
                                "description": "Key product features",
                                "type": "array",
                                "items": {"type": "string"}
                            },
                            "category": {
                                "type": "string",
                                "description": "Product category"
                            },
                            "price": {
                                "type": "number",
                                "description": "Price in USD"
                            }
                        },
                        "required": ["name", "category", "price", "features"]
                    }
                }
            }
        }
    ],
    "toolChoice": {
        "tool": {"name": "ProductAnalysis"}
    }
}
```

### 工具選擇選項
<a name="tool-choice-options"></a>

Amazon Nova 支援三種工具選擇參數：

工具  
指定的工具將呼叫一次，非常適合結構化輸出使用案例

任何  
其中一個提供的工具至少會呼叫一次，適用於 API 選擇案例

自動  
模型決定是否呼叫工具，以及要呼叫多少工具 （預設行為）

## 呼叫工具
<a name="call-tool"></a>

當 Amazon Nova 決定呼叫工具時，它會傳回工具使用區塊，做為 stopReason 設定為 "tool\$1use" 之輔助訊息的一部分。工具區塊包含工具名稱及其輸入。

**注意**  
在單一 Python 工作階段中依序執行下列程式碼區段 （呼叫工具 → 處理工具呼叫 → 傳回工具結果）。若要再次執行範例，請重新啟動 Python 工作階段。

**Example 呼叫工具**  

```
import boto3
import json

# Create Bedrock client
bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')

# Complex calculation that benefits from precise computation
messages = [{
    "role": "user",
    "content": [{
        "text": "Calculate the compound interest on $10,000 invested at 4.75% annual rate for 7 years, compounded quarterly. Use the formula A = P(1 + r/n)^(nt) where P=10000, r=0.0475, n=4, t=7"
    }]
}]

# Define tool configuration with calculator
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"]
                }
            }
        }
    }]
}

# Invoke Model
response = bedrock.converse(
    modelId="us.amazon.nova-2-lite-v1:0",
    messages=messages,
    toolConfig=tool_config
)

# Extract tool use from response
tool = next(
    block["toolUse"]
    for block in response["output"]["message"]["content"]
    if "toolUse" in block
)

print(f"Tool: {tool['name']}")
print(f"Expression: {tool['input']['expression']}")
```

### 處理工具呼叫
<a name="process-tool-calls"></a>

從訊息中擷取工具名稱和引數，然後叫用工具：

```
def calculate(expression):
    """Evaluate mathematical expression"""
    print(f"Calculating: {expression}")
    P = 10000
    r = 0.0475
    n = 4
    t = 7
    result = P * (1 + r/n) ** (n*t)
    return result

stop_reason = response["stopReason"]

if stop_reason == "tool_use":
    if tool["name"] == "calculator":
        result = calculate(tool["input"]["expression"])
```

### 傳回工具結果
<a name="return-tool-results"></a>

使用 ToolResultBlock 結構描述傳回工具結果：

```
messages.append(response["output"]["message"])

# Add the tool result
messages.append({
    "role": "user",
    "content": [{
        "toolResult": {
            "toolUseId": tool['toolUseId'],
            "content": [{"json": {"result": result}}],
            "status": "success"
        }
    }]
})

# Send the tool result to the model
response = bedrock.converse(
    modelId="us.amazon.nova-2-lite-v1:0",
    messages=messages,
    toolConfig=tool_config
)

# Extract and display final response
final_text = next(
    block["text"]
    for block in response["output"]["message"]["content"]
    if "text" in block
)

print(f"\nFinal Response:\n{final_text}")
```

### 錯誤處理
<a name="tool-error-handling"></a>

向 Amazon Nova 回報錯誤，以允許修改請求並重試：

```
tool_result_message = {
    "role": "user",
    "content": [
        {
            "toolResult": {
                "toolUseId": tool["toolUseId"],
                "content": [{"text": "A validation exception occurred on field: sample.field"}],
                "status": "error"
            }
        }
    ]
}
```

### 安全考量
<a name="tool-security"></a>
+ 在叫用工具之前驗證工具是否存在
+ 確保輸入格式正確
+ 在工具執行之前，確認有適當的許可
+ 依賴工作階段詳細資訊，而不是允許 Amazon Nova 將使用者資訊注入工具呼叫
+ 請記住，LLMs可以幻化工具呼叫；在執行之前一律驗證

## 內建系統工具
<a name="builtin-tools"></a>

Amazon Nova 2.0 模型包含完全受管的內建工具，不需要自訂實作。在 Converse API 中使用簡單的切換來啟用這些工具。

### 程式碼解譯器
<a name="code-interpreter"></a>

Code Interpreter 可讓 Nova 在隔離的沙盒環境中安全地執行 Python 程式碼。此工具專為數學運算、邏輯操作和迭代演算法而設計。

**注意**  
程式碼解譯器適用於 IAD、PDX 和 NRT AWS 區域。若要確保您的請求路由到支援的 區域，請使用全域 CRIS。使用 Bedrock API 金鑰時，您需要手動將`InvokeTool`許可新增至政策定義。預設 Bedrock 角色不允許 `InvokeTool`動作。

透過指定 systemTool 參數啟用程式碼解譯器：

```
import boto3
import json

bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')

tool_config = {
    "tools": [{
        "systemTool": {
            "name": "nova_code_interpreter"
        }
    }]
}

response = bedrock.converse(
    modelId="us.amazon.nova-2-lite-v1:0",
    messages=[{
        "role": "user",
        "content": [{
            "text": "What is the average of 10, 24, 2, 3, 43, 52, 13, 68, 6, 7, 902, 82"
        }]
    }],
    toolConfig=tool_config,
    inferenceConfig={"maxTokens": 10000, "temperature": 0}
)

# Pretty print the response
for block in response["output"]["message"]["content"]:
    if "toolUse" in block:
        print("=== Tool Use ===")
        print(f"Tool: {block['toolUse']['name']}")
        print(f"Code:\n{block['toolUse']['input']['snippet']}\n")
    
    elif "toolResult" in block:
        print("=== Tool Result ===")
        result = block['toolResult']['content'][0]['json']
        print(f"Output: {result['stdOut']}")
        if result['stdErr']:
            print(f"Error: {result['stdErr']}")
        print(f"Exit Code: {result['exitCode']}\n")
    
    elif "text" in block:
        print("=== Final Answer ===")
        print(block["text"])
```

解譯器會在沙盒中執行程式碼，並傳回標準結構描述的結果：

```
{
    "stdOut": "String",
    "stdErr": "String",
    "exitCode": "int",
    "isError": "boolean"
}
```

### Web Grounding
<a name="web-grounding-tool"></a>

Web 接地可讓 Amazon Nova 從網際網路存取即時資訊，提供up-to-date回應並減少幻覺。透過指定 nova\$1grounding 系統工具來啟用 ：

```
tool_config = {
    "tools": [{
        "systemTool": {"name": "nova_grounding"}
    }]
}
```

如需 Web Grounding 的詳細資訊，請參閱 [Web Grounding](web-grounding.md)。

### 模型內容通訊協定 (MCP)
<a name="mcp-protocol"></a>

模型內容通訊協定 (MCP) 是一種開放標準，可在資料來源和 AI 支援的工具之間啟用安全的雙向連線。執行 MCP 伺服器並讓 Amazon Nova 透過用戶端橋接自動探索其工具，而不是為每個 API 或服務撰寫自訂轉接器。

連線後，Amazon Nova 會將 MCP 工具視為任何其他外部整合：它會決定何時呼叫它們、傳送必要的參數，並將結果納入回應中。搭配 Strands 使用 Amazon Nova 可讓您更輕鬆地使用內建的 MCPClient，自動管理探索、連線和結果映射。