Function Calling

Learn how to use function calling (also known as tool calling) to build AI agents that can interact with external APIs, databases, and services.

What is Function Calling?

Function calling allows AI models to intelligently call functions you define. The model doesn't execute the functions directly—instead, it generates structured JSON that your code can use to call the appropriate function with the right parameters.

How It Works

  1. You define available functions with descriptions and parameters
  2. The model decides which function(s) to call based on the user's request
  3. The model returns structured JSON with function name and arguments
  4. Your code executes the function and returns results
  5. You send the results back to the model for a final response

Basic Function Calling

Define a function with a clear description and parameter schema, then let the model decide when to call it.

Basic Example

1from openai import OpenAI
2import json
3
4client = OpenAI(
5    api_key="your-api-key-here",
6    base_url="https://api.selamgpt.com/v1"
7)
8
9# Define the function
10tools = [
11    {
12        "type": "function",
13        "function": {
14            "name": "get_weather",
15            "description": "Get the current weather for a location",
16            "parameters": {
17                "type": "object",
18                "properties": {
19                    "location": {
20                        "type": "string",
21                        "description": "The city and state, e.g. San Francisco, CA"
22                    },
23                    "unit": {
24                        "type": "string",
25                        "enum": ["celsius", "fahrenheit"],
26                        "description": "The temperature unit"
27                    }
28                },
29                "required": ["location"]
30            }
31        }
32    }
33]
34
35# Make the request
36response = client.chat.completions.create(
37    model="selam-turbo",
38    messages=[
39        {"role": "user", "content": "What's the weather in Addis Ababa?"}
40    ],
41    tools=tools
42)
43
44# Check if the model wants to call a function
45message = response.choices[0].message
46if message.tool_calls:
47    tool_call = message.tool_calls[0]
48    function_name = tool_call.function.name
49    function_args = json.loads(tool_call.function.arguments)
50    
51    print(f"Function: {function_name}")
52    print(f"Arguments: {function_args}")

Complete Function Execution Flow

Here's a complete example showing how to execute the function and send results back to the model.

Complete Flow Example

1from openai import OpenAI
2import json
3
4client = OpenAI(
5    api_key="your-api-key-here",
6    base_url="https://api.selamgpt.com/v1"
7)
8
9# Define available functions
10def get_weather(location, unit="celsius"):
11    """Simulate getting weather data"""
12    return {
13        "location": location,
14        "temperature": 22,
15        "unit": unit,
16        "condition": "Sunny"
17    }
18
19tools = [
20    {
21        "type": "function",
22        "function": {
23            "name": "get_weather",
24            "description": "Get the current weather for a location",
25            "parameters": {
26                "type": "object",
27                "properties": {
28                    "location": {"type": "string"},
29                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
30                },
31                "required": ["location"]
32            }
33        }
34    }
35]
36
37# Step 1: Initial request
38messages = [{"role": "user", "content": "What's the weather in Addis Ababa?"}]
39
40response = client.chat.completions.create(
41    model="selam-turbo",
42    messages=messages,
43    tools=tools
44)
45
46message = response.choices[0].message
47messages.append(message)
48
49# Step 2: Execute function if requested
50if message.tool_calls:
51    for tool_call in message.tool_calls:
52        function_name = tool_call.function.name
53        function_args = json.loads(tool_call.function.arguments)
54        
55        # Execute the function
56        if function_name == "get_weather":
57            function_response = get_weather(**function_args)
58        
59        # Add function result to messages
60        messages.append({
61            "role": "tool",
62            "tool_call_id": tool_call.id,
63            "content": json.dumps(function_response)
64        })
65    
66    # Step 3: Get final response with function results
67    final_response = client.chat.completions.create(
68        model="selam-turbo",
69        messages=messages
70    )
71    
72    print(final_response.choices[0].message.content)

Parallel Function Calling

The model can call multiple functions in parallel when appropriate, improving efficiency.

Parallel Calling Example

