載入中

實作多輪對話

第 27 課15 分鐘
載入中

建立一個具有工具的對話系統,需要實作一個迴圈,持續呼叫 Claude,直到它不再要求使用工具為止。當 Claude 不再要求使用工具時,就表示它已經準備好給使用者最終的回應。

偵測工具請求

判斷 Claude 是否想要使用工具的關鍵,在於回應訊息中的 stop_reason 欄位。當 Claude 判斷它需要呼叫工具時,這個欄位會被設為 "tool_use"。這讓我們有一個簡潔的方式來檢查是否需要繼續對話迴圈:

python
if response.stop_reason != "tool_use":
    break  # Claude is done, no more tools needed

對話迴圈

主要的對話函式遵循一個簡單的模式:

python
def run_conversation(messages):
    while True:
        response = chat(messages, tools=[get_current_datetime_schema])
        add_assistant_message(messages, response)
        print(text_from_message(response))
        
        if response.stop_reason != "tool_use":
            break
            
        tool_results = run_tools(response)
        add_user_message(messages, tool_results)
    
    return messages

這個迴圈會持續進行,直到 Claude 在不要求任何工具的情況下提供最終答案為止。

處理多個工具呼叫

Claude 可以在單一回應中請求多個工具。訊息內容包含一個區塊列表,我們需要分別處理每個工具使用區塊:

message.content 持有一個 TextBlock,以及針對「10 + 10」和「30 + 30」的 ToolUseBlocks,每個都會被執行並以 ToolResultBlock 回傳。

run_tools 函式透過篩選出工具使用區塊並逐一處理來達成這點:

python
def run_tools(message):
    tool_requests = [
        block for block in message.content if block.type == "tool_use"
    ]
    tool_result_blocks = []
    
    for tool_request in tool_requests:
        # 處理每個工具請求……

工具結果區塊

每個工具使用區塊都必須以對應的工具結果區塊來回覆。兩者之間的關聯是透過相符的 ID 來維持:

在 Notebook 儲存格中,當工具名稱相符時,run_tools 會呼叫 get_current_datetime,接著建立一個工具結果區塊。

工具結果區塊的結構包含:

python
tool_result_block = {
    "type": "tool_result",
    "tool_use_id": tool_request.id,
    "content": json.dumps(tool_output),
    "is_error": False
}

錯誤處理

穩健的工具執行需要處理潛在的錯誤。當工具失敗時,我們仍然需要提供一個結果區塊給 Claude:

python
try:
    tool_output = run_tool(tool_request.name, tool_request.input)
    tool_result_block = {
        "type": "tool_result",
        "tool_use_id": tool_request.id,
        "content": json.dumps(tool_output),
        "is_error": False
    }
except Exception as e:
    tool_result_block = {
        "type": "tool_result", 
        "tool_use_id": tool_request.id,
        "content": f"Error: {e}",
        "is_error": True
    }

可擴充的工具路由

為了支援多個工具,請建立一個路由函式,將工具名稱對應到其實作:

python
def run_tool(tool_name, tool_input):
    if tool_name == "get_current_datetime":
        return get_current_datetime(**tool_input)
    elif tool_name == "another_tool":
        return another_tool(**tool_input)
    # 依需要新增更多工具

這種做法讓新增工具變得容易,而不需要修改核心的對話邏輯。

完整流程

完整的多輪對話運作方式如下:

  • 將使用者訊息連同可用的工具一起傳送給 Claude
  • Claude 以文字及(或)工具請求來回應
  • 執行所有被請求的工具並建立結果區塊
  • 將工具結果以使用者訊息的形式回傳
  • 重複上述步驟,直到 Claude 提供最終答案

這建立了一種無縫的體驗,讓 Claude 能夠跨越數個回合使用多個工具,以完整地回答複雜的使用者請求。對話歷史記錄維持了完整的脈絡,讓 Claude 能夠根據先前的工具結果進一步建構,提供全面的回應。