How to handle function call results
function_call field in the OpenAI chat completion response to detect and extract function call results. Parse the arguments JSON string from response.choices[0].message.function_call.arguments to handle structured outputs properly.model_behavior function_call.arguments JSON string from the response to correctly handle function call results.Why this happens
When using function_call with the OpenAI API, the model returns the function call details inside the message.function_call object. The arguments field is a JSON string, not a Python dict, so if you treat it as a dict directly, you get errors or incorrect handling.
Example broken code:
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Call the weather function"}],
functions=[{
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}],
function_call="auto"
)
# Incorrect: treating arguments as dict directly
args = response.choices[0].message.function_call.arguments
print(args["location"])This raises a TypeError because arguments is a JSON string, not a dict.
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Call the weather function"}],
functions=[{
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}],
function_call="auto"
)
# Incorrect: treating arguments as dict directly
args = response.choices[0].message.function_call.arguments
print(args["location"]) TypeError: string indices must be integers
The fix
Parse the arguments string as JSON to convert it into a Python dict before accessing its fields. This ensures you handle the structured output correctly.
from openai import OpenAI
import os
import json
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Call the weather function"}],
functions=[{
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}],
function_call="auto"
)
func_call = response.choices[0].message.function_call
args = json.loads(func_call.arguments)
print(f"Function called: {func_call.name}")
print(f"Arguments: {args}")
print(f"Location argument: {args['location']}") Function called: get_weather
Arguments: {'location': 'San Francisco'}
Location argument: San Francisco Preventing it in production
Always validate and parse function_call.arguments as JSON before use. Implement error handling for JSON parsing failures to catch malformed responses. Use retries with exponential backoff for transient API errors. Consider fallback logic if the function call is missing or incomplete.
import json
def handle_function_call(response):
try:
func_call = response.choices[0].message.function_call
if func_call and func_call.arguments:
args = json.loads(func_call.arguments)
# Process args safely here
return func_call.name, args
else:
return None, None
except json.JSONDecodeError:
# Log error and fallback
return None, None Key Takeaways
- Always parse
function_call.argumentsas JSON before accessing its contents. - Implement error handling around JSON parsing to avoid runtime crashes.
- Use retries and validation to handle transient API or malformed response issues.