当前位置: 首页 > news >正文

Qwen3:8B 模型(通过 Ollama)搭建智能体 - 义美

太好了!你已经在本地成功运行了 Qwen3:8B 模型(通过 Ollama),这是搭建智能体非常理想的起点 👍。接下来,我会为你量身定制一套完整方案,教你如何用 LangChain + Ollama(qwen3:8b) 从 01 搭建一个完全离线、无需联网、不依赖 OpenAI/通义 API 的智能体,并支持调用工具(如查天气、计算器、搜索等)。✅ 目标
构建一个本地智能体,能:
- 理解自然语言指令
- 自主决定是否需要调用工具
- 执行多步任务(如“北京今天多少度?加5是多少?”)
- 全程在你的 Windows 电脑上运行(无网络请求到外部 AI 服务)第一步:安装必要 Python 包打开命令行(CMD 或 PowerShell),执行:pip install langchain langchain-core langchain-community langchain-ollama python-dotenv requests💡 注意:langchain-ollama 是 LangChain 官方对 Ollama 的集成包(2025 年后推荐使用)。第二步:确保 Ollama 正常运行你已经能运行 ollama run qwen3:8b,说明 Ollama 服务已启动。⚠️ 重要:保持 Ollama 后台运行(不要关闭那个终端窗口,或设置为系统服务)。  
LangChain 会通过 http://localhost:11434 与 Ollama 通信。

你可以测试 API 是否通:
curl http://localhost:11434/api/tags

如果返回模型列表,说明一切正常。第三步:编写智能体代码(纯本地版)创建文件 local_agent.py:local_agent.py
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.tools import Tool
from langchain_ollama import ChatOllama  # 关键:使用 Ollama 集成import os
import re====== 1. 加载本地 Ollama 模型 ======
llm = ChatOllama(model="qwen3:8b",temperature=0,base_url="http://localhost:11434",  # Ollama 默认地址streaming=True,
)====== 2. 定义工具 ======工具1:简易天气模拟(因本地无真实API,我们用模拟数据)
def get_weather(city: str) -> str:# 实际项目中可替换为本地数据库或内网APIweather_data = {"北京": "5°C, 晴","上海": "12°C, 多云","广州": "20°C, 小雨","深圳": "22°C, 阴"}return weather_data.get(city.strip(), "未知城市")weather_tool = Tool(name="CurrentWeather",func=get_weather,description="获取指定城市的当前天气和温度。输入应为城市名,如'北京'。"
)工具2:安全计算器(避免 eval 风险)
def safe_calculator(expr: str) -> str:# 只允许数字、小数点、+ - * / 和空格expr = expr.strip()if not re.match(r'^[ds+-*/.()]+$', expr):return "表达式包含非法字符"try:# 使用 ast.literal_eval 更安全?但不支持运算 → 这里简单用 eval + 限制# 生产环境建议用专用数学库如 simpleevalresult = eval(expr, {"builtins": {}}, {})return str(result)except Exception as e:return f"计算错误: {str(e)}"calc_tool = Tool(name="Calculator",func=safe_calculator,description="执行简单的数学计算,如 '5 + 3' 或 '(10 * 2) - 4'。"
)tools = [weather_tool, calc_tool]====== 3. 构建 Prompt ======
prompt = ChatPromptTemplate.from_messages([("system", "你是一个有用的助手,可以回答问题、查询天气、进行数学计算。请使用提供的工具完成任务。"),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),
])====== 4. 创建智能体 ======
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)====== 5. 交互式运行 ======
if name == "main":print("💬 本地智能体已启动(基于 Qwen3:8B + Ollama)")print("输入你的问题(输入 'quit' 退出):n")while True:user_input = input("你: ").strip()if user_input.lower() in ["quit", "exit", "退出"]:breakif not user_input:continuetry:response = agent_executor.invoke({"input": user_input})print(f"🤖: {response['output']}n")except Exception as e:print(f"❌ 错误: {e}n")第四步:运行你的本地智能体!在项目目录下执行:python local_agent.py然后尝试提问:你: 北京今天多少度?
你: 15 + 7 等于多少?
你: 上海天气如何?乘以2是多少度?(看它能否分步处理)你应该能看到类似输出:
Thought: 我需要先查上海的天气...
Action: CurrentWeather
Action Input: 上海
Observation: 12°C, 多云
Thought: 现在计算 12 * 2...
Action: Calculator
Action Input: 12 * 2
Observation: 24
Final Answer: 上海今天12°C,乘以2是24°C。✅ 成功!你的 完全本地化智能体 已经跑起来了!🔧 后续优化建议1. 接入真实本地工具
- 把 get_weather 改成调用你内网的天气服务
- 添加“读取本地文件”、“执行Python脚本”等工具2. 增加记忆能力
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
在 AgentExecutor 中加入 memory=memory3. 图形界面(可选)
用 Gradio 快速加个 Web UI:
import gradio as grdef chat(message, history):result = agent_executor.invoke({"input": message})return result["output"]gr.ChatInterface(chat).launch()4. 提升工具调用准确性
- Qwen3 对 function calling 支持较好,但可加提示词强化:你必须严格使用以下工具,不要自己编造数据。📌 注意事项(Windows 用户)- 确保 Ollama 服务持续运行(可设置为 Windows 服务)
- 如果遇到编码问题,在 .py 文件开头加:import syssys.stdout.reconfigure(encoding='utf-8')- 显存不足?可改用 qwen3:4b 或启用量化模型(如 qwen3:8b-q4_K_M)如果你希望我帮你:
- 把天气工具换成真实 API(即使本地也可调内网)
- 添加“搜索本地文档”功能(RAG)
- 打包成 EXE 或部署为桌面应用随时告诉我!你现在离“个人 AI 助手”只差几步 😎

 

