How to validate function call arguments
Quick answer
To validate function call arguments from an OpenAI chat completion, parse the
tool_calls field in the response, then use json.loads() to convert the arguments string into a Python dict. Validate this dict against your function's expected schema using libraries like jsonschema or Pydantic before executing the function.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0 jsonschema pydantic
Setup
Install the required Python packages and set your OpenAI API key as an environment variable.
pip install openai jsonschema pydantic output
Collecting openai\nCollecting jsonschema\nCollecting pydantic\nSuccessfully installed openai jsonschema pydantic
Step by step
This example shows how to call an OpenAI chat completion with a function call, extract the function call arguments, and validate them using jsonschema. It assumes you have a function expecting a location string argument.
import os
import json
from openai import OpenAI
from jsonschema import validate, ValidationError
# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define the JSON schema for expected function arguments
function_schema = {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
# Call the chat completion with a function call tool
response = client.chat.completions.create(
model="gpt-4o-mini",
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a location",
"parameters": function_schema
}
}],
messages=[{"role": "user", "content": "What's the weather in New York?"}]
)
choice = response.choices[0]
if choice.finish_reason == "tool_calls":
tool_call = choice.message.tool_calls[0]
# Parse the JSON string arguments
try:
args = json.loads(tool_call.arguments)
# Validate arguments against schema
validate(instance=args, schema=function_schema)
print("Arguments are valid:", args)
except json.JSONDecodeError as e:
print("Invalid JSON in function call arguments:", e)
except ValidationError as e:
print("Arguments failed schema validation:", e)
else:
print("No function call detected in response.") output
Arguments are valid: {'location': 'New York'} Common variations
- Use
pydanticmodels instead ofjsonschemafor argument validation with type hints and parsing. - For asynchronous calls, use
asyncandawaitwith the OpenAI client. - Validate arguments for multiple functions by defining separate schemas or models per function.
from pydantic import BaseModel, ValidationError
class GetWeatherArgs(BaseModel):
location: str
try:
args_obj = GetWeatherArgs.parse_obj(args)
print("Pydantic validation passed:", args_obj)
except ValidationError as e:
print("Pydantic validation error:", e) output
Pydantic validation passed: location='New York'
Troubleshooting
- If you see
json.JSONDecodeError, check that theargumentsstring is valid JSON. ValidationErrormeans the arguments don't match your schema; update your schema or handle missing/extra fields.- Ensure you use the
tools=parameter (not deprecatedfunctions=) when requesting function calls.
Key Takeaways
- Always parse function call arguments from
tool_callsusingjson.loads()before validation. - Use
jsonschemaorpydanticto enforce argument structure and types before executing functions. - Handle JSON parsing and validation errors gracefully to avoid runtime failures.
- Use the
tools=parameter in OpenAI chat completions to enable function calling and argument extraction.