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

2023-12-28 16:31:38
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设置到自己电脑的环境变量中,通过这行代码获取

文章来源:https://blog.csdn.net/chunmiao3032/article/details/135265703
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。