Usare le API Kora da Python
Ogni sezione parte da una domanda e la risposta è il codice Python da usare. Le funzioni sono indipendenti: copia solo quelle che ti servono, insieme alla configurazione iniziale.
Come configuro l’accesso alle API?
URL base e chiave API si leggono dalle variabili d’ambiente (anche da un file .env). Ogni richiesta invia la chiave nell’header Authorization come Bearer token.
# .env
KORA_BASE_URL=https://...
KORA_API_KEY=la-tua-chiave
from typing import Dict, Any, Optional
import requests
import os
from dotenv import load_dotenv
load_dotenv()
KORA_BASE_URL: str = str(os.environ["KORA_BASE_URL"])
KORA_API_KEY: str = str(os.environ["KORA_API_KEY"])
# header di autorizzazione usato in tutte le richieste
HEADERS: Dict[str, str] = {"Authorization": f"Bearer {KORA_API_KEY}"}
Il codice usa verify=False, che disattiva il controllo del certificato TLS. Va bene in test; in produzione è meglio rimuoverlo e usare un certificato valido.
Come richiedo le categorie di un’organizzazione?
GET /Categories
La chiamata restituisce tutte le categorie visibili con la tua chiave. Ogni categoria include il campo organizationGUID, quindi puoi raggrupparle per organizzazione. Il guid della categoria serve per creare una chat.
def get_categories() -> Dict[str, str]:
"""Recupera tutte le categorie visibili."""
response = requests.get(
url=f"{KORA_BASE_URL}/Categories",
headers=HEADERS,
verify=False,
)
response.raise_for_status() # eccezione su errori 40x/50x
return response.json()
# esempio d'uso
categories = get_categories()
for category in categories:
print(f"GUID: {category['guid']}, name: {category['name']}, ORG_GUID: {category['organizationGUID']}")
Risposta
[
{
"guid": "64sfg...",
"name": "test_category",
"organizationGUID": "6fgf..."
}
]
Come creo una nuova chat?
POST /Chat
Una chat appartiene a una categoria. Servono organizationGUID e categoryGUID (li ottieni dalla chiamata precedente) e un titolo. Il parametro external_user è facoltativo e associa la chat a un utente esterno.
def create_chat(organization_guid: str,
category_guid: str,
title: str,
external_user: Optional[Dict[str, str]] = None) -> Dict[Any, Any]:
"""Crea una nuova chat per una categoria."""
payload: dict[str, Any] = {
"organizationGUID": organization_guid,
"categoryGUID": category_guid,
"title": title,
}
if external_user: # aggiunge l'utente esterno solo se presente
payload["externalUser"] = external_user
response = requests.post(
url=f"{KORA_BASE_URL}/Chat",
headers=HEADERS,
json=payload,
verify=False,
)
response.raise_for_status()
return response.json()
# esempio d'uso: crea una chat nella prima categoria
category = categories[0]
chat = create_chat(
organization_guid=category["organizationGUID"],
category_guid=category["guid"],
title="Test API kora Python",
)
chat_guid = chat["chatGUID"] # da conservare per le chiamate successive
Risposta
{
"chatGUID": "60f5ee65-e43a-4ab8-a83d-87436ab054b3",
"title": "Test API kora python",
"categoryGUID": "1de9c564-dbdb-4866-a68a-209bb427d1de",
"categoryName": "test",
"lastUpdate": "2026-10-12T15:24:48.6646769Z",
"externalUser": None
}
Esempio con utente esterno
chat = create_chat(
organization_guid=category["organizationGUID"],
category_guid=category["guid"],
title="Warranty question",
external_user={
"id": "u-4821",
"name": "Mario Rossi",
"email": "Questo indirizzo email è protetto dagli spambots. È necessario abilitare JavaScript per vederlo. ",
},
)
Come faccio una domanda in una chat?
POST /Chat/{chat_guid}/Messages → GET /Chat/{chat_guid}/Messages/{message_guid}/Stream
Sono due passaggi. Prima si invia la domanda: la risposta contiene l’elenco dei messaggi e l’ultimo ha stato PENDING (risposta in elaborazione). Poi si apre lo stream di quel messaggio e si leggono i frammenti di risposta man mano che arrivano.
Lo stream usa eventi che iniziano con data: ; una riga vuota chiude l’evento. Il valore [DONE] indica la fine senza errori, mentre [ERROR:...] segnala un problema.
def ask(chat_guid: str, question: str) -> None:
"""Invia una domanda e stampa la risposta man mano che arriva."""
# 1) invia la domanda
messages = requests.post(
f"{KORA_BASE_URL}/Chat/{chat_guid}/Messages",
json={"message": question},
headers=HEADERS,
verify=False,
)
messages.raise_for_status()
answer = messages.json()[-1] # l'ultimo messaggio è la risposta in arrivo
if answer["status"] != "PENDING":
raise RuntimeError(f"Kora can't answer: {answer['status']}")
# 2) legge la risposta in streaming
url = f"{KORA_BASE_URL}/Chat/{chat_guid}/Messages/{answer['guid']}/Stream"
with requests.get(url, headers=HEADERS, stream=True, verify=False) as stream:
stream.raise_for_status()
lines = []
for line in stream.iter_lines(decode_unicode=True):
if str(line).startswith("data: "): # frammento di risposta
lines.append(line[len("data: "):])
elif line == "" and lines: # una riga vuota chiude l'evento
piece, lines = "\n".join(lines), []
if piece == "[DONE]": # fine, nessun errore
break
if piece.startswith("[ERROR:"):
raise RuntimeError(f"Kora can't answer: {piece}")
print(piece, end="", flush=True)
# esempio d'uso
ask(chat_guid=chat_guid, question="cosa sai fare per me?")
La funzione stampa la risposta ma non la restituisce. Se ti serve il testo completo, accumula i valori di piece in una lista invece di stamparli e restituisci "".join(...) alla fine.
Come recupero i messaggi già scambiati in una chat?
GET /Chat/{chat_guid}/Messages
Restituisce la cronologia completa, in ordine di messageIndex. Il campo role distingue le domande (user) dalle risposte (assistant).
def get_chat_messages(chat_guid: str):
"""Recupera i messaggi scambiati in una chat."""
history = requests.get(
f"{KORA_BASE_URL}/Chat/{chat_guid}/Messages",
headers=HEADERS,
verify=False,
)
history.raise_for_status()
return history.json()
# esempio d'uso
for m in get_chat_messages(chat_guid=chat_guid):
print(f"[{m['role']}] {m['content']}")
Risposta
[
{
"guid": "aaff6450-dab4-4933-bcde-b5f0688725fb",
"messageIndex": 0,
"role": "user",
"content": "cosa sai fare per me?",
"sentAt": "2026-10-14T07:58:57.168664Z",
"status": "COMPLETE",
"answerFound": True
},
{
"guid": "a1c44bf5-c47d-44f8-97b6-501ac71853cf",
"messageIndex": 1,
"role": "assistant",
"content": "Posso aiutarti a gestire e recuperare informazioni aziendali...",
"sentAt": "2026-10-14T07:58:57.168664Z",
"status": "COMPLETE",
"answerFound": False
}
]