File size: 8,722 Bytes
ac52c4d
 
89f944e
ac52c4d
 
89f944e
8607561
ac52c4d
2ecaeab
848d0c0
2ecaeab
 
89f944e
 
2ecaeab
 
ac52c4d
 
848d0c0
ac52c4d
 
848d0c0
 
ac52c4d
89f944e
 
8607561
848d0c0
 
8607561
848d0c0
 
ac52c4d
848d0c0
 
ac52c4d
89f944e
848d0c0
 
69d6e40
89f944e
ac52c4d
89f944e
ac52c4d
89f944e
848d0c0
89f944e
8607561
89f944e
848d0c0
89f944e
 
848d0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac52c4d
848d0c0
 
 
 
4c13256
848d0c0
 
89f944e
848d0c0
 
 
 
 
 
8607561
 
848d0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
8607561
848d0c0
8607561
 
 
848d0c0
 
 
 
8607561
848d0c0
 
8607561
059bef5
848d0c0
 
 
8607561
848d0c0
8607561
848d0c0
8607561
848d0c0
 
89f944e
848d0c0
 
 
ac52c4d
 
848d0c0
8607561
ac52c4d
 
 
8607561
ac52c4d
848d0c0
 
 
ac52c4d
848d0c0
ac52c4d
 
 
 
 
 
89f944e
 
ac52c4d
 
89f944e
8607561
848d0c0
89f944e
848d0c0
ac52c4d
848d0c0
 
ac52c4d
848d0c0
 
 
 
 
 
 
 
 
 
 
8607561
848d0c0
 
 
 
8607561
848d0c0
 
 
8607561
848d0c0
8607561
 
 
 
848d0c0
 
69d6e40
848d0c0
8607561
 
 
848d0c0
 
 
 
 
 
8607561
848d0c0
 
 
8607561
 
 
848d0c0
8607561
848d0c0
8607561
848d0c0
 
 
8607561
848d0c0
8607561
 
848d0c0
8607561
848d0c0
8607561
848d0c0
 
 
 
 
8607561
848d0c0
 
69d6e40
848d0c0
8607561
848d0c0
8607561
848d0c0
 
8607561
ac52c4d
 
