找回密码
 立即注册
查看: 21|回复: 0

Python中使用OpenAI API并结合function_tools来获取天气情况

[复制链接]

4

主题

0

回帖

74

积分

管理员

积分
74
发表于 昨天 18:33 | 显示全部楼层 |阅读模式
要在Python中使用OpenAI API并结合function_tools来获取天气情况,你可以按照以下步骤进行操作。假设你已经有了OpenAI的API密钥,并且已经安装了openai库。
1. 安装所需的库
首先,确保你已经安装了openai库。如果没有安装,可以使用以下命令进行安装:
pip install openai
2. 编写Python代码
接下来,你可以编写一个Python脚本来调用OpenAI API,并使用function_tools来获取天气情况。

  1. import openai
  2. import requests

  3. # 设置OpenAI API密钥
  4. openai.api_key = 'your-openai-api-key'

  5. # 定义一个函数来获取天气情况
  6. def get_weather(city: str) -> str:
  7.     """
  8.     获取指定城市的天气情况
  9.     :param city: 城市名称
  10.     :return: 天气情况描述
  11.     """
  12.     # 这里使用一个简单的天气API作为示例
  13.     api_key = 'your-weather-api-key'  # 你需要一个天气API的密钥
  14.     url = f'http://api.weatherapi.com/v1/current.json?key={api_key}&q={city}'
  15.     response = requests.get(url)
  16.     data = response.json()
  17.    
  18.     if 'error' in data:
  19.         return f"无法获取{city}的天气信息: {data['error']['message']}"
  20.    
  21.     weather = data['current']['condition']['text']
  22.     temperature = data['current']['temp_c']
  23.     return f"{city}的天气情况: {weather}, 温度: {temperature}°C"

  24. # 定义function_tools
  25. function_tools = [
  26.     {
  27.         "name": "get_weather",
  28.         "description": "获取指定城市的天气情况",
  29.         "parameters": {
  30.             "type": "object",
  31.             "properties": {
  32.                 "city": {
  33.                     "type": "string",
  34.                     "description": "城市名称"
  35.                 }
  36.             },
  37.             "required": ["city"]
  38.         }
  39.     }
  40. ]

  41. # 调用OpenAI API
  42. def chat_with_gpt(prompt):
  43.     response = openai.ChatCompletion.create(
  44.         model="gpt-3.5-turbo",
  45.         messages=[{"role": "user", "content": prompt}],
  46.         functions=function_tools,
  47.         function_call="auto"
  48.     )
  49.    
  50.     return response

  51. # 处理OpenAI的响应
  52. def handle_response(response):
  53.     message = response['choices'][0]['message']
  54.    
  55.     if message.get("function_call"):
  56.         function_name = message["function_call"]["name"]
  57.         if function_name == "get_weather":
  58.             city = eval(message["function_call"]["arguments"])["city"]
  59.             return get_weather(city)
  60.    
  61.     return message["content"]

  62. # 示例对话
  63. prompt = "请问北京的天气怎么样?"
  64. response = chat_with_gpt(prompt)
  65. result = handle_response(response)
  66. print(result)
复制代码


3. 运行代码
将上述代码保存为一个Python文件(例如weather_bot.py),然后运行它。你应该会看到类似以下的输出:
北京的天气情况: 晴, 温度: 25°C
4. 注意事项
  • 你需要替换your-openai-api-key和your-weather-api-key为你自己的API密钥。
  • 这个示例使用了weatherapi.com作为天气数据源,你可以根据需要替换为其他天气API。
  • function_tools是OpenAI API中的一个功能,允许你定义自定义函数并在对话中调用它们。

通过这种方式,你可以结合OpenAI的强大语言模型和自定义函数来获取实时的天气信息。


带着自己的梦,以一种骄傲的姿态走下去。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|混沌风论坛

GMT+8, 2025-3-14 16:06 , Processed in 0.176005 second(s), 34 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表