要在Python中使用OpenAI API并结合function_tools来获取天气情况,你可以按照以下步骤进行操作。假设你已经有了OpenAI的API密钥,并且已经安装了openai库。 1. 安装所需的库首先,确保你已经安装了openai库。如果没有安装,可以使用以下命令进行安装: pip install openai
2. 编写Python代码接下来,你可以编写一个Python脚本来调用OpenAI API,并使用function_tools来获取天气情况。
- import openai
- import requests
-
- # 设置OpenAI API密钥
- openai.api_key = 'your-openai-api-key'
-
- # 定义一个函数来获取天气情况
- def get_weather(city: str) -> str:
- """
- 获取指定城市的天气情况
- :param city: 城市名称
- :return: 天气情况描述
- """
- # 这里使用一个简单的天气API作为示例
- api_key = 'your-weather-api-key' # 你需要一个天气API的密钥
- url = f'http://api.weatherapi.com/v1/current.json?key={api_key}&q={city}'
- response = requests.get(url)
- data = response.json()
-
- if 'error' in data:
- return f"无法获取{city}的天气信息: {data['error']['message']}"
-
- weather = data['current']['condition']['text']
- temperature = data['current']['temp_c']
- return f"{city}的天气情况: {weather}, 温度: {temperature}°C"
-
- # 定义function_tools
- function_tools = [
- {
- "name": "get_weather",
- "description": "获取指定城市的天气情况",
- "parameters": {
- "type": "object",
- "properties": {
- "city": {
- "type": "string",
- "description": "城市名称"
- }
- },
- "required": ["city"]
- }
- }
- ]
-
- # 调用OpenAI API
- def chat_with_gpt(prompt):
- response = openai.ChatCompletion.create(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": prompt}],
- functions=function_tools,
- function_call="auto"
- )
-
- return response
-
- # 处理OpenAI的响应
- def handle_response(response):
- message = response['choices'][0]['message']
-
- if message.get("function_call"):
- function_name = message["function_call"]["name"]
- if function_name == "get_weather":
- city = eval(message["function_call"]["arguments"])["city"]
- return get_weather(city)
-
- return message["content"]
-
- # 示例对话
- prompt = "请问北京的天气怎么样?"
- response = chat_with_gpt(prompt)
- result = handle_response(response)
- 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的强大语言模型和自定义函数来获取实时的天气信息。
|