Created
June 24, 2023 02:58
-
-
Save Pagliacii/7eb52c5e389a9ef1c5391f65c8f633f1 to your computer and use it in GitHub Desktop.
OpenAI function call example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding=utf-8 -*- | |
import json | |
import requests | |
from loguru import logger | |
logger.remove() | |
logger.add('{time}.log') | |
key = '' | |
functions = [ | |
{ | |
"name": "weather_forecast", | |
"description": "Weather forecast for the given location", | |
"parameters": { | |
"type": "object", | |
"properties": { | |
"latitude": { | |
"type": "number", | |
"description": "Geographical WGS84 coordinate of the location", | |
}, | |
"longitude": { | |
"type": "number", | |
"description": "Geographical WGS84 coordinate of the location", | |
}, | |
"unit": { | |
"type": "string", | |
"enum": ["celsius", "fahrenheit"], | |
}, | |
"current_weather": { | |
"type": "boolean", | |
"description": "Current weather of the location", | |
}, | |
"forecast_days": { | |
"type": "integer", | |
"description": "Days of weather forecast", | |
}, | |
"timezone": { | |
"type": "string", | |
"description": ( | |
"Time zone name of the location. " | |
"Any time zone name from the time zone database is suuported" | |
), | |
}, | |
}, | |
"required": ["latitude", "longitude", "timezone"], | |
}, | |
}, | |
] | |
def send_to_openai(data): | |
url = 'https://api.openai.com/v1/chat/completions' | |
headers = {'Content-Type': 'application/json'} | |
response = requests.post( | |
url, | |
json=data, | |
headers=headers, | |
auth=("", key), | |
) | |
response.raise_for_status() | |
return response.json() | |
def weather_forecast( | |
latitude: float, | |
longitude: float, | |
timezone: str, | |
current_weather: bool = True, | |
unit: str = 'celsius', | |
forecast_days: int = 7, | |
): | |
url = 'https://api.open-meteo.com/v1/forecast' | |
response = requests.get( | |
url, | |
params={ | |
'latitude': latitude, | |
'longitude': longitude, | |
'timezone': timezone, | |
'temperature_unit': unit, | |
'daily': ','.join([ | |
'temperature_2m_max', | |
'temperature_2m_min', | |
'apparent_temperature_max', | |
'apparent_temperature_min', | |
]), | |
'forecast_days': forecast_days, | |
'current_weather': current_weather, | |
}, | |
) | |
response.raise_for_status() | |
return response.json() | |
def main(): | |
while True: | |
user_input = input("[🤖 Ask your question]\n") | |
if user_input == 'exit': | |
print('See you next time! 😀') | |
break | |
data = { | |
'model': 'gpt-3.5-turbo-0613', | |
'messages': [{'role': 'user', 'content': user_input}], | |
'functions': functions, | |
} | |
resp_data = send_to_openai(data) | |
logger.info('OpenAI response: {}', resp_data) | |
message = resp_data['choices'][0]['message'] | |
if 'function_call' not in message: | |
print('[🤖 Reply]\n', message['content']) | |
continue | |
arguments = json.loads(message['function_call']['arguments']) | |
weather_data = weather_forecast(**arguments) | |
logger.info('Weather data: {}', weather_data) | |
data['messages'].append(message) | |
data['messages'].append({ | |
'role': 'function', | |
'name': message['function_call']['name'], | |
'content': json.dumps(weather_data), | |
}) | |
resp_data = send_to_openai(data) | |
logger.info('OpenAI response: {}', resp_data) | |
message = resp_data['choices'][0]['message'] | |
print('[🤖 Reply (Func)]\n', message['content']) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment