用LangChain给ChatGPT装插件:从天气查询到智能家居的功能扩展指南

张开发
2026/4/13 17:30:50 15 分钟阅读

分享文章

用LangChain给ChatGPT装插件:从天气查询到智能家居的功能扩展指南
用LangChain构建AI功能扩展从天气查询到智能家居的实战指南当AI助手不再局限于对话而是能主动查询天气、控制家电、管理日程时用户体验将发生质的飞跃。LangChain作为当前最流行的AI功能扩展框架为开发者提供了将大语言模型与真实世界连接的能力。本文将带你从零开始通过两个渐进式案例掌握LangChain的核心技术栈。1. 为什么需要功能扩展传统的大语言模型如ChatGPT本质上是一个基于统计概率的文本生成器。它无法实时获取外部信息也无法直接操作系统或设备。这就导致了几个典型痛点信息滞后性无法回答训练数据之外的最新信息如实时天气操作局限性不能执行实际动作如开关灯光数据隔离性难以接入私有数据库或业务系统通过LangChain的函数调用(Function Calling)机制我们可以为AI助手赋予手脚和感官。以下是三种典型应用场景对比场景类型代表需求技术实现复杂度信息查询天气/股价/航班API调用★★☆系统控制智能家居/IT运维设备SDK★★★业务流程订单查询/CRM私有API★★★★2. 开发环境准备2.1 基础工具链配置推荐使用Python 3.9环境并安装以下核心库pip install langchain-openai python-dotenv requests创建.env文件存储敏感信息OPENAI_API_KEYsk-your_key_here OPENAI_BASE_URLhttps://api.your_proxy.com/v12.2 两种开发模式对比LangChain支持两种主要的功能扩展方式直接函数调用适合简单场景需手动处理交互流程Agent代理模式自动选择工具适合复杂任务链from langchain_openai import ChatOpenAI from langchain.agents import initialize_agent # 直接调用示例 llm ChatOpenAI(modelgpt-3.5-turbo) # Agent模式示例 tools [...] # 工具列表 agent initialize_agent(tools, llm, agentzero-shot-react-description)3. 天气查询功能实战3.1 对接气象API我们使用和风天气API作为数据源首先封装请求函数import requests from datetime import datetime def get_weather(location: str) - str: params { location: location, key: YOUR_API_KEY, lang: zh, unit: m } resp requests.get(https://api.qweather.com/v7/weather/now, paramsparams) data resp.json() return f{location}当前天气{data[now][text]}温度{data[now][temp]}℃3.2 注册LangChain工具将函数包装成LangChain可识别的工具from langchain.tools import tool tool def weather_tool(location: str) - str: 查询指定城市的实时天气输入应为城市名称 return get_weather(location)3.3 构建对话链创建能自动调用天气工具的对话系统from langchain.agents import AgentExecutor tools [weather_tool] agent AgentExecutor.from_agent_and_tools( agentchat-conversational-react-description, toolstools, llmllm, verboseTrue ) response agent.run(上海现在天气如何) print(response) # 输出上海当前天气晴温度28℃提示实际部署时应添加错误处理如API限流、城市不存在等情况4. 智能家居控制进阶案例4.1 设备控制协议封装以小米智能家居为例通过MIoT协议控制设备import miio class SmartHomeController: def __init__(self, ip: str, token: str): self.device miio.Device(ip, token) def control_light(self, power: bool) - str: self.device.send(set_power, [on if power else off]) return f灯光已{开启 if power else 关闭}4.2 多工具协同工作创建包含多个功能的工具集controller SmartHomeController(192.168.1.100, your_token) tool def light_control(command: str) - str: 控制智能灯光支持on/off命令 return controller.control_light(command on) tool def check_time() - str: 返回当前时间信息 from datetime import datetime now datetime.now() return f当前时间{now.hour}点{now.minute}分4.3 实现条件逻辑让AI能根据条件自动触发设备控制tools [light_control, check_time] agent initialize_agent(tools, llm, agentstructured-chat-zero-shot-react-description) response agent.run(如果现在是晚上就开灯) # 可能的输出当前时间是20点30分已为您开启灯光5. 生产环境优化策略5.1 性能调优技巧缓存机制对天气API等结果添加缓存批量处理合并多个工具调用请求超时设置避免长时间等待API响应from langchain.cache import InMemoryCache from langchain.globals import set_llm_cache set_llm_cache(InMemoryCache()) # 启用简单缓存5.2 安全防护方案风险类型防护措施实现示例API滥用速率限制FastAPI中间件敏感操作二次确认工具返回确认提示数据泄露字段过滤Pydantic模型5.3 中文处理特别优化在Agent初始化时添加中文提示agent_kwargs{suffix: 请用中文回答。 prompt.SUFFIX}工具描述使用中文编写对API返回结果进行本地化处理在实际项目中我发现最实用的调试技巧是在verbose模式下观察LangChain的思考过程。当功能调用不符合预期时检查工具描述是否足够清晰准确往往能快速定位问题。

更多文章