DeepSeek实现FunctionCalling调用API查询天气

server/2025/2/28 8:35:42/

什么是FunctionCalling

Function Calling(函数调用)是大型语言模型(如 OpenAI 的 GPT 系列)提供的一种能力,允许模型在生成文本的过程中调用外部函数或工具,以完成更复杂的任务。通过 Function Calling,模型可以将自然语言请求转换为结构化的函数调用,从而与外部系统、API 或工具进行交互。

想象你有一个智能助手(比如 GPT),它可以回答你的问题,但它本身无法直接执行某些操作,比如查询天气、发送邮件或查询数据库。这时,Function Calling 就像给这个助手提供了一组工具(函数),让它可以根据你的需求调用这些工具来完成具体任务。例如:

  • 你问助手:“今天北京的天气怎么样?”

  • 助手不会直接回答天气,而是调用一个外部的“天气查询函数”,获取天气数据后,再生成回答。

Function Calling工作流程

Function Calling指的是大模型在生成回复的过程中可以调用外部函数来处理它无法解决的问题,的实现原理如下

  1. 要使用 Function Calling我们需要先定义函数:比如预先定义一组函数(例如查询天气、发送邮件、查询数据库等),并描述这些函数的功能和输入参数。

  2. 当用户提出请求时,模型会判断是否需要调用函数。如果需要,模型会生成一个结构化的函数调用请求

  3. 执行函数:开发者编写的代码接收到函数调用请求后,执行对应的函数,模型根据函数返回的结果,生成自然语言回答给用户

在这里插入图片描述

实现天气查询助手

以下是一个简单的 Function Calling 示例,假设我们需要实现一个天气查询助手,首先找到一个天气查询的平台,我这里使用:https://www.weatherapi.com/my/,注册账号后得到一个APIkey,如下
在这里插入图片描述

然后我们需要准备一个调用天气API的函数,python 代码片段如下:(后面会有完整代码)

# 使用 WeatherAPI 的天气查询函数
def get_weather(city: str):# 使用 WeatherAPI 的 API 来获取天气信息api_key = "你的天气的APIkEY"  # 替换为你自己的 WeatherAPI APIKEYbase_url = "http://api.weatherapi.com/v1/current.json"params = {'key': api_key,'q': 'Beijing','aqi': 'no'  # 不需要空气质量数据}# 调用天气 APIresponse = requests.get(base_url, params=params)if response.status_code == 200:data = response.json()#拿到天气和温度weather = data['current']['condition']['text']temperature = data['current']['temp_c']return f"城市 {city} 天气是 {weather} 温度为 {temperature}°C."else:return f"无法检索 {city} 的天气信息 ."

然后我们定义 tools ,大模型通过tools来调用天气函数:(后面会有完整代码)

# 定义 OpenAI 的 function calling tools
tools = [{'type': 'function','function': {'name': 'get_weather','description': 'Get the current weather for a given city.','parameters': {'type': 'object','properties': {'city': {'type': 'string','description': 'The name of the city to query weather for.',},},'required': ['city'],},}}
]

接着我们调用大模型,并指定 tools 属性,如下

def function_call_playground(prompt):messages = [{'role': 'user', 'content': prompt}]# 发送请求到 OpenAI APIresponse = client.chat.completions.create(model="deepseek-ai/DeepSeek-V2.5",messages=messages,temperature=0.01,top_p=0.95,stream=False,# 默认值,由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数,详见官方文档tool_choice="auto",tools=tools #指定 function calling tools)

完整代码如下:

import requests
from openai import OpenAI
#这里使用的是硅基流动的API接口
client = OpenAI(api_key="硅基流动的apikey", # 从https://cloud.siliconflow.cn/account/ak获取base_url="https://api.siliconflow.cn/v1"
)# 使用 WeatherAPI 的天气查询函数
def get_weather(city: str):# 使用 WeatherAPI 的 API 来获取天气信息api_key = "天气的APIkey"  # 替换为你自己的 WeatherAPI APIKEYbase_url = "http://api.weatherapi.com/v1/current.json"params = {'key': api_key,'q': 'Beijing','aqi': 'no'  # 不需要空气质量数据}# 调用天气 APIresponse = requests.get(base_url, params=params)if response.status_code == 200:data = response.json()#拿到天气和温度weather = data['current']['condition']['text']temperature = data['current']['temp_c']return f"城市 {city} 天气是 {weather} 温度为 {temperature}°C."else:return f"无法检索 {city} 的天气信息 ."# 定义 OpenAI 的 function calling tools
tools = [{'type': 'function','function': {'name': 'get_weather','description': 'Get the current weather for a given city.','parameters': {'type': 'object','properties': {'city': {'type': 'string','description': 'The name of the city to query weather for.',},},'required': ['city'],},}}
]# 发送请求并处理 function calling
def function_call_playground(prompt):messages = [{'role': 'user', 'content': prompt}]# 发送请求到 OpenAI APIresponse = client.chat.completions.create(model="deepseek-ai/DeepSeek-V2.5",messages=messages,temperature=0.01,top_p=0.95,stream=False,# 默认值,由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数,详见官方文档tool_choice="auto",tools=tools)# 处理 API 返回的工具调用请求func1_name = response.choices[0].message.tool_calls[0].function.namefunc1_args = response.choices[0].message.tool_calls[0].function.argumentsfunc1_out = eval(f'{func1_name}(**{func1_args})')# 将结果添加到对话中并返回messages.append({'role': 'tool','content': f'{func1_out}','tool_call_id': response.choices[0].message.tool_calls[0].id})return messages# 示例使用
prompt = "how is the weather today in chegndu?"print(function_call_playground(prompt))

