Agentic RAG 简介

使用 Hugging Face smolagents 的 AI Agents

Adel Nehme

VP of AI Curriculum, DataCamp

Agentic RAG:迭代检索 + 推理

使用 Hugging Face smolagents 的 AI Agents

smolagents 中的无状态 vs 有状态工具

函数式工具(@tool 装饰器)

  • 无状态:调用间无记忆
  • 调用间无法记住向量库

基于类的工具(Tool 子类)

  • 有状态:跨调用保留引用
  • 可存储复杂对象
使用 Hugging Face smolagents 的 AI Agents

基于类的工具结构解析

from smolagents import Tool

class ToolName(Tool):
    name = "tool_name"

description = "为 agent 提供的清晰描述"
inputs = { "parameter_name": {"type": "parameter_type", "description": "参数用途"} } output_type = "string"
def __init__(self, custom_parameters): super().__init__() self.custom_attribute = custom_parameters
def forward(self, parameter_name): # Agent 调用此方法 return "processed output"
使用 Hugging Face smolagents 的 AI Agents

构建菜谱搜索工具

class RecipeSearchTool(Tool):
    name = "recipe_search" 
    description = "在烹饪文档中搜索菜谱、技巧和餐食规划信息"
    inputs = {
        "query": {"type": "string", "description": "自然语言烹饪查询"}
    }
    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 Agents

烹饪助手机器人:整合示例

# 初始化检索工具
recipe_search = RecipeSearchTool(vector_store)

agent = CodeAgent(
    tools=[recipe_search],
    model=model,
    instructions="请充分检索,给出完整的菜谱答案。\n  \t若初始结果不完整,请尝试不同检索词。",
    verbosity_level=1,
    max_steps=8
)
使用 Hugging Face smolagents 的 AI Agents

Agent 运行示例

询问:如何用专业技巧用香草烹饪三文鱼?

[步骤 1] 搜索 "salmon herbs cooking techniques"...

[步骤 2] 搜索 "professional salmon preparation"...

[最终答案]

"将鱼排拍干、用香草调味,然后:

  • 皮面朝下煎,配黄油、蒜、百里香淋汁;
  • 或以 200°C 烘烤,配柠檬与香草黄油 10–12 分钟。"
使用 Hugging Face smolagents 的 AI Agents

Passons à la pratique !

使用 Hugging Face smolagents 的 AI Agents

Preparing Video For Download...