AI个人学习
和实操指南

Smolagents:快速开发AI智能体,轻量级构建智能体的开源项目

综合介绍

Smolagents是由HuggingFace开发的轻量级智能代理库,专注于简化AI代理系统的开发过程。该项目以其简洁的设计理念著称,核心代码仅约1000行,却提供了强大的功能集成能力。它最显著的特点是支持代码执行代理,让AI能够直接通过编写Python代码来调用各种工具和完成任务。Smolagents支持多种主流大语言模型,包括可通过HuggingFace Hub访问的模型、OpenAI和Anthropic的模型等。特别值得一提的是,该框架在安全性方面做了充分考虑,提供了安全的Python解释器和沙盒环境,有效降低了代码执行可能带来的风险。作为一个开源项目,Smolagents不仅提供了基础的代理开发框架,还支持通过HuggingFace Hub共享和加载工具,使开发者能够更便捷地构建和部署智能代理系统。


 

 

功能列表

  • 轻量级代理开发框架,核心逻辑仅约1000行代码
  • 支持多种大语言模型集成(HuggingFace、OpenAI、Anthropic等)
  • 代码执行代理功能,支持直接通过Python代码调用工具
  • 提供安全的代码执行环境和沙盒机制
  • 支持通过HuggingFace Hub共享和加载工具
  • 简单直观的API设计,便于快速开发和部署
  • 完整的文档支持和示例代码
  • 支持自定义工具开发和集成
  • 提供多种预置工具(如搜索工具DuckDuckGoSearchTool)

 

使用帮助

1. 安装步骤

首先需要通过pip安装Smolagents包:

pip install smolagents

2. 基础使用方法

2.1 创建简单代理

from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
# 创建代理实例
agent = CodeAgent(
tools=[DuckDuckGoSearchTool()],  # 添加所需工具
model=HfApiModel()  # 指定使用的模型
)
# 运行代理
response = agent.run("你的问题或任务描述")

2.2 安全性配置

为确保代码执行的安全性,Smolagents提供了两种安全机制:

  • 安全Python解释器:通过限制可用模块和函数来保护系统
  • 沙盒环境:提供隔离的执行环境

使用安全解释器示例:

from smolagents import CodeAgent, SecureInterpreter
agent = CodeAgent(
tools=[your_tools],
interpreter=SecureInterpreter()
)

3. 高级功能

3.1 自定义工具开发

开发者可以创建自己的工具类:

from smolagents import BaseTool
class MyCustomTool(BaseTool):
def __init__(self):
super().__init__()
def __call__(self, *args, **kwargs):
# 实现工具的具体功能
pass

3.2 与HuggingFace Hub集成

可以轻松从Hub加载和分享工具:

# 从Hub加载工具
from smolagents import load_tool
tool = load_tool("tool_name", from_hub=True)
# 分享工具到Hub
tool.push_to_hub("your-username/tool-name")

4. 最佳实践建议

  1. 始终使用安全解释器或沙盒环境来执行代码
  2. 根据需求选择适合的模型,考虑性能和成本
  3. 合理组织工具集,避免功能重复
  4. 定期更新依赖包以获取最新特性和安全修复
  5. 充分利用文档和示例代码加速开发

5. 常见问题解决

  • 如果遇到模型加载问题,检查网络连接和API密钥配置
  • 代码执行错误,查看是否受到安全限制,可能需要调整安全策略
  • 工具导入失败,确认是否正确安装了所有依赖

 

Smolagents中的关键prompt内容

参考:https://github.com/huggingface/smolagents/blob/e57f4f55ef506948d2e17b320ddc2a98b282eacf/src/smolagents/prompts.py

  1. 工具调用系统提示 (TOOL_CALLING_SYSTEM_PROMPT)
You are an expert assistant who can solve any task using tool calls. You will be given a task to solve as best you can.
To do so, you have been given access to the following tools: {{tool_names}}
The tool call you write is an action: after the tool is executed, you will get the result of the tool call as an "observation".
This Action/Observation can repeat N times, you should take several steps when needed.
You can use the result of the previous action as input for the next action.
The observation will always be a string: it can represent a file, like "image_1.jpg".
Then you can use it as input for the next action. You can do it for instance as follows:
Observation: "image_1.jpg"
Action:
{
"tool_name": "image_transformer",
"tool_arguments": {"image": "image_1.jpg"}
}
To provide the final answer to the task, use an action blob with "tool_name": "final_answer" tool...
[示例部分省略]
Here are the rules you should always follow to solve your task:
1. ALWAYS provide a tool call, else you will fail.
2. Always use the right arguments for the tools. Never use variable names as the action arguments, use the value instead.
3. Call a tool only when needed: do not call the search agent if you do not need information, try to solve the task yourself.
4. Never re-do a tool call that you previously did with the exact same parameters.
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
  1. 代码执行系统提示 (CODE_SYSTEM_PROMPT)
You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
[示例部分省略]
Here are the rules you should always follow to solve your task:
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
2. Use only variables that you have defined!
3. Always use the right arguments for the tools.
4. Take care to not chain too many sequential tool calls in the same code block
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
6. Don't name any new variable with the same name as a tool
7. Never create any notional variables in our code
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
9. The state persists between code executions
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
  1. 事实收集提示 (SYSTEM_PROMPT_FACTS)
Below I will present you a task.
You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
### 1. Facts given in the task
List here the specific facts given in the task that could help you (there might be nothing here).
### 2. Facts to look up
List here any facts that we may need to look up.
Also list where to find each of these, for instance a website, a file...
### 3. Facts to derive
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
  1. 计划制定提示 (SYSTEM_PROMPT_PLAN)
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
  1. 事实更新提示 (SYSTEM_PROMPT_FACTS_UPDATE)
You are a world expert at gathering known and unknown facts based on a conversation.
Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
### 1. Facts given in the task
### 2. Facts that we have learned
### 3. Facts still to look up
### 4. Facts still to derive
  1. 计划更新提示 (SYSTEM_PROMPT_PLAN_UPDATE)
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
You have been given a task:
```{task}```
Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
If the previous tries so far have met some success, you can make an updated plan based on these actions.
If you are stalled, you can make a completely new plan starting from scratch.
  1. 管理代理提示 (MANAGED_AGENT_PROMPT)
You're a helpful agent named '{name}'.
You have been submitted this task by your manager.
---
Task:
{task}
---
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
Your final_answer WILL HAVE to contain these parts:
### 1. Task outcome (short version):
### 2. Task outcome (extremely detailed version):
### 3. Additional context (if relevant):
未经允许不得转载:首席AI分享圈 » Smolagents:快速开发AI智能体,轻量级构建智能体的开源项目

首席AI分享圈

首席AI分享圈专注于人工智能学习,提供全面的AI学习内容、AI工具和实操指导。我们的目标是通过高质量的内容和实践经验分享,帮助用户掌握AI技术,一起挖掘AI的无限潜能。无论您是AI初学者还是资深专家,这里都是您获取知识、提升技能、实现创新的理想之地。

联系我们
zh_CN简体中文