执行效果如下:
在这里插入图片描述

实现附近地图搜索

通过FunctionCalling调用百度地图进行附近搜索,和上面的思路一样,下面贴一下代码

import requests
from openai import OpenAIclient = OpenAI(api_key="你的key", # 从https://cloud.siliconflow.cn/account/ak获取base_url="https://api.siliconflow.cn/v1"
)# 使用 百度地图查询
def doQuery(keyword: str):api_key = "你的百度地图的key"  # 替换为你自己的APIKEYbase_url = "https://api.map.baidu.com/place/v2/search"params = {'ak': api_key,'query': keyword,'radius': 2000,'output': "json",'location': '30.538031,104.061420'  # 以成都为中心点}# 调用APIresponse = requests.get(base_url, params=params)if response.status_code == 200:data = response.json()return dataelse:return f"无法检索 {keyword} 信息."# 定义 OpenAI 的 function calling tools
tools = [{'type': 'function','function': {'name': 'doQuery','description': 'Search for nearby restaurants based on the given keyword','parameters': {'type': 'object','properties': {'keyword': {'type': 'string','description': 'The name of the keyword to query for near.',},},'required': ['keyword'],},}}
]# 发送请求并处理 function calling
def function_call_playground(prompt):messages = [{'role': 'user', 'content': prompt}]# 发送请求到 OpenAI APIresponse = client.chat.completions.create(model="deepseek-ai/DeepSeek-V2.5",messages=messages,temperature=0.01,top_p=0.95,stream=False,# 默认值,由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数,详见官方文档tool_choice="auto",tools=tools)# 处理 API 返回的工具调用请求func1_name = response.choices[0].message.tool_calls[0].function.namefunc1_args = response.choices[0].message.tool_calls[0].function.argumentsfunc1_out = eval(f'{func1_name}(**{func1_args})')# 将结果添加到对话中并返回messages.append({'role': 'tool','content': f'{func1_out}','tool_call_id': response.choices[0].message.tool_calls[0].id})return messages# 示例使用
prompt = "附近有哪些:饭店"print(function_call_playground(prompt))

文章就写到这,喜欢请给个好评!!!


http://www.ppmy.cn/server/171255.html

相关文章

机器学习数学基础:33.肯德尔和谐系数教程

肯德尔和谐系数教程 一、定义与用途 肯德尔和谐系数(Kendall’s W)是一种用于衡量多个评价者对一组对象进行评价时,评价结果一致性程度的统计量。它的取值范围在0到1之间。当W \ 0时,表示评价者之间的评价完全不一致&#xff1…

从零到一:如何用阿里云百炼和火山引擎搭建专属 AI 助手(DeepSeek)?

本文首发:从零到一:如何用阿里云百炼和火山引擎搭建专属 AI 助手(DeepSeek)? 阿里云百炼和火山引擎都推出了免费的 DeepSeek 模型体验额度,今天我和大家一起搭建一个本地的专属 AI 助手。  阿里云百炼为 …

idea 编码设置

新项目 File -> New Projects Setup -> Settings for New Projects… 当前项目 File -> Settings -> Editor-> File Encodings 设置同上即可。

springboot413-基于Java高校科技创新项目评审系统的设计与实现(源码+数据库+纯前后端分离+部署讲解等)

💕💕作者: 爱笑学姐 💕💕个人简介:十年Java,Python美女程序员一枚,精通计算机专业前后端各类框架。 💕💕各类成品Java毕设 。javaweb,ssm&#xf…

【Mastering Vim 2_08】第七章:Vim 的个性化配置

【最新版《Mastering Vim》封面,涵盖 Vim 9.0 版特性】 文章目录 第七章 Vim 的个性化配置1 升级到最新版 pip2 定制配色方案2.1 配色方案 PaperColor 实战演练 3 美化并增强 Vim 状态栏4 gVim 的个性化定制5 实战:vimrc 配置文件的同步6 Vim 个性化定制…

从实测看声网:用技术重构直播,为电商创业赋能

我实际测试了搭载声网对话式AI引擎的直播间功能,AI不仅能根据观众星座推荐商品,还会在用户长时间停留时启动AR试穿——这种读心级的交互,能让客单价快速提升。 声网还有全球首个软件定义实时网SD-RTN™,可实现跨国直播600ms超低延…

pta天梯L1-004 计算摄氏温度

L1-004 计算摄氏温度 - 团体程序设计天梯赛-练习集 import sys input lambda: sys.stdin.readline().strip() def slove():F int(input())a Celsius ans 5 * (F - 32) / 9ans int(ans)a str(ans)print(a) slove()

PHP如何与HTML结合使用?

PHP与HTML结合使用的主要方式是通过在HTML文件中嵌入PHP代码&#xff0c;从而实现动态内容的生成和网页的交互性。以下是详细的方法和最佳实践&#xff1a; 1. 嵌入PHP代码到HTML中 PHP代码可以直接嵌入到HTML文件中&#xff0c;通过<?php ?>标签来包裹PHP代码。服务…