news 2026/5/23 19:01:50

基于LangChain与Ollama的Qwen2.5智能助手:打造支持网络搜索与假期查询 Agent

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
基于LangChain与Ollama的Qwen2.5智能助手:打造支持网络搜索与假期查询 Agent

前言

在AI技术飞速发展的今天,构建一个功能强大且易于部署的本地AI助手是许多开发者的梦想。本文将详细介绍如何使用LangChain、Ollama和Qwen2.5模型构建一个功能丰富的本地AI Agent,该Agent不仅支持网络搜索和数学计算,还能查询节假日信息,真正实现一个全方位的智能助手。

项目概述

本项目是一个基于LangChain框架和Ollama平台的Qwen2.5智能助手,能够实现:

  • 网络搜索功能
  • 数学计算能力
  • 节假日查询功能
  • 本地部署,无需云端依赖

项目结构如下:

langchain_qwen_agent/ ├── agent.py # Agent核心创建模块 ├── run.py # 主运行模块 ├── tools.py # 工具函数模块 ├── requirements.txt # 项目依赖

项目依赖

首先,让我们看看项目的依赖文件requirements.txt

langchain==1.2.0 langchain-classic==1.0.1 langchain-community==0.4.1 langchain-core==1.2.6 langchain-ollama==1.0.1 langchain-text-splitters==1.1.0 requests

这些依赖库是构建AI Agent的核心组件,其中LangChain用于构建Agent框架,Ollama用于本地模型部署,requests用于HTTP请求。

Agent核心实现

Agent的核心逻辑实现在agent.py文件中:

# agent.pyfromlangchain_ollamaimportChatOllamafromlangchain_core.promptsimportChatPromptTemplate,MessagesPlaceholderfromlangchain_classic.agentsimportcreate_tool_calling_agent,AgentExecutorfromtoolsimporttools# 绝对导入defcreate_qwen_agent():llm=ChatOllama(model="qwen2.5:7b",base_url="http://localhost:11434",temperature=0.7,)# 使用 ChatPromptTemplate + MessagesPlaceholder 的标准方式(推荐且稳定)prompt=ChatPromptTemplate.from_messages([("system","你是一个聪明强大的助手,能够使用工具来帮助解决问题。请严格按照思考格式行动。"),("placeholder","{chat_history}"),# 可选:如果以后要加记忆("human","{input}"),MessagesPlaceholder("agent_scratchpad"),])# 创建 tool-calling agentagent=create_tool_calling_agent(llm=llm,tools=tools,prompt=prompt)# 创建执行器agent_executor=AgentExecutor(agent=agent,tools=tools,verbose=True,handle_parsing_errors=True,max_iterations=15,max_execution_time=90,)returnagent_executor

这个文件定义了AI Agent的核心创建函数,通过LangChain的工具调用功能,使模型能够使用外部工具来增强其能力。

工具模块详解

tools.py文件是整个项目的关键,它定义了AI Agent可以使用的各种工具:

# tools.pyfromlangchain_core.toolsimporttoolfromlangchain_community.toolsimportDuckDuckGoSearchRunimportrequestsfromdatetimeimportdatetime# 原有工具search_tool=DuckDuckGoSearchRun()@tooldefcalculator(expression:str)->str:"""计算数学表达式"""try:result=eval(expression,{"__builtins__":{}})returnf"结果是{result}"exceptExceptionase:returnf"计算错误:{str(e)}"# ── 下面是更原子化的节假日工具(推荐使用这个版本) ──@tooldefget_today_holiday()->str:"""获取今天的法定节假日信息"""base_url="http://127.0.0.1:5007/api/holiday"try:resp=requests.get(f"{base_url}/today",timeout=8)ifresp.status_code==200:data=resp.json()desc=data["description"]name=data.get("name","")returnf"今天是:{name+','ifnameelse''}{desc}"else:return"无法获取今日节假日信息"exceptExceptionase:returnf"查询出错:{str(e)}"@tooldefget_date_holiday(date_str:str)->str:"""查询指定日期(格式:YYYY-MM-DD)的法定节假日信息"""base_url="http://127.0.0.1:5007/api/holiday"try:resp=requests.get(f"{base_url}/{date_str}",timeout=8)ifresp.status_code==200:data=resp.json()desc=data["description"]name=data.get("name","")returnf"{date_str}是:{name+','ifnameelse''}{desc}"else:returnf"无效日期或无法查询:{date_str}"exceptExceptionase:returnf"查询出错:{str(e)}"@tooldefget_month_holidays(year:int,month:int)->str:"""查询指定年月的节假日完整日历(返回当月所有放假/调休日期)"""base_url="http://127.0.0.1:5007/api/holiday"try:resp=requests.get(f"{base_url}/month/{year}/{month}",timeout=10)ifresp.status_code==200:data=resp.json()holidays=[f"{d['date']}{d['description']}"fordindata["days"]ifd["is_off_day"]ord["type"]=="makeup_workday"]ifholidays:returnf"{year}{month}月节假日/调休安排:\n"+"\n".join(holidays)else:returnf"{year}{month}月没有法定节假日或调休安排"else:returnf"无法查询{year}{month}月"exceptExceptionase:returnf"查询出错:{str(e)}"@tooldefget_year_holidays(year:int)->str:"""查询整年法定节假日安排概要(列出所有节日名称和放假/调休状态)"""base_url="http://127.0.0.1:5007/api/holiday"try:resp=requests.get(f"{base_url}/year/{year}",timeout=15)ifresp.status_code==200:data=resp.json()items=[]seen=set()fordindata.get("days",[]):name=d["name"]status="放假"ifd["isOffDay"]else"调休上班"key=f"{name}-{status}"ifkeynotinseen:seen.add(key)items.append(f"{name}{status})")returnf"{year}年法定节假日安排概要:\n"+"\n".join(sorted(items))else:returnf"无法获取{year}年节假日数据"exceptExceptionase:returnf"查询出错:{str(e)}"# 工具列表(现在更清晰、更原子)tools=[search_tool,calculator,get_today_holiday,get_date_holiday,get_month_holidays,get_year_holidays,]

