工具是向 Amazon Nova 提供外部功能的方式,例如 API 呼叫或程式碼函數。本節將介紹如何在使用 Amazon Nova 模型時定義和整合工具。
工具使用涉及三個高階步驟:
-
使用者查詢 - 您可以透過提供描述每個工具功能和輸入要求的 JSON 結構描述,定義 Amazon Nova 可以使用的工具。
-
工具選取 - 當使用者傳送訊息時,Amazon Nova 會對其進行分析,以判斷是否需要工具來產生回應。這稱為 Auto 工具選取。如需詳細資訊,請參閱選擇工具。如果 Amazon Nova 確定了合適的工具,它會「呼叫工具」並傳回工具的名稱和要使用的參數。
身為開發人員,您負責根據模型的請求執行該工具。這表示您需要撰寫程式碼來調用工具的功能,並處理模型提供的輸入參數。
如同所有 LLM 回應,Amazon Nova 可能會對工具呼叫產生幻覺。開發人員有責任驗證工具是否存在、輸入格式是否正確,並且已具備適當的權限。
-
傳回結果 - 執行工具後,必須以結構化格式將結果傳回 Amazon Nova。有效格式包括 JSON 或文字和影像的組合。這可讓 Amazon Nova 將工具的輸出納入對使用者的最終回應中。
如果在工具執行期間出現任何錯誤,您可以在對 Amazon Nova 的工具回應中指出這些錯誤,讓 Amazon Nova 相應地調整其回應。
考慮一個簡單的計算器工具範例:
- User query
-
工具呼叫工作流程的第一個步驟是,使用者查詢 Amazon Nova 以取得數學方程式 - 10 乘以 5 的結果。此查詢會作為提示詞,與代表計算器的工具規格一起傳送至 Amazon Nova。
user_query = "10*5"
messages = [{
"role": "user",
"content": [{"text": user_query}]
}]
tool_config = {
"tools": [
{
"toolSpec": {
"name": "calculator", # Name of the tool
"description": "A calculator tool that can execute a math equation", # Concise description of the tool
"inputSchema": {
"json": {
"type": "object",
"properties": {
"equation": { # The name of the parameter
"type": "string", # parameter type: string/int/etc
"description": "The full equation to evaluate" # Helpful description of the parameter
}
},
"required": [ # List of all required parameters
"equation"
]
}
}
}
}
]
}
- Tool selection
-
Amazon Nova 會使用工具的上下文以及使用者提示,來判斷需要使用的工具和所需的組態。這會作為 API 回應的一部分傳回。
{
"toolUse": {
"toolUseId": "tooluse_u7XTryCSReawd9lXwljzHQ",
"name": "calculator",
"input": {
"equation": "10*5"
}
}
}
應用程式負責執行工具並存放結果。
def calculator(equation: str):
return eval(equation)
tool_result = calculator("10*5")
- Return results
-
若要將工具的結果傳回 Amazon Nova,工具結果會包含在新的 API 請求中。請注意,工具使用 ID 與上一個回應中從 Amazon Nova 傳回的 ID 是一致的。
{
"toolResult": {
"toolUseId": "tooluse_u7XTryCSReawd9lXwljzHQ",
"content": [
{
"json": {
"result": "50"
}
}
],
"status": "success"
}
}
Amazon Nova 允許在 Invoke 和 Converse API 中使用工具,但為完整功能廣度,我們建議使用 Converse API,並會在後文中使用此 API 的範例。