How to define functions for OpenAI assistant
Quick answer
Use the
functions parameter in client.chat.completions.create to define callable functions for the OpenAI assistant. Provide function schemas with names, descriptions, and parameters, then handle the assistant's function call response to execute the function.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) orsetx OPENAI_API_KEY "your_api_key"(Windows)
pip install openai Step by step
Define functions as JSON schemas and pass them to the functions parameter. The assistant can then call these functions by name with arguments. Parse the response to detect function calls and execute accordingly.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define a function schema
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"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
]
messages = [
{"role": "user", "content": "What's the weather like in New York?"}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
functions=functions,
function_call="auto" # Let the model decide to call a function
)
message = response.choices[0].message
if message.get("function_call"):
function_name = message["function_call"]["name"]
arguments = message["function_call"]["arguments"]
print(f"Function called: {function_name}")
print(f"Arguments: {arguments}")
# Here you would implement the actual function logic
else:
print(message.content) output
Function called: get_current_weather
Arguments: {"location": "New York"} Common variations
You can specify function_call as "none" to disable function calls or provide a specific function name to force a call. Async usage requires asyncio with the OpenAI client. You can also define multiple functions and handle them dynamically.
import asyncio
import os
from openai import OpenAI
async def main():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
functions = [
{
"name": "get_current_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}
]
messages = [{"role": "user", "content": "Weather in Boston?"}]
response = await client.chat.completions.acreate(
model="gpt-4o-mini",
messages=messages,
functions=functions,
function_call="get_current_weather"
)
message = response.choices[0].message
print(message.function_call)
asyncio.run(main()) output
{'name': 'get_current_weather', 'arguments': '{"location": "Boston"}'} Troubleshooting
- If the assistant never calls your function, ensure your function schema is valid JSON Schema and the
functionsparameter is passed correctly. - If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set. - For unexpected responses, check the
function_callfield in the response message to debug function invocation.
Key Takeaways
- Use the
functionsparameter to define callable functions with JSON schemas. - Check the
function_callfield in the assistant's response to detect and handle function calls. - You can control function calling behavior with the
function_callparameter: 'auto', 'none', or specific function name. - Async calls are supported with
client.chat.completions.acreatefor concurrency. - Validate your function schemas carefully to ensure the assistant recognizes and calls them.