import sys
import os
import re
from langchain_classic.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.tools import Tool
from langchain_ollama import ChatOllama  # 关键:使用 Ollama 集成# 解决 Windows 终端编码问题
if sys.platform == "win32":sys.stdout.reconfigure(encoding='utf-8')# ====== 1. 加载本地 Ollama 模型 ======
llm = ChatOllama(model="qwen3:8b",temperature=0,base_url="http://localhost:11434",  # Ollama 默认地址
)# ====== 2. 定义工具 ======# 工具1:简易天气模拟
def get_weather(city: str) -> str:# 实际项目中可替换为本地数据库或内网APIweather_data = {"北京": "5°C, 晴","上海": "12°C, 多云","广州": "20°C, 小雨","深圳": "22°C, 阴"}return weather_data.get(city.strip(), "未知城市")weather_tool = Tool(name="CurrentWeather",func=get_weather,description="获取指定城市的当前天气和温度。输入应为城市名,如'北京'。"
)# 工具2:安全计算器
def safe_calculator(expr: str) -> str:# 只允许数字、小数点、+ - * / () 和空格expr = expr.strip()if not re.match(r'^[0-9\s\+\-\*\/\.\(\)]+$', expr):return "表达式包含非法字符"try:# 使用 eval 时限制 globals 和 localsresult = eval(expr, {"__builtins__": {}}, {})return str(result)except Exception as e:return f"计算错误: {str(e)}"calc_tool = Tool(name="Calculator",func=safe_calculator,description="执行简单的数学计算,如 '5 + 3' 或 '(10 * 2) - 4'。"
)tools = [weather_tool, calc_tool]# ====== 3. 构建 Prompt ======
prompt = ChatPromptTemplate.from_messages([("system", "你是一个有用的助手,可以回答问题、查询天气、进行数学计算。请使用提供的工具完成任务。"),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),
])# ====== 4. 创建智能体 ======
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)# ====== 5. 交互式运行 ======
if __name__ == "__main__":print("💬 本地智能体已启动(基于 Qwen3:8B + Ollama)")print("输入你的问题(输入 'quit' 退出):\n")while True:try:user_input = input("你: ").strip()if user_input.lower() in ["quit", "exit", "退出"]:breakif not user_input:continueresponse = agent_executor.invoke({"input": user_input})print(f"🤖: {response['output']}\n")except KeyboardInterrupt:breakexcept Exception as e:print(f"❌ 错误: {e}\n")# python local_agent.py

 

http://www.jsqmd.com/news/332170/

相关文章:

  • 本科论文“减负”指南:如何让百考通AI成为你的智能学术伙伴
  • 2026年封头品牌推荐:宜兴市宏明机械科技有限公司
  • 告别论文焦虑:百考通AI如何助力本科生高效完成毕业论文
  • 2026年菏泽地区靠谱的百度推广代理商排名,瑞兴广告口碑如何
  • 多智能体协同新突破 反思机制驱动的COPPER框架深度解析
  • 百考通AI:重新定义本科毕业论文写作,一场以学生为本的智能革新
  • DNA甲基化为何是表观遗传研究的核心?
  • 告别论文焦虑:我用百考通AI高效搞定硕士毕业论文的实战分享
  • 2000-2024年 上市公司-平台生态嵌入程度(数据+代码+文献)
  • 2000-2024年 上市公司-融资约束KZ、SA、WW、FC指数(+文献)
  • ACPI!ACPISystemPowerInitializeRootMapping函数分析和ACPI!ACPISystemPowerGetSxD函数分析
  • Transformer模型原理全面详解(通俗易懂)
  • 口碑见证实力:2026年保健食品供应商优选榜单,大牌热销品/大牌保健食品/保健食品集合店,保健食品加盟代理有哪些
  • 洛谷一键跳转vjudge插件
  • 审稿人已无法分辨AI生成与研究者撰写的论文,中山大学、东南大学、兰州大学网安学院导师拆解“真创新”
  • 模型越复杂越不准?2026风电光伏功率预测的“三座误差大山”与破解之道
  • 2026地产开发运营商排名,云桥资管专业团队保障海外投资收益
  • IDEA 免费了,2025.3 版本开始,JetBrains 发布了“统一版”,免费版(即原来的社区版)的功能得到了显著增强,缩小了与旗舰版的差距。
  • 从从52x(521/522)超时错误突围:云上云下双场景排查与通用化解决方案
  • 聊聊靠谱的家用净水器品牌公司,哪家性价比高
  • malloc 在多线程下为什么慢?——从原理到实测
  • 开题卡住了?AI论文写作软件 千笔写作工具 VS PaperRed,本科生专属神器!
  • 2026年国内排行前列的包衣机订制厂家口碑推荐,高效粉碎机/粉碎整粒机/高效包衣机附件/换筒包衣机,包衣机制造厂哪家好
  • AGV智能物流规划公司哪家好,浙江锦舜净化优势突出
  • 学霸同款10个降AI率工具 千笔AI帮你降AIGC
  • 选购讯灵AI智能生态系统代理,有哪些口碑好的品牌推荐?
  • 【算法实战】C 语言实现无重复字符的最长子串:滑动窗口 + 哈希表高效解法(附完整可运行代码)
  • Linux Shell(四)-- 设置信号功能 trap
  • 2026年行业内有实力的升降机品牌排行,自行走升降机/装车平台/防爆升降机/升降机/防爆升降平台,升降机企业哪家靠谱
  • 深度测评9个降AIGC网站 千笔AI帮你精准降AI率