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

相关推荐
量子位2 天前
GPT-5编程专用版发布!独立连续编程7小时,简单任务提速10倍,VS Code就能用
gpt·chatgpt
coder_pig2 天前
🤔 试试 OpenAI 的最强编程模型 "GPT-5-Codex"?
chatgpt·openai·claude
齐杰拉3 天前
源码精读:拆解 ChatGPT 打字机效果背后的数据流水线
前端·chatgpt
mit6.8244 天前
[code-review] 日志机制 | `LOG_LEVEL`
人工智能·chatgpt·代码复审
Orange_sparkle4 天前
解决Dify中接入xinference模型无法开关思考模式和使用function calling的问题
人工智能·深度学习·语言模型·chatgpt
gptplus4 天前
【重要通知】ChatGPT Plus将于9月16日调整全球充值定价,低价区将被弃用,开发者如何应对?
人工智能·gpt·chatgpt
跨境小新4 天前
ChatGPT大模型训练指南:如何借助动态代理IP提高训练效率
网络协议·tcp/ip·chatgpt
sinat_286945194 天前
Case-Based Reasoning用于RAG
人工智能·算法·chatgpt
陈敬雷-充电了么-CEO兼CTO4 天前
突破多模态极限!InstructBLIP携指令微调革新视觉语言模型,X-InstructBLIP实现跨模态推理新高度
人工智能·自然语言处理·chatgpt·blip·clip·多模态大模型·gpt-5
007tg5 天前
从ChatGPT家长控制功能看AI合规与技术应对策略
人工智能·chatgpt·企业数据安全