Skip to navigation

Function Calling

View as Markdown

Function calling enables AI models to interact with external systems, APIs, and custom code. This powerful feature allows you to build dynamic applications that can fetch live data, perform actions, and integrate with your existing infrastructure.

Requirements

Subscription Level: Function calling requires a ‘Basic’ subscription or higher.

Model Support: Check the Models page to verify which models support function calling by looking for the function_calling parameter.

How It Works

  1. Define functions with schemas describing parameters
  2. Send a request with your functions and a user query
  3. The model decides if it needs to call a function
  4. If needed, the model returns structured function call data
  5. Execute the function in your code
  6. Send the result back to the model for final response

Basic Example

from openai import OpenAI
client = OpenAI(
base_url="https://api.neura-ai.app/v1"
)
# Define available functions
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
}
},
"required": ["location"],
"additionalProperties": False
},
"strict": True
}
}]
# Make request
completion = client.chat.completions.create(
model="gpt-5",
messages=[{"role": "user", "content": "What is the weather like in Paris today?"}],
tools=tools
)
# Check if model wants to call a function
print(completion.choices[0].message.tool_calls)

Complete Workflow Example

Here’s a full implementation including function execution:

import json
from openai import OpenAI
client = OpenAI(base_url="https://api.neura-ai.app/v1")
# Your actual function implementations
def get_weather(location):
# In production, call a real weather API
return {
"location": location,
"temperature": "22°C",
"condition": "Partly cloudy"
}
def get_stock_price(symbol):
# In production, call a real stock API
return {
"symbol": symbol,
"price": 150.25,
"change": "+2.3%"
}
# Define function schemas
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}
},
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get current stock price",
"parameters": {
"type": "object",
"properties": {
"symbol": {"type": "string", "description": "Stock symbol"}
},
"required": ["symbol"]
}
}
}
]
# Initial request
messages = [{"role": "user", "content": "What's the weather in Tokyo and the price of AAPL stock?"}]
response = client.chat.completions.create(
model="gpt-5",
messages=messages,
tools=tools
)
# Process function calls
while response.choices[0].message.tool_calls:
messages.append(response.choices[0].message)
for tool_call in response.choices[0].message.tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
# Execute the appropriate function
if function_name == "get_weather":
result = get_weather(arguments["location"])
elif function_name == "get_stock_price":
result = get_stock_price(arguments["symbol"])
# Add function result to messages
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})
# Get final response with function results
response = client.chat.completions.create(
model="gpt-5",
messages=messages,
tools=tools
)
print(response.choices[0].message.content)

Advanced Use Cases

Database Queries

tools = [{
"type": "function",
"function": {
"name": "query_database",
"description": "Execute SQL query on the customer database",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "SQL SELECT query"
},
"limit": {
"type": "integer",
"description": "Maximum number of results",
"default": 10
}
},
"required": ["query"]
}
}
}]

E-commerce Actions

tools = [
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search for products in inventory",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"category": {"type": "string"},
"max_price": {"type": "number"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "add_to_cart",
"description": "Add product to shopping cart",
"parameters": {
"type": "object",
"properties": {
"product_id": {"type": "string"},
"quantity": {"type": "integer", "default": 1}
},
"required": ["product_id"]
}
}
}
]

Calendar Management

tools = [{
"type": "function",
"function": {
"name": "create_event",
"description": "Create a calendar event",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"start_time": {"type": "string", "format": "date-time"},
"duration_minutes": {"type": "integer"},
"attendees": {
"type": "array",
"items": {"type": "string"}
}
},
"required": ["title", "start_time", "duration_minutes"]
}
}
}]

Function Schema Best Practices

Clear Descriptions

{
"name": "send_email",
"description": "Send an email to one or more recipients. Use this when the user wants to communicate via email.",
"parameters": {...}
}

Detailed Parameters

"parameters": {
"type": "object",
"properties": {
"recipient": {
"type": "string",
"description": "Email address of the recipient (e.g., user@example.com)"
},
"subject": {
"type": "string",
"description": "Subject line of the email"
},
"body": {
"type": "string",
"description": "Main content of the email message"
}
}
}

Required vs Optional

"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius"
}
},
"required": ["city"] # units is optional with default
}

Error Handling

Always handle potential errors in function execution:

try:
if function_name == "get_data":
result = get_data(arguments["id"])
except Exception as e:
result = {
"error": str(e),
"message": "Failed to fetch data"
}
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})

Tips for Success

  • Write clear, descriptive function and parameter descriptions
  • Use strict schema validation when possible
  • Handle errors gracefully and return informative messages
  • Test functions independently before integrating
  • Consider rate limits and timeouts for external APIs
  • Log function calls for debugging and analytics
  • Validate function arguments before execution
  • Return structured JSON responses from your functions