太好了!你已经在本地成功运行了 Qwen3:8B 模型(通过 Ollama),这是搭建智能体非常理想的起点 👍。
接下来,我会为你量身定制一套完整方案,教你如何用 LangChain + Ollama(qwen3:8b) 从 0 到 1 搭建一个完全离线、无需联网、不依赖 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:
# 实际项目中可替换为本地数据库或内网API
weather_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 + 限制
# 生产环境建议用专用数学库如 simpleeval
result = 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", "退出"]:
break
if not user_input:
continue
try:
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=memory
3. 图形界面(可选)
用 Gradio 快速加个 Web UI:
import gradio as gr
def 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 sys
sys.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:
# 实际项目中可替换为本地数据库或内网API
weather_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 和 locals
result = 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", "退出"]:
break
if not user_input:
continue
response = agent_executor.invoke({"input": user_input})
print(f"🤖: {response['output']}\n")
except KeyboardInterrupt:
break
except Exception as e:
print(f"❌ 错误: {e}\n")
# python local_agent.py