File size: 21,643 Bytes
ac52c4d
 
cb51311
ac52c4d
 
89f944e
51695fc
d9ab7eb
 
 
 
8b2fc25
b6960a0
8b2fc25
 
 
ac52c4d
3421ea1
2ecaeab
be4828b
2ecaeab
51695fc
2ecaeab
ac52c4d
 
3421ea1
ac52c4d
 
848d0c0
 
ac52c4d
3421ea1
 
 
dbeb9da
8607561
3421ea1
e250196
 
3421ea1
 
 
d9ab7eb
3421ea1
 
 
 
ff8bfcc
3421ea1
ac52c4d
3421ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbeb9da
3421ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
dbeb9da
3421ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
ac52c4d
3421ea1
 
 
 
 
 
30e0c2a
3421ea1
 
 
 
 
 
 
 
30e0c2a
3421ea1
 
 
 
 
30e0c2a
3421ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a264007
3421ea1
 
 
 
 
 
 
 
 
 
a264007
3421ea1
 
 
 
 
 
 
 
 
69d6e40
3421ea1
 
 
 
 
 
89f944e
ac52c4d
89f944e
3421ea1
ac52c4d
3421ea1
848d0c0
89f944e
e250196
51695fc
 
 
 
 
 
 
 
e250196
51695fc
 
 
 
 
 
 
 
 
 
3421ea1
 
 
 
 
 
 
51695fc
3421ea1
 
51695fc
e250196
dbeb9da
51695fc
dbeb9da
51695fc
dbeb9da
3421ea1
51695fc
3421ea1
e250196
51695fc
3421ea1
 
 
 
 
 
 
 
30e0c2a
3421ea1
 
 
30e0c2a
3421ea1
 
 
 
30e0c2a
3421ea1
 
 
30e0c2a
3421ea1
 
 
 
30e0c2a
3421ea1
 
 
 
 
 
 
 
ff8bfcc
3421ea1
ac52c4d
d9ab7eb
 
4c13256
dbeb9da
d3f5358
 
 
 
848d0c0
d3f5358
 
d9ab7eb
 
d3f5358
 
3421ea1
 
 
 
 
 
 
d3f5358
dbeb9da
3421ea1
d3f5358
dbeb9da
d3f5358
 
 
 
51695fc
 
3421ea1
 
dbeb9da
e250196
8607561
bfa70d6
51695fc
ff8bfcc
30e0c2a
b6960a0
ff8bfcc
 
 
30e0c2a
b6960a0
 
 
 
 
 
 
 
 
 
 
30e0c2a
ac52c4d
b6960a0
 
 
 
a2371d8
b6960a0
 
 
 
 
 
 
 
 
 
 
30e0c2a
ff8bfcc
bfa70d6
 
 
ac52c4d
b6960a0
ac52c4d
 
cb51311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e0c2a
 
cb51311
30e0c2a
cb51311
 
 
 
 
30e0c2a
3421ea1
 
 
 
 
 
cb51311
 
 
8b2fc25
ac52c4d
 
8b2fc25
30e0c2a
8b2fc25
ac52c4d
 
8b2fc25
 
e250196
 
30e0c2a
 
 
 
 
 
3421ea1
 
 
 
 
 
d9ab7eb
3421ea1
ff8bfcc
8b2fc25
bfa70d6
3421ea1
ff8bfcc
3421ea1
 
 
 
51695fc
bfa70d6
 
8b2fc25
ff8bfcc
3421ea1
ff8bfcc
3421ea1
 
 
 
 
 
 
 
848d0c0
8b2fc25
8607561
bfa70d6
8b2fc25
8607561
8b2fc25
3421ea1
8607561
bfa70d6
8b2fc25
e250196
8607561
8b2fc25
3421ea1
8607561
8b2fc25
ff8bfcc
3421ea1
ff8bfcc
3421ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
8607561
8b2fc25
 
8607561
bfa70d6
8b2fc25
8607561
3421ea1
dbeb9da
e250196
8b2fc25
51695fc
e250196
8b2fc25
3421ea1
ff8bfcc
3421ea1
 
 
69d6e40
8607561
8b2fc25
 
 
 
8607561
ac52c4d
 
848d0c0
dbeb9da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import os
import logging
from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
import rdflib
from rdflib import RDF, RDFS, OWL
from sentence_transformers import SentenceTransformer
import faiss
import json
import numpy as np
from dotenv import load_dotenv
import requests