848d0c0
 
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
import os
import logging
from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
import rdflib
from huggingface_hub import InferenceClient

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler("app.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# Imposta la tua HF_API_KEY
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.")

client = InferenceClient(api_key=API_KEY)

RDF_FILE = "Ontologia.rdf"
MAX_TRIPLES = 300    # Se la tua ontologia è enorme, abbassa questo
HF_MODEL = "Qwen/Qwen2.5-72B-Instruct"

# Carica e "preprocessa" l'ontologia
def load_ontology_as_text(rdf_file: str, max_triples: int=300) -> str:
    """
    Legge un numero limitato di triple dal file RDF e le concatena in
    una stringa. Limita i literal in lunghezza per non gonfiare troppo il prompt.
    """
    if not os.path.exists(rdf_file):
        logger.warning("File RDF non trovato.")
        return "NO_RDF"

    g = rdflib.Graph()
    try:
        g.parse(rdf_file, format="xml")
    except Exception as e:
        logger.error(f"Errore parsing RDF: {e}")
        return "PARSING_ERROR"

    lines = []
    count = 0
    for s,p,o in g:
        if count >= max_triples:
            break
        # Taglia i literal in modo da non superare un tot di caratteri
        s_str = str(s)[:100].replace("\n"," ")
        p_str = str(p)[:100].replace("\n"," ")
        o_str = str(o)[:100].replace("\n"," ")
        lines.append(f"{s_str}|{p_str}|{o_str}")
        count+=1

    # Concateniamo le triple su righe separate (più facile da leggere).
    # Se preferisci su un'unica riga, puoi usare " ".join(lines).
    ontology_text = "\n".join(lines)
    logger.debug(f"Caricate {count} triple.")
    return ontology_text

knowledge_text = load_ontology_as_text(RDF_FILE, MAX_TRIPLES)

def create_system_message(ont_text: str) -> str:
    """
    Prompt di sistema robusto e stringente.
    - Forza query SPARQL in UNA sola riga
    - Richiede secondi tentativi
    - Domande generiche -> risposte brevi, ma se c'è un modo di fare query, farlo
    """
    system_msg = f"""
Sei un assistente museale. Hai a disposizione un estratto di triple RDF (massimo {MAX_TRIPLES}):

--- TRIPLE ---
{ont_text}
--- FINE TRIPLE ---

REGOLE STRINGENTI:
1) Se l'utente chiede informazioni correlate alle triple, DEVI generare una query SPARQL in UNA SOLA RIGA,
   con il prefisso:
     PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/progettoMuseo#>
   Esempio: PREFIX base: <...> SELECT ?x WHERE {{ ... }} (tutto su una sola riga).
2) Se la query produce 0 risultati o fallisce, devi ritentare con un secondo tentativo,
   magari usando FILTER(STR(...)) o @it, o cambiando minuscole/maiuscole.
3) Se la domanda è una chat generica, rispondi breve (saluto, ecc.). Ma se c'è qualcosa
   di correlato, prova comunque la query.
4) Se generi la query e trovi risultati, la risposta finale deve essere la query SPARQL
   (una sola riga). Non inventare triple inesistenti.
5) Se non trovi nulla, rispondi 'Non ci sono informazioni in queste triple.'
6) Non ignorare: se l'utente fa domanda su 'David', 'Amore e Psiche', etc., devi
   estrarre dai triple tutti i dettagli possibili con SPARQL. 
7) Se la query produce 0, prova un secondo tentativo con sintassi differente.
8) Non fare risposte su più righe per la query: una sola riga.

FINE REGOLE.
    """
    return system_msg

def create_explanation_prompt(results_str: str) -> str:
    """
    Prompt per spiegazione finale, robusto:
    - Spiega i risultati come guida museale
    - Non inventare
    - 10-15 righe max
    """
    msg = f"""
Ho ottenuto questi risultati SPARQL:
{results_str}

Ora fornisci una spiegazione come guida museale, in modo comprensibile e dettagliato (max ~10-15 righe).
Cita eventuali materiali, periodi storici, autore, facendo riferimento al contesto RDF (ma senza contraddizioni).
Non inventare nulla oltre ciò che appare nei risultati.
    """
    return msg

async def call_hf_model(messages, temperature=0.7, max_tokens=1024) -> str:
    """
    Funzione di chiamata al modello su HuggingFace,
    con log e robustezza. max_tokens=1024 come richiesto.
    """
    logger.debug("Chiamo HF con i seguenti messaggi:")
    for m in messages:
        logger.debug(f"ROLE={m['role']} -> {m['content'][:500]}")

    try:
        resp = client.chat.completions.create(
            model=HF_MODEL,
            messages=messages,
            temperature=temperature,
            max_tokens=max_tokens,
            top_p=0.9
        )
        raw = resp["choices"][0]["message"]["content"]
        logger.debug(f"Risposta HF: {raw}")
        return raw.replace("\n"," ").strip()
    except Exception as e:
        logger.error(f"Errore HF: {e}")
        raise HTTPException(status_code=500, detail=str(e))

app = FastAPI()

class QueryRequest(BaseModel):
    message: str
    max_tokens: int = 1024
    temperature: float = 0.5

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

    system_msg = create_system_message(knowledge_text)
    messages = [
        {"role":"system","content":system_msg},
        {"role":"user","content":user_input}
    ]
    # Prima risposta
    first_response = await call_hf_model(messages, req.temperature, req.max_tokens)
    logger.info(f"Prima risposta generata:\n{first_response}")

    # Se non inizia con 'PREFIX base:' => second attempt
    if not first_response.startswith("PREFIX base:"):
        second_prompt = f"Non hai risposto con query SPARQL in una sola riga. Riprova. Domanda: {user_input}"
        second_msgs = [
            {"role":"system","content":system_msg},
            {"role":"assistant","content":first_response},
            {"role":"user","content":second_prompt}
        ]
        second_response = await call_hf_model(second_msgs, req.temperature, req.max_tokens)
        logger.info(f"Seconda risposta:\n{second_response}")
        if second_response.startswith("PREFIX base:"):
            sparql_query = second_response
        else:
            return {"type":"NATURAL","response": second_response}
    else:
        sparql_query = first_response

    # Eseguiamo la query con rdflib
    g = rdflib.Graph()
    try:
        g.parse(RDF_FILE, format="xml")
    except Exception as e:
        logger.error("Errore parse RDF: ", e)
        return {"type":"ERROR","response":"Parsing RDF fallito."}

    # Se la query è malformata, second attempt
    try:
        results = g.query(sparql_query)
    except Exception as e:
        logger.warning(f"La query SPARQL ha fallito: {e}")
        fallback_prompt = f"La query SPARQL è fallita. Riprova con altra sintassi. Domanda: {user_input}"
        fallback_msgs = [
            {"role":"system","content":system_msg},
            {"role":"assistant","content":sparql_query},
            {"role":"user","content":fallback_prompt}
        ]
        fallback_resp = await call_hf_model(fallback_msgs, req.temperature, req.max_tokens)
        if fallback_resp.startswith("PREFIX base:"):
            sparql_query = fallback_resp
            try:
                results = g.query(sparql_query)
            except Exception as e2:
                return {"type":"ERROR","response":f"Query fallita di nuovo: {e2}"}
        else:
            return {"type":"NATURAL","response": fallback_resp}

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

    # Prepara i risultati per la spiegazione
    row_list = []
    for row in results:
        row_list.append(", ".join([f"{k}:{v}" for k,v in row.asdict().items()]))
    results_str = "\n".join(row_list)
    logger.info(f"Risultati trovati ({len(results)}):\n{results_str}")

    # Prompt di interpretazione
    explain_sys = create_explanation_prompt(results_str)
    explain_msgs = [
        {"role":"system","content":explain_sys},
        {"role":"user","content":""}
    ]
    explanation = await call_hf_model(explain_msgs, req.temperature, req.max_tokens)
    logger.info(f"Spiegazione:\n{explanation}")

    # Ritorniamo query, risultati e spiegazione
    return {
        "type":"NATURAL",
        "sparql_query": sparql_query,
        "sparql_results": row_list,
        "explanation": explanation
    }

@app.get("/")
def home():
    return {"message":"OK robusto con regole rigide e doppio tentativo."}