smolagents hf minimal agent

smolagents:HuggingFace 极简 Agent 框架实战

极简主义的胜利 在 Agent 框架越来越复杂的 2026 年,HuggingFace 的 smolagents 反其道而行之——用不到 1000 行核心代码实现一个功能完备的 Agent 框架。这不是噱头,而是对"Agent 本质"的深刻理解:Agent 的核心就是 LLM + 工具调用,其余都是装饰。 设计哲学 smolagents 的三个设计原则: Code as Action:Agent 直接生成 Python 代码作为 Action,而非 JSON/函数调用 Minimal Abstraction:最少抽象层,开发者直接控制每个细节 HF Ecosystem First:与 HuggingFace 生态无缝集成 快速上手 安装 pip install smolagents 第一个 Agent from smolagents import CodeAgent, HfApiModel, tool # 定义工具 @tool def get_weather(city: str) -> str: """ 获取指定城市的天气信息。 Args: city: 城市名称,如 "北京"、"上海" Returns: 天气描述字符串 """ # 实际实现中调用天气 API import requests resp = requests.get(f"https://api.weather.com/v1/{city}") data = resp.json() return f"{city}:{data['condition']},温度 {data['temp']}°C" @tool def calculate(expression: str) -> float: """ 安全地计算数学表达式。 Args: expression: 数学表达式,如 "2 + 3 * 4" Returns: 计算结果 """ import ast import operator ops = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow } node = ast.parse(expression, mode='eval').body if isinstance(node, ast.BinOp): return ops[type(node.op)]( calculate(ast.unparse(node.left)), calculate(ast.unparse(node.right)) ) return ast.literal_eval(node) # 创建 Agent agent = CodeAgent( model=HfApiModel("Qwen/Qwen2.5-72B-Instruct"), # 免费使用 HF Inference API tools=[get_weather, calculate], max_steps=10, verbosity_level=2 ) # 运行 result = agent.run( "北京和上海今天哪个温度更高?高多少度?" ) # Agent 会: # 1. 调用 get_weather("北京") # 2. 调用 get_weather("上海") # 3. 调用 calculate("上海温度 - 北京温度") # 4. 返回自然语言回答 Code Agent:代码即行动 smolagents 最独特的特性是 Code Agent 模式。与传统 Tool Calling 不同,Code Agent 直接生成可执行 Python 代码: ...

2026-06-28 · 4 min · 798 words · 硅基 AGI 探索者
鲁ICP备2026018361号