# Carica le variabili d'ambiente
load_dotenv()

# Configura il logging
logging.basicConfig(
    level=logging.INFO,  # Ridotto da DEBUG per migliorare le prestazioni
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[logging.FileHandler("app.log"), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

# Recupera la chiave API
API_KEY = os.getenv("HF_API_KEY")
if not API_KEY:
    logger.error("HF_API_KEY non impostata.")
    raise EnvironmentError("HF_API_KEY non impostata.")

# Definisci i percorsi dei file
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
RDF_FILE = os.path.join(BASE_DIR, "Ontologia.rdf")
HF_MODEL = "google/flan-t5-xxl"  # Modello ottimizzato per seguire istruzioni

MAX_CLASSES = 30
MAX_PROPERTIES = 30

# Percorsi dei file generati
DOCUMENTS_FILE = os.path.join(BASE_DIR, "data", "documents.json")
FAISS_INDEX_FILE = os.path.join(BASE_DIR, "data", "faiss.index")

def create_data_directory():
    """Crea la directory 'data/' se non esiste."""
    os.makedirs(os.path.join(BASE_DIR, "data"), exist_ok=True)
    logger.info("Directory 'data/' creata o già esistente.")

def extract_ontology(rdf_file: str, output_file: str):
    """
    Estrae classi, proprietà ed entità dall'ontologia RDF e le salva in un file JSON come un unico documento.
    """
    logger.info(f"Inizio estrazione dell'ontologia da {rdf_file}.")
    g = rdflib.Graph()
    try:
        g.parse(rdf_file, format="xml")
        logger.info(f"Parsing RDF di {rdf_file} riuscito.")
    except Exception as e:
        logger.error(f"Errore nel parsing RDF: {e}")
        raise e

    # Estrai Classi
    classes = []
    for cls in g.subjects(RDF.type, OWL.Class):
        label = g.value(cls, RDFS.label, default=str(cls))
        description = g.value(cls, RDFS.comment, default="No description.")
        classes.append({"class": str(cls), "label": str(label), "description": str(description)})

    for cls in g.subjects(RDF.type, RDFS.Class):
        label = g.value(cls, RDFS.label, default=str(cls))
        description = g.value(cls, RDFS.comment, default="No description.")
        classes.append({"class": str(cls), "label": str(label), "description": str(description)})

    # Estrai Proprietà
    properties = []
    for prop in g.subjects(RDF.type, OWL.ObjectProperty):
        label = g.value(prop, RDFS.label, default=str(prop))
        description = g.value(prop, RDFS.comment, default="No description.")
        properties.append({"property": str(prop), "label": str(label), "description": str(description)})

    for prop in g.subjects(RDF.type, OWL.DatatypeProperty):
        label = g.value(prop, RDFS.label, default=str(prop))
        description = g.value(prop, RDFS.comment, default="No description.")
        properties.append({"property": str(prop), "label": str(label), "description": str(description)})

    for prop in g.subjects(RDF.type, RDF.Property):
        label = g.value(prop, RDFS.label, default=str(prop))
        description = g.value(prop, RDFS.comment, default="No description.")
        properties.append({"property": str(prop), "label": str(label), "description": str(description)})

    # Estrai Entità (NamedIndividuals)
    entities = []
    for entity in g.subjects(RDF.type, OWL.NamedIndividual):
        label = g.value(entity, RDFS.label, default=str(entity))
        description = g.value(entity, RDFS.comment, default="No description.")
        # Estrai le proprietà dell'entità
        entity_properties = {}
        for predicate, obj in g.predicate_objects(entity):
            if predicate not in [RDFS.label, RDFS.comment]:
                entity_properties[str(predicate)] = str(obj)
        entities.append({
            "entity": str(entity),
            "label": str(label),
            "description": str(description),
            "properties": entity_properties
        })

    # Crea un unico documento
    ontology_summary = {
        "title": "Ontologia Museo",
        "classes": classes[:MAX_CLASSES],
        "properties": properties[:MAX_PROPERTIES],
        "entities": entities,  # Aggiungi le entità
        "full_ontology": g.serialize(format="xml").decode('utf-8') if isinstance(g.serialize(format="xml"), bytes) else g.serialize(format="xml")  # Decodifica rimossa
    }

    # Salva il documento in JSON
    try:
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(ontology_summary, f, ensure_ascii=False, indent=2)
        logger.info(f"Ontologia estratta e salvata in {output_file}")
    except Exception as e:
        logger.error(f"Errore nel salvataggio di {output_file}: {e}")
        raise e

def create_faiss_index(documents_file: str, index_file: str, embedding_model: str = 'all-MiniLM-L6-v2'):
    """
    Crea un indice FAISS a partire dal documento estratto.
    """
    logger.info(f"Inizio creazione dell'indice FAISS da {documents_file}.")
    try:
        # Carica il documento
        with open(documents_file, "r", encoding="utf-8") as f:
            document = json.load(f)
        logger.info(f"Documento caricato da {documents_file}.")

        # Genera embedding
        model = SentenceTransformer(embedding_model)
        # Concatenazione delle classi, proprietà e entità per l'embedding
        texts = [f"Classe: {cls['label']}. Descrizione: {cls['description']}" for cls in document['classes']]
        texts += [f"Proprietà: {prop['label']}. Descrizione: {prop['description']}" for prop in document['properties']]
        texts += [f"Entità: {entity['label']}. Descrizione: {entity['description']}. Proprietà: {entity['properties']}" for entity in document.get('entities', [])]
        embeddings = model.encode(texts, convert_to_numpy=True)
        logger.info("Embedding generati con SentenceTransformer.")

        # Crea l'indice FAISS
        dimension = embeddings.shape[1]
        index = faiss.IndexFlatL2(dimension)
        index.add(embeddings)
        logger.info(f"Indice FAISS creato con dimensione: {dimension}.")

        # Salva l'indice
        faiss.write_index(index, index_file)
        logger.info(f"Indice FAISS salvato in {index_file}.")
    except Exception as e:
        logger.error(f"Errore nella creazione dell'indice FAISS: {e}")
        raise e

def prepare_retrieval():
    """Prepara i file necessari per l'approccio RAG."""
    logger.info("Inizio preparazione per il retrieval.")
    create_data_directory()

    # Verifica se Ontologia.rdf esiste
    if not os.path.exists(RDF_FILE):
        logger.error(f"File RDF non trovato: {RDF_FILE}")
        raise FileNotFoundError(f"File RDF non trovato: {RDF_FILE}")
    else:
        logger.info(f"File RDF trovato: {RDF_FILE}")

    # Verifica se documents.json esiste, altrimenti generarlo
    if not os.path.exists(DOCUMENTS_FILE):
        logger.info(f"File {DOCUMENTS_FILE} non trovato. Estrazione dell'ontologia.")
        try:
            extract_ontology(RDF_FILE, DOCUMENTS_FILE)
        except Exception as e:
            logger.error(f"Errore nell'estrazione dell'ontologia: {e}")
            raise e
    else:
        logger.info(f"File {DOCUMENTS_FILE} trovato.")

    # Verifica se faiss.index esiste, altrimenti crearlo
    if not os.path.exists(FAISS_INDEX_FILE):
        logger.info(f"File {FAISS_INDEX_FILE} non trovato. Creazione dell'indice FAISS.")
        try:
            create_faiss_index(DOCUMENTS_FILE, FAISS_INDEX_FILE)
        except Exception as e:
            logger.error(f"Errore nella creazione dell'indice FAISS: {e}")
            raise e
    else:
        logger.info(f"File {FAISS_INDEX_FILE} trovato.")

def extract_classes_and_properties(rdf_file: str) -> str:
    """
    Carica l'ontologia e crea un 'sunto' di Classi, Proprietà ed Entità
    (senza NamedIndividuals) per ridurre i token.
    """
    logger.info(f"Inizio estrazione di classi, proprietà ed entità da {rdf_file}.")
    g = rdflib.Graph()
    try:
        g.parse(rdf_file, format="xml")
        logger.info(f"Parsing RDF di {rdf_file} riuscito.")
    except Exception as e:
        logger.error(f"Errore nel parsing RDF: {e}")
        return "PARSING_ERROR"

    # Troviamo le classi
    classes_found = set()
    for s in g.subjects(RDF.type, OWL.Class):
        classes_found.add(s)
    for s in g.subjects(RDF.type, RDFS.Class):
        classes_found.add(s)
    classes_list = sorted(str(c) for c in classes_found)
    classes_list = classes_list[:MAX_CLASSES]

    # Troviamo le proprietà
    props_found = set()
    for p in g.subjects(RDF.type, OWL.ObjectProperty):
        props_found.add(p)
    for p in g.subjects(RDF.type, OWL.DatatypeProperty):
        props_found.add(p)
    for p in g.subjects(RDF.type, RDF.Property):
        props_found.add(p)
    props_list = sorted(str(x) for x in props_found)
    props_list = props_list[:MAX_PROPERTIES]

    # Troviamo le entità
    entities_found = set()
    for e in g.subjects(RDF.type, OWL.NamedIndividual):
        entities_found.add(e)
    entities_list = sorted(str(e) for e in entities_found)
    entities_list = entities_list[:MAX_CLASSES]  # Puoi impostare un limite adeguato

    txt_classes = "\n".join([f"- CLASSE: {c}" for c in classes_list])
    txt_props = "\n".join([f"- PROPRIETÀ: {p}" for p in props_list])
    txt_entities = "\n".join([f"- ENTITÀ: {e}" for e in entities_list])

    summary = f"""\
# CLASSI (max {MAX_CLASSES})
{txt_classes}
# PROPRIETÀ (max {MAX_PROPERTIES})
{txt_props}
# ENTITÀ (max {MAX_CLASSES})
{txt_entities}
"""
    logger.info("Estrazione di classi, proprietà ed entità completata.")
    return summary

def retrieve_relevant_documents(query: str, top_k: int = 5):
    """Recupera i documenti rilevanti usando FAISS."""
    logger.info(f"Recupero dei documenti rilevanti per la query: {query}")
    try:
        # Carica il documento
        with open(DOCUMENTS_FILE, "r", encoding="utf-8") as f:
            document = json.load(f)
        logger.info(f"Documento caricato da {DOCUMENTS_FILE}.")

        # Carica l'indice FAISS
        index = faiss.read_index(FAISS_INDEX_FILE)
        logger.info(f"Indice FAISS caricato da {FAISS_INDEX_FILE}.")

        # Genera embedding della query
        model = SentenceTransformer('all-MiniLM-L6-v2')
        query_embedding = model.encode([query], convert_to_numpy=True)
        logger.info("Embedding della query generati.")

        # Ricerca nell'indice
        distances, indices = index.search(query_embedding, top_k)
        logger.info(f"Ricerca FAISS completata. Risultati ottenuti: {len(indices[0])}")

        # Concatenazione delle descrizioni per la ricerca
        texts = [f"Classe: {cls['label']}. Descrizione: {cls['description']}" for cls in document['classes']]
        texts += [f"Proprietà: {prop['label']}. Descrizione: {prop['description']}" for prop in document['properties']]
        texts += [f"Entità: {entity['label']}. Descrizione: {entity['description']}. Proprietà: {entity['properties']}" for entity in document.get('entities', [])]

        # Recupera i testi rilevanti
        relevant_texts = [texts[idx] for idx in indices[0] if idx < len(texts)]
        retrieved_docs = "\n".join(relevant_texts)
        logger.info(f"Documenti rilevanti recuperati: {len(relevant_texts)}")
        return retrieved_docs
    except Exception as e:
        logger.error(f"Errore nel recupero dei documenti rilevanti: {e}")
        raise e

def create_system_message(ont_text: str, retrieved_docs: str) -> str:
    """
    Prompt di sistema robusto, con regole su query in una riga e
    informazioni recuperate tramite RAG.
    """
    return f"""\
### Istruzioni ###
Sei un assistente museale esperto in ontologie RDF. Utilizza le informazioni fornite per generare query SPARQL precise e pertinenti.

### Ontologia ###
{ont_text}
### FINE Ontologia ###

Ecco alcune informazioni rilevanti recuperate dalla base di conoscenza:
{retrieved_docs}

### Regole Stringenti ###
1) Se l'utente chiede informazioni su questa ontologia, genera SEMPRE una query SPARQL in UNA SOLA RIGA, con prefix:
   PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/progettoMuseo#>
2) La query SPARQL deve essere precisa e cercare esattamente le entità specificate dall'utente. Ad esempio, se l'utente chiede "Chi ha creato l'opera 'Amore e Psiche'?", la query dovrebbe cercare l'opera esattamente con quel nome.
3) Se la query produce 0 risultati o fallisce, ritenta con un secondo tentativo.
4) Se la domanda è generica (tipo 'Ciao, come stai?'), rispondi breve.
5) Se trovi risultati, la risposta finale deve essere la query SPARQL (una sola riga).
6) Se non trovi nulla, rispondi con 'Nessuna info.'
7) Non multiline. Esempio: PREFIX base: <...> SELECT ?x WHERE {{ ... }}.
Esempio:
Utente: Chi ha creato l'opera 'Amore e Psiche'?
Risposta: PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/progettoMuseo#> SELECT ?creatore WHERE {{ ?opera base:hasName "Amore e Psiche" . ?opera base:creatoDa ?creatore . }}
FINE REGOLE

### Conversazione ###
Utente: che ore sono?
Assistente:
"""

def create_explanation_prompt(results_str: str) -> str:
    """Prompt per generare una spiegazione museale dei risultati SPARQL."""
    return f"""\
Ho ottenuto questi risultati SPARQL:
{results_str}
Ora fornisci una breve spiegazione museale (massimo ~10 righe), senza inventare oltre i risultati.
"""

async def call_hf_model(prompt: str, temperature: float = 0.5, max_tokens: int = 150) -> str:
    """Chiama il modello Hugging Face tramite l'API REST e gestisce la risposta."""
    logger.debug("Chiamo HF con il seguente prompt:")
    content_preview = (prompt[:300] + '...') if len(prompt) > 300 else prompt
    logger.debug(f"PROMPT => {content_preview}")

    headers = {
        "Authorization": f"Bearer {API_KEY}"
    }
    payload = {
        "inputs": prompt,
        "parameters": {
            "temperature": temperature,
            "max_new_tokens": max_tokens,
            "top_p": 0.9
        }
    }

    try:
        response = requests.post(
            f"https://api-inference.huggingface.co/models/{HF_MODEL}",
            headers=headers,
            json=payload
        )
        if response.status_code != 200:
            logger.error(f"Errore nella chiamata all'API Hugging Face: {response.status_code} - {response.text}")
            raise HTTPException(status_code=500, detail=f"Errore nell'API Hugging Face: {response.text}")
        data = response.json()
        logger.debug(f"Risposta completa dal modello: {data}")
        if isinstance(data, list) and len(data) > 0 and "generated_text" in data[0]:
            raw = data[0]["generated_text"]
        elif "generated_text" in data:
            raw = data["generated_text"]
        else:
            raise ValueError("Nessun campo 'generated_text' nella risposta.")

        # Forza la risposta su una singola linea se multilinea
        single_line = " ".join(raw.splitlines())
        logger.debug(f"Risposta HF single-line: {single_line}")
        return single_line.strip()
    except Exception as e:
        logger.error(f"Errore nella chiamata all'API Hugging Face tramite requests: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# Variabile globale per le etichette delle entità
entity_labels: List[str] = []

def load_entity_labels(documents_file: str):
    """Carica le etichette delle entità dal file documents.json."""
    global entity_labels
    try:
        with open(documents_file, "r", encoding="utf-8") as f:
            document = json.load(f)
        entity_labels = [entity['label'].lower() for entity in document['entities']]
        logger.info(f"Elenco delle etichette delle entità caricato: {entity_labels}")
    except Exception as e:
        logger.error(f"Errore nel caricamento delle etichette delle entità: {e}")
        entity_labels = []

def is_ontology_related(query: str) -> bool:
    """Determina se la domanda è pertinente all'ontologia."""
    query_lower = query.lower()
    keywords = ["opera", "museo", "stanza", "tour", "visitatore", "biglietto", "guida", "evento", "agente"]
    if any(keyword in query_lower for keyword in keywords):
        return True
    if any(entity in query_lower for entity in entity_labels):
        return True
    return False

# Prepara i file necessari per RAG
prepare_retrieval()

# Carica il 'sunto' di classi, proprietà ed entità
knowledge_text = extract_classes_and_properties(RDF_FILE)

# Carica le etichette delle entità
load_entity_labels(DOCUMENTS_FILE)

app = FastAPI()

class QueryRequest(BaseModel):
    message: str
    max_tokens: int = 150  # Ridotto per risposte concise
    temperature: float = 0.5

@app.post("/generate-response/")
async def generate_response(req: QueryRequest):
    user_input = req.message
    logger.info(f"Utente dice: {user_input}")

    if not is_ontology_related(user_input):
        return {
            "type": "NATURAL",
            "response": "Ciao! Sono un assistente museale e non ho informazioni sulle ore attuali. Ti consiglio di consultare un orologio o un dispositivo mobile per conoscere l'ora esatta."
        }

    try:
        # Recupera documenti rilevanti usando RAG
        retrieved_docs = retrieve_relevant_documents(user_input, top_k=3)
    except Exception as e:
        logger.error(f"Errore nel recupero dei documenti rilevanti: {e}")
        return {"type": "ERROR", "response": f"Errore nel recupero dei documenti: {e}"}

    sys_msg = create_system_message(knowledge_text, retrieved_docs)
    prompt = f"{sys_msg}\nUtente: {user_input}\nAssistente:"

    # Primo tentativo
    try:
        r1 = await call_hf_model(prompt, req.temperature, req.max_tokens)
        logger.info(f"PRIMA RISPOSTA:\n{r1}")
    except Exception as e:
        logger.error(f"Errore nella chiamata al modello Hugging Face: {e}")
        return {"type": "ERROR", "response": f"Errore nella generazione della risposta: {e}"}

    # Se non parte con "PREFIX base:"
    if not r1.startswith("PREFIX base:"):
        sc = f"Non hai risposto con query SPARQL su una sola riga. Riprova. Domanda: {user_input}"
        fallback_prompt = f"{sys_msg}\nAssistente: {r1}\nUtente: {sc}\nAssistente:"
        try:
            r2 = await call_hf_model(fallback_prompt, req.temperature, req.max_tokens)
            logger.info(f"SECONDA RISPOSTA:\n{r2}")
            if r2.startswith("PREFIX base:"):
                sparql_query = r2
            else:
                return {"type": "NATURAL", "response": r2}
        except Exception as e:
            logger.error(f"Errore nella seconda chiamata al modello Hugging Face: {e}")
            return {"type": "ERROR", "response": f"Errore nella generazione della seconda risposta: {e}"}
    else:
        sparql_query = r1

    # Esegui la query con rdflib
    g = rdflib.Graph()
    try:
        g.parse(RDF_FILE, format="xml")
        logger.info(f"Parsing RDF di {RDF_FILE} riuscito per l'esecuzione della query.")
    except Exception as e:
        logger.error(f"Parsing RDF error: {e}")
        return {"type": "ERROR", "response": f"Parsing RDF error: {e}"}

    try:
        results = g.query(sparql_query)
        logger.info(f"Query SPARQL eseguita con successo. Risultati: {len(results)}")
    except Exception as e:
        fallback = f"La query SPARQL ha fallito. Riprova. Domanda: {user_input}"
        fallback_prompt = f"{sys_msg}\nAssistente: {sparql_query}\nUtente: {fallback}\nAssistente:"
        try:
            r3 = await call_hf_model(fallback_prompt, req.temperature, req.max_tokens)
            logger.info(f"TERZA RISPOSTA (fallback):\n{r3}")
            if r3.startswith("PREFIX base:"):
                sparql_query = r3
                try:
                    results = g.query(sparql_query)
                    logger.info(f"Seconda query SPARQL eseguita con successo. Risultati: {len(results)}")
                except Exception as e2:
                    logger.error(f"Seconda Query fallita: {e2}")
                    return {"type": "ERROR", "response": f"Query fallita di nuovo: {e2}"}
            else:
                return {"type": "NATURAL", "response": r3}
        except Exception as e:
            logger.error(f"Errore nella chiamata al modello Hugging Face durante il fallback: {e}")
            return {"type": "ERROR", "response": f"Errore durante il fallback della risposta: {e}"}

    if len(results) == 0:
        return {"type": "NATURAL", "sparql_query": sparql_query, "response": "Nessun risultato."}

    # Confeziona risultati
    row_list = []
    for row in results:
        row_dict = row.asdict()
        row_str = ", ".join([f"{k}: {v}" for k, v in row_dict.items()])
        row_list.append(row_str)
    results_str = "\n".join(row_list)

    # Spiegazione
    exp_prompt = create_explanation_prompt(results_str)
    try:
        explanation = await call_hf_model(exp_prompt, req.temperature, req.max_tokens)
    except Exception as e:
        logger.error(f"Errore nella generazione della spiegazione: {e}")
        return {"type": "ERROR", "response": f"Errore nella generazione della spiegazione: {e}"}

    return {
        "type": "NATURAL",
        "sparql_query": sparql_query,
        "sparql_results": row_list,
        "explanation": explanation
    }

@app.get("/")
def home():
    return {"message": "Assistente Museale con supporto SPARQL."}