載入中
載入中

在撰寫完您的工具函式後,下一步是建立一個 JSON 結構描述,告訴 Claude 您的函式需要哪些參數,以及如何使用它。這個結構描述就像是文件一樣,Claude 會閱讀它以了解何時以及如何呼叫您的工具。

理解 JSON Schema

JSON Schema 並非專屬於 AI 或工具呼叫——它是一個廣泛使用的數據驗證規範,已經存在多年。AI 社群採用它是因為它是描述函式參數和驗證數據的一種便利方式。

get_weather 工具的 JSON 結構描述:input_schema 是一個物件,具有一個必填的字串屬性「location」。

完整的工具規格有三個主要部分:

  • name - 函式名稱(例如「get_weather」)
  • description - 這個工具做什麼以及何時使用它
  • input_schema - 描述參數的實際 JSON 結構描述

撰寫有效的描述

已標註的 get_weather 工具結構描述,包含 name、description,以及描述必填 location 字串的 input_schema。

description 欄位對於幫助 Claude 理解您的工具至關重要。請遵循以下最佳實務:

  • 說明這個工具做什麼、何時使用它,以及它會回傳什麼
  • 目標是 3 到 4 個句子
  • 也為每個參數提供詳細的描述

input_schema 區段使用標準的 JSON Schema 格式描述您函式的參數,包括型別資訊以及每個參數的詳細描述。

簡單的方法:讓 Claude 撰寫您的結構描述

您可以使用 Claude 本身來產生 JSON 結構描述,而不必從頭開始撰寫。以下是這個流程:

  1. 複製您的工具函式
  2. 前往 Claude,請它為工具呼叫撰寫一個 JSON 結構描述
  3. 將 Anthropic 有關工具使用的文件作為上下文提供
  4. 讓 Claude 依循最佳實務產生一個格式正確的結構描述

Claude.ai 新對話,訊息框中包含提示文字和 get_current_datetime 函式,以及一個工具使用文件分頁。

提示大概會像這樣:「為了工具呼叫的目的,為這個函式撰寫一個有效的 JSON 結構描述規格。請遵循附件文件中列出的最佳實務。」

在程式碼中實作結構描述

一旦 Claude 產生了您的結構描述,請將它複製到您的程式碼檔案中。使用像 function_name_schema 這樣一致的命名模式來保持整齊:

python
get_current_datetime_schema = {
    "name": "get_current_datetime",
    "description": "Returns the current date and time formatted according to the specified format",
    "input_schema": {
        "type": "object",
        "properties": {
            "date_format": {
                "type": "string",
                "description": "A string specifying the format of the returned datetime. Uses Python's strftime format codes.",
                "default": "%Y-%m-%d %H:%M:%S"
            }
        },
        "required": []
    }
}

新增型別安全性

為了更好的型別檢查,請從 Anthropic 函式庫匯入並使用 ToolParam 型別:

python
from anthropic.types import ToolParam

get_current_datetime_schema = ToolParam({
    # 您的結構描述字典放在這裡
})

這對功能性而言並非嚴格必要,但它能防止您之後在程式碼中使用這個結構描述時發生型別錯誤。

一個撰寫良好的工具函式,搭配一個詳細的 JSON 結構描述,能讓 Claude 在對話中擁有理解並正確使用您工具所需的一切。