載入中
載入中

編寫完工具函式之後,下一步是建立一個 JSON 結構描述(schema),告訴 Claude 您的函式需要什麼引數,以及如何使用它。這個結構描述就像文件一樣,Claude 會讀取它以了解何時以及如何呼叫您的工具。

理解 JSON 結構描述

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

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

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

  • name(名稱) - 為您的工具取一個清楚、具描述性的名稱(如「get_weather」)
  • description(描述) - 此工具的功能、何時使用,以及傳回什麼
  • input_schema(輸入結構描述) - 描述函式引數的實際 JSON 結構描述

撰寫有效的描述

您的工具描述對於幫助 Claude 理解何時使用您的函式至關重要。最佳實務包括:

  • 以 3-4 句話說明工具的功能
  • 描述 Claude 應該在何時使用它
  • 說明它傳回的資料類型
  • 為每個引數提供詳細的描述

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

產生結構描述的簡易方法

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

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

提示應類似於:「請為這個函式撰寫一個有效的 JSON 結構描述規格,用於工具呼叫。請遵循附帶文件中列出的最佳實務。」

Claude.ai 新聊天視窗,訊息框中有提示及 get_current_datetime 函式,以及一個工具使用文件分頁。

在程式碼中實作結構描述

一旦 Claude 產生您的結構描述,請將其複製到您的程式碼檔案中。以下是一個良好的命名模式可供遵循:

python
def get_current_datetime(date_format="%Y-%m-%d %H:%M:%S"):
    if not date_format:
        raise ValueError("date_format cannot be empty")
    return datetime.now().strftime(date_format)

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": []
    }
}

請使用 function_name 後接 function_name_schema 的模式,以保持您的結構描述井然有序,並易於與對應的函式相互比對。

增加型別安全性

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

python
from anthropic.types import ToolParam

get_current_datetime_schema = ToolParam({
    "name": "get_current_datetime",
    "description": "Returns the current date and time formatted according to the specified format",
    # ……結構描述其餘部分
})

雖然這並非功能上嚴格必要的步驟,但它能在您將結構描述用於 Claude API 時防止型別錯誤,並使您的程式碼更加穩健。