

# 调用工具
<a name="tool-use-invocation"></a>

如果 Amazon Nova 决定调用工具，则“工具使用”块将作为助手消息的一部分返回，停止原因将是“tool\$1use”。工具块将包含工具的名称及其输入。

**注意**  
为提高工具调用的准确性，Amazon Nova 模型的默认行为是使用思维链推理进行工具调用。思维过程将在助手消息中提供给您，并将包含在 <thinking> 标签中。回复中可能有多个工具调用和思维块，因此您的应用程序应将其考虑在内。  
如果将工具选择配置为 `any` 或 `tool`，这会覆盖思维链行为，回复也只会包含必要的工具调用。

```
{
   "toolUse": 
    {
        "toolUseId": "tooluse_20Z9zl0BQWSXjFuLKdTJcA", 
        "name": "top_song", 
        "input": {
            "sign": "WZPZ"
        }
    }
}
```

要实际调用该工具，可以从消息中提取工具名称和参数，然后应用程序就可以调用该工具。

以下示例演示了如何处理工具调用。

```
def get_top_song(sign):
    print(f"Getting the top song at {sign}")
    return ("Espresso", "Sabrina Carpenter")

stop_reason = response["stopReason"]

tool, song, artist = None, None, None
if stop_reason == "tool_use":
    thought_process = next(
        block["text"]
        for block in response["output"]["message"]["content"]
        if "text" in block
    )

    print(thought_process)

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

    if tool["name"] == "top_song":
        song, artist = get_top_song(tool["input"]["sign"])
```

在定义和调用工具时，务必牢记安全性。像 Amazon Nova 这样的 LLM 无法获取会话详细信息，因此在调用工具之前，应在必要时验证权限。应依靠会话中的用户详细信息，而不是增加提示并让 Amazon Nova 将其注入到工具调用中。