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

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
   
 
获取返回的内容
{"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"}

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

你可能感兴趣的:(chatgpt)