
5分钟打造智能天气助手GPT-3.5-turbo-16k函数调用实战指南当开发者第一次接触大语言模型的函数调用能力时往往会陷入复杂的API文档和参数配置中。但事实上只需5分钟和一个简单的天气查询场景你就能掌握这项改变游戏规则的技术。本文将带你从零开始用实际代码演示如何构建一个能理解自然语言、自动调用天气API并生成友好回复的智能助手。1. 环境准备与基础配置在开始编码之前我们需要准备好开发环境。与传统的API调用不同函数调用功能需要特定版本的模型支持。以下是必要的准备工作必备工具清单OpenAI账号及API密钥从平台后台获取Python 3.7环境官方openai库版本≥0.27.0一个可用的天气API如OpenWeatherMap安装依赖只需一行命令pip install openai requests python-dotenv建议将API密钥存储在环境变量中避免硬编码在脚本里。创建.env文件OPENAI_API_KEY你的实际API密钥 WEATHER_API_KEY你的天气API密钥提示使用python-dotenv加载环境变量时确保.gitignore中添加了.env防止敏感信息泄露2. 定义天气查询函数函数调用的核心在于明确定义工具函数的结构和用途。我们需要创建一个能让模型理解的天气查询函数描述import json import requests from openai import OpenAI client OpenAI() def get_current_weather(location: str, unit: str celsius): 获取指定地区的当前天气情况 Args: location: 城市名如北京或New York unit: 温度单位celsius或fahrenheit # 这里替换为实际的天气API调用 params { q: location, units: metric if unit celsius else imperial, appid: os.getenv(WEATHER_API_KEY) } response requests.get(https://api.openweathermap.org/data/2.5/weather, paramsparams) return response.json() # 供模型识别的函数描述 weather_function { name: get_current_weather, description: 获取指定地区的当前天气信息, parameters: { type: object, properties: { location: { type: string, description: 城市及国家/地区如北京,中国 }, unit: { type: string, enum: [celsius, fahrenheit], description: 温度单位 } }, required: [location] } }这个JSON结构定义了函数的所有关键信息name: 函数标识符description: 帮助模型理解何时调用该函数parameters: 详细的参数规范包括类型、描述和约束3. 实现智能对话流程现在我们来构建完整的对话处理流程。整个过程分为三个关键阶段3.1 初始用户请求处理def chat_with_ai(user_query): response client.chat.completions.create( modelgpt-3.5-turbo-16k, messages[{role: user, content: user_query}], functions[weather_function], function_callauto, ) return response.choices[0].message当用户询问上海现在天气怎么样时模型可能返回{ role: assistant, content: null, function_call: { name: get_current_weather, arguments: {\location\:\上海,中国\} } }3.2 执行外部API调用解析模型返回的function_call并执行实际天气查询def execute_function_call(message): if message.function_call.name get_current_weather: args json.loads(message.function_call.arguments) weather_data get_current_weather(**args) return { name: get_current_weather, content: json.dumps(weather_data) } return None3.3 生成最终用户回复将API结果返回给模型进行自然语言转换def get_ai_response_with_data(user_query, function_response): messages [ {role: user, content: user_query}, { role: function, name: function_response[name], content: function_response[content] } ] response client.chat.completions.create( modelgpt-3.5-turbo-16k, messagesmessages ) return response.choices[0].message.content完整调用示例# 用户提问 query 旧金山现在的气温是多少用华氏度显示 initial_response chat_with_ai(query) # 获取函数调用参数并执行 func_args json.loads(initial_response.function_call.arguments) func_args[unit] fahrenheit # 覆盖用户指定的单位 weather_result get_current_weather(**func_args) # 生成最终回复 final_response get_ai_response_with_data( query, {name: get_current_weather, content: json.dumps(weather_result)} ) print(final_response)可能的输出 旧金山目前气温为68°F天气晴朗风速每小时5英里。4. 错误处理与优化技巧在实际应用中我们需要考虑各种边界情况和异常处理常见问题解决方案问题类型可能原因解决方案地点不明确用户输入北方这类模糊地点让模型要求用户澄清API限制天气服务调用次数超限实现缓存机制存储最近查询结果参数错误模型返回的参数格式不正确添加参数验证逻辑网络延迟第三方API响应慢设置合理超时添加重试机制增强版的错误处理示例def safe_get_weather(location, unit): try: return get_current_weather(location, unit) except requests.exceptions.RequestException as e: return {error: f天气服务暂时不可用: {str(e)}} except json.JSONDecodeError: return {error: 天气数据解析失败}对于用户体验优化可以考虑添加对话历史支持多轮交互实现本地缓存减少API调用支持更灵活的地点输入如我家附近需要结合位置服务# 对话历史保持示例 conversation_history [] def chat_with_history(user_input): global conversation_history conversation_history.append({role: user, content: user_input}) response client.chat.completions.create( modelgpt-3.5-turbo-16k, messagesconversation_history, functions[weather_function] ) message response.choices[0].message conversation_history.append(message) if hasattr(message, function_call): # 处理函数调用... pass return message注意实际项目中建议限制对话历史长度避免超出模型的上下文窗口通过这个完整的天气机器人示例我们不仅实现了基本功能还考虑了生产环境需要的健壮性和用户体验。函数调用的真正价值在于它让大语言模型成为了一个智能的决策中心能够自主判断何时以及如何调用外部工具开发者只需定义好这些工具的使用规范即可。