開始使用免費開始

以狀態為核心:建立 RAG 搜尋工具

在上一個課程中,你已看到如何使用嵌入向量(embedding)來建立與搜尋以家電手冊為基礎的向量化知識庫。

接下來,你要建立一個自訂工具,將這段搜尋邏輯包裝起來,讓代理(agent)可以用它來回答與家電相關的問題。

你要撰寫的工具會繼承 Tool 基底類別,並只暴露一個輸入:一個關於家電操作的問題。

你已可使用以下資源:

  • 名為 vector_store 的變數,裡面包含你先前建立的 FAISS 索引
  • 來自家電手冊內容的文件分塊,已完成嵌入,可供搜尋

你的工作是實作這個工具的結構與邏輯,讓代理可以存取這個知識庫。

本練習屬於課程

使用 Hugging Face smolagents 的 AI 代理

檢視課程

練習說明

  • __init__() 方法中接受 vector_store 參數。
  • forward() 方法中加入 query 作為參數。
  • 使用 self.k 來設定相似度搜尋要回傳的相關文件數量。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

class ApplianceSearchTool(Tool):
    name = "appliance_manual_search"
    description = "Search appliance manuals for maintenance and usage information"
    inputs = {"query": {"type": "string", "description": "Question about appliance operation"}}
    output_type = "string"

    # Pass the vector store into the constructor
    def __init__(self, ____, k=3):
        super().__init__()
        self.vector_store = vector_store
        self.k = k

    # Accept the query string as input to the forward method
    def forward(self, ____):
        # Use self.k here to specify how many chunks to return
        docs = self.vector_store.similarity_search(query, k=____)
        return "\n\n".join(doc.page_content for doc in docs) or "No relevant manual sections found."
編輯並執行程式碼