Agentic RAG 入門

使用 Hugging Face smolagents 的 AI 代理

Adel Nehme

VP of AI Curriculum, DataCamp

Agentic RAG:反覆擷取+推理

使用 Hugging Face smolagents 的 AI 代理

smolagents 中的無狀態 vs. 有狀態工具

函式工具(@tool 裝飾器)

  • 無狀態:呼叫間不保留記憶
  • 呼叫間無法記住你的向量儲存

類別式工具(Tool 子類)

  • 有狀態:可在多次呼叫間保留參照
  • 可儲存複雜物件
使用 Hugging Face smolagents 的 AI 代理

類別式工具的結構

from smolagents import Tool

class ToolName(Tool):
    name = "tool_name"

description = "Clear description for the agent"
inputs = { "parameter_name": {"type": "parameter_type", "description": "Parameter purpose"} } output_type = "string"
def __init__(self, custom_parameters): super().__init__() self.custom_attribute = custom_parameters
def forward(self, parameter_name): # Agent calls this method return "processed output"
使用 Hugging Face smolagents 的 AI 代理

打造食譜搜尋工具

class RecipeSearchTool(Tool):
    name = "recipe_search" 
    description = "Search cooking documentation for recipes, techniques, and meal planning information"
    inputs = {
        "query": {"type": "string", "description": "Natural language cooking query"}
    }
    output_type = "string"

def __init__(self, vectorstore, k=6): super().__init__() self.vectorstore = vectorstore self.k = k
def forward(self, query): docs = self.vectorstore.similarity_search(query, k=self.k) return "\n\n".join(doc.page_content for doc in docs) or "Nothing found."
使用 Hugging Face smolagents 的 AI 代理

料理助理代理:整合實作

# Initialize the retrieval tool
recipe_search = RecipeSearchTool(vector_store)

agent = CodeAgent(
    tools=[recipe_search],
    model=model,
    instructions="Search thoroughly to provide complete recipe answers. 
      If initial results seem incomplete, try different search terms.",
    verbosity_level=1,
    max_steps=8
)
使用 Hugging Face smolagents 的 AI 代理

代理執行範例

查詢:如何用專業技巧烹調香草鮭魚?

[步驟 1] 搜尋「salmon herbs cooking techniques」...

[步驟 2] 搜尋「professional salmon preparation」...

[最終答案]

「將魚排擦乾、以香草調味,然後:

  • 平底鍋皮面朝下煎,並以奶油、蒜、百里香澆淋
  • 或以 200°C 與檸檬香草奶油烤 10–12 分鐘」
使用 Hugging Face smolagents 的 AI 代理

一起來練習吧!

使用 Hugging Face smolagents 的 AI 代理

Preparing Video For Download...