Function calling
Program sends the functions
Functions as tools with schema
Model requests a function call
A function name and its parameters
Program executes the function
Function results loops in generation
Introduction
Function calling gives large language models (LLMs) access to new functionality and data they can use to extend their capabilities and respond to prompts.
Function calling works inside computer programs by implementing concrete functions and then disseminating themselve to LLMs. The dissemination process adopts JSON schema to detail the function requirements. The programs will execute the functions with arguments provided by LLMs and then feed back the function results to enhance the generation.
To learn more about function calling, please visit https://developers.openai.com/api/docs/guides/function-calling for more details.
Interaction model
The LLM never sees the function's implementation. If the description is vague, or the schema does not describe precisely, the model's call request may fail. An failed execution should feed back as error message, so the model can get it and may try again.
Scaffold code
One entry in the tools list: a name, a description, one required argument.
tools = [
{
"type": "function",
"function": {
"name": "function_name",
"description": "One sentence about what it does and when to use it.",
"parameters": {
"type": "object",
"properties": {
"required_arg": {
"type": "string",
"description": "The caller must pass this argument.",
},
"optional_arg": {
"type": "string",
"description": "The caller can omit this argument.",
},
},
"required": ["required_arg"],
},
},
}
]
def function_name(required_arg: str, optional_arg: str = "default_value") -> str:
# Do the work, and return a short, plain-text result.
return "result"Your program passes a tools list on the request. name is the function name that the model calls for, and it must match the exact Python function name below. description tells what it does and when to use it. parameters, a JSON schema of the arguments, specifies the details about the parameter names, data types, and descriptions. The required parameters are list in required field.
The model would answer with tool_calls: the name, and the arguments in a JSON string. Your program parses that string, runs the requested function, and sends the executed function return value back.
See the code below for a concrete example.
Code example
Type a request in natural language and inpsect the internal process.
"""Convert temperatures and distances, through function calling."""
import json
from openai import OpenAI
client = OpenAI()
TOOLS = [
{
"type": "function",
"function": {
"name": "convert_temperature",
"description": "Convert a temperature between Celsius and Fahrenheit.",
"parameters": {
"type": "object",
"properties": {
"value": {"type": "number", "description": "The temperature to convert"},
"to": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Unit to convert into",
},
},
"required": ["value", "to"],
},
},
},
{
"type": "function",
"function": {
"name": "convert_distance",
"description": "Convert a distance between kilometres and miles.",
"parameters": {
"type": "object",
"properties": {
"value": {"type": "number", "description": "The distance to convert"},
"to": {
"type": "string",
"enum": ["km", "miles"],
"description": "Unit to convert into",
},
},
"required": ["value", "to"],
},
},
},
]
def convert_temperature(value: float, to: str) -> str:
if to == "fahrenheit":
result = value * 9 / 5 + 32
else:
result = (value - 32) * 5 / 9
return f"{result:.1f}"
def convert_distance(value: float, to: str) -> str:
if to == "km":
result = value * 1.609344
else:
result = value / 1.609344
return f"{result:.2f}"
FUNCTIONS = {
"convert_temperature": convert_temperature,
"convert_distance": convert_distance,
}
def ask(question: str) -> str:
messages = [{"role": "user", "content": question}]
while True:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=messages,
tools=TOOLS,
)
message = response.choices[0].message
if not message.tool_calls:
return message.content
messages.append(message)
for call in message.tool_calls:
name = call.function.name
arguments = json.loads(call.function.arguments)
fn = FUNCTIONS.get(name)
content = fn(**arguments) if fn else f"error: unknown function {name}"
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": content,
})
if __name__ == "__main__":
print(ask("Convert 100F to C"))