Function Calling: Verbind AI met Uw Systemen
Op deze pagina
Function Calling: Verbind AI met Uw Systemen
Met function calling kan het model functies aanroepen die u definieert. Houd één regel voor ogen, want daar volgt alles uit: het model voert ze niet uit. Het vertelt u welke functie moet worden aangeroepen en met welke argumenten; uw code voert de uitvoering uit en retourneert het resultaat. Uw database, inloggegevens en bedrijfslogica verlaten nooit uw infrastructuur.
De Volledige Stroom, Stap voor Stap
De uitwisseling verloopt in vier fasen:
- U declareert beschikbare functies samen met hun parameters
- Het model analyseert het verzoek en besluit een functie aan te roepen
- Uw code voert de functie uit en verkrijgt het resultaat
- U stuurt het resultaat terug naar het model zodat het zijn antwoord kan formuleren
De declaratie verdient speciale zorg: de description van de functie en de beschrijving van elke parameter zijn de enige documentatie waarover het model beschikt om zijn beslissing te nemen. Vage beschrijvingen leiden tot benaderende aanroepen. Let ook op hoe u de kring sluit: het resultaat gaat terug met de call_id die u hebt ontvangen, wat dient als bevestiging en de API in staat stelt het antwoord aan het verzoek te koppelen.
from openai import OpenAI
import json
client = OpenAI()
# Stap 1: Declareer beschikbare functies
tools = [{
"type": "function",
"name": "get_meteo",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"ville": {
"type": "string",
"description": "The name of the city"
},
"unite": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["ville"]
}
}]
# Stap 2: Het model besluit de functie aan te roepen
response = client.responses.create(
model="gpt-5.6-terra",
input="What's the weather like in Marseille?",
tools=tools
)
# Stap 3: Voer de functie uit
for item in response.output:
if item.type == "function_call":
print(f"Function: {item.name}")
print(f"Arguments: {item.arguments}")
args = json.loads(item.arguments)
# Uw daadwerkelijke implementatie
resultat_meteo = {"temperature": 22, "condition": "sunny"}
# Stap 4: Stuur het resultaat terug naar het model
final = client.responses.create(
model="gpt-5.6-terra",
input=[
{"role": "user", "content": "What's the weather like in Marseille?"},
{
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(resultat_meteo)
}
],
tools=tools
)
print(f"Response: {final.output_text}")
# Resultaat:
# Function: get_meteo
# Arguments: {"ville": "Marseille"}
# Response: It is currently 22 C in Marseille with sunny weather.
Het Model Laten Kiezen Tussen Meerdere Tools
De echte waarde komt naar voren wanneer u een volledige catalogus van mogelijkheden beschikbaar stelt. In een e-commerce-assistent zou u productzoeken, voorraadcontrole en orderplaatsing declareren, en vervolgens het model laten arbitrereren. Geconfronteerd met “Is de XPS gaming-laptop beschikbaar?”, zal het geen zoekopdracht uitvoeren, maar direct de voorraad raadplegen: uw functiebeschrijvingen, en niet een hard-gecodeerde regel, stuurden die keuze.
tools = [
{
"type": "function",
"name": "rechercher_produit",
"description": "Search for a product in the catalog",
"parameters": {
"type": "object",
"properties": {
"requête": {"type": "string", "description": "Search terms"},
"categorie": {"type": "string", "description": "Category (optional)"}
},
"required": ["requête"]
}
},
{
"type": "function",
"name": "verifier_stock",
"description": "Check product availability",
"parameters": {
"type": "object",
"properties": {
"produit_id": {"type": "string", "description": "Product ID"}
},
"required": ["produit_id"]
}
},
{
"type": "function",
"name": "passer_commande",
"description": "Place an order for a product",
"parameters": {
"type": "object",
"properties": {
"produit_id": {"type": "string"},
"quantite": {"type": "integer", "description": "Number of units"}
},
"required": ["produit_id", "quantite"]
}
}
]
# Het model kiest automatisch de juiste functie
response = client.responses.create(
model="gpt-5.6-terra",
input="Is the XPS gaming laptop available?",
tools=tools
)
for item in response.output:
if item.type == "function_call":
print(f"Function chosen: {item.name}")
print(f"Arguments: {item.arguments}")
# Resultaat: Function chosen: verifier_stock
# Arguments: {"produit_id": "xps-gaming"}
Een enkel verzoek kan ook meerdere aanroepen tegelijkertijd activeren. Het vergelijken van het weer in twee steden levert twee onafhankelijke aanroepen op: uw code moet daarom itereren door response.output en alle function_call-items afhandelen, nooit slechts de eerste. Dit is ook een kans om deze aanroepen parallel uit te voeren en de latentie te halveren.
response = client.responses.create(
model="gpt-5.6-terra",
input="Compare the weather between Paris and Lyon.",
tools=[{
"type": "function",
"name": "get_meteo",
"description": "Get the weather for a city",
"parameters": {
"type": "object",
"properties": {
"ville": {"type": "string"}
},
"required": ["ville"]
}
}]
)
# Het model doet twee aanroepen parallel
function_calls = [item for item in response.output if item.type == "function_call"]
print(f"Number of calls: {len(function_calls)}")
for call in function_calls:
args = json.loads(call.arguments)
print(f" - get_meteo({args['ville']})")
# Resultaat:
# Number of calls: 2
# - get_meteo(Paris)
# - get_meteo(Lyon)
De Agent-lus
Een enkele round-trip is zelden voldoende: het resultaat van één functie leidt het model er vaak toe een andere aan te roepen. U wikkelt de uitwisseling daarom in een lus die draait zolang het antwoord functieaanroepen bevat en stopt zodra dit niet meer het geval is – een teken dat het model zijn definitieve antwoord heeft geformuleerd. Dit is het skelet van elke agent, en u zult het in verschillende gedaanten tegenkomen in alle agent-frameworks.
def executer_fonction(nom: str, arguments: str) -> str:
"""Execute a function and return the result."""
args = json.loads(arguments)
if nom == "get_meteo":
# Simulatie — vervang door uw echte API
return json.dumps({"temp": 18, "condition": "cloudy"})
elif nom == "get_heure":
return json.dumps({"heure": "14:30", "timezone": "CET"})
return json.dumps({"error": "Unknown function"})
def agent_loop(question: str, tools: list) -> str:
"""Agent loop: call functions until the final response."""
input_messages = [{"role": "user", "content": question}]
while True:
response = client.responses.create(
model="gpt-5.6-terra",
input=input_messages,
tools=tools
)
# Controleer op functieaanroepen
function_calls = [i for i in response.output if i.type == "function_call"]
if not function_calls:
# Geen functieaanroepen = definitief antwoord
return response.output_text
# Voer elke functie uit en voeg resultaten toe
for call in function_calls:
resultat = executer_fonction(call.name, call.arguments)
input_messages.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": resultat
})
# Gebruik
reponse = agent_loop("What's the weather like in Paris?", tools)
print(reponse)
Een woord van waarschuwing bij dit patroon: de while True-lus heeft geen beveiliging. Voeg in productie een maximale iteratieteller toe; anders zal een model dat eindeloos dezelfde tool aanvraagt uw budget opbranden zonder ooit tot een conclusie te komen.
Vergrendel Argumenten met Strikte Modus
Strikte modus past dezelfde garantie toe op functieparameters als Structured Output op antwoorden: argumenten houden zich strikt aan het gedeclareerde schema. Voor een functie die een gebruiker aanmaakt, voorkomt dit dat u een leeftijd als string ontvangt, of een extra veld waarop uw code niet was voorbereid.
tools = [{
"type": "function",
"name": "creer_utilisateur",
"description": "Create a new user",
"strict": True,
"parameters": {
"type": "object",
"properties": {
"nom": {"type": "string"},
"email": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["nom", "email", "age"],
"additionalProperties": False
}
}]
Belangrijkste punten
- Function calling verbindt het model met uw systemen zonder uw data bloot te stellen
- Het model beslist welke functie wordt aangeroepen; uw code voert deze uit
- Retourneer het resultaat met
function_call_outputen decall_id - Het model kan meerdere functies parallel aanroepen
- Gebruik een agent-lus voor conversaties met meerdere beurten waarbij functies betrokken zijn
- Schakel
strict: Truein om naleving van argumenten te garanderen