利用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

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

最近更新

  1. TCP协议是安全的吗?

    2023-12-31 17:36:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-31 17:36:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-31 17:36:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-31 17:36:01       20 阅读

热门阅读

  1. 速盾网络:cdn数量对网站访问速度的影响

    2023-12-31 17:36:01       41 阅读
  2. 2023年广东省网络安全B模块(笔记详解)

    2023-12-31 17:36:01       28 阅读
  3. 使用Python绘制各种图表

    2023-12-31 17:36:01       43 阅读
  4. python随机生成数字random模块

    2023-12-31 17:36:01       44 阅读
  5. 成立一个理解起来很直观的 cpu cmodel 项目

    2023-12-31 17:36:01       39 阅读
  6. 计算机硬件 4.3显示器

    2023-12-31 17:36:01       29 阅读
  7. 编程笔记 html5&css&js 016 HTML表格

    2023-12-31 17:36:01       34 阅读
  8. 2023.12.27力扣每日一题——保龄球游戏的获胜者

    2023-12-31 17:36:01       42 阅读
  9. SystemVerilog:always_ff,always_comb,always_latch

    2023-12-31 17:36:01       32 阅读