这个模块定义了多个实用工具:

  1. calculator:用于数学计算
  2. get_today_holiday:获取今天节假日信息
  3. get_date_holiday:查询指定日期节假日
  4. get_month_holidays:查询月份节假日安排
  5. get_year_holidays:查询年度节假日概要

主程序入口

run.py文件是程序的入口,实现了用户交互逻辑:

# run.pyfromagentimportcreate_qwen_agentdefmain():print("正在启动本地 Qwen2.5-7B Agent(Ollama)...")print("请确保你已运行:ollama serve 并且已下载模型:ollama pull qwen2.5:7b\n")agent_executor=create_qwen_agent()print("Agent 已就绪!支持网络搜索和数学计算。")print("输入 'exit'、'quit' 或 'bye' 退出程序。\n")whileTrue:try:user_input=input("You: ").strip()ifuser_input.lower()in["exit","quit","bye"]:print("再见!")breakifnotuser_input:print("请输入内容哦~")continueprint("Agent 正在思考...\n")response=agent_executor.invoke({"input":user_input})print(f"Agent:{response['output']}\n")exceptKeyboardInterrupt:print("\n\n再见!")breakexceptExceptionase:print(f"发生错误:{e}\n")if__name__=="__main__":main()

部署与运行

要运行这个项目,需要以下步骤:

  1. 安装依赖:
pipinstall-rrequirements.txt
  1. 启动Ollama服务:
ollama serve
  1. 下载Qwen2.5模型:
ollama pull qwen2.5:7b
  1. 运行主程序:
python run.py

5.接口请参考:

https://blog.csdn.net/weixin_46244623/article/details/156257588

功能演示

运行程序后,您可以与AI Agent进行交互,例如:

  • 询问数学问题:“计算 25*36+128”
  • 搜索网络:“今天天气如何?”
  • 查询节假日:“今天是什么节日?”

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/16 13:08:06

基于 SpringBoot的高校学生实习综合服务平台设计与实现

基于SpringBoot的高校学生实习综合服务平台设计与实现 第一章 系统整体架构设计 基于SpringBoot的高校学生实习综合服务平台以“校企协同、流程闭环、全程管控”为核心目标,采用“前端交互-服务层-数据层”三层架构。系统核心包含七大功能模块:实习基地管…

作者头像 李华
网站建设 2026/5/19 11:40:35

使用Ultralytics YOLO11的TrackZone

什么是TrackZone? TrackZone 专门用于监控框架内指定区域的对象,而不是整个框架。基于 Ultralytics YOLO11,它在视频和实时摄像头流中特定区域的物体检测和跟踪中进行了集成。YOLO11 的高级算法和 深度学习 技术使其成为实时用例的完美选择&…

作者头像 李华
网站建设 2026/5/21 7:06:57

Docker容器 runtime 安全如何保障:3步实现Falco实时威胁检测

第一章:Docker容器 runtime 安全如何保障:3步实现Falco实时威胁检测在现代云原生架构中,Docker容器的运行时安全成为关键防线。一旦攻击者突破应用层防护,缺乏运行时监控将导致威胁无法及时发现。Falco作为开源的运行时安全工具&a…

作者头像 李华
网站建设 2026/5/17 1:12:36

Docker Git 工作树切换全攻略(开发者必藏的4种高阶方案)

第一章:Docker Git 工作树切换全攻略(开发者必藏的4种高阶方案)在现代开发流程中,频繁切换 Git 分支并同步 Docker 环境是常见需求。若处理不当,极易导致容器环境与代码版本不一致。掌握高效的工作树切换策略&#xff…

作者头像 李华
网站建设 2026/5/23 17:26:26

Docker Rollout无停机实践全曝光(从CI/CD到流量切换的完整链路)

第一章:Docker Rollout无停机实践概述在现代微服务架构中,应用的持续交付与高可用性成为核心诉求。Docker Rollout 的无停机部署(Zero-downtime Deployment)技术,能够在不中断用户请求的前提下完成服务更新&#xff0c…

作者头像 李华