Volanie funkcií: Pripojte AI k svojim systémom
Na tejto strane
Volanie funkcií: Pripojte AI k svojim systémom
Volanie funkcií umožňuje modelu vyvolávať funkcie, ktoré definuješ ty. Zapamätaj si jedno zásadné pravidlo, pretože od neho sa odvíja všetko ostatné: model tieto funkcie nevykonáva. Iba ti oznámi, ktorú funkciu zavolať a s akými argumentmi; vykonanie zabezpečí tvoj kód a vráti výsledok. Tvoja databáza, poverenia ani business logika nikdy neopustia tvoju infraštruktúru.
Celý proces krok za krokom
Komunikácia prebieha v štyroch fázach:
- Deklaruješ dostupné funkcie spolu s ich parametrami
- Model analyzuje požiadavku a rozhodne sa zavolať funkciu
- Tvoj kód funkciu vykoná a získa výsledok
- Výsledok pošleš späť modelu, aby mohol sformulovať odpoveď
Deklarácia si vyžaduje osobitnú pozornosť: description funkcie a popis každého parametra sú jedinou dokumentáciou, ktorú model má k dispozícii pri rozhodovaní. Vágne popisy vedú k nepresným volaniam. Všimni si tiež, ako uzavrieť cyklus – výsledok sa vracia s call_id, ktoré si dostal. To slúži ako potvrdenie a umožňuje API spárovať odpoveď s požiadavkou.
from openai import OpenAI
import json
client = OpenAI()
# Step 1: Declare available functions
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"]
}
}]
# Step 2: The model decides to call the function
response = client.responses.create(
model="gpt-5.6-terra",
input="What's the weather like in Marseille?",
tools=tools
)
# Step 3: Execute the function
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)
# Your actual implementation
resultat_meteo = {"temperature": 22, "condition": "sunny"}
# Step 4: Send the result back to the 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}")
# Result:
# Function: get_meteo
# Arguments: {"ville": "Marseille"}
# Response: It is currently 22 C in Marseille with sunny weather.
Nechaj model vybrať si z viacerých nástrojov
Skutočná hodnota sa prejaví, keď vystavíš celý katalóg schopností. V asistentovi pre e-commerce by si deklaroval vyhľadávanie produktov, overenie skladových zásob a zadanie objednávky a nechal model, aby rozhodol. Keď dostane otázku „Je herný notebook XPS dostupný?“, nevykoná vyhľadávanie, ale priamo sa opýta na stav zásob: toto rozhodnutie riadili tvoje popisy funkcií, nie natvrdo naprogramované pravidlo.
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"]
}
}
]
# The model automatically chooses the right function
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}")
# Result: Function chosen: verifier_stock
# Arguments: {"produit_id": "xps-gaming"}
Jedna požiadavka môže zároveň spustiť viacero volaní naraz. Porovnanie počasia v dvoch mestách vygeneruje dve nezávislé volania: tvoj kód preto musí iterovať cez response.output a spracovať všetky položky function_call, nie len prvú. Je to tiež príležitosť vykonať tieto volania paralelne a skrátiť latenciu na polovicu.
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"]
}
}]
)
# The model makes two calls in 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']})")
# Result:
# Number of calls: 2
# - get_meteo(Paris)
# - get_meteo(Lyon)
Cyklus agenta
Jedna výmena zriedka stačí: výsledok jednej funkcie často vedie model k tomu, aby zavolal ďalšiu. Celú komunikáciu preto zabalíš do cyklu, ktorý beží dovtedy, kým odpoveď obsahuje volania funkcií, a zastaví sa hneď, ako ich neobsahuje – čo je signál, že model sformuloval konečnú odpoveď. Toto je kostra každého agenta a stretneš sa s ňou v rôznych podobách vo všetkých frameworkoch pre agentov.
def executer_fonction(nom: str, arguments: str) -> str:
"""Execute a function and return the result."""
args = json.loads(arguments)
if nom == "get_meteo":
# Simulation — replace with your real 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
)
# Check for function calls
function_calls = [i for i in response.output if i.type == "function_call"]
if not function_calls:
# No function calls = final response
return response.output_text
# Execute each function and add results
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
})
# Usage
reponse = agent_loop("What's the weather like in Paris?", tools)
print(reponse)
Pri tomto vzore buď opatrný: cyklus while True nemá žiadne ochranné mechanizmy. V produkčnom prostredí pridaj maximálny počet iterácií; inak model, ktorý bude donekonečna požadovať ten istý nástroj, minie tvoj rozpočet bez toho, aby niekedy dospel k záveru.
Uzamkni argumenty pomocou striktného režimu
Striktný režim aplikuje na parametre funkcií rovnakú záruku, akú poskytuje Štruktúrovaný výstup pre odpovede: argumenty striktne dodržiavajú deklarovanú schému. Pri funkcii, ktorá vytvára používateľa, to zabraňuje situácii, keď dostaneš vek ako reťazec alebo extra pole, ktoré tvoj kód neočakával.
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
}
}]
Kľúčové poznatky
- Volanie funkcií pripája model k tvojim systémom bez toho, aby odhalilo tvoje dáta
- Model rozhoduje, ktorú funkciu zavolať; tvoj kód ju vykonáva
- Výsledok vráť pomocou
function_call_outputacall_id - Model môže volať viacero funkcií paralelne
- Na konverzácie zahŕňajúce funkcie s viacerými kolami použij cyklus agenta
- Povoľ
strict: Truepre garantovanie súladu argumentov