How to build a function calling schema dict in Python
Build an OpenAI-compatible function calling schema dictionary with a helper function that takes name, description, parameters, and required fields.
Python code
37 linesimport json
from typing import Dict, Any, List, Optional
def build_function_schema(
name: str,
description: str,
parameters: Optional[Dict[str, Any]] = None,
required: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Build an OpenAI-compatible function calling schema dictionary."""
schema: Dict[str, Any] = {
"type": "function",
"function": {
"name": name,
"description": description,
"parameters": {
"type": "object",
"properties": parameters or {},
"required": required or []
}
}
}
return schema
if __name__ == "__main__":
schema = build_function_schema(
name="get_weather",
description="Get the current weather for a city",
parameters={
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
required=["city"]
)
print(json.dumps(schema, indent=2))
Output
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"city"
]
}
}
}
How it works
The helper returns a plain Python dict that matches the JSON Schema structure OpenAI expects for tool calling. Defaults handle optional parameters and required lists, so you always get a well-formed schema. The type hints (Dict, List, Optional) make the function self-documenting and IDE-friendly. When you pass this dict to an LLM API as tools, the model can decide to call your function with valid arguments. This pattern keeps schema definitions centralized and testable.
Common mistakes
- Forgetting to set `type: "function"` at the top level.
- Passing an empty string for required but expecting the model to fill it.
- Using a list instead of a dict for properties.
- Not including `description` on each parameter, which lowers model accuracy.
Variations
- Use `json.dumps(schema)` directly in the API call for JSON payloads.
- Refactor to return a JSON string with `json.dumps` if you need to cache the schema.
Real-world use cases
- Define tool schemas for ChatGPT function calling so the model can fetch live data.
- Validate LLM-generated arguments by comparing against the schema in a guardrail step.
- Share schemas across API versions and teams for consistent tool registration.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.