From 85c9ebf7514f00ff9e9b8e0f2aeb9e3b53974b93 Mon Sep 17 00:00:00 2001 From: ShawnSiao Date: Sun, 13 Apr 2025 22:04:57 +0800 Subject: [PATCH 1/4] add unit3 of zh-CN --- units/zh-CN/unit3/README.md | 0 units/zh-CN/unit3/agentic-rag/agent.mdx | 508 ++++++++++++++++++ units/zh-CN/unit3/agentic-rag/agentic-rag.mdx | 27 + units/zh-CN/unit3/agentic-rag/conclusion.mdx | 20 + .../zh-CN/unit3/agentic-rag/introduction.mdx | 40 ++ units/zh-CN/unit3/agentic-rag/invitees.mdx | 453 ++++++++++++++++ units/zh-CN/unit3/agentic-rag/tools.mdx | 434 +++++++++++++++ 7 files changed, 1482 insertions(+) create mode 100644 units/zh-CN/unit3/README.md create mode 100644 units/zh-CN/unit3/agentic-rag/agent.mdx create mode 100644 units/zh-CN/unit3/agentic-rag/agentic-rag.mdx create mode 100644 units/zh-CN/unit3/agentic-rag/conclusion.mdx create mode 100644 units/zh-CN/unit3/agentic-rag/introduction.mdx create mode 100644 units/zh-CN/unit3/agentic-rag/invitees.mdx create mode 100644 units/zh-CN/unit3/agentic-rag/tools.mdx diff --git a/units/zh-CN/unit3/README.md b/units/zh-CN/unit3/README.md new file mode 100644 index 00000000..e69de29b diff --git a/units/zh-CN/unit3/agentic-rag/agent.mdx b/units/zh-CN/unit3/agentic-rag/agent.mdx new file mode 100644 index 00000000..96d3e76e --- /dev/null +++ b/units/zh-CN/unit3/agentic-rag/agent.mdx @@ -0,0 +1,508 @@ +# 创建你的 Gala 智能体 + +现在我们已经为 Alfred 构建了所有必要组件,是时候将它们整合成一个完整的智能体来协助举办我们的奢华盛会了。 + +在本节中,我们将把宾客信息检索、网络搜索、天气信息和 Hub 统计工具整合成一个强大的智能体。 + +## 组装 Alfred:完整智能体 + +我们不需要重新实现之前章节创建的所有工具,只需从保存的tools.py和retriever.py模块中导入它们即可。 + + +如果你尚未实现这些工具,请返回工具检索器章节进行实现,并将它们添加到`tools.py`和`retriever.py`文件中。 + + +让我们从之前章节导入必要的库和工具: + + + + +```python +# 导入必要的库 +import random +from smolagents import CodeAgent, HfApiModel + +# 从自定义模块导入工具 +from tools import DuckDuckGoSearchTool, WeatherInfoTool, HubStatsTool +from retriever import load_guest_dataset +``` + +现在让我们将所有工具组合成一个智能体: + +```python +# 初始化 Hugging Face 模型 +model = HfApiModel() + +# 初始化网络搜索工具 +search_tool = DuckDuckGoSearchTool() + +# 初始化天气工具 +weather_info_tool = WeatherInfoTool() + +# 初始化 Hub 统计工具 +hub_stats_tool = HubStatsTool() + +# 加载宾客数据集并初始化宾客信息工具 +guest_info_tool = load_guest_dataset() + +# 创建包含所有工具的 Alfred +alfred = CodeAgent( + tools=[guest_info_tool, weather_info_tool, hub_stats_tool, search_tool], + model=model, + add_base_tools=True, # 添加额外的基础工具 + planning_interval=3 # 每 3 步启用规划 +) +``` + + + + +```python +# 导入必要库 +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +from tools import search_tool, weather_info_tool, hub_stats_tool +from retriever import guest_info_tool +``` + +Now, let's combine all these tools into a single agent: + +```python +# 初始化 Hugging Face 模型 +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") + +# 创建包含所有工具的 Alfred +alfred = AgentWorkflow.from_tools_or_functions( + [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool], + llm=llm, +) +``` + + + + +```python +from typing import TypedDict, Annotated +from langgraph.graph.message import add_messages +from langchain_core.messages import AnyMessage, HumanMessage, AIMessage +from langgraph.prebuilt import ToolNode +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import tools_condition +from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace + +from tools import DuckDuckGoSearchRun, weather_info_tool, hub_stats_tool +from retriever import guest_info_tool +``` + +现在将所有工具整合到单一智能体: + +```python +# 初始化网络搜索工具 +search_tool = DuckDuckGoSearchRun() + +# 生成包含工具的聊天接口 +llm = HuggingFaceEndpoint( + repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", + huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, +) + +chat = ChatHuggingFace(llm=llm, verbose=True) +tools = [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool] +chat_with_tools = chat.bind_tools(tools) + +# 生成 AgentState 和 Agent 图 +class AgentState(TypedDict): + messages: Annotated[list[AnyMessage], add_messages] + +def assistant(state: AgentState): + return { + "messages": [chat_with_tools.invoke(state["messages"])], + } + +## 构建流程图 +builder = StateGraph(AgentState) + +# 定义节点:执行具体工作 +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# 定义边:控制流程走向 +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # 如果最新消息需要工具调用,则路由到 tools 节点 + # 否则直接响应 + tools_condition, +) +builder.add_edge("tools", "assistant") +alfred = builder.compile() +``` + + + +您的智能体现已准备就绪! + +## 使用 Alfred:端到端示例 + +现在 Alfred 已配备所有必要工具,让我们看看他如何协助处理晚会中的各种任务。 + +### 示例 1:查找嘉宾信息 + +展示 Alfred 如何协助获取嘉宾信息: + + + + +```python +query = "Tell me about 'Lady Ada Lovelace'" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +根据检索到的信息,Ada Lovelace 女士是位备受尊敬的数学家兼好友。她因在数学和计算领域的开创性工作而闻名,常因其在 Charles Babbage 分析机方面的工作被誉为第一位计算机程序员。她的电子邮箱是 ada.lovelace@example.com。 +``` + + + + +```python +query = "Tell me about Lady Ada Lovelace. What's her background?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response.response.blocks[0].text) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Ada Lovelace 女士是英国数学家和作家,以她在 Charles Babbage 分析机方面的工作闻名。她是第一个认识到该机器具有纯计算之外应用潜力的人。 +``` + + + + +```python +response = alfred.invoke({"messages": "Tell me about 'Lady Ada Lovelace'"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Ada Lovelace,全名 Augusta Ada King,洛夫莱斯伯爵夫人,是英国数学家和作家。出生于 1815 年 12 月 10 日,逝世于 1852 年 11 月 27 日,她因在 Charles Babbage 提出的机械通用计算机分析机方面的工作而闻名。Ada Lovelace 被誉为第一位计算机程序员,因为她于 1843 年为分析机创建了程序。她认识到该机器的用途不仅限于计算,这种远见在当时极为罕见。她对计算机科学领域的贡献为未来发展奠定了基础。每年十月设立的 Ada Lovelace 日正是为了纪念她在科技领域的开创性工作,激励女性在 STEM 领域的发展。 +``` + + + + + +### 示例 2:烟花天气核查 + +展示 Alfred 如何协助天气查询: + + + + +```python +query = "What's the weather like in Paris tonight? Will it be suitable for our fireworks display?" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出(存在随机性差异): +``` +🎩 Alfred's Response: +已为您查询巴黎天气。当前天气晴朗,气温 25°C。这样的条件非常适合今晚的烟花表演。晴朗的夜空将为壮观表演提供绝佳能见度,舒适的温度也能确保宾客们愉快享受户外活动。 +``` + + + + +```python +query = "What's the weather like in Paris tonight? Will it be suitable for our fireworks display?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +巴黎今夜有雨,气温 15°C。考虑到降雨情况,可能不适宜进行烟花表演。 +``` + + + + +```python +response = alfred.invoke({"messages": "What's the weather like in Paris tonight? Will it be suitable for our fireworks display?"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +预期输出: + +``` +🎩 Alfred's Response: +巴黎今夜有雨且气温 15°C,可能不适宜您的烟花表演计划。 +``` + + + +### 示例 3:给 AI 研究者留下深刻印象 + +展示 Alfred 如何协助与 AI 研究者互动: + + + + +```python +query = "One of our guests is from Qwen. What can you tell me about their most popular model?" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Qwen 最受欢迎的模型是 Qwen/Qwen2.5-VL-7B-Instruct,下载量达 3,313,345 次。 +``` + + + +```python +query = "One of our guests is from Google. What can you tell me about their most popular model?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Hugging Face Hub 上 Google 最受欢迎的模型是 google/electra-base-discriminator,下载量达 28,546,752 次。 +``` + + + + +```python +response = alfred.invoke({"messages": "One of our guests is from Qwen. What can you tell me about their most popular model?"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Qwen 下载量最高的模型是 Qwen/Qwen2.5-VL-7B-Instruct,下载量达 3,313,345 次。 +``` + + + +### 示例 4:组合多工具应用 + +展示 Alfred 如何协助准备与 Nikola Tesla 博士的对话: + + + + + +```python +query = "I need to speak with Dr. Nikola Tesla about recent advancements in wireless energy. Can you help me prepare for this conversation?" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +我已收集信息帮助您准备与 Nikola Tesla 博士的对话。 + +嘉宾信息: +姓名:Dr. Nikola Tesla +关系:大学时期的老友 +描述:他是您大学时期的老友,最近刚获得新型无线能量传输系统的专利,非常乐意与您讨论。请记住他对鸽子情有独钟,这可能是很好的闲聊话题。 +邮箱:nikola.tesla@gmail.com + +无线能源最新进展: +根据网络搜索,以下是无线能量传输领域的最新发展: +1. 研究人员在使用聚焦电磁波进行远距离无线输电方面取得进展 +2. 多家公司正在开发用于消费电子的谐振感应耦合技术 +3. 无物理连接的电动汽车充电新应用 + +对话切入点: +1. "我很想听听您关于无线能量传输新专利的情况,与大学时期的原始概念相比有何改进?" +2. "您是否关注近期消费电子谐振感应耦合技术的发展?对他们的方法有何看法?" +3. "您的鸽子最近好吗?我记得您对它们特别着迷" + +这些内容将为您与 Tesla 博士的对话提供充足话题,同时展现您对他兴趣领域和专业发展的了解。 +``` + + + + +```python +query = "I need to speak with Dr. Nikola Tesla about recent advancements in wireless energy. Can you help me prepare for this conversation?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +以下是您与 Nikola Tesla 博士讨论无线能源时可能有用的最新进展: + +1. **无线电力传输的进展与挑战**:本文讨论无线电力传输(WPT)从传统有线方式到现代应用(包括太空太阳能电站)的演变,重点介绍微波技术的初期应用及当前电子设备兴起带来的需求。 + +2. **面向体表电子设备的无线能量传输技术新进展**:探索无线能量传输(WET)作为无电池/导线供电方案的潜力,讨论其优势及潜在应用场景。 + +3. **无线电力传输与能量收集:现状与未来趋势**:概述无线供能方法的最新进展,包括能量收集和无线输电技术,展示多个前景应用并探讨领域未来趋势。 + +4. **无线电力传输:应用、挑战与障碍** +``` + + + + +```python +response = alfred.invoke({"messages":"I need to speak with 'Dr. Nikola Tesla' about recent advancements in wireless energy. Can you help me prepare for this conversation?"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +预期输出: + +``` +根据提供的信息,以下是准备与 'Dr. Nikola Tesla' 讨论无线能源最新进展的关键要点: +1. **无线电力传输 (WPT)**:探讨如何通过消除线缆需求并利用感应和谐振耦合机制革新能量传输 +2. **无线充电进展**:强调效率提升、更快充电速度及 Qi/Qi2 认证解决方案的兴起 +3. **5G-Advanced 创新与 NearLink 协议**:作为提升无线网络速度、安全性和效率的技术,可支持先进无线能源应用 +4. **边缘 AI/ML**:讨论人工智能如何依赖无线网络实现边缘智能化,提升智能家居自动化水平 +5. **Matter 标准与安全增强**:作为推动 IoT 设备连接效率和安全性提升的关键创新 +6. **无线充电技术突破**:包括仁川国立大学等机构的最新研究成果 +``` + + + +## 高级功能:对话记忆 + +为了让 Alfred 在晚会中更智能,我们可以启用对话记忆功能使其记住先前交流: + + + + +```python +# 创建带记忆的 Alfred +alfred_with_memory = CodeAgent( + tools=[guest_info_tool, weather_info_tool, hub_stats_tool, search_tool], + model=model, + add_base_tools=True, + planning_interval=3 +) + +# 首次交互 +response1 = alfred_with_memory.run("Tell me about Lady Ada Lovelace.") +print("🎩 Alfred's First Response:") +print(response1) + +# 二次交互(引用首次内容) +response2 = alfred_with_memory.run("What projects is she currently working on?", reset=False) +print("🎩 Alfred's Second Response:") +print(response2) +``` + + + + +```python +from llama_index.core.workflow import Context + +alfred = AgentWorkflow.from_tools_or_functions( + [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool], + llm=llm +) + +# 记忆状态 +ctx = Context(alfred) + +# 首次交互 +response1 = await alfred.run("Tell me about Lady Ada Lovelace.", ctx=ctx) +print("🎩 Alfred's First Response:") +print(response1) + +# 二次交互(引用首次内容) +response2 = await alfred.run("What projects is she currently working on?", ctx=ctx) +print("🎩 Alfred's Second Response:") +print(response2) +``` + + + + +```python +# 首次交互 +response = alfred.invoke({"messages": [HumanMessage(content="Tell me about 'Lady Ada Lovelace'. What's her background and how is she related to me?")]}) + + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +print() + +# 二次交互(引用首次内容) +response = alfred.invoke({"messages": response["messages"] + [HumanMessage(content="What projects is she currently working on?")]}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + + + + +注意到这三种智能体框架都没有直接集成记忆模块,这种设计有何特殊考量?🧐 +* smolagents:记忆在不同执行周期中不保留,需通过 reset=False 显式声明 +* LlamaIndex: 需显式添加 context 对象进行运行周期内的记忆管理 +* LangGraph: 提供检索历史消息选项或专用 [MemorySaver](https://langchain-ai.github.io/langgraph/tutorials/introduction/#part-3-adding-memory-to-the-chatbot) 组件 + +## 结语 + +恭喜!您已成功构建 Alfred——配备多种工具的智能体助手,可协助举办本世纪最盛大的晚会。Alfred 现在能够: + +1. 检索嘉宾详细信息 +2. 核查天气条件规划户外活动 +3. 提供顶尖 AI 开发者及其模型洞察 +4. 网络搜索最新资讯 +5. 通过记忆维持对话上下文 + +凭借这些能力,Alfred 已准备就绪,确保您的晚会取得圆满成功,通过个性化服务和实时信息给宾客留下深刻印象。 diff --git a/units/zh-CN/unit3/agentic-rag/agentic-rag.mdx b/units/zh-CN/unit3/agentic-rag/agentic-rag.mdx new file mode 100644 index 00000000..a23394fa --- /dev/null +++ b/units/zh-CN/unit3/agentic-rag/agentic-rag.mdx @@ -0,0 +1,27 @@ +# 智能体增强检索生成(Agentic RAG) + +在本单元中,我们将探讨如何利用智能体增强检索生成(Agentic RAG)帮助 Alfred 筹备精彩的晚会。 + +提示:我们已在先前单元讨论过检索增强生成(RAG)和智能体增强 RAG,如果您已熟悉这些概念可跳过本节。 + +大语言模型(LLMs)通过海量数据训练获得通用知识。 +但其世界知识模型可能包含过时或不相关信息。 +**RAG 通过从您的数据中检索相关信息并传递给大语言模型,有效解决了这个问题。** + +![RAG 示意图](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) + +思考 Alfred 的工作流程: + +1. 我们要求 Alfred 协助策划晚会 +2. Alfred 需要获取最新新闻和天气信息 +3. Alfred 需要整理和检索宾客信息 + +正如 Alfred 需要搜索家庭信息才能提供有效帮助,任何智能体都需要理解和检索相关数据的能力。 +**智能体增强 RAG 是帮助智能体解答数据问题的强大工具**,我们可以为 Alfred 提供多种工具来辅助问题解答。 +与传统文档自动问答不同,Alfred 可以自主决定使用任何工具或流程来回答问题。 + +![智能体增强 RAG 架构](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agentic-rag.png) + +现在让我们开始**构建智能体增强 RAG 工作流**! + +首先创建用于检索最新受邀者详情的 RAG 工具,接着开发网络搜索、天气更新和 Hugging Face Hub 模型下载统计等工具,最终整合所有组件实现我们的智能体增强 RAG 智能体! \ No newline at end of file diff --git a/units/zh-CN/unit3/agentic-rag/conclusion.mdx b/units/zh-CN/unit3/agentic-rag/conclusion.mdx new file mode 100644 index 00000000..c8f5b434 --- /dev/null +++ b/units/zh-CN/unit3/agentic-rag/conclusion.mdx @@ -0,0 +1,20 @@ +# 总结 + +在本单元中,我们学习了如何创建智能体增强的检索生成(RAG)系统,帮助我们友好的智能体 Alfred 筹备并管理一场盛大的晚会。 + +RAG 与智能体能力的结合展示了当 AI 助手具备以下能力时的强大潜力: +- 访问结构化知识(宾客信息) +- 获取实时信息(网络搜索) +- 领域专用工具(天气信息、Hub 统计) +- 历史交互记忆 + +凭借这些能力,Alfred 现已具备完美主持者的素质,能够回答宾客问题、提供最新信息、确保晚会顺利进行——甚至能精准控制烟花表演的时机! + + +完成智能体构建后,您可以进一步探索: + +- 为特定用例创建定制化工具 +- 使用嵌入技术实现更复杂的 RAG 系统 +- 构建可协作的多智能体系统 +- 将智能体部署为可交互的服务 + diff --git a/units/zh-CN/unit3/agentic-rag/introduction.mdx b/units/zh-CN/unit3/agentic-rag/introduction.mdx new file mode 100644 index 00000000..d0471b08 --- /dev/null +++ b/units/zh-CN/unit3/agentic-rag/introduction.mdx @@ -0,0 +1,40 @@ +# 代理增强检索生成(Agentic RAG)用例介绍 + +![代理增强 RAG 横幅图](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit3/agentic-rag/thumbnail.jpg) + +在本单元中,我们将通过代理增强检索生成(Agentic RAG)技术,帮助负责主持晚会的友好智能体 Alfred 创建用于解答宾客问题的工具。 + + +这是代理增强 RAG 的「真实世界」应用案例,您可直接应用于个人项目或工作场景。若想获得更多实践收获,何不尝试将其应用于您的实际场景并在 Discord 社区分享? + + +您可以选择课程中讨论的任何框架来实现本用例。我们已在独立标签页中为每个框架提供代码示例。 + +## 值得铭记的盛会 + +现在让我们进入实战环节,为这场盛会搭建舞台! + +**您决定举办本世纪最奢华、最盛大的派对**——这意味着将包含:豪华宴席、魅惑舞者、知名 DJ、精致饮品、震撼烟花表演等极致元素。 + +您的好邻居智能体 Alfred 正着手统筹派对的各项需求,**Alfred 将全权管理所有事务**。为此,他需要掌握包括菜单、宾客名单、日程安排、天气预报等在内的完整派对信息! + +除此之外,他还需确保派对圆满成功,因此**必须具备在派对期间实时解答各类问题的能力**,同时处理可能出现的突发状况。 + +Alfred 无法孤军奋战,我们需要确保他能够获取所需的所有信息和工具。 + +首先,让我们为晚会制定核心需求清单。 + +## 晚会核心需求 + +在**文艺复兴时期**,真正受过良好教育的人需具备三大核心素养: +需精通**体育、文化与科学知识**。因此,我们必须通过知识储备给宾客留下深刻印象,呈现真正难忘的盛会。 +但为避免冲突,**政治与宗教等敏感话题应在晚会中回避**,确保派对氛围轻松愉快,不涉及信仰与理念分歧。 + +根据礼仪规范,**优秀的主办方应充分了解宾客背景**,包括其兴趣爱好与事业成就。同时应善于通过宾客间的故事分享促进交流。 + +最后,我们还需掌握**基础天气知识**,以便实时获取更新信息,精准把握烟花表演时机,为晚会画上完美句号!🎆 + +由此可见,Alfred 需要大量信息支持才能办好晚会。 +幸运的是,我们可以通过**检索增强生成(RAG)训练**为 Alfred 做好准备! + +现在让我们开始创建 Alfred 主持晚会所需的工具集! \ No newline at end of file diff --git a/units/zh-CN/unit3/agentic-rag/invitees.mdx b/units/zh-CN/unit3/agentic-rag/invitees.mdx new file mode 100644 index 00000000..41194f2f --- /dev/null +++ b/units/zh-CN/unit3/agentic-rag/invitees.mdx @@ -0,0 +1,453 @@ +# 创建宾客信息检索生成(RAG)工具 + +您信赖的智能体 Alfred 正在筹备本世纪最盛大的晚会。为确保活动顺利进行,Alfred 需要快速获取最新宾客信息。让我们通过定制化的检索增强生成(RAG)工具(基于专属数据集)为 Alfred 赋能。 + +## 为何选择 RAG 技术? + +试想 Alfred 在宾客间穿梭时需即时调取详细信息,传统大语言模型(LLM)可能面临以下挑战: +1. 宾客名单属于特定活动数据,不在模型训练范围内 +2. 宾客信息可能频繁变更或更新 +3. 需精确检索电子邮件地址等细节信息 + +这正是检索增强生成(RAG)技术的优势所在!通过结合检索系统与 LLM,Alfred 可按需获取准确、实时的宾客信息。 + + +您可以选择课程涵盖的任何框架实现本用例,请通过代码标签页选择偏好方案。 + + +## 应用搭建 + +我们将以 Hugging Face Space 为开发环境,采用结构化 Python 项目构建智能体。这种架构通过功能模块化实现代码整洁,更贴近实际部署场景。 + +### 项目结构 +- **`tools.py`** – 为智能体提供辅助工具 +- **`retriever.py`** – 实现支持知识访问的检索功能 +- **`app.py`** – 整合所有组件形成完整功能智能体(将在本单元最后完成) + +实操参考:[Hugging Face Space 示例](https://huggingface.co/spaces/agents-course/Unit_3_Agentic_RAG),该空间已部署本单元开发的智能体增强 RAG 系统,欢迎克隆体验! + +可直接测试下方智能体: + + +## 数据集概览 + +数据集 [`agents-course/unit3-invitees`](https://huggingface.co/datasets/agents-course/unit3-invitees/) 包含以下字段: +- **Name**: 宾客全名 +- **Relation**: 与主办方关系 +- **Description**: 简要传记或趣闻 +- **Email Address**: 邀请函发送及跟进联系方式 + +数据集预览: + + + +实际场景可扩展数据集字段,包含饮食偏好、礼品兴趣、禁忌话题等对主持人有用的详细信息。 + + +## 构建宾客信息工具 + +我们将创建 Alfred 在晚会期间快速检索宾客信息的定制工具,分三步实现: +1. 加载并预处理数据集 +2. 创建检索工具 +3. 工具与 Alfred 集成 + +### 步骤一:加载并预处理数据集 + +首先将原始宾客数据转换为适合检索的格式: + + + + +```python +import datasets +from langchain.docstore.document import Document + +# 加载数据集 +guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") + +# 转换为 Document 对象 +docs = [ + Document( + page_content="\n".join([ + f"Name: {guest['name']}", + f"Relation: {guest['relation']}", + f"Description: {guest['description']}", + f"Email: {guest['email']}" + ]), + metadata={"name": guest["name"]} + ) + for guest in guest_dataset +] + +``` + + + + +我们将使用 Hugging Face `datasets` 库来加载数据集并将其转换为来自 `llama_index.core.schema` 模块的 `Document` 对象列表。 + +```python +import datasets +from llama_index.core.schema import Document + +# 加载数据集 +guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") + +# 转换为 Document 对象 +docs = [ + Document( + text="\n".join([ + f"Name: {guest_dataset['name'][i]}", + f"Relation: {guest_dataset['relation'][i]}", + f"Description: {guest_dataset['description'][i]}", + f"Email: {guest_dataset['email'][i]}" + ]), + metadata={"name": guest_dataset['name'][i]} + ) + for i in range(len(guest_dataset)) +] +``` + + + + +我们将使用 Hugging Face `datasets` 库来加载数据集并将其转换为来自 `langchain.docstore.document` 模块的 `Document` 对象列表。 + +```python +import datasets +from langchain.docstore.document import Document + +# 加载数据集 +guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") + +# 转换为 Document 对象 +docs = [ + Document( + page_content="\n".join([ + f"Name: {guest['name']}", + f"Relation: {guest['relation']}", + f"Description: {guest['description']}", + f"Email: {guest['email']}" + ]), + metadata={"name": guest["name"]} + ) + for guest in guest_dataset +] +``` + + + + +在上面的代码中,我们: +- 加载数据集 +- 将每条房客记录转换为包含格式化内容的 “Document” 对象 +- 将 “Document” 对象存储在列表中 + +这意味着我们已经准备好所有数据,可以开始配置检索功能了。 + +### 步骤 2:创建检索工具 + +现在,让我们创建一个自定义工具,Alfred 可以使用它来搜索房客信息。 + + + + +我们将使用“langchain_community.retrievers”模块中的“BM25Retriever”来创建一个检索工具。 + + +BM25Retriever 是检索的一个很好的起点,但对于更高级的语义搜索,您可以考虑使用基于嵌入的检索器,例如来自 sentence-transformers 的检索器。 + + +```python +from smolagents import Tool +from langchain_community.retrievers import BM25Retriever + +class GuestInfoRetrieverTool(Tool): + name = "guest_info_retriever" + description = "Retrieves detailed information about gala guests based on their name or relation." + inputs = { + "query": { + "type": "string", + "description": "The name or relation of the guest you want information about." + } + } + output_type = "string" + + def __init__(self, docs): + self.is_initialized = False + self.retriever = BM25Retriever.from_documents(docs) + + def forward(self, query: str): + results = self.retriever.get_relevant_documents(query) + if results: + return "\n\n".join([doc.page_content for doc in results[:3]]) + else: + return "No matching guest information found." + +# 初始化工具 +guest_info_tool = GuestInfoRetrieverTool(docs) +``` + +让我们逐步了解这个工具: +- `name` 和 `description` 帮助智能体了解何时以及如何使用此工具 +- `inputs` 定义工具所需的参数(在本例中为搜索查询) +- 我们使用 `BM25Retriever`,这是一种强大的文本检索算法,不需要嵌入 +- `forward` 方法处理查询并返回最相关的客人信息 + + + + +我们将使用 `llama_index.retrievers.bm25` 模块中的 `BM25Retriever` 来创建一个检索工具。 + + +BM25Retriever 是一个很好的检索起点,但对于更高级的语义搜索,您可以考虑使用基于嵌入的检索器,例如 sentence-transformers 中的检索器。 + + +```python +from llama_index.core.tools import FunctionTool +from llama_index.retrievers.bm25 import BM25Retriever + +bm25_retriever = BM25Retriever.from_defaults(nodes=docs) + +def get_guest_info_retriever(query: str) -> str: + """Retrieves detailed information about gala guests based on their name or relation.""" + results = bm25_retriever.retrieve(query) + if results: + return "\n\n".join([doc.text for doc in results[:3]]) + else: + return "No matching guest information found." + +# 初始化工具 +guest_info_tool = FunctionTool.from_defaults(get_guest_info_retriever) +``` + +让我们逐步了解这个工具。 +- 文档字符串帮助智能体了解何时以及如何使用此工具 +- 类型装饰器定义了工具所需的参数(在本例中为搜索查询) +- 我们使用 `BM25Retriever`,这是一种强大的文本检索算法,不需要嵌入 +- 该方法处理查询并返回最相关的客人信息 + + + + +我们将使用 `langchain_community.retrievers` 模块中的 `BM25Retriever` 来创建一个检索工具。 + + +BM25Retriever 是一个很好的检索起点,但对于更高级的语义搜索,您可以考虑使用基于嵌入的检索器,例如 sentence-transformers 中的检索器。 + + +```python +from langchain_community.retrievers import BM25Retriever +from langchain.tools import Tool + +bm25_retriever = BM25Retriever.from_documents(docs) + +def extract_text(query: str) -> str: + """Retrieves detailed information about gala guests based on their name or relation.""" + results = bm25_retriever.invoke(query) + if results: + return "\n\n".join([doc.page_content for doc in results[:3]]) + else: + return "No matching guest information found." + +guest_info_tool = Tool( + name="guest_info_retriever", + func=extract_text, + description="Retrieves detailed information about gala guests based on their name or relation." +) +``` + +让我们逐步了解这个工具。 +- `name` 和 `description` 帮助智能体了解何时以及如何使用此工具。 +- 类型装饰器定义了工具所需的参数(在本例中为搜索查询)。 +- 我们使用 `BM25Retriever`,这是一种强大的文本检索算法,无需嵌入。 +- 该方法处理查询并返回最相关的客人信息。 + + + + + +### 步骤 3:将工具与 Alfred 集成 + +最后,让我们创建智能体并为其配备自定义工具,将所有内容整合在一起: + + + + +```python +from smolagents import CodeAgent, HfApiModel + +# 初始化 Hugging Face 模型 +model = HfApiModel() + +# 使用宾客信息工具创建我们的晚会智能体 Alfred +alfred = CodeAgent(tools=[guest_info_tool], model=model) + +# Example query Alfred might receive during the gala +response = alfred.run("Tell me about our guest named 'Lady Ada Lovelace'.") + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +根据我检索到的信息,艾达·洛夫莱斯夫人是一位受人尊敬的数学家和朋友。她因其在数学和计算机领域的开创性工作而闻名,并因其在查尔斯·巴贝奇的分析机方面的贡献而被誉为第一位计算机程序员。她的电子邮件地址是 ada.lovelace@example.com。 +``` + +这最后一步具体做了什么: +- 我们使用 `HfApiModel` 类初始化 Hugging Face 模型 +- 我们将智能体 (Alfred) 创建为 `CodeAgent`,它可以执行 Python 代码来解决问题 +- 我们让 Alfred 检索一位名叫“Lady Ada Lovelace”的客人的信息 + + + + +```python +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +# 初始化 Hugging Face 模型 +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") + +# 使用宾客信息工具创建我们的晚会智能体 Alfred +alfred = AgentWorkflow.from_tools_or_functions( + [guest_info_tool], + llm=llm, +) + +# Example query Alfred might receive during the gala +response = await alfred.run("Tell me about our guest named 'Lady Ada Lovelace'.") + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Lady Ada Lovelace 是一位受人尊敬的数学家和朋友,因其在数学和计算领域的开创性工作而闻名。她因参与查尔斯·巴贝奇的分析机研究而被誉为第一位计算机程序员。她的邮箱是 ada.lovelace@example.com。 +``` + +这最后一步具体做了什么: +- 我们使用 `HuggingFaceInferenceAPI` 类初始化 Hugging Face 模型 +- 我们将智能体 (Alfred) 创建为 `AgentWorkflow`,其中包含我们刚刚创建的工具 +- 我们请求 Alfred 检索名为“Lady Ada Lovelace”的客人的信息 + + + + +```python +from typing import TypedDict, Annotated +from langgraph.graph.message import add_messages +from langchain_core.messages import AnyMessage, HumanMessage, AIMessage +from langgraph.prebuilt import ToolNode +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import tools_condition +from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace + +# 生成聊天界面,包括工具 +llm = HuggingFaceEndpoint( + repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", + huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, +) + +chat = ChatHuggingFace(llm=llm, verbose=True) +tools = [guest_info_tool] +chat_with_tools = chat.bind_tools(tools) + +# 生成 AgentState 和 Agent 图 +class AgentState(TypedDict): + messages: Annotated[list[AnyMessage], add_messages] + +def assistant(state: AgentState): + return { + "messages": [chat_with_tools.invoke(state["messages"])], + } + +## 构建流程图 +builder = StateGraph(AgentState) + +# 定义节点:这些节点完成工作 +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# 定义边:这些决定了控制流如何移动 +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # If the latest message requires a tool, route to tools + # Otherwise, provide a direct response + tools_condition, +) +builder.add_edge("tools", "assistant") +alfred = builder.compile() + +messages = [HumanMessage(content="Tell me about our guest named 'Lady Ada Lovelace'.")] +response = alfred.invoke({"messages": messages}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Lady Ada Lovelace 是一位受人尊敬的数学家和计算机领域的先驱,由于她在查尔斯·巴贝奇的分析机上所做的工作,她经常被誉为第一位计算机程序员。 +``` + +这最后一步具体做了什么: +- 我们使用 `HuggingFaceEndpoint` 类初始化 Hugging Face 模型。我们还生成了一个聊天界面并附加了工具。 +- 我们将智能体 (Alfred) 创建为一个 `StateGraph`,它使用一条边连接两个节点(`Assistant` 和 `tools`)。 +- 我们让 Alfred 检索一位名叫“Lady Ada Lovelace”的客人的信息。 + + + + +## 互动示例 + +在晚会上,对话可能像这样进行: + +**你**:“Alfred,那位正在和大使说话的先生是谁?” + +**Alfred** *快速搜索嘉宾数据库* “先生,那是尼古拉·特斯拉博士。他是你大学时代的老朋友。他最近申请了一种新的无线能量传输系统的专利,很乐意和你讨论一下。不过别忘了,他对鸽子很感兴趣,所以这或许会成为一次很好的闲聊。” + +```json +{ + "name": "Dr. Nikola Tesla", + "relation": "old friend from university days", + "description": "Dr. Nikola Tesla is an old friend from your university days. He's recently patented a new wireless energy transmission system and would be delighted to discuss it with you. Just remember he's passionate about pigeons, so that might make for good small talk.", + "email": "nikola.tesla@gmail.com" +} +``` + +## 更进一步 + +既然 Alfred 可以检索宾客信息,不妨考虑如何增强这个系统: + +1. **改进检索器**,使用更复杂的算法,例如 [sentence-transformers](https://www.sbert.net/) +2. **实现对话记忆**,让 Alfred 记住之前的互动 +3. **结合网页搜索**,获取陌生宾客的最新信息 +4. **整合多个索引**,从经过验证的来源获取更完整的信息 + +现在,Alfred 已经完全有能力轻松处理宾客的咨询,确保您的晚会成为本世纪最精致、最令人愉悦的盛事! + +<提示> +尝试扩展检索工具,使其能够根据每位宾客的兴趣或背景返回对话开场白。您将如何修改该工具来实现这一点? + +完成后,在 retriever.py 文件中实现您的宾客检索工具。 + diff --git a/units/zh-CN/unit3/agentic-rag/tools.mdx b/units/zh-CN/unit3/agentic-rag/tools.mdx new file mode 100644 index 00000000..5617919c --- /dev/null +++ b/units/zh-CN/unit3/agentic-rag/tools.mdx @@ -0,0 +1,434 @@ +# 构建并集成智能体工具 + +节将为 Alfred 赋予网络访问能力,使其能够获取实时新闻与全球资讯。 +同时还将集成天气数据和 Hugging Face Hub 模型下载统计功能,帮助其进行时效性话题交流。 + +## 赋予智能体网络访问能力 + +请记住,我们希望 Alfred 能够展现出一位真正的文艺复兴主持人的风采,并对世界有着深刻的了解。 + +为此,我们需要确保 Alfred 能够获取有关世界的最新新闻和信息。 + +让我们从为 Alfred 创建一个网络搜索工具开始吧! + + + + +```python +from smolagents import DuckDuckGoSearchTool + +# 初始化 DuckDuckGo 搜索工具 +search_tool = DuckDuckGoSearchTool() + +# 示例用法 +results = search_tool("Who's the current President of France?") +print(results) +``` + +预期输出: + +``` +法国现任总统为 Emmanuel Macron。 +``` + + + + + +```python +from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec +from llama_index.core.tools import FunctionTool + +# 初始化 DuckDuckGo 搜索工具 +tool_spec = DuckDuckGoSearchToolSpec() + +search_tool = FunctionTool.from_defaults(tool_spec.duckduckgo_full_search) +# 示例用法 +response = search_tool("Who's the current President of France?") +print(response.raw_output[-1]['body']) +``` + +预期输出: + +``` +法兰西共和国总统是法国的国家元首。现任总统是 Emmanuel Macron,于2017年5月14日就任,并在2017年5月7日举行的总统选举第二轮中击败 Marine Le Pen。法国第五共和国总统名单 编号 肖像 姓名 ... +``` + + + + +```python +from langchain_community.tools import DuckDuckGoSearchRun + +search_tool = DuckDuckGoSearchRun() +results = search_tool.invoke("Who's the current President of France?") +print(results) +``` + +预期输出: + +``` +Emmanuel Macron (1977年12月21日生于亚眠)法国政治家,2017年当选总统... +``` + + + + +## 创建天气信息工具(烟花调度) + +完美的庆典应该在晴朗的天空下燃放烟花,我们需要确保烟花不会因为恶劣天气而取消。 + +让我们创建一个自定义工具,用于调用外部天气 API 并获取指定位置的天气信息。 + + +为了简单起见,我们在本例中使用了一个虚拟的天气 API。如果您想使用真实的天气 API,您可以实现一个使用 OpenWeatherMap API 的天气工具,就像Unit 1中提到的那样。 + + + + + +```python +from smolagents import Tool +import random + +class WeatherInfoTool(Tool): + name = "weather_info" + description = "Fetches dummy weather information for a given location." + inputs = { + "location": { + "type": "string", + "description": "The location to get weather information for." + } + } + output_type = "string" + + def forward(self, location: str): + # 虚拟天气数据 + weather_conditions = [ + {"condition": "Rainy", "temp_c": 15}, + {"condition": "Clear", "temp_c": 25}, + {"condition": "Windy", "temp_c": 20} + ] + # 随机选择一种天气状况 + data = random.choice(weather_conditions) + return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" + +# 初始化工具 +weather_info_tool = WeatherInfoTool() +``` + + + + +```python +import random +from llama_index.core.tools import FunctionTool + +def get_weather_info(location: str) -> str: + """Fetches dummy weather information for a given location.""" + # 虚拟天气数据 + weather_conditions = [ + {"condition": "Rainy", "temp_c": 15}, + {"condition": "Clear", "temp_c": 25}, + {"condition": "Windy", "temp_c": 20} + ] + # 随机选择一种天气状况 + data = random.choice(weather_conditions) + return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" + +# 初始化工具 +weather_info_tool = FunctionTool.from_defaults(get_weather_info) +``` + + + + +```python +from langchain.tools import Tool +import random + +def get_weather_info(location: str) -> str: + """Fetches dummy weather information for a given location.""" + # 虚拟天气数据 + weather_conditions = [ + {"condition": "Rainy", "temp_c": 15}, + {"condition": "Clear", "temp_c": 25}, + {"condition": "Windy", "temp_c": 20} + ] + # 随机选择一种天气状况 + data = random.choice(weather_conditions) + return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" + +# 初始化工具 +weather_info_tool = Tool( + name="get_weather_info", + func=get_weather_info, + description="Fetches dummy weather information for a given location." +) +``` + + + + +## 为有影响力的 AI 开发者创建 Hub 统计工具 + +出席此次盛会的都是 AI 开发者的精英。Alfred 希望通过讨论他们最受欢迎的模型、数据集和空间来给他们留下深刻印象。我们将创建一个工具,根据用户名从 Hugging Face Hub 获取模型统计数据。 + + + + +```python +from smolagents import Tool +from huggingface_hub import list_models + +class HubStatsTool(Tool): + name = "hub_stats" + description = "Fetches the most downloaded model from a specific author on the Hugging Face Hub." + inputs = { + "author": { + "type": "string", + "description": "The username of the model author/organization to find models from." + } + } + output_type = "string" + + def forward(self, author: str): + try: + # 列出指定作者的模型,按下载次数排序 + models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) + + if models: + model = models[0] + return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." + else: + return f"No models found for author {author}." + except Exception as e: + return f"Error fetching models for {author}: {str(e)}" + +# 初始化工具 +hub_stats_tool = HubStatsTool() + +# 示例用法 +print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook +``` + +预期输出: + +``` +Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 12,544,550 次。 +``` + + + + +```python +import random +from llama_index.core.tools import FunctionTool +from huggingface_hub import list_models + +def get_hub_stats(author: str) -> str: + """Fetches the most downloaded model from a specific author on the Hugging Face Hub.""" + try: + # 列出指定作者的模型,按下载次数排序 + models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) + + if models: + model = models[0] + return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." + else: + return f"No models found for author {author}." + except Exception as e: + return f"Error fetching models for {author}: {str(e)}" + +# 初始化工具 +hub_stats_tool = FunctionTool.from_defaults(get_hub_stats) + +# 示例用法 +print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook +``` + +预期输出: + +``` +Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 12,544,550 次。 +``` + + + + +```python +from langchain.tools import Tool +from huggingface_hub import list_models + +def get_hub_stats(author: str) -> str: + """Fetches the most downloaded model from a specific author on the Hugging Face Hub.""" + try: + # 列出指定作者的模型,按下载次数排序 + models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) + + if models: + model = models[0] + return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." + else: + return f"No models found for author {author}." + except Exception as e: + return f"Error fetching models for {author}: {str(e)}" + +# 初始化工具 +hub_stats_tool = Tool( + name="get_hub_stats", + func=get_hub_stats, + description="Fetches the most downloaded model from a specific author on the Hugging Face Hub." +) + +# 示例用法 +print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook +``` + +预期输出: + +``` +Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 13,109,861 次。 +``` + + + + +借助 Hub Stats 工具,Alfred 现在可以通过讨论他们最受欢迎的模型来打动有影响力的 AI 开发者。 + +## 将工具与 Alfred 集成 + +现在我们已经拥有了所有工具,让我们将它们集成到 Alfred 的智能体中: + + + + +```python +from smolagents import CodeAgent, HfApiModel + +# 初始化 Hugging Face 模型 +model = HfApiModel() + +# 使用所有工具创建 Alfred +alfred = CodeAgent( + tools=[search_tool, weather_info_tool, hub_stats_tool], + model=model +) + +# Alfred 在庆典期间可能会收到的示例查询 +response = alfred.run("What is Facebook and what's their most popular model?") + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Facebook 是一个社交网站,用户可以在这里互相联系、分享信息并互动。Facebook 在 Hugging Face Hub 上下载次数最多的模型是 ESMFold_v1。 +``` + + + + +```python +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +# 初始化 Hugging Face 模型 +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") +# 使用所有工具创建 Alfred +alfred = AgentWorkflow.from_tools_or_functions( + [search_tool, weather_info_tool, hub_stats_tool], + llm=llm +) + +# Alfred 在庆典期间可能会收到的示例查询 +response = await alfred.run("What is Facebook and what's their most popular model?") + +print("🎩 Alfred's Response:") +print(response) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Facebook 是一家总部位于加利福尼亚州门洛帕克的社交网络服务和科技公司。它由马克·扎克伯格创立,允许用户创建个人资料、与亲朋好友联系、分享照片和视频,以及加入基于共同兴趣的群组。Facebook 在 Hugging Face Hub 上最受欢迎的模型是“facebook/esmfold_v1”,下载量达 13,109,861 次。 +``` + + + + +```python +from typing import TypedDict, Annotated +from langgraph.graph.message import add_messages +from langchain_core.messages import AnyMessage, HumanMessage, AIMessage +from langgraph.prebuilt import ToolNode +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import tools_condition +from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace + +# 生成聊天界面,包括工具 +llm = HuggingFaceEndpoint( + repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", + huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, +) + +chat = ChatHuggingFace(llm=llm, verbose=True) +tools = [search_tool, weather_info_tool, hub_stats_tool] +chat_with_tools = chat.bind_tools(tools) + +# 生成 AgentState 和 Agent 图 +class AgentState(TypedDict): + messages: Annotated[list[AnyMessage], add_messages] + +def assistant(state: AgentState): + return { + "messages": [chat_with_tools.invoke(state["messages"])], + } + +## 构建流程图 +builder = StateGraph(AgentState) + +# 定义节点:这些节点完成工作 +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# 定义边:这些决定了控制流如何移动 +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # If the latest message requires a tool, route to tools + # Otherwise, provide a direct response + tools_condition, +) +builder.add_edge("tools", "assistant") +alfred = builder.compile() + +messages = [HumanMessage(content="Who is Facebook and what's their most popular model?")] +response = alfred.invoke({"messages": messages}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +预期输出: + +``` +🎩 Alfred's Response: +Facebook 是一家社交媒体公司,以其社交网站 Facebook 以及 Instagram 和 WhatsApp 等其他服务而闻名。Facebook 在 Hugging Face Hub 上下载次数最多的模型是 facebook/esmfold_v1,下载量达 13,202,321 次。 +``` + + + +## 结论 + +通过集成这些工具,Alfred 现在可以处理各种任务,从网页搜索到天气更新和模型统计。这确保他始终是晚会上最了解情况、最有魅力的主持人。 + + +尝试实现一个可用于获取特定主题最新消息的工具。 + +完成后,在 tools.py 文件中实现您的自定义工具。 + From 9a111fd5702131ca124844697f51db4a754932f4 Mon Sep 17 00:00:00 2001 From: ShawnSiao Date: Mon, 21 Apr 2025 23:14:45 +0800 Subject: [PATCH 2/4] update the toctree --- units/zh-CN/_toctree.yml | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/units/zh-CN/_toctree.yml b/units/zh-CN/_toctree.yml index 35b6e743..899425b4 100644 --- a/units/zh-CN/_toctree.yml +++ b/units/zh-CN/_toctree.yml @@ -108,6 +108,20 @@ title: 快速测验1 - local: unit2/langgraph/conclusion title: 结论 +- title: 第 3 单元. Agentic RAG 的用例 + sections: + - local: unit3/agentic-rag/introduction + title: Agentic RAG 用例简介 + - local: unit3/agentic-rag/agentic-rag + title: Agentic 检索增强生成(RAG) + - local: unit3/agentic-rag/invitees + title: 为宾客故事创建 RAG 工具 + - local: unit3/agentic-rag/tools + title: 为你的智能体构建和集成工具 + - local: unit3/agentic-rag/agent + title: 创建你的 Gala 智能体 + - local: unit3/agentic-rag/conclusion + title: 结论 - title: 附加单元 1. 为函数调用微调大型语言模型 sections: - local: bonus-unit1/introduction @@ -118,7 +132,17 @@ title: 让我们为函数调用微调模型 - local: bonus-unit1/conclusion title: 结论 +- title: 附加单元 2. 智能体可观测性与评估 + sections: + - local: bonus-unit2/introduction + title: 简介 + - local: bonus-unit2/what-is-agent-observability-and-evaluation + title: 什么是智能体可观测性与评估? + - local: bonus-unit2/monitoring-and-evaluating-agents-notebook + title: 监控和评估智能体 + - local: bonus-unit2/quiz + title: 测验 - title: 后续内容何时发布? sections: - local: communication/next-units - title: 后续单元 + title: 后续单元 \ No newline at end of file From 2daefb83f21561ba0f64c076d473311e08560574 Mon Sep 17 00:00:00 2001 From: ShawnSiao Date: Sun, 27 Apr 2025 22:54:22 +0800 Subject: [PATCH 3/4] remove bonus-unit2 in _toctree --- units/zh-CN/_toctree.yml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/units/zh-CN/_toctree.yml b/units/zh-CN/_toctree.yml index 899425b4..0c901273 100644 --- a/units/zh-CN/_toctree.yml +++ b/units/zh-CN/_toctree.yml @@ -132,16 +132,6 @@ title: 让我们为函数调用微调模型 - local: bonus-unit1/conclusion title: 结论 -- title: 附加单元 2. 智能体可观测性与评估 - sections: - - local: bonus-unit2/introduction - title: 简介 - - local: bonus-unit2/what-is-agent-observability-and-evaluation - title: 什么是智能体可观测性与评估? - - local: bonus-unit2/monitoring-and-evaluating-agents-notebook - title: 监控和评估智能体 - - local: bonus-unit2/quiz - title: 测验 - title: 后续内容何时发布? sections: - local: communication/next-units From cd1a933cc33b897f12601b1c693bc4b73ecbbe51 Mon Sep 17 00:00:00 2001 From: Sergio Paniego Blanco Date: Tue, 29 Apr 2025 09:00:48 +0200 Subject: [PATCH 4/4] Update units/zh-CN/unit3/agentic-rag/conclusion.mdx --- units/zh-CN/unit3/agentic-rag/conclusion.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/units/zh-CN/unit3/agentic-rag/conclusion.mdx b/units/zh-CN/unit3/agentic-rag/conclusion.mdx index c8f5b434..f0cecb88 100644 --- a/units/zh-CN/unit3/agentic-rag/conclusion.mdx +++ b/units/zh-CN/unit3/agentic-rag/conclusion.mdx @@ -11,10 +11,12 @@ RAG 与智能体能力的结合展示了当 AI 助手具备以下能力时的强 凭借这些能力,Alfred 现已具备完美主持者的素质,能够回答宾客问题、提供最新信息、确保晚会顺利进行——甚至能精准控制烟花表演的时机! + 完成智能体构建后,您可以进一步探索: - 为特定用例创建定制化工具 - 使用嵌入技术实现更复杂的 RAG 系统 - 构建可协作的多智能体系统 - 将智能体部署为可交互的服务 +