LLM开发实战:如何用Function Calling快速实现天气查询API(附Python代码)

发布时间:2026/5/19 18:02:23

LLM开发实战:如何用Function Calling快速实现天气查询API(附Python代码) LLM开发实战如何用Function Calling快速实现天气查询API附Python代码最近在开发一个智能助手项目时遇到了一个典型需求让大语言模型能够查询实时天气。传统方法需要复杂的提示词工程和结果解析而OpenAI的Function Calling功能完美解决了这个问题。本文将分享如何从零开始用不到100行Python代码实现这个功能。1. 理解Function Calling的核心机制Function Calling本质上是大语言模型与外部世界交互的桥梁。当模型识别到用户需要执行某个特定操作如查询天气、发送邮件等时它会生成一个结构化请求而不是普通的文本回复。这个请求包含了调用哪个函数、传递什么参数等信息。与传统的API调用相比Function Calling有几个显著优势自然语言转结构化请求用户可以用上海明天天气怎么样这样的自然语言触发精确的API调用错误处理更智能模型可以理解API返回的错误信息并决定重试或调整参数多步骤操作简化模型可以自动组合多个函数调用完成复杂任务# 一个典型的Function Calling请求示例 { name: get_current_weather, arguments: {location:上海,unit:celsius} }2. 开发环境准备在开始编码前需要确保开发环境满足以下要求Python 3.8OpenAI Python包1.0以上版本一个可用的OpenAI API密钥安装依赖非常简单pip install openai python-dotenv建议将API密钥存储在环境变量中通过.env文件管理# .env文件内容 OPENAI_API_KEY你的API密钥3. 定义天气查询函数核心是创建一个符合OpenAI Function Calling规范的函数描述。这个描述会告诉模型什么时候该调用这个函数、需要哪些参数、参数的类型是什么。def get_current_weather(location, unitcelsius): 模拟获取当前天气的函数 Args: location (str): 城市名称如上海 unit (str): 温度单位celsius或fahrenheit Returns: dict: 包含天气信息的字典 # 这里应该是实际调用天气API的代码 # 为演示使用模拟数据 weather_data { location: location, temperature: 25, unit: unit, forecast: [晴朗, 微风], humidity: 65% } return weather_data对应的函数描述JSON结构如下tools [ { type: function, function: { name: get_current_weather, description: 获取指定城市的当前天气, parameters: { type: object, properties: { location: { type: string, description: 城市名称如上海 }, unit: { type: string, enum: [celsius, fahrenheit], description: 温度单位 } }, required: [location] } } } ]4. 实现完整的调用流程现在我们将所有部分组合起来创建一个完整的对话流程用户输入自然语言查询模型判断是否需要调用函数执行对应的函数将结果返回给模型生成最终回复import openai import json from dotenv import load_dotenv import os load_dotenv() client openai.OpenAI(api_keyos.getenv(OPENAI_API_KEY)) def chat_completion_with_function(messages, tools): response client.chat.completions.create( modelgpt-3.5-turbo, messagesmessages, toolstools, tool_choiceauto ) return response def process_function_call(response, messages): tool_call response.choices[0].message.tool_calls[0] func_name tool_call.function.name if func_name get_current_weather: args json.loads(tool_call.function.arguments) weather_info get_current_weather(**args) messages.append({ role: tool, content: json.dumps(weather_info), tool_call_id: tool_call.id }) second_response client.chat.completions.create( modelgpt-3.5-turbo, messagesmessages ) return second_response.choices[0].message.content else: return 暂不支持该功能5. 实战测试与优化建议让我们测试几个不同的查询# 测试用例1 messages [{role: user, content: 上海现在的天气怎么样}] response chat_completion_with_function(messages, tools) if response.choices[0].message.tool_calls: print(process_function_call(response, messages)) else: print(response.choices[0].message.content) # 测试用例2 messages [{role: user, content: 比较北京和广州的天气}] response chat_completion_with_function(messages, tools) if response.choices[0].message.tool_calls: print(process_function_call(response, messages)) else: print(response.choices[0].message.content)在实际项目中有几个优化方向值得考虑错误处理增加API调用失败的重试机制结果缓存对相同参数的查询结果进行缓存多函数组合支持模型自动组合多个函数调用参数验证在函数执行前验证参数有效性6. 进阶连接真实天气API上面的示例使用了模拟数据要连接真实天气服务也很简单。以和风天气API为例import requests def get_real_weather(location, unitcelsius): # 这里替换为实际的API密钥和端点 url fhttps://api.weather.com/v3/... params { location: location, key: 你的API密钥, unit: unit } response requests.get(url, paramsparams) if response.status_code 200: return response.json() else: return {error: 获取天气信息失败}7. 性能优化与监控在生产环境中使用时建议添加以下监控指标指标名称说明监控频率调用成功率成功完成函数调用的比例每分钟平均响应时间从用户提问到获得最终回复的时间每分钟函数调用次数各函数被调用的频率统计每小时错误类型分布各类错误的发生频率每天实现这些监控只需在关键节点添加日志记录import time from datetime import datetime def log_function_call(func_name, duration, successTrue): timestamp datetime.now().isoformat() log_entry { timestamp: timestamp, function: func_name, duration: duration, success: success } # 这里可以写入数据库或日志文件 print(f[LOG] {log_entry})8. 安全最佳实践处理外部API调用时安全性不容忽视参数过滤对所有传入参数进行严格验证速率限制防止API被过度调用敏感信息不要在返回结果中暴露API密钥等敏感信息错误处理不要让原始错误信息直接返回给用户def safe_get_weather(location, unitcelsius): # 验证location只包含中英文和空格 if not re.match(r^[\u4e00-\u9fa5a-zA-Z\s]$, location): return {error: 无效的地理位置} try: start_time time.time() result get_real_weather(location, unit) duration time.time() - start_time log_function_call(get_weather, duration, error not in result) if error in result: return {error: 获取天气信息失败} return result except Exception as e: log_function_call(get_weather, 0, False) return {error: 服务暂时不可用}在实际项目中Function Calling极大地简化了LLM与外部系统的集成。从最初的概念验证到生产部署我们团队仅用两天时间就实现了天气、股票、航班查询等多个功能的集成。最令人惊喜的是模型能够智能地处理用户的各种表达方式甚至能自动纠正一些常见的参数错误。

相关新闻