from openai import OpenAI
import json
client = OpenAI()
def get_current_weather(location, unit="fahrenheit"):
weather_info = {
"location": location,
"temperature": "72",
"unit": unit,
"forecast": ["sunny", "windy"],
}
return json.dumps(weather_info)
def run_conversation(prompt):
messages = [{"role": "user", "content": prompt}]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
}
}
]
response = client.chat.completions.create(
model="gpt-3.5-turbo-0613",
messages=messages,
tools=tools,
tool_choice=None
)
response_message = response.choices[0].message
print ("First response:\n")
print(response_message)
if response_message.tool_calls:
available_functions = {
"get_current_weather": get_current_weather,
} function_name = response_message.tool_calls[0].function.name
function_to_call = available_functions[function_name]
function_args = json.loads(response_message.tool_calls[0].function.arguments)
function_response = function_to_call(
location=function_args.get("location"),
unit=function_args.get("unit"),
)
print("Appending function response to conversation:\n")
print(function_response)
messages.append(response_message) messages.append(
{
"role": "tool",
"tool_call_id": response_message.tool_calls[0].id,
"name": function_name,
"content": function_response,
}
)
print (messages)
second_response = client.chat.completions.create(
model="gpt-3.5-turbo-0613",
messages=messages,
)
print("Final response:\n")
return second_response
prompt = input("Ask me about the weather somewhere. You know you want to: ")
print(run_conversation(prompt))