Yes I can. Here is the code:
import openai
import json
api_key = "API-KEY-HERE"
openai.api_key = api_key
def get_current_weather(location, unit="fahrenheit"):
"""Get the current weather in a given location"""
if "tokyo" in location.lower():
return json.dumps({"location": "Tokyo", "temperature": "10", "unit": "celsius"})
elif "san francisco" in location.lower():
return json.dumps({"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"})
elif "paris" in location.lower():
return json.dumps({"location": "Paris", "temperature": "22", "unit": "celsius"})
else:
return json.dumps({"location": location, "temperature": "unknown"})
def run_conversation():
messages = [{
"role": "user",
"content": "What's the weather in Tokyo, San Francisco, and Paris. Provide the temps for Tokyo in celsius, San Francisco in fahrenheit, and Paris in celsius."
}]
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", "unit"]
}
}
}
]
response = openai.chat.completions.create(
model="gpt-4-1106-preview",
messages=messages,
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
if tool_calls:
available_functions = {
"get_current_weather": get_current_weather,
}
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = globals().get(function_name)
if function_to_call:
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
function_response = function_to_call(
location=function_args.get("location"),
unit=function_args.get("unit"),
)
messages.append({
"role": "assistant",
"content": str(response),
})
messages.append({
"tool_call_id": tool_call.id,
"role": "function",
"name": function_name,
"content": function_response,
})
else:
print(f"No function found for the name {function_name}")
else:
print("No tool calls made by the model.")
response = openai.chat.completions.create(
model="gpt-4-1106-preview",
messages=messages,
tools=tools,
tool_choice="none"
)
messages.append({
"role": "assistant",
"content": str(response),
})
print(messages)
return json.dumps(messages, indent=2)
print(run_conversation())
Also they changed what the function response must return with, now you have to return the response in JSON format as it is in the code I provided.