How to beginner · 3 min read

How to define functions for OpenAI function calling

Quick answer
Use the functions parameter in client.chat.completions.create to define JSON schema-based functions for OpenAI function calling. Specify each function's name, description, and parameters as a JSON Schema object to enable structured, reliable outputs.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official OpenAI Python SDK and set your API key as an environment variable.

bash
pip install openai>=1.0

Step by step

Define functions using JSON Schema in the functions parameter and call the chat completion with function_call="auto" to enable automatic function calling by the model.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

functions = [
    {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
    }
]

messages = [
    {"role": "user", "content": "What's the weather like in Boston?"}
]

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
    functions=functions,
    function_call="auto"
)

print("Model response:", response.choices[0].message.content)
print("Function call:", response.choices[0].message.function_call)
output
Model response: null
Function call: {'name': 'get_current_weather', 'arguments': '{"location": "Boston"}'}

Common variations

  • Use function_call="none" to disable function calling.
  • Explicitly call a specific function with function_call={"name": "function_name"}.
  • Use async calls with asyncio and await in Python.
  • Use different models like gpt-4o-mini if supported.
python
import asyncio
import os
from openai import OpenAI

async def async_function_call():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    functions = [
        {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }
    ]
    messages = [{"role": "user", "content": "Weather in New York?"}]

    response = await client.chat.completions.acreate(
        model="gpt-4o-mini",
        messages=messages,
        functions=functions,
        function_call="auto"
    )
    print(response.choices[0].message.content)

asyncio.run(async_function_call())
output
null
{'name': 'get_current_weather', 'arguments': '{"location": "New York"}'}

Troubleshooting

  • If you get 400 Bad Request, verify your JSON schema is valid and all required fields are present.
  • If the model does not call functions, ensure function_call is set to "auto" or the specific function name.
  • Check your API key and environment variable setup if authentication errors occur.

Key Takeaways

  • Define functions with JSON Schema in the functions parameter for structured outputs.
  • Use function_call="auto" to let the model decide when to call functions.
  • Always validate your function schema and required parameters to avoid request errors.
Verified 2026-04 · gpt-4o-mini
Verify ↗