使用 Hugging Face smolagents 的 AI Agents
Adel Nehme
VP of AI Curriculum, DataCamp

函数式工具(@tool 装饰器)
基于类的工具(Tool 子类)
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_parametersdef forward(self, parameter_name): # Agent 调用此方法 return "processed output"
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 = kdef 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."
# 初始化检索工具
recipe_search = RecipeSearchTool(vector_store)
agent = CodeAgent(
tools=[recipe_search],
model=model,
instructions="请充分检索,给出完整的菜谱答案。\n \t若初始结果不完整,请尝试不同检索词。",
verbosity_level=1,
max_steps=8
)
询问:如何用专业技巧用香草烹饪三文鱼?
[步骤 1] 搜索 "salmon herbs cooking techniques"...
[步骤 2] 搜索 "professional salmon preparation"...
[最终答案]
"将鱼排拍干、用香草调味,然后:
使用 Hugging Face smolagents 的 AI Agents