How to use function calling for calculations
Quick answer
Use the OpenAI API's
tools parameter to define calculation functions with JSON schema, then detect tool_calls in the response to execute calculations programmatically. This enables the AI to delegate math tasks to your custom functions via function calling.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python package (v1+) and set your API key as an environment variable for secure authentication.
pip install openai>=1.0 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 a calculation function using the tools parameter with JSON schema describing the function name, description, and parameters. Send a chat completion request with a user prompt asking for a calculation. When the AI responds with a tool_call, parse the arguments, perform the calculation in Python, then send the result back to the AI for final output.
import os
import json
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define the calculation function schema
tools = [{
"type": "function",
"function": {
"name": "calculate",
"description": "Perform basic arithmetic calculations",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Arithmetic expression to evaluate"}
},
"required": ["expression"]
}
}
}]
# User prompt asking for a calculation
messages = [{"role": "user", "content": "Calculate 12 * (3 + 4)"}]
# Send chat completion request with tools
response = client.chat.completions.create(
model="gpt-4o-mini",
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)
expression = args["expression"]
# Safely evaluate the arithmetic expression
# WARNING: Use a safe parser in production; here eval is for demo only
result = str(eval(expression))
# Send the result back to the AI
followup_messages = messages + [
{
"role": "assistant",
"content": null,
"tool_calls": [tool_call]
},
{
"role": "function",
"name": tool_call.function.name,
"content": result
}
]
final_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=followup_messages
)
print("Calculation result:", final_response.choices[0].message.content)
else:
print("Response:", choice.message.content) output
Calculation result: 84
Common variations
You can use async calls with asyncio and await for non-blocking execution. Different models like gpt-4o or gpt-4o-mini can be used depending on your latency and cost needs. The function calling pattern is consistent across OpenAI SDK versions 1.x and above.
import os
import json
import asyncio
from openai import OpenAI
async def async_calculation():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "calculate",
"description": "Perform basic arithmetic calculations",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string"}
},
"required": ["expression"]
}
}
}]
messages = [{"role": "user", "content": "Calculate 10 / 2 + 7"}]
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)
expression = args["expression"]
result = str(eval(expression))
followup_messages = messages + [
{"role": "assistant", "content": null, "tool_calls": [tool_call]},
{"role": "function", "name": tool_call.function.name, "content": result}
]
final_response = await client.chat.completions.create(
model="gpt-4o",
messages=followup_messages
)
print("Async calculation result:", final_response.choices[0].message.content)
else:
print("Response:", choice.message.content)
asyncio.run(async_calculation()) output
Async calculation result: 12.0
Troubleshooting
- If you see
finish_reasonnot equal totool_calls, ensure yourtoolsparameter is correctly defined and the model supports function calling. - Never use
evalon untrusted input in production; use a safe math expression parser likeastevalorsympy. - If the API returns errors about
tools, verify you are using the latest OpenAI SDK (v1+) and the correct model that supports function calling.
Key Takeaways
- Use the OpenAI
toolsparameter to define calculation functions with JSON schema. - Detect
tool_callsin the response to execute calculations programmatically. - Send the calculation result back as a
functionmessage for the AI to continue the conversation. - Always use safe evaluation methods for expressions in production environments.
- Async and different models support the same function calling pattern with the OpenAI SDK v1+.