2026/4/18 10:22:29
网站建设
项目流程
ui设计网站设计与网页制作视频教程,莒县网站建设,软件开发工程师就业企业,网页备用页前言
在AI技术飞速发展的今天#xff0c;构建一个功能强大且易于部署的本地AI助手是许多开发者的梦想。本文将详细介绍如何使用LangChain、Ollama和Qwen2.5模型构建一个功能丰富的本地AI Agent#xff0c;该Agent不仅支持网络搜索和数学计算#xff0c;还能查询节假日信息构建一个功能强大且易于部署的本地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.txtlangchain1.2.0 langchain-classic1.0.1 langchain-community0.4.1 langchain-core1.2.6 langchain-ollama1.0.1 langchain-text-splitters1.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():llmChatOllama(modelqwen2.5:7b,base_urlhttp://localhost:11434,temperature0.7,)# 使用 ChatPromptTemplate MessagesPlaceholder 的标准方式推荐且稳定promptChatPromptTemplate.from_messages([(system,你是一个聪明强大的助手能够使用工具来帮助解决问题。请严格按照思考格式行动。),(placeholder,{chat_history}),# 可选如果以后要加记忆(human,{input}),MessagesPlaceholder(agent_scratchpad),])# 创建 tool-calling agentagentcreate_tool_calling_agent(llmllm,toolstools,promptprompt)# 创建执行器agent_executorAgentExecutor(agentagent,toolstools,verboseTrue,handle_parsing_errorsTrue,max_iterations15,max_execution_time90,)returnagent_executor这个文件定义了AI Agent的核心创建函数通过LangChain的工具调用功能使模型能够使用外部工具来增强其能力。工具模块详解tools.py文件是整个项目的关键它定义了AI Agent可以使用的各种工具# tools.pyfromlangchain_core.toolsimporttoolfromlangchain_community.toolsimportDuckDuckGoSearchRunimportrequestsfromdatetimeimportdatetime# 原有工具search_toolDuckDuckGoSearchRun()tooldefcalculator(expression:str)-str:计算数学表达式try:resulteval(expression,{__builtins__:{}})returnf结果是{result}exceptExceptionase:returnf计算错误:{str(e)}# ── 下面是更原子化的节假日工具推荐使用这个版本 ──tooldefget_today_holiday()-str:获取今天的法定节假日信息base_urlhttp://127.0.0.1:5007/api/holidaytry:resprequests.get(f{base_url}/today,timeout8)ifresp.status_code200:dataresp.json()descdata[description]namedata.get(name,)returnf今天是{nameifnameelse}{desc}else:return无法获取今日节假日信息exceptExceptionase:returnf查询出错{str(e)}tooldefget_date_holiday(date_str:str)-str:查询指定日期格式YYYY-MM-DD的法定节假日信息base_urlhttp://127.0.0.1:5007/api/holidaytry:resprequests.get(f{base_url}/{date_str},timeout8)ifresp.status_code200:dataresp.json()descdata[description]namedata.get(name,)returnf{date_str}是{nameifnameelse}{desc}else:returnf无效日期或无法查询{date_str}exceptExceptionase:returnf查询出错{str(e)}tooldefget_month_holidays(year:int,month:int)-str:查询指定年月的节假日完整日历返回当月所有放假/调休日期base_urlhttp://127.0.0.1:5007/api/holidaytry:resprequests.get(f{base_url}/month/{year}/{month},timeout10)ifresp.status_code200:dataresp.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_urlhttp://127.0.0.1:5007/api/holidaytry:resprequests.get(f{base_url}/year/{year},timeout15)ifresp.status_code200:dataresp.json()items[]seenset()fordindata.get(days,[]):named[name]status放假ifd[isOffDay]else调休上班keyf{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,]这个模块定义了多个实用工具calculator用于数学计算get_today_holiday获取今天节假日信息get_date_holiday查询指定日期节假日get_month_holidays查询月份节假日安排get_year_holidays查询年度节假日概要主程序入口run.py文件是程序的入口实现了用户交互逻辑# run.pyfromagentimportcreate_qwen_agentdefmain():print(正在启动本地 Qwen2.5-7B AgentOllama...)print(请确保你已运行ollama serve 并且已下载模型ollama pull qwen2.5:7b\n)agent_executorcreate_qwen_agent()print(Agent 已就绪支持网络搜索和数学计算。)print(输入 exit、quit 或 bye 退出程序。\n)whileTrue:try:user_inputinput(You: ).strip()ifuser_input.lower()in[exit,quit,bye]:print(再见)breakifnotuser_input:print(请输入内容哦)continueprint(Agent 正在思考...\n)responseagent_executor.invoke({input:user_input})print(fAgent:{response[output]}\n)exceptKeyboardInterrupt:print(\n\n再见)breakexceptExceptionase:print(f发生错误:{e}\n)if__name____main__:main()部署与运行要运行这个项目需要以下步骤安装依赖pipinstall-rrequirements.txt启动Ollama服务ollama serve下载Qwen2.5模型ollama pull qwen2.5:7b运行主程序python run.py5.接口请参考https://blog.csdn.net/weixin_46244623/article/details/156257588功能演示运行程序后您可以与AI Agent进行交互例如询问数学问题“计算 25*36128”搜索网络“今天天气如何”查询节假日“今天是什么节日”