Created
June 14, 2023 01:06
-
-
Save xtekky/28e1320d593e04e586ba2da807778176 to your computer and use it in GitHub Desktop.
Openai Function Calling Model 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
import json | |
import requests | |
import openai | |
from datetime import datetime | |
import inspect | |
import json | |
from typing import get_type_hints | |
# Set OpenAI API key | |
openai.api_key = 'sk-...' | |
# Function to convert a Python function to JSON representation | |
def to_json(func) -> str: | |
json_representation = dict() | |
json_representation['name'] = func.__name__ # Function name | |
json_representation['description'] = func.__doc__.strip() # Function description | |
# Get function parameters and their type hints | |
parameters = inspect.signature(func).parameters | |
func_type_hints = get_type_hints(func) | |
json_parameters = dict() | |
json_parameters['type'] = 'object' | |
json_parameters['properties'] = {} | |
# Process each parameter | |
for name, param in parameters.items(): | |
if name == 'return': | |
continue | |
param_info = {} | |
# Parameter description from the default value | |
param_info['description'] = inspect.signature(func).parameters[name].default | |
param_annotation = func_type_hints.get(name) | |
if param_annotation: | |
# Convert parameter type hint to JSON type | |
if param_annotation.__name__ == 'str': | |
param_info['type'] = 'string' | |
else: | |
param_info['type'] = param_annotation.__name__ | |
if name == 'self': | |
continue | |
json_parameters['properties'][name] = param_info | |
json_representation['parameters'] = json_parameters | |
return json_representation | |
# Function to format a function call as a string | |
def format_call(function_call: dict) -> str: | |
json_data: dict = json.loads(function_call.__str__()) | |
function_name: str = json_data["name"] | |
args_json: str = json_data["arguments"] | |
args_dict: dict = json.loads(args_json) | |
args: str = ', '.join([f"{k}='{v}'" for k, v in args_dict.items()]) | |
return f"{function_name}({args})" | |
# Example conversation | |
prompt = 'whats the weather rn' | |
conversation = [ | |
{ | |
'role': 'assistant', | |
'content': f'You are ChatGPT an Artificial Intelligence developed by OpenAI, respond in a concise way, date: {datetime.today().strftime("%Y/%m/%d %H:%M:%S")}, current location: New York, USA' | |
}, | |
{ | |
'role': 'user', | |
'content': prompt | |
} | |
] | |
# Function to get current weather using OpenWeatherMap API | |
def get_current_weather(location: str = 'CityName, CountryCode') -> dict: | |
"""get weather in location""" | |
# Make API request to get weather data | |
weather_data = requests.get(f'https://openweathermap.org/data/2.5/weather?q={location}&appid=439d4b804bc8187953eb36d2a8c26a02').json() | |
# Extract relevant weather information | |
return json.dumps(separators=(',', ':'), obj={ | |
'description': weather_data['weather'][0]['description'], | |
'temperature': weather_data['main']['temp'], | |
'humidity': weather_data['main']['humidity'], | |
# 'wind_speed': weather_data['wind']['speed'], | |
# 'unit': 'celsius', | |
# 'wind_speed_unit_pronunciation': 'meters per second' | |
}) | |
# Convert get_current_weather function to JSON representation | |
weather_function_json = to_json(get_current_weather) | |
# Use the Chat API to interact with the model | |
completion = openai.ChatCompletion.create(model='gpt-3.5-turbo-0613', | |
messages=conversation, functions=[weather_function_json]) | |
# Add the function call and its result to the conversation | |
conversation += [json.loads(completion.choices[0].message.__str__())] | |
conversation += [{ | |
'role': 'function', | |
'name': completion.choices[0].message.function_call.name, | |
'content': eval(format_call(completion.choices[0].message.function_call)), | |
}] | |
# Continue the conversation with the updated function call | |
completion = openai.ChatCompletion.create(model='gpt-3.5-turbo-0613', | |
messages=conversation, functions=[weather_function_json]) | |
# Print the generated response | |
print(completion.choices[0].message.content) |
你好
你好
你是谁?
你好
您好
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
你是谁?