基于deepseek api和openweather 天气API实现Function Calling技术讲解

news/2025/2/21 1:50:16/
aidu_pl">

以下是一个结合DeepSeek API和OpenWeather API的完整Function Calling示例,包含意图识别、API调用和结果整合:

import requests
import json
import os# 配置API密钥(从环境变量获取)
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")# Function Definitions (JSON Schema格式)
functions = [{"name": "get_current_weather","description": "获取指定城市的当前天气信息","parameters": {"type": "object","properties": {"location": {"type": "string","description": "城市名称,如:'北京' 或 'London'"},"unit": {"type": "string","enum": ["celsius", "fahrenheit"],"description": "温度单位"}},"required": ["location"]}},{"name": "ask_deepseek","description": "回答通用问题,涉及知识查询、建议、解释概念等","parameters": {"type": "object","properties": {"question": {"type": "string","description": "用户提出的问题或请求"}},"required": ["question"]}}
]def call_function(function_name, arguments):"""路由函数调用到具体实现"""if function_name == "get_current_weather":return get_current_weather(location=arguments.get("location"),unit=arguments.get("unit", "celsius"))elif function_name == "ask_deepseek":return ask_deepseek(question=arguments.get("question"))else:return "未找到对应功能"# OpenWeather API实现
def get_current_weather(location, unit="celsius"):try:url = "https://api.openweathermap.org/data/2.5/weather"params = {"q": location,"appid": OPENWEATHER_API_KEY,"units": "metric" if unit == "celsius" else "imperial"}response = requests.get(url, params=params)data = response.json()if response.status_code == 200:weather_info = {"location": data["name"],"temperature": data["main"]["temp"],"unit": "°C" if unit == "celsius" else "°F","description": data["weather"][0]["description"],"humidity": f"{data['main']['humidity']}%","wind_speed": f"{data['wind']['speed']} m/s"}return json.dumps(weather_info)else:return f"获取天气信息失败:{data.get('message', '未知错误')}"except Exception as e:return f"天气API调用异常:{str(e)}"# DeepSeek API实现
def ask_deepseek(question):try:url = "https://api.deepseek.com/v1/chat/completions"headers = {"Content-Type": "application/json","Authorization": f"Bearer {DEEPSEEK_API_KEY}"}payload = {"model": "deepseek-chat","messages": [{"role": "user","content": question}],"temperature": 0.7}response = requests.post(url, headers=headers, json=payload)data = response.json()if response.status_code == 200:return data["choices"][0]["message"]["content"]else:return f"DeepSeek API错误:{data.get('error', {}).get('message', '未知错误')}"except Exception as e:return f"DeepSeek API调用异常:{str(e)}"def process_query(user_query):"""处理用户查询的主函数"""# 这里应该接入LLM进行意图识别,以下是模拟实现if "天气" in user_query or "气温" in user_query:return call_function("get_current_weather", {"location": user_query.replace("天气", "").strip(),"unit": "celsius"})else:return call_function("ask_deepseek", {"question": user_query})# 使用示例
if __name__ == "__main__":queries = ["北京现在的天气怎么样?","请解释量子计算的基本原理","上海今天的温度","如何学习机器学习?"]for query in queries:print(f"用户问:{query}")response = process_query(query)# 尝试解析JSON响应(适用于天气API)try:weather_data = json.loads(response)print("天气信息:")print(f"城市:{weather_data['location']}")print(f"温度:{weather_data['temperature']}{weather_data['unit']}")print(f"天气状况:{weather_data['description']}")print(f"湿度:{weather_data['humidity']}")print(f"风速:{weather_data['wind_speed']}\n")except:print(f"回答:{response}\n")

关键要素说明:

  1. 功能定义
  • get_current_weather:使用OpenWeather API获取实时天气数据
  • ask_deepseek:调用DeepSeek API回答通用问题
  1. 处理流程
  • 用户输入 -> 意图识别 -> 路由到对应API -> 格式化响应
  1. 增强点建议
# 可以添加的改进功能:
# 1. 更智能的意图识别(使用LLM判断)
def detect_intent(query):"""使用LLM进行意图识别"""prompt = f"""判断用户意图并返回JSON:{{"function": "get_current_weather" | "ask_deepseek","parameters": {{...}}}}示例:输入:北京天气怎么样?输出:{{"function": "get_current_weather", "parameters": {{"location": "北京"}}}}当前输入:{query}"""# 调用DeepSeek API进行意图分析response = ask_deepseek(prompt)return json.loads(response)# 2. 添加单位自动转换
def convert_temperature(temp, from_unit, to_unit):if from_unit == to_unit:return tempif from_unit == "celsius" and to_unit == "fahrenheit":return (temp * 9/5) + 32else:return (temp - 32) * 5/9# 3. 添加缓存机制
from functools import lru_cache@lru_cache(maxsize=100)
def cached_weather(location, unit):return get_current_weather(location, unit)

部署注意事项:

  1. 将API密钥存储在环境变量中
  2. 添加错误处理和重试机制
  3. 添加API调用速率限制
  4. 对用户输入进行消毒处理
  5. 添加日志记录系统

这个实现展示了:

  • REST API调用
  • JSON数据处理
  • 基本的函数路由
  • 错误处理机制
  • 可扩展的架构设计

可以根据具体需求添加更多功能,例如:

  • 多城市天气对比
  • 天气预测集成
  • 多步推理(例如结合天气数据和旅行建议)
  • 对话历史管理

http://www.ppmy.cn/news/1573778.html

相关文章

PyTorch与TensorFlow的对比:哪个框架更适合你的项目?

在机器学习和深度学习领域,PyTorch 和 TensorFlow 是最流行的两个框架。它们各有特点,适用于不同的开发需求和场景。本文将详细对比这两个框架,帮助你根据项目需求选择最合适的工具。 一、概述 PyTorch 和 TensorFlow 都是深度学习框架&…

git如何打patch

在 Git 中&#xff0c;生成和应用补丁是共享代码更改和进行代码审查的重要操作。以下是详细的步骤&#xff1a; 生成补丁 1. 生成单个提交的补丁 要为特定的提交生成补丁&#xff0c;可以使用以下命令&#xff1a; git format-patch -1 <commit-hash><commit-hash…

Soft Actor-Critic (SAC)算法

Soft Actor-Critic (SAC)算法 Kullback-Leibler Divergence (KL divergence) 定义 假设对随机变量 ξ \xi ξ&#xff0c;存在两个概率分布 P , Q P, Q P,Q。如果 ξ \xi ξ 为离散随机变量&#xff0c;定义从 P P P 到 Q Q Q 的KL散度为: D KL ( P ∣ ∣ Q ) ∑ i P …

网络安全非对称发展 网络安全 非传统安全

&#x1f345; 点击文末小卡片 &#xff0c;免费获取网络安全全套资料&#xff0c;资料在手&#xff0c;涨薪更快 的概 念&#xff0c;有很多不同的定义。在一些场合中&#xff0c;我们最多的考虑的还是网络的技术安全&#xff0c;但是技术延伸出来的安全又会涉及到社会安全、文…

DeepSeek 引领AI 大模型时代,服务器产业如何破局进化?

2025 年 1 月&#xff0c;DeepSeek - R1 以逼近 OpenAI o1 的性能表现&#xff0c;在业界引起轰动。其采用的混合专家架构&#xff08;MoE&#xff09;与 FP8 低精度训练技术&#xff0c;将单次训练成本大幅压缩至 557 万美元&#xff0c;比行业平均水平降低 80%。这一成果不仅…

无人机避障——感知篇(采用Livox-Mid360激光雷达获取点云数据显示)

电脑配置&#xff1a;Xavier-nx、ubuntu 18.04、ros melodic 激光雷达&#xff1a;Livox_Mid-360 1、安装激光雷达驱动 下载安装Livox-SDK2 如果git clone不了&#xff0c;在github上下载相应的zip进行手动安装&#xff0c;安装网址如下&#xff1a; https://github.com/L…

探索低空,旅游景区无人机应用技术详解

在低空领域&#xff0c;无人机技术在旅游景区中的应用已经日益广泛&#xff0c;为旅游业带来了前所未有的变革。以下是对旅游景区无人机应用技术的详细解析&#xff1a; 一、无人机景区巡检系统 1. 高清拍摄与实时监控&#xff1a;无人机搭载高清摄像头&#xff0c;能够对景区…

计算机学习建议

对于现代得计算机开发者而言&#xff1b;最快的是要见到成效&#xff1b;这是一个功利性的社会&#xff1b;对于99%的人来说&#xff0c;先保证自己可以在社会上活下去才是最重要的&#xff1b;而不是追求梦想&#xff1b; 一、职业 Web前端&#xff1a;HTML、CSS、JavaScrip…