I’m trying to use OpenAI’s function calling feature to get building details and location coordinates when I provide a building name or address. Right now I’m using basic prompts and parsing with regex which is unreliable and breaks sometimes.
I want to properly implement function calling so the API returns structured data like this: name: ‘Building Name’, details: ‘Description here’, location: ‘lat: xx.xxx, lng: xx.xxx’
I’ve been stuck on this for hours and can’t get my code to work properly. Here’s what I have so far:
def fetch_building_data(name, details, location_coords):
"""Retrieve building information"""
building_data = {
"name": name,
"details": details,
"location_coords": location_coords
}
return json.dumps(building_data)
def execute_search():
# Send user input and function definitions to OpenAI
user_messages = [{"role": "user", "content": "Tell me about the library on Main Street"}]
available_functions = [
{
"name": "fetch_building_data",
"description": "Get information about a specific building",
"parameters": {
"type": "object",
"properties": {
"details": {
"type": "string",
"description": "Building description and details",
},
"name": {"type": "string", "description": "Building name"},
},
"required": ["name"],
},
}
]
api_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=user_messages,
functions=available_functions,
function_call="auto",
)
message_response = api_response["choices"][0]["message"]
# Check if OpenAI wants to use our function
if message_response.get("function_call"):
function_registry = {
"fetch_building_data": fetch_building_data,
}
called_function = message_response["function_call"]["name"]
target_function = function_registry[called_function]
parsed_args = json.loads(message_response["function_call"]["arguments"])
result = target_function(
name=parsed_args.get("name"),
details=parsed_args.get("details"),
location_coords=parsed_args.get("location_coords"),
)
# Send function result back to OpenAI
user_messages.append(message_response)
user_messages.append(
{
"role": "function",
"name": called_function,
"content": result,
}
)
final_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=user_messages,
)
return final_response
print(execute_search())
What am I doing wrong here? The function calling isn’t working as expected.