
LangChain函数调用实战构建智能天气与商品查询系统的完整指南在当今AI应用开发领域让大语言模型(LLM)与外部系统无缝对接已成为提升产品智能化的关键。LangChain作为这一领域的标杆框架其函数调用能力为开发者提供了将自然语言转化为实际操作的强大工具。本文将深入探讨如何利用LangChain构建能够自动查询天气和商品信息的智能系统从基础原理到高级应用场景为您呈现一套完整的解决方案。1. LangChain函数调用核心原理函数调用(Function Calling)是LangChain最令人兴奋的特性之一它使LLM能够理解何时需要调用外部工具并自动生成符合要求的参数。这一机制本质上是在LLM与真实世界之间架起了一座桥梁。工作原理三要素函数描述用JSON格式明确定义函数名称、描述、参数类型和必需字段意图识别LLM分析用户输入判断是否需要调用外部函数参数提取从自然语言中结构化提取函数所需参数以下是一个典型的天气查询函数定义示例weather_function { name: get_current_weather, description: 获取指定城市的当前天气情况, parameters: { type: object, properties: { location: { type: string, description: 城市名称如北京、上海 }, unit: { type: string, enum: [celsius, fahrenheit] } }, required: [location] } }提示函数描述中的description字段至关重要它决定了LLM是否能准确理解何时调用该函数2. 构建基础函数调用链让我们从创建一个最简单的天气查询链开始。这个链将完成从用户自然语言到函数调用的完整转换过程。实现步骤初始化Chat模型并绑定函数描述创建提示模板处理用户输入组合成可执行链from langchain.prompts import ChatPromptTemplate from langchain.chat_models import ChatOpenAI # 创建提示模板 prompt ChatPromptTemplate.from_messages([ (human, {input}) ]) # 初始化模型并绑定天气函数 model ChatOpenAI(temperature0).bind( functions[weather_function], function_call{name: get_current_weather} ) # 组合成链 chain prompt | model测试这个基础链response chain.invoke({input: 上海现在天气怎么样}) print(response.additional_kwargs)您将看到类似这样的输出其中包含了LLM建议调用的函数及其参数{ function_call: { name: get_current_weather, arguments: {location:上海,unit:celsius} } }3. 多函数调度与电商查询实现实际应用中系统往往需要处理多种类型的查询。让我们扩展系统能力加入商品查询功能。商品查询函数定义product_function { name: product_search, description: 查询电商平台商品信息, parameters: { type: object, properties: { product_name: { type: string, description: 商品名称如iPhone 15 }, max_price: { type: number, description: 最高价格限制 } }, required: [product_name] } }创建支持多函数调用的链multi_function_model ChatOpenAI(temperature0).bind( functions[weather_function, product_function] ) multi_chain prompt | multi_function_model测试多函数调度能力# 测试天气查询 weather_response multi_chain.invoke({input: 北京今天气温多少}) print(weather_response.additional_kwargs) # 测试商品查询 product_response multi_chain.invoke({input: 最新款MacBook Pro多少钱}) print(product_response.additional_kwargs)注意LLM会根据函数描述自动选择最合适的函数当用户查询模糊时可能会要求澄清4. 实战构建端到端查询系统现在我们将把理论转化为完整可用的系统包含函数调用和实际API对接。系统架构接收用户自然语言输入LLM解析并生成函数调用建议执行实际API调用将API结果转化为自然语言回复天气API对接示例import requests def get_weather(location: str, unit: str celsius): 实际调用天气API的函数 # 这里使用模拟数据实际项目应替换为真实API调用 mock_data { location: location, temperature: 25 if unit celsius else 77, unit: unit, forecast: [sunny, cloudy] } return mock_data # 完整执行链 def execute_weather_query(user_input: str): # 获取函数调用建议 chain_response multi_chain.invoke({input: user_input}) if not chain_response.additional_kwargs.get(function_call): return 抱歉我无法处理这个请求 func_call chain_response.additional_kwargs[function_call] # 根据函数名路由到不同处理逻辑 if func_call[name] get_current_weather: import json args json.loads(func_call[arguments]) weather_data get_weather(args[location], args.get(unit)) return f{args[location]}当前天气{weather_data[temperature]}°{args.get(unit, celsius).upper()}, 预计{, .join(weather_data[forecast])} elif func_call[name] product_search: return 商品查询功能正在建设中... return 未知请求类型测试端到端流程print(execute_weather_query(杭州明天天气如何)) print(execute_weather_query(查询三亚当前温度用华氏度))5. 高级技巧与性能优化当系统投入生产环境时以下几个高级技巧可以显著提升性能和可靠性1. 函数调用缓存 对频繁查询的内容实现缓存机制减少API调用次数from functools import lru_cache lru_cache(maxsize100) def cached_weather_query(location: str, unit: str): return get_weather(location, unit)2. 异步处理 利用LangChain的异步接口提升并发性能async def async_weather_query(location: str): model ChatOpenAI(temperature0) prompt ChatPromptTemplate.from_template(获取{city}天气) chain prompt | model return await chain.ainvoke({city: location})3. 流式输出 对长时间操作提供渐进式反馈async def stream_weather_response(location: str): model ChatOpenAI(temperature0) prompt ChatPromptTemplate.from_template(正在获取{city}天气...) chain prompt | model async for chunk in chain.astream({city: location}): print(chunk.content, end, flushTrue)4. 后备策略 当主模型不可用时自动降级from langchain.schema.runnable import RunnableLambda primary_model ChatOpenAI(temperature0) fallback_model ChatOpenAI(model_namegpt-3.5-turbo-16k, temperature0) chain prompt | primary_model.with_fallbacks([fallback_model])6. 生产环境最佳实践在将函数调用系统部署到生产环境时以下经验值得注意错误处理矩阵错误类型处理策略用户反馈示例API超时重试2次正在获取最新数据请稍候...无效位置请求澄清您能确认一下城市名称吗无权限记录日志当前服务不可用已通知管理员监控指标函数调用准确率API响应时间P99用户查询意图分布错误类型统计安全考虑对所有API调用实施速率限制敏感参数过滤如SQL注入防护用户查询日志脱敏存储def sanitize_input(user_input: str): 基础输入清洗 import re return re.sub(r[^\w\s\u4e00-\u9fa5], , user_input)[:200]通过本文的深度技术解析和实战演示您已经掌握了使用LangChain构建智能函数调用系统的核心方法。从基础的单函数对接到复杂的多函数调度再到生产级的优化策略这套方案能够灵活适应各种业务场景需求。