资讯详情

smol-course Agents 模块实战指南:用 smolagents 构建检索、代码与自定义函数 Agent

📅 2026/10/9 2:14:00 | 华诺云谱 👁 阅读
smol-course Agents 模块实战指南:用 smolagents 构建检索、代码与自定义函数 Agent
教程人工智能大模型NLP微调【免费下载链接】smol-courseA course on aligning smol models.项目地址https://gitcode.com/gh_mirrors/smo/smol-course点击查看免费下载导读本指南围绕 smol-course v1 的 Agents 模块展开系统讲解如何基于smolagents轻量级框架构建三类典型 Agent具备知识检索能力的 Agentic RAG 系统、面向软件开发任务的代码型 Agent以及通过自定义函数与业务逻辑深度集成的函数型 Agent。读完本文你将掌握 Agent 的核心组成、CodeAgent/Tool的关键用法并能通过配套 Notebook 完成从简单 RAG 到完整研究助手的分级实战练习。Agents 模块概览Agent 的三大核心能力在 Agents 模块首页 中AI Agent 被定义为能够理解用户请求、将其拆解为步骤并执行动作以完成任务的自主系统。它把语言模型与工具、外部函数结合起来与环境交互而smolagents正是这门课程用来构建此类 Agent 的轻量级框架。构建一个有效的 Agent 需要理解三个关键组件检索能力Retrieval让 Agent 能够从多种来源访问和利用相关信息函数调用Function Calling让 Agent 能够在环境中采取具体行动领域知识与工具Domain-Specific Knowledge and Tooling为 Agent 装备执行代码操作等专业任务的能力。这三者分别对应本模块的三个子主题检索型 Agent、代码型 Agent 与自定义函数 Agent。此外模块还附带一份分级练习 Notebook帮助你从基础到复杂逐步上手。环境准备与练习入口安装与认证Notebook 的安装步骤见 agents.ipynb非常轻量核心依赖只有一个smolagents包运行在 Google Colab 等环境时可同时安装transformers、datasets、trl、huggingface_hub等常用依赖!pip install smolagents # Install the requirements in Google Colab # !pip install transformers datasets trl huggingface_hub # Authenticate to Hugging Face from huggingface_hub import login login()代码中的HfApiModel()默认调用 Hugging Face 上的推理 API因此首次使用前需要先完成登录认证调用login()并填入 access token。Notebook 练习结构配套练习 agents.ipynb 采用三档难度递进的设计练习主题目标 Exercise 1基础代码 Agent用DuckDuckGoSearchTool回答编程问题 Exercise 2自定义函数 Agent用tool装饰器实现计算器工具 Exercise 3高级检索 Agent结合 Web 搜索与记忆维护多轮对话上下文下文将依次讲解支撑这些练习的三大技术主题。检索型 Agent构建 Agentic RAG 系统传统 RAG 的局限与 Agentic RAG 的优势retrieval_agents.md 开篇点明了 Agentic RAG检索增强生成与传统 RAG 的本质区别传统 RAG 只是用 LLM 基于检索到的信息回答查询而 Agentic RAG 允许系统智能地控制自身的检索与回答过程。传统 RAG 的关键局限在于只执行单次检索仅依赖用户查询与文档之间的直接语义相似度容易遗漏相关信息。Agentic RAG 通过让 Agent 自主拟定搜索查询、批判性评估结果、按需执行多次检索来解决上述问题。第一步用 DuckDuckGo 构建最简检索 Agent最简单的检索型 Agent 只需三步初始化搜索工具、初始化模型、组合成 Agentfrom smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel # Initialize the search tool search_tool DuckDuckGoSearchTool() # Initialize the model model HfApiModel() agent CodeAgent( model model, tools[search_tool] ) # Example usage response agent.run( What are the latest developments in fusion energy? ) print(response)该 Agent 的执行链路是分析查询确定需要哪些信息搜索用 DuckDuckGo 检索相关内容综合把检索结果整合为连贯回答记忆将交互存入记忆供后续引用。第二步自定义知识库工具向量检索对于领域特定应用往往需要把 Web 搜索与自己的知识库结合起来。此时可以继承smolagents的Tool基类编写自定义工具。课程示例用BM25Retriever对 transformers 文档做语义检索from smolagents import Tool class RetrieverTool(Tool): name retriever description Uses semantic search to retrieve the parts of transformers documentation that could be most relevant to answer your query. inputs { query: { type: string, description: The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question., } } output_type string def __init__(self, docs, **kwargs): super().__init__(**kwargs) self.retriever BM25Retriever.from_documents( docs, k10 ) def forward(self, query: str) - str: assert isinstance(query, str), Your search query must be a string docs self.retriever.invoke( query, ) return \nRetrieved documents:\n .join( [ f\n\n Document {str(i)} \n doc.page_content for i, doc in enumerate(docs) ] ) retriever_tool RetrieverTool(docs_processed)自定义Tool的关键点在于name与description是 Agent 选择工具的依据description应写清适用场景与查询写作建议示例中甚至建议用肯定句而非疑问句inputs声明参数的 JSON Schema类型 描述供模型理解参数语义forward是实际执行逻辑返回的字符串会作为工具输出注入模型上下文。把这个工具加入 Agent 后检索型 Agent 可以先在文档中查找相关信息 → 必要时回退到 Web 搜索 → 综合两个来源的信息 → 通过记忆维护对话上下文。第三步构建知识库数据处理流水线RetrieverTool的输入docs_processed来自一条标准的文档处理流水线加载数据集 → 过滤源 → 构造Document→ 按块切分。示例以m-ric/huggingface_doc数据集中的 transformers 文档为原料import datasets from langchain.docstore.document import Document from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.retrievers import BM25Retriever knowledge_base datasets.load_dataset(m-ric/huggingface_doc, splittrain) knowledge_base knowledge_base.filter(lambda row: row[source].startswith(huggingface/transformers)) source_docs [ Document(page_contentdoc[text], metadata{source: doc[source].split(/)[1]}) for doc in knowledge_base ] text_splitter RecursiveCharacterTextSplitter( chunk_size500, chunk_overlap50, add_start_indexTrue, strip_whitespaceTrue, separators[\n\n, \n, ., , ], ) docs_processed text_splitter.split_documents(source_docs)其中RecursiveCharacterTextSplitter的chunk_size500、chunk_overlap50、按[\n\n, \n, ., , ]的优先级递归切分是为了在保持语义完整性的同时让每个块足够小提升 BM25 检索命中质量。增强检索策略不止于一次搜索Agentic RAG 的价值在于 Agent 可以主动采用更复杂的检索策略查询改写Query Reformulation不用原始用户查询而是构造更贴合目标文档的优化搜索词多步检索Multi-Step Retrieval执行多次搜索用初次结果指导后续查询来源整合Source Integration综合 Web 搜索与本地文档等多个来源的信息结果校验Result Validation在回答前分析检索内容的相关性与准确性。要做出有效的 Agentic RAG 系统还需重点考虑根据查询类型与上下文在可用工具间做选择、用记忆系统维护对话历史并避免重复检索、设计主检索失败时的回退策略以及加入校验步骤保证信息准确。该模块的后续衔接见 代码型 Agent。代码型 Agent面向软件开发的自主系统为什么需要代码 Agentcode_agents.md 指出代码型 Agent 是专门处理编码任务的自主系统覆盖分析、生成、重构与测试等环节。它利用编程语言、构建系统与版本控制方面的领域知识来增强软件开发工作流。其价值在于通过自动化重复性任务加速开发、生成样板代码、执行系统性重构、借助静态分析发现潜在问题——这些能力的基础是把检索能力访问外部文档与仓库和函数调用创建文件、运行测试等具体动作结合起来。代码 Agent 的构成代码 Agent 建立在针对代码理解做过微调的语言模型之上再叠加 linter、formatter、编译器之类的开发工具与真实环境交互通过检索技术访问文档与代码历史以维持上下文感知、对齐组织模式与规范通过动作导向的函数执行提交更改、发起 merge request 等具体任务。最小示例带 Web 搜索的代码 Agent与前面检索型 Agent 一脉相承最简单的代码 Agent 同样可以挂上 DuckDuckGo 搜索工具from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel agent CodeAgent(tools[DuckDuckGoSearchTool()], modelHfApiModel()) agent.run(How many seconds would it take for a leopard at full speed to run through Pont des Arts?)CodeAgent的名字揭示了它的工作机制它会编写并执行 Python 代码片段来完成推理与调用工具而不只是逐个调用工具。用 tool 装饰器定义自定义函数第二个示例展示了用tool装饰器把一个普通函数升级为 Agent 工具并用来查询两地之间的行程时间from smolagents import CodeAgent, HfApiModel, tool tool def get_travel_duration(start_location: str, destination_location: str, departure_time: Optional[int] None) - str: Gets the travel time in car between two places. Args: start_location: the place from which you start your ride destination_location: the place of arrival departure_time: the departure time, provide only a datetime.datetime if you want to specify this import googlemaps # All imports are placed within the function, to allow for sharing to Hub. import os gmaps googlemaps.Client(os.getenv(GMAPS_API_KEY)) if departure_time is None: from datetime import datetime departure_time datetime(2025, 1, 6, 11, 0) directions_result gmaps.directions( start_location, destination_location, modetransit, departure_timedeparture_time ) return directions_result[0][legs][0][duration][text] agent CodeAgent(tools[get_travel_duration], modelHfApiModel(), additional_authorized_imports[datetime]) agent.run(Can you give me a nice one-day trip around Paris with a few locations and the times? Could be in the city or outside, but should fit in one day. Im travelling only via public transportation.)值得注意的工程细节装饰器函数内的所有import都放在函数体内部以便函数可分享到 Hub分享时外部依赖会一并打包密钥通过os.getenv(GMAPS_API_KEY)从环境变量读取CodeAgent增加了additional_authorized_imports[datetime]参数即额外授权 Agent 在生成的代码中导入datetime模块——这是smolagents沙箱化执行安全机制的一部分只有显式授权的导入才会被执行。框架特性轻量与沙箱课程对smolagents框架特性做了概述核心实现仅约 1000 行代码是名副其实的轻量级框架它专注于让 Agent 编写并执行 Python 代码片段并提供沙箱化执行以保证安全同时支持开源与专有语言模型适配多种开发环境。自定义函数 Agent与业务逻辑直接集成为什么用自定义函数 Agentcustom_functions.md 定义了自定义函数 Agent 的定位利用专门的函数调用即“工具”来执行任务的 Agent。与通用 Agent 不同它聚焦于通过直接集成应用逻辑来驱动高级工作流——例如把数据库查询、系统命令或任意自定义工具封装成独立函数供 Agent 调用。它的三大优势是模块化与可扩展把单个 Agent 拆成一组代表离散能力的独立函数架构更易扩展细粒度控制开发者通过指定哪些函数可用、接受哪些参数来精确控制 Agent 行为可靠性提升每个函数配清晰的 schema 与校验减少错误和意外行为。基本工作流四步法识别函数Identify Functions确定哪些任务可以转化为自定义函数如文件 I/O、数据库查询、流式数据处理定义接口Define the Interface用函数签名或 schema 精确描述每个函数的输入、输出与预期行为在 Agent 与环境之间建立强契约注册到 AgentRegister with the Agent把描述每个函数接口的元数据传给语言模型或 Agent 框架让 Agent“学会”可用的函数调用并校验Invoke and ValidateAgent 选定函数后用给定参数执行校验结果有效后回传给 Agent 作为上下文驱动后续决策。示例数据库搜索函数课程给出的简化伪代码演示了这一流程以agent.register_function风格呈现# Define a custom function with clear input/output types def search_database(query: str) - list: Search the database for articles matching the query. Args: query (str): The query search string Returns: list: List of matching article results try: results database.search(query) return results except DatabaseError as e: logging.error(fDatabase search failed: {e}) return [] # Register the function with the agent agent.register_function( namesearch_database, functionsearch_database, descriptionSearches database for articles matching a query ) # Example usage def process_search(): query Find recent articles on AI results agent.invoke(search_database, query) if results: agent.process_results(results) else: logging.info(No results found for query)这段示例体现了函数接口设计的要点用类型注解声明输入输出、用 docstring 描述行为、对失败路径做显式处理捕获DatabaseError并返回空列表而非抛异常。注意真实smolagents项目中的写法通常是上面检索模块演示的Tool子类或tool装饰器本示例是用于说明流程的伪代码风格。综合练习从简单 RAG 到完整研究助手agents.ipynb 把上述三大主题串成一份可运行的练习 Exercise 1 —— 基础代码 Agent用CodeAgent(tools[DuckDuckGoSearchTool()], modelHfApiModel())回答 Python 概念问题并挑战它处理基础语法、语言特性、代码示例三类问题。 Exercise 2 —— 自定义函数 Agent用tool装饰器实现一个calculate工具支持sum/average/multiply/min/max并让 Agent 回答“10、15、20、25、30 的平均值”这类问题from smolagents import CodeAgent, tool from typing import Union tool def calculate(operation: str, numbers: object) - float: Performs basic mathematical operations on a list of numbers. Args: operation: One of sum, average, multiply, min, max numbers: List of numbers to operate on Returns: float: Result of the operation if operation sum: return sum(numbers) elif operation average: return sum(numbers) / len(numbers) elif operation multiply: result 1 for n in numbers: result * n return result elif operation min: return min(numbers) elif operation max: return max(numbers) else: raise ValueError(fUnknown operation: {operation}) # Create agent with custom tool math_agent CodeAgent(tools[calculate], modelHfApiModel()) # Test the agent response math_agent.run(What is the average of 10, 15, 20, 25, and 30?) print(response)进阶挑战为计算器增加更多运算新建自定义工具如字符串处理、日期计算在同一个 Agent 里组合多个工具。 Exercise 3 —— 高级检索 Agent把 Web 搜索与记忆结合构建多轮对话中保持上下文的研究 Agent其 TODO 骨架要求你自行补全research_agent CodeAgent(...)并用一组连续问题测试上下文保持能力。进阶挑战包括测试跨主题上下文保持、实现自定义知识库工具参照 retrieval_agents.md 的RetrieverTool示例、构建“代码理解 研究能力”的混合 Agent。小结Agents 模块围绕“语言模型 工具 外部函数”这一核心范式给出了三条清晰的技术路径检索型 Agent 通过 Agentic RAG 实现自主、多步的信息检索代码型 Agent 以CodeAgent编写并沙箱执行 Python 片段配合tool装饰器与additional_authorized_imports机制实现安全可控的工具调用自定义函数 Agent 则强调接口契约、注册流程与校验逻辑让 Agent 可靠地接入业务系统。你可以从模块首页 v1/8_agents/README.md 开始依次阅读 检索型 Agent、代码型 Agent、自定义函数 Agent最后用 agents.ipynb 完成从 到 的分级实战即可完整掌握 smolagents 构建生产级 Agent 的核心能力。赞分享教程人工智能大模型NLP微调【免费下载链接】smol-courseA course on aligning smol models.项目地址https://gitcode.com/gh_mirrors/smo/smol-course点击查看免费下载相关推荐HarmonyOS 设备用 microG 补齐 Google 服务权限、定位与排障全流程HarmonyOS 设备用 microG 补齐 Google 服务权限、定位与排障全流程 microG Services Core 是 Google PlayAPI网关认证鉴权移动开发Smol Course 自定义领域评估指南用 LightEval 构建专属评估管线Smol Course 自定义领域评估指南用 LightEval 构建专属评估管线 本篇指南基于 Smol Course 第 4 模块评估中的 custo教程人工智能大模型NLP微调smol-course 自定义领域评估实战基于 LightEval 构建任务、指标与数据集评估管线smol course 自定义领域评估实战基于 LightEval 构建任务、指标与数据集评估管线 本指南聚焦 smol course 第 4 单元的核心主题教程人工智能大模型NLP微调上一篇拯救老Mac用OpenCore Legacy Patcher让2008-2017年设备重获新生下一篇searx Docker 部署实战指南镜像运行、配置注入与自建镜像创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
📝

华诺云谱内容团队

资深建站顾问 · 行业研究员

10年+企业数字化服务经验,专注智能建站、SEO优化与品牌营销,持续输出建站技巧、行业洞察与营销干货,已帮助5000+企业实现数字化增长。

你可能需要的服务

订阅华诺云谱资讯周报

每周一封,精选建站技巧、SEO与营销干货,直达邮箱。已有 8,000+ 企业主订阅,助你少走弯路。

↑