利用chatGPT的function calling 调用高德的接口获取天气信息

python 复制代码
import openai
import os
import json
import requests

from openai import OpenAI
client = OpenAI(
    api_key = os.getenv("OPENAI_API_KEY"),
)

def get_weather(city, date):
    base_url = "https://restapi.amap.com/v3/weather/weatherInfo"
    api_key =  os.getenv("AMAP_API_KEY") # 高德API的API-KEY从环境变量获取
    params = {
        'key': api_key,
        'city': city,
        'extensions': 'base',  # 可根据需求选择 'base' 或 'all'
        'output': 'json',
        'date': date  # 指定日期,格式如:2023-01-01
    }
    
    try:
        response = requests.get(base_url, params=params)
        data = response.json()
        # print(data) 
        if data['status'] == '1':
            weather_info = data['lives'][0]  # 如果选择了 'base' 扩展,使用 'lives';选择 'all' 扩展,使用 'forecasts'
            # print(f"城市: {weather_info['city']}")
            # print(f"日期: {date}")
            # print(f"天气: {weather_info['weather']}")
            # print(f"温度: {weather_info['temperature']} ℃")
            # print(f"风力: {weather_info['windpower']} 级")
            rlt = json.dumps(weather_info)
            print(rlt)
            return rlt
        else:
            print("查询天气信息失败,错误码:" + data['infocode'])
    except Exception as e:
        print("查询天气信息时发生错误:" + str(e))


tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "查询指定城市,指定日期的天气情况",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "要查询的城市名称,如:北京",
                        },
                        # "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                        "date": {
                            "type": "string",
                            "description": "要查询的日期,示例:2023-11-23", 
                        }
                    },
                    "required": ["city", "date"],
                },
            },
        }
    ]

## 我们需要将用户的输入一并传递给OpenAI,以便从中提取函数调用所需要的参数。
messages = [
            {
                "role": "user", 
                "content": "北京12月27号天气怎么样"
            }
        ]

### 第一次调用 Chat Completions API, 提取参数
response = client.chat.completions.create(
        model="gpt-3.5-turbo-1106",
        messages=messages,
        tools=tools,
        tool_choice="auto",  # auto is default, but we'll be explicit
    )


response_message = response.choices[0].message
tool_calls = response_message.tool_calls # 包含了函数调用所需要的信息



if tool_calls:
        tool_call = tool_calls[0]
        # 大模型根据问题,传入的函数说明,拆分出调用函数的需要的两个参数
        function_args = json.loads(tool_call.function.arguments)
        # 将大模型传出的两个参数给到自己的函数,获取返回值
        function_response = get_weather(
            city=function_args.get("city"),
            date=function_args.get("date"),
        )
        # 打印返回值
        function_response

        function_name = tool_call.function.name
        messages.append(
            {
                "tool_call_id": tool_call.id,
                "role": "assistant",
                "name": function_name,
                "content": function_response,
            }
        )  # extend conversation with function response

        #再次调用模型,将message对象给大模型
        second_response = client.chat.completions.create(
            model="gpt-3.5-turbo-1106",
            messages=messages,
        )  # get a new response from the model where it can see the function response
   
 
复制代码
# 打印返回值
function_response

{"province": "\u5317\u4eac", "city": "\u5317\u4eac\u5e02", "adcode": "110000", "weather": "\u6674", "temperature": "2", "winddirection": "\u5357", "windpower": "\u22643", "humidity": "43", "reporttime": "2023-12-27 15:09:13", "temperature_float": "2.0", "humidity_float": "43.0"}

second_response

复制代码
ChatCompletion(id='chatcmpl-8adUanEwuGsYBi5XNGb6kasUJEIjm', choices=[Choice(finish_reason='stop', index=0, message=ChatCompletionMessage(content='北京12月27号的天气是晴天,气温大约4摄氏度,西南风,风力小于3级,湿度44%。', role='assistant', function_call=None, tool_calls=None), logprobs=None)], created=1703742308, model='gpt-3.5-turbo-1106', object='chat.completion', system_fingerprint='fp_772e8125bb', usage=CompletionUsage(completion_tokens=46, prompt_tokens=138, total_tokens=184))

os.getenv("OPENAI_API_KEY"), # OPENAI的API-KEY设置到自己电脑的环境变量中,通过这行代码获取

os.getenv("AMAP_API_KEY") # 高德API的API-KEY设置到自己电脑的环境变量中,通过这行代码获取

相关推荐
集成显卡4 小时前
AI探索 | 豆包智能助手跟扣子空间(AI办公助手)有什么区别
人工智能·chatgpt·agent·智能助理
Jet45054 小时前
第100+43步 ChatGPT学习:R语言实现特征选择曲线图
学习·chatgpt·r语言
小马过河R9 小时前
Prompt提示词的主要类型和核心原则
人工智能·chatgpt·prompt
陈敬雷-充电了么-CEO兼CTO1 天前
主流大模型Agent框架 AutoGPT详解
人工智能·python·gpt·ai·chatgpt·nlp·aigc
代码能跑就行管它可读性2 天前
【论文复现】利用生成式AI进行选股和分配权重
人工智能·chatgpt
前端小盆友2 天前
从零实现一个GPT 【React + Express】--- 【4】实现文生图的功能
react.js·chatgpt·express
czkm2 天前
苹果🍎的奇幻漂流,当你提问后,ChatGPT在“想”什么?
chatgpt·llm
陈敬雷-充电了么-CEO兼CTO2 天前
复杂任务攻坚:多模态大模型推理技术从 CoT 数据到 RL 优化的突破之路
人工智能·python·神经网络·自然语言处理·chatgpt·aigc·智能体
G皮T3 天前
【人工智能】ChatGPT、DeepSeek-R1、DeepSeek-V3 辨析
人工智能·chatgpt·llm·大语言模型·deepseek·deepseek-v3·deepseek-r1
坤坤爱学习2.04 天前
求医十年,病因不明,ChatGPT:你看起来有基因突变
人工智能·ai·chatgpt·程序员·大模型·ai编程·大模型学