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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 15 views 0 copies

Python code

37 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Use `json.dumps(schema)` directly in the API call for JSON payloads.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.