I am trying to use function calling of openai. However, it throws an error. The code is given below:
import openai
def fetch_weather_with_openai(location, unit='celsius'):
"""
Fetch weather using OpenAI's ChatCompletion.create with a simulated function call.
Args:
location (str): The location for which weather information is requested.
unit (str): The unit of temperature (celsius or fahrenheit).
Returns:
str: The generated response simulating weather information.
"""
function_payload = {
"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"]
}
}
}
}
# Define the input message
messages = [
{"role": "user", "content": f"What's the weather like in {location}?"}
]
response = openai.ChatCompletion.create(
model=llm_config['model_name'],
deployment_id=llm_config['deployment_name'],
messages=messages,
tools=[function_payload]
)
# Extract and return the response
return response.choices[0].message['content']
# Example usage
response = fetch_weather_with_openai("Paris, France")
print(response)
The error is given below:
File "c:\metatool-tool-desc-gen_reasoning_func_call.py", line 74, in <module>
response = fetch_weather_with_openai("Paris, France")
File "c\:metatool-tool-desc-gen_reasoning_func_call.py", line 63, in fetch_weather_with_openai
response = openai.ChatCompletion.create(
File "C:\project\lib\site-packages\openai\api_resources\chat_completion.py", line 25, in create
return super().create(*args, **kwargs)
File "C:\project\lib\site-packages\openai\api_resources\abstract\engine_api_resource.py", line 153, in create
response, _, api_key = requestor.request(
File "C:\project\lib\site-packages\openai\api_requestor.py", line 298, in request
resp, got_stream = self._interpret_response(result, stream)
File "C:\project\lib\site-packages\openai\api_requestor.py", line 700, in _interpret_response
self._interpret_response_line(
File "C:\project\lib\site-packages\openai\api_requestor.py", line 763, in _interpret_response_line
raise self.handle_error_response(
openai.error.InvalidRequestError: 'type' is a required property - 'tools.0'
I am also confused that some function calls use "tools" as a parameter, while in some sources the parameter is "functions".
Can you please help me to work this code out? Thanks!
You are not doing it correctly. Below is the modified code. Also use openai v0 version(openai==0.28.0)