LangChain与Qwen模型实战5分钟构建多功能AI助手在当今AI技术快速发展的时代能够理解用户意图并执行具体任务的智能助手正变得越来越重要。本文将带你快速上手LangChain框架与Qwen大模型的结合使用无需复杂配置只需5分钟就能搭建一个既能聊天又能查天气、做数学题的实用AI助手。1. 环境准备与工具定义首先确保你的Python环境已安装最新版LangChain和相关依赖pip install langchain langchain-openai python-dotenv接下来定义两个基础工具函数——天气查询和加法计算from langchain_core.tools import tool tool def get_weather(city: str) - str: 返回指定城市的模拟天气信息 return f{city}今天晴转多云气温25-32°C湿度45% tool def add_numbers(a: int, b: int) - int: 返回两个整数的和 return a b提示实际应用中get_weather应接入真实天气API这里使用模拟数据便于演示2. 模型初始化与工具绑定使用Qwen模型的阿里云兼容接口进行初始化from langchain_openai import ChatOpenAI qwen_llm ChatOpenAI( base_urlhttps://dashscope.aliyuncs.com/compatible-mode/v1, api_keyyour_api_key_here, # 替换为你的DashScope API Key modelqwen-turbo, temperature0.7 ) # 将工具绑定到模型 llm_with_tools qwen_llm.bind_tools([get_weather, add_numbers])关键参数说明参数说明推荐值base_url阿里云兼容接口地址固定值model模型名称qwen-turbo或qwen-plustemperature生成多样性0.7(平衡创意与准确)3. 构建对话循环系统实现带有多轮对话记忆和自动工具调用的主循环from langchain_core.messages import HumanMessage, AIMessage, ToolMessage import json # 初始化对话历史 messages [ AIMessage(content你好我是你的AI助手可以查天气、做数学题有什么需要帮忙的吗) ] available_tools {get_weather: get_weather, add_numbers: add_numbers} while True: user_input input(你).strip() if user_input.lower() in {exit, quit}: break # 添加用户消息到历史 messages.append(HumanMessage(contentuser_input)) # 获取模型响应 response llm_with_tools.invoke(messages) # 处理工具调用 if response.tool_calls: print(检测到工具调用:) print(json.dumps(response.tool_calls, indent2, ensure_asciiFalse)) messages.append(response) for tool_call in response.tool_calls: tool_func available_tools.get(tool_call[name]) if tool_func: tool_result tool_func.invoke(tool_call[args]) messages.append(ToolMessage( contentstr(tool_result), tool_call_idtool_call[id] )) print(f执行 {tool_call[name]} → {tool_result}) else: messages.append(response) print(AI:, response.content)4. 实战效果演示运行程序后你将体验到完整的交互流程你北京天气怎么样 检测到工具调用: [ { name: get_weather, args: {city: 北京}, id: call_abc123 } ] 执行 get_weather → 北京今天晴转多云气温25-32°C湿度45% AI: 北京今天晴转多云气温在25到32摄氏度之间湿度为45%适合外出但要注意防晒。 你123加456等于多少 检测到工具调用: [ { name: add_numbers, args: {a: 123, b: 456}, id: call_def456 } ] 执行 add_numbers → 579 AI: 123加456的计算结果是5795. 进阶功能扩展5.1 添加更多工具只需定义新函数并用tool装饰即可扩展助手能力tool def get_stock_price(symbol: str) - str: 获取股票当前价格模拟 prices {AAPL: 182.63, TSLA: 168.29} return prices.get(symbol, 未知股票代码) # 绑定新工具 llm_with_tools qwen_llm.bind_tools([get_weather, add_numbers, get_stock_price])5.2 流式输出支持对于需要长时间运行的工具可以添加流式响应from langchain_core.runnables import RunnableLambda def stream_tool_result(tool_call): tool_func available_tools.get(tool_call[name]) if tool_func: for chunk in tool_func.stream(tool_call[args]): yield chunk streaming_chain llm_with_tools | RunnableLambda(stream_tool_result)5.3 错误处理机制增强系统鲁棒性的错误处理方案try: response llm_with_tools.invoke(messages) except Exception as e: print(f模型调用出错: {str(e)}) # 重试或降级处理6. 性能优化建议缓存策略对天气查询等结果缓存5-10分钟批量处理同时处理多个工具调用请求限流控制避免API调用频率超出限制from ratelimit import limits, sleep_and_retry sleep_and_retry limits(calls30, period60) def call_weather_api(city): # 实际API调用 pass这套方案特别适合需要快速验证创意的开发者以及希望为现有系统添加智能对话能力的技术团队。我在实际项目中发现Qwen模型在中文场景下的工具调用准确率显著优于同等规模的国际模型。