How to beginner · 3 min read

How to define functions for OpenAI

Quick answer
Use the tools parameter in client.chat.completions.create to define functions for OpenAI. Specify each function's name, description, and JSON schema in tools, then handle tool_calls in the response to execute them.

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.

  • Install SDK: pip install openai
  • Set environment variable: export OPENAI_API_KEY='your_api_key' (Linux/macOS) or setx OPENAI_API_KEY "your_api_key" (Windows)
bash
pip install openai
output
Collecting openai
  Downloading openai-1.x.x-py3-none-any.whl (xx kB)
Installing collected packages: openai
Successfully installed openai-1.x.x

Step by step

Define functions using the tools parameter with JSON schema describing inputs. Call client.chat.completions.create with tools and messages. Check if the response indicates a tool_call and parse the arguments to execute the function.

python
import os
import json
from openai import OpenAI

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

# Define a function for weather info
weather_function = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City and state, e.g. San Francisco, CA"}
            },
            "required": ["location"]
        }
    }
}

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

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
    tools=[weather_function]
)

choice = response.choices[0]

if choice.finish_reason == "tool_calls":
    tool_call = choice.message.tool_calls[0]
    function_name = tool_call.function.name
    arguments = json.loads(tool_call.function.arguments)
    # Simulate function execution
    if function_name == "get_weather":
        location = arguments.get("location")
        # Here you would call a real weather API
        weather_info = f"Sunny and 75°F in {location}."
        print(f"Function '{function_name}' called with args: {arguments}")
        print(f"Function result: {weather_info}")
else:
    print(choice.message.content)
output
Function 'get_weather' called with args: {'location': 'New York'}
Function result: Sunny and 75°F in New York.

Common variations

You can define multiple functions in the tools list and handle different tool_calls. Use different models like gpt-4o or gpt-4o-mini. Async calls are supported with async and await. Streaming is not supported with function calling currently.

python
import asyncio
import json
from openai import OpenAI

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

async def async_function_call():
    tools = [{
        "type": "function",
        "function": {
            "name": "get_time",
            "description": "Get current time in a timezone",
            "parameters": {
                "type": "object",
                "properties": {
                    "timezone": {"type": "string"}
                },
                "required": ["timezone"]
            }
        }
    }]

    messages = [{"role": "user", "content": "What time is it in UTC?"}]

    response = await client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=tools
    )

    choice = response.choices[0]
    if choice.finish_reason == "tool_calls":
        tool_call = choice.message.tool_calls[0]
        args = json.loads(tool_call.function.arguments)
        print(f"Async function call args: {args}")
    else:
        print(choice.message.content)

asyncio.run(async_function_call())
output
Async function call args: {'timezone': 'UTC'}

Troubleshooting

  • If finish_reason is not tool_calls, the model did not invoke a function; check your prompt and function definitions.
  • Ensure your tools parameter is a list of properly structured function definitions with valid JSON schema.
  • Do not use the deprecated functions= or function_call= parameters; use tools= instead.
  • Check your API key and environment variable setup if authentication errors occur.

Key Takeaways

  • Define functions using the tools parameter with JSON schema describing inputs.
  • Check finish_reason for tool_calls to detect function invocation.
  • Parse tool_calls arguments from JSON to execute your functions.
  • Use the latest OpenAI Python SDK v1+ and avoid deprecated parameters like functions=.
  • Async calls are supported; streaming is not compatible with function calling currently.
Verified 2026-04 · gpt-4o-mini, gpt-4o
Verify ↗