1from openai import OpenAI
2import json
3
4client = OpenAI(
5    api_key="your-api-key-here",
6    base_url="https://api.selamgpt.com/v1"
7)
8
9tools = [
10    {
11        "type": "function",
12        "function": {
13            "name": "get_weather",
14            "description": "Get weather for a location",
15            "parameters": {
16                "type": "object",
17                "properties": {
18                    "location": {"type": "string"}
19                },
20                "required": ["location"]
21            }
22        }
23    },
24    {
25        "type": "function",
26        "function": {
27            "name": "get_time",
28            "description": "Get current time for a location",
29            "parameters": {
30                "type": "object",
31                "properties": {
32                    "location": {"type": "string"}
33                },
34                "required": ["location"]
35            }
36        }
37    }
38]
39
40messages = [{
41    "role": "user",
42    "content": "What's the weather and time in Addis Ababa and Nairobi?"
43}]
44
45response = client.chat.completions.create(
46    model="selam-turbo",
47    messages=messages,
48    tools=tools
49)
50
51message = response.choices[0].message
52
53# The model may call multiple functions
54if message.tool_calls:
55    print(f"Model wants to call {len(message.tool_calls)} functions:")
56    for tool_call in message.tool_calls:
57        print(f"  - {tool_call.function.name}: {tool_call.function.arguments}")

Tip

Pro tip: Parallel function calling is especially useful when the user's request requires multiple independent operations that can be executed simultaneously.

Controlling Function Calls

Use the tool_choice parameter to control when and which functions the model calls.

Tool Choice Options

  • "auto" (default): Model decides whether to call functions
  • "none": Model will not call any functions
  • "required": Model must call at least one function
  • {"type": "function", "function": {"name": "function_name"}}: Force a specific function

Tool Choice Example

1from openai import OpenAI
2
3client = OpenAI(
4    api_key="your-api-key-here",
5    base_url="https://api.selamgpt.com/v1"
6)
7
8# Force the model to call a specific function
9response = client.chat.completions.create(
10    model="selam-turbo",
11    messages=[
12        {"role": "user", "content": "Tell me about the weather"}
13    ],
14    tools=tools,
15    tool_choice={
16        "type": "function",
17        "function": {"name": "get_weather"}
18    }
19)
20
21# Require the model to call at least one function
22response = client.chat.completions.create(
23    model="selam-turbo",
24    messages=[
25        {"role": "user", "content": "Help me with something"}
26    ],
27    tools=tools,
28    tool_choice="required"
29)

Built-in Web Search Tool

The Selam API includes a built-in web search tool that allows models to access real-time information.

Web Search Example

1from openai import OpenAI
2
3client = OpenAI(
4    api_key="your-api-key-here",
5    base_url="https://api.selamgpt.com/v1"
6)
7
8response = client.chat.completions.create(
9    model="selam-turbo",
10    messages=[
11        {"role": "user", "content": "What are the latest news about AI?"}
12    ],
13    tools=[
14        {
15            "type": "web_search",
16            "web_search": {
17                "search": {
18                    "query": "latest AI news"
19                }
20            }
21        }
22    ]
23)
24
25print(response.choices[0].message.content)

Information

The web search tool is automatically executed by the API. You don't need to handle the function execution yourself. See the Web Search Guide for more details.

Best Practices

Write Clear Function Descriptions

The model relies on function descriptions to decide when to call them. Be specific about what the function does, when to use it, and what parameters it needs.

Use Descriptive Parameter Names

Parameter names and descriptions help the model understand what values to provide. Use clear names like location instead of loc.

Validate Function Arguments

Always validate arguments before executing functions. The model may occasionally provide invalid or unexpected values.

Handle Function Errors

Implement error handling for function execution. Return error messages in the function response so the model can inform the user appropriately.

Limit Function Count

Too many functions can confuse the model. Start with a focused set of functions and expand as needed. Consider grouping related operations.

Use Enums for Constrained Values

When parameters have a limited set of valid values, use enums in your schema. This helps the model choose the correct value.

Test Function Calling Thoroughly

Test with various user inputs to ensure the model calls the right functions with correct arguments. Edge cases and ambiguous requests are especially important to test.

Common Use Cases

Weather & Time

Get real-time weather, time zones, and location-based information.

Database Queries

Query databases, retrieve records, and perform CRUD operations.

API Integration

Call external APIs for payments, shipping, notifications, and more.

Calculations

Perform complex calculations, conversions, and mathematical operations.

Information Retrieval

Search knowledge bases, documents, and internal systems.

Scheduling

Create, update, and manage calendar events and appointments.

Related Resources

Was this page helpful?