We use cookies to enhance your experience on the site
CodeWorlds

Function Calling - AI with Tools

Function Calling allows AI to invoke functions and tools! 🔧

Function Calling Basics

1from openai import OpenAI
2import json
3
4client = OpenAI()
5
6# Define tools
7tools = [
8    {
9        "type": "function",
10        "function": {
11            "name": "get_animal_info",
12            "description": "Retrieves information about a Safari animal",
13            "parameters": {
14                "type": "object",
15                "properties": {
16                    "animal_name": {
17                        "type": "string",
18                        "description": "Name of the animal, e.g. 'lion', 'elephant'"
19                    }
20                },
21                "required": ["animal_name"]
22            }
23        }
24    },
25    {
26        "type": "function",
27        "function": {
28            "name": "get_weather",
29            "description": "Retrieves weather for a Safari location",
30            "parameters": {
31                "type": "object",
32                "properties": {
33                    "location": {
34                        "type": "string",
35                        "description": "Location name, e.g. 'Serengeti'"
36                    }
37                },
38                "required": ["location"]
39            }
40        }
41    }
42]
43
44# Call with tools
45response = client.chat.completions.create(
46    model="gpt-5",
47    messages=[{"role": "user", "content": "Tell me about lions and the weather in Serengeti"}],
48    tools=tools,
49    tool_choice="auto"
50)
51
52# Check if the model wants to call a function
53message = response.choices[0].message
54if message.tool_calls:
55    for tool_call in message.tool_calls:
56        function_name = tool_call.function.name
57        arguments = json.loads(tool_call.function.arguments)
58        print(f"Model wants to call: {function_name}({arguments})")

Function Implementation

1# Our function implementations
2def get_animal_info(animal_name: str) -> dict:
3    animals_db = {
4        "lion": {
5            "name": "African lion",
6            "population": 20000,
7            "habitat": "Savanna",
8            "diet": "Carnivore"
9        },
10        "elephant": {
11            "name": "African elephant",
12            "population": 415000,
13            "habitat": "Savanna and forests",
14            "diet": "Herbivore"
15        }
16    }
17    return animals_db.get(animal_name.lower(), {"error": "Unknown animal"})
18
19def get_weather(location: str) -> dict:
20    # In a real application - call a weather API
21    return {
22        "location": location,
23        "temperature": 28,
24        "conditions": "Sunny",
25        "humidity": 45
26    }
27
28# Function name mapping
29available_functions = {
30    "get_animal_info": get_animal_info,
31    "get_weather": get_weather
32}

Full Flow with Function Calling

1def chat_with_tools(user_message: str):
2    messages = [{"role": "user", "content": user_message}]
3
4    # First call
5    response = client.chat.completions.create(
6        model="gpt-5",
7        messages=messages,
8        tools=tools
9    )
10
11    message = response.choices[0].message
12
13    # If the model wants to call functions
14    if message.tool_calls:
15        messages.append(message)  # Add assistant response
16
17        # Execute all function calls
18        for tool_call in message.tool_calls:
19            function_name = tool_call.function.name
20            arguments = json.loads(tool_call.function.arguments)
21
22            # Call the function
23            function_response = available_functions[function_name](**arguments)
24
25            # Add result to messages
26            messages.append({
27                "role": "tool",
28                "tool_call_id": tool_call.id,
29                "content": json.dumps(function_response)
30            })
31
32        # Second call - model processes the results
33        final_response = client.chat.completions.create(
34            model="gpt-5",
35            messages=messages
36        )
37
38        return final_response.choices[0].message.content
39
40    return message.content
41
42# Test
43result = chat_with_tools("What is the largest animal and what's the weather in Serengeti?")
44print(result)

LangChain Tools

1from langchain.tools import tool
2from langchain.agents import create_tool_calling_agent, AgentExecutor
3from langchain_openai import ChatOpenAI
4from langchain_core.prompts import ChatPromptTemplate
5
6@tool
7def search_safari_animals(query: str) -> str:
8    """Searches for information about Safari animals."""
9    # Implementation
10    return f"Information about: {query}"
11
12@tool
13def calculate_distance(from_loc: str, to_loc: str) -> str:
14    """Calculates the distance between Safari locations."""
15    return f"Distance from {from_loc} to {to_loc}: 150 km"
16
17# Agent with tools
18tools = [search_safari_animals, calculate_distance]
19llm = ChatOpenAI(model="gpt-5")
20
21prompt = ChatPromptTemplate.from_messages([
22    ("system", "You are a helpful Safari assistant."),
23    ("human", "{input}"),
24    ("placeholder", "{agent_scratchpad}")
25])
26
27agent = create_tool_calling_agent(llm, tools, prompt)
28agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
29
30result = agent_executor.invoke({
31    "input": "How far is it from Nairobi to Serengeti?"
32})
Go to CodeWorlds