Funzioni personalizzate (chiamata di funzioni)
In questa pagina
Collega Grok ai tuoi servizi
Gli strumenti server (web_search, x_search, code_interpreter) sono utili ma limitati ai servizi xAI. Con gli strumenti function personalizzati, puoi collegare Grok a qualsiasi API o servizio nella tua infrastruttura.
Come funziona
La chiamata di funzioni segue un ciclo in tre fasi:
- Dichiarazione: Descrivi le tue funzioni (nome, descrizione, parametri) nella richiesta
- Chiamata: Il modello genera una chiamata di funzione con gli argomenti appropriati e mette in pausa la generazione
- Risultato: Il tuo codice esegue la funzione, poi invii il risultato al modello affinché possa formulare la sua risposta
Dichiarare una funzione
{
"model": "grok-4.20-0309-reasoning",
"input": "Book me a table for 2 people tonight at 8 PM.",
"tools": [{
"type": "function",
"name": "book_restaurant",
"description": "Books a table at a restaurant",
"parameters": {
"type": "object",
"properties": {
"restaurant_name": {
"type": "string",
"description": "Restaurant name"
},
"date": {
"type": "string",
"description": "Date in YYYY-MM-DD format"
},
"time": {
"type": "string",
"description": "Time in HH:MM format"
},
"guests": {
"type": "integer",
"description": "Number of guests"
}
},
"required": ["date", "time", "guests"]
}
}]
}
La descrizione di ogni funzione e parametro è cruciale. Il modello li utilizza per decidere quando chiamare la funzione e come compilare gli argomenti.
Ricevere la chiamata di funzione
Quando il modello decide di chiamare la tua funzione, la risposta contiene un elemento function_call:
{
"id": "resp-xyz789",
"status": "completed",
"output": [{
"type": "function_call",
"name": "book_restaurant",
"arguments": "{\"date\": \"2026-04-03\", \"time\": \"20:00\", \"guests\": 2}",
"call_id": "call-abc123"
}]
}
Il campo arguments è una stringa JSON che devi analizzare. Il call_id identifica questa chiamata specifica.
Restituire il risultato
Dopo aver eseguito la funzione nel tuo codice, restituisci il risultato:
import json
# 1. Initial request
response = client.responses.create(
model="grok-4.20-0309-reasoning",
input="What's the weather like in Paris?",
tools=[{
"type": "function",
"name": "get_weather",
"description": "Retrieves current weather",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}]
)
# 2. Check if the model wants to call a function
for item in response.output:
if item.type == "function_call":
args = json.loads(item.arguments)
# 3. Execute your function
weather_data = get_weather_from_api(args["city"])
# 4. Return the result to the model
final = client.responses.create(
model="grok-4.20-0309-reasoning",
input=[{
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(weather_data)
}],
previous_response_id=response.id
)
print(final.output[0].content[0].text)
Migliori pratiche per le descrizioni
Il modello si basa sulle descrizioni per comprendere le tue funzioni. Sii preciso:
{
"name": "search_products",
"description": "Searches for products in the e-commerce catalog. Returns the top 10 results sorted by relevance. Supports search by name, category, or price range.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search terms (product name, brand, keyword)"
},
"category": {
"type": "string",
"enum": ["electronics", "clothing", "home", "sports"],
"description": "Product category to filter"
},
"max_price": {
"type": "number",
"description": "Maximum price in euros"
}
},
"required": ["query"]
}
}
Usa enum per valori predefiniti, una description dettagliata per ogni parametro e contrassegna come required solo i parametri essenziali.
Gestione degli errori
Se la tua funzione fallisce, restituisci l’errore come risultato:
try:
result = call_external_api(args)
output = json.dumps(result)
except Exception as e:
output = json.dumps({"error": str(e)})
final = client.responses.create(
model="grok-4.20-0309-reasoning",
input=[{
"type": "function_call_output",
"call_id": call_id,
"output": output
}],
previous_response_id=response.id
)
Il modello interpreta l’errore e può riformulare la sua risposta o provare un approccio diverso.
Punti chiave
- Le funzioni personalizzate collegano Grok ai tuoi servizi
- Il ciclo è: dichiara, ricevi la chiamata, esegui, restituisci il risultato
- Le descrizioni di funzioni e parametri guidano la scelta del modello
- Il campo
argumentsè una stringa JSON da analizzare lato client - Restituisci gli errori come risultati affinché il modello possa adattarsi