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

1from openai import OpenAI
2
3client = OpenAI(
4 base_url="https://api.neura-ai.app/v1"
5)
6
7# Define available functions
8tools = [{
9 "type": "function",
10 "function": {
11 "name": "get_weather",
12 "description": "Get current temperature for a given location.",
13 "parameters": {
14 "type": "object",
15 "properties": {
16 "location": {
17 "type": "string",
18 "description": "City and country e.g. Bogotá, Colombia"
19 }
20 },
21 "required": ["location"],
22 "additionalProperties": False
23 },
24 "strict": True
25 }
26}]
27
28# Make request
29completion = client.chat.completions.create(
30 model="gpt-5",
31 messages=[{"role": "user", "content": "What is the weather like in Paris today?"}],
32 tools=tools
33)
34
35# Check if model wants to call a function
36print(completion.choices[0].message.tool_calls)

Complete Workflow Example

Here’s a full implementation including function execution:

1import json
2from openai import OpenAI
3
4client = OpenAI(base_url="https://api.neura-ai.app/v1")
5
6# Your actual function implementations
7def get_weather(location):
8 # In production, call a real weather API
9 return {
10 "location": location,
11 "temperature": "22°C",
12 "condition": "Partly cloudy"
13 }
14
15def get_stock_price(symbol):
16 # In production, call a real stock API
17 return {
18 "symbol": symbol,
19 "price": 150.25,
20 "change": "+2.3%"
21 }
22
23# Define function schemas
24tools = [
25 {
26 "type": "function",
27 "function": {
28 "name": "get_weather",
29 "description": "Get current weather for a location",
30 "parameters": {
31 "type": "object",
32 "properties": {
33 "location": {"type": "string", "description": "City name"}
34 },
35 "required": ["location"]
36 }
37 }
38 },
39 {
40 "type": "function",
41 "function": {
42 "name": "get_stock_price",
43 "description": "Get current stock price",
44 "parameters": {
45 "type": "object",
46 "properties": {
47 "symbol": {"type": "string", "description": "Stock symbol"}
48 },
49 "required": ["symbol"]
50 }
51 }
52 }
53]
54
55# Initial request
56messages = [{"role": "user", "content": "What's the weather in Tokyo and the price of AAPL stock?"}]
57
58response = client.chat.completions.create(
59 model="gpt-5",
60 messages=messages,
61 tools=tools
62)
63
64# Process function calls
65while response.choices[0].message.tool_calls:
66 messages.append(response.choices[0].message)
67
68 for tool_call in response.choices[0].message.tool_calls:
69 function_name = tool_call.function.name
70 arguments = json.loads(tool_call.function.arguments)
71
72 # Execute the appropriate function
73 if function_name == "get_weather":
74 result = get_weather(arguments["location"])
75 elif function_name == "get_stock_price":
76 result = get_stock_price(arguments["symbol"])
77
78 # Add function result to messages
79 messages.append({
80 "role": "tool",
81 "tool_call_id": tool_call.id,
82 "content": json.dumps(result)
83 })
84
85 # Get final response with function results
86 response = client.chat.completions.create(
87 model="gpt-5",
88 messages=messages,
89 tools=tools
90 )
91
92print(response.choices[0].message.content)

Advanced Use Cases

Database Queries

1tools = [{
2 "type": "function",
3 "function": {
4 "name": "query_database",
5 "description": "Execute SQL query on the customer database",
6 "parameters": {
7 "type": "object",
8 "properties": {
9 "query": {
10 "type": "string",
11 "description": "SQL SELECT query"
12 },
13 "limit": {
14 "type": "integer",
15 "description": "Maximum number of results",
16 "default": 10
17 }
18 },
19 "required": ["query"]
20 }
21 }
22}]

E-commerce Actions

1tools = [
2 {
3 "type": "function",
4 "function": {
5 "name": "search_products",
6 "description": "Search for products in inventory",
7 "parameters": {
8 "type": "object",
9 "properties": {
10 "query": {"type": "string"},
11 "category": {"type": "string"},
12 "max_price": {"type": "number"}
13 },
14 "required": ["query"]
15 }
16 }
17 },
18 {
19 "type": "function",
20 "function": {
21 "name": "add_to_cart",
22 "description": "Add product to shopping cart",
23 "parameters": {
24 "type": "object",
25 "properties": {
26 "product_id": {"type": "string"},
27 "quantity": {"type": "integer", "default": 1}
28 },
29 "required": ["product_id"]
30 }
31 }
32 }
33]

Calendar Management

1tools = [{
2 "type": "function",
3 "function": {
4 "name": "create_event",
5 "description": "Create a calendar event",
6 "parameters": {
7 "type": "object",
8 "properties": {
9 "title": {"type": "string"},
10 "start_time": {"type": "string", "format": "date-time"},
11 "duration_minutes": {"type": "integer"},
12 "attendees": {
13 "type": "array",
14 "items": {"type": "string"}
15 }
16 },
17 "required": ["title", "start_time", "duration_minutes"]
18 }
19 }
20}]

Function Schema Best Practices

Clear Descriptions

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

Detailed Parameters

1"parameters": {
2 "type": "object",
3 "properties": {
4 "recipient": {
5 "type": "string",
6 "description": "Email address of the recipient (e.g., user@example.com)"
7 },
8 "subject": {
9 "type": "string",
10 "description": "Subject line of the email"
11 },
12 "body": {
13 "type": "string",
14 "description": "Main content of the email message"
15 }
16 }
17}

Required vs Optional

1"parameters": {
2 "type": "object",
3 "properties": {
4 "city": {"type": "string"},
5 "units": {
6 "type": "string",
7 "enum": ["celsius", "fahrenheit"],
8 "default": "celsius"
9 }
10 },
11 "required": ["city"] # units is optional with default
12}

Error Handling

Always handle potential errors in function execution:

1try:
2 if function_name == "get_data":
3 result = get_data(arguments["id"])
4except Exception as e:
5 result = {
6 "error": str(e),
7 "message": "Failed to fetch data"
8 }
9
10messages.append({
11 "role": "tool",
12 "tool_call_id": tool_call.id,
13 "content": json.dumps(result)
14})

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