DeepSeek Function Calling实战:5分钟搞定天气查询机器人(附完整代码)
DeepSeek Function Calling实战5分钟构建智能天气助手最近在开发一个智能客服系统时发现用户最常问的就是天气信息。传统做法需要手动解析用户意图再调用天气API整个过程既繁琐又容易出错。直到尝试了DeepSeek的Function Calling功能才发现原来可以如此优雅地解决这个问题。1. 环境准备与快速配置在开始之前确保你的开发环境满足以下基本要求Python 3.8有效的DeepSeek API密钥可在官网申请稳定的网络连接安装必要的依赖只需一行命令pip install openai requests python-dotenv我习惯使用.env文件管理敏感信息创建一个.env文件并填入你的API密钥DEEPSEEK_API_KEYyour_api_key_here提示永远不要将API密钥直接硬编码在代码中这是最基本的安全实践2. 天气API的选择与封装市面上有许多天气数据提供商经过对比测试我最终选择了和风天气API因为它提供免费的开发者套餐且响应速度快。首先需要注册获取API Key然后我们可以封装一个简单的天气查询函数import requests from typing import Dict, Any def get_weather(location: str) - Dict[str, Any]: 获取指定城市的天气信息 :param location: 城市名称如北京 :return: 包含天气信息的字典 base_url https://devapi.qweather.com/v7/weather/now params { location: location, key: 你的和风天气API_KEY, lang: zh, unit: m } try: response requests.get(base_url, paramsparams) response.raise_for_status() data response.json() if data[code] 200: return { temperature: data[now][temp], conditions: data[now][text], wind: f{data[now][windDir]} {data[now][windScale]}级, humidity: f{data[now][humidity]}% } else: return {error: f天气查询失败: {data[message]}} except Exception as e: return {error: fAPI请求异常: {str(e)}}这个函数做了几件事构造请求URL和参数发送HTTP请求并处理响应提取关键天气信息并格式化返回包含基本的错误处理3. 配置DeepSeek Function Calling要让DeepSeek知道何时调用我们的天气函数需要按照特定格式描述这个函数weather_function { type: function, function: { name: get_weather, description: 获取指定城市的当前天气情况包括温度、天气状况、风速和湿度, parameters: { type: object, properties: { location: { type: string, description: 城市名称如北京、上海 } }, required: [location] } } }几个关键点name必须与实际函数名一致description要清晰说明函数用途这直接影响AI是否调用它parameters定义了函数需要的参数及其类型4. 完整实现与交互逻辑现在我们可以将这些部分组合起来创建一个完整的天气查询机器人from openai import OpenAI import os from dotenv import load_dotenv load_dotenv() # 加载环境变量 client OpenAI( api_keyos.getenv(DEEPSEEK_API_KEY), base_urlhttps://api.deepseek.com/ ) def chat_with_weather(query: str) - str: messages [{role: user, content: query}] response client.chat.completions.create( modeldeepseek-chat, messagesmessages, tools[weather_function], tool_choiceauto ) response_message response.choices[0].message if response_message.tool_calls: function_name response_message.tool_calls[0].function.name if function_name get_weather: import json arguments json.loads(response_message.tool_calls[0].function.arguments) weather_data get_weather(arguments[location]) if error in weather_data: return f获取天气信息失败: {weather_data[error]} return (f{arguments[location]}当前天气:\n f- 温度: {weather_data[temperature]}℃\n f- 天气状况: {weather_data[conditions]}\n f- 风力: {weather_data[wind]}\n f- 湿度: {weather_data[humidity]}) return response_message.content or 未能获取有效响应这个实现有几个值得注意的细节使用tool_choiceauto让DeepSeek自行决定是否需要调用函数处理了API调用可能出现的各种错误情况对天气数据进行了人性化的格式化输出5. 实际应用与效果测试让我们测试几个典型场景print(chat_with_weather(北京现在天气怎么样)) # 输出示例 # 北京当前天气: # - 温度: 25℃ # - 天气状况: 晴 # - 风力: 东南风 2级 # - 湿度: 45% print(chat_with_weather(上海和北京的天气对比)) # DeepSeek会智能地分别查询两个城市的天气并对比 print(chat_with_weather(明天会下雨吗)) # 由于我们只实现了实时天气查询DeepSeek会回答它无法预测未来天气在实际项目中我发现几个优化点添加城市名称的模糊匹配处理用户输入帝都对应到北京等情况缓存天气查询结果避免频繁调用API支持更多天气数据如空气质量、紫外线指数等6. 扩展思路与进阶应用这个基础框架可以轻松扩展到其他功能领域多函数支持示例functions [ weather_function, { type: function, function: { name: get_stock_price, description: 获取指定股票的实时价格, parameters: { type: object, properties: { symbol: { type: string, description: 股票代码如AAPL } }, required: [symbol] } } } ]上下文记忆实现conversation_history [] def chat_with_context(query: str) - str: global conversation_history conversation_history.append({role: user, content: query}) response client.chat.completions.create( modeldeepseek-chat, messagesconversation_history, toolsfunctions ) # ...处理函数调用逻辑... # 将AI回复也加入历史 conversation_history.append({role: assistant, content: response}) return response错误处理增强try: response client.chat.completions.create(...) except Exception as e: return f请求DeepSeek API时出错: {str(e)} if not response.choices: return 未能获取有效响应请稍后再试7. 部署与性能优化当准备将天气机器人部署到生产环境时有几个关键考虑API调用限制DeepSeek API有速率限制天气API通常也有每日调用限额实现适当的缓存和节流机制异步处理 对于高并发场景可以使用异步IOimport asyncio async def async_get_weather(location: str): # 异步实现天气查询 pass async def async_chat_with_weather(query: str): # 异步处理整个对话流程 pass日志记录 记录所有交互用于分析和改进import logging logging.basicConfig(filenameweather_bot.log, levellogging.INFO) def log_interaction(query, response): logging.info(f用户查询: {query}) logging.info(f系统响应: {response})这个天气查询机器人的实现展示了DeepSeek Function Calling的强大之处——它让我们能够轻松地将自然语言理解与具体功能实现连接起来。在实际项目中这种技术可以大大减少传统对话系统中复杂的意图识别和槽位填充逻辑。