File size: 4,261 Bytes
47e4aa2
 
 
 
 
 
 
 
 
 
a45dfb0
47e4aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a45dfb0
47e4aa2
a45dfb0
47e4aa2
a45dfb0
47e4aa2
 
a45dfb0
47e4aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a45dfb0
47e4aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import logging
import os
import shutil

from openai import OpenAI
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
import gradio as gr

from app.config import OPENAI_API_KEY
from app.functions.database_handling import BASE_DB_PATH  # Aggiungi questo import

logging.basicConfig(level=logging.INFO)

def answer_question(question, db_name, chat_history=None):
    """
    Risponde alla domanda 'question' usando i documenti del database 'db_name'.
    Restituisce una lista di 2 messaggi in formato:
      [
        {"role": "user", "content": <domanda>},
        {"role": "assistant", "content": <risposta>}
      ]

    In questa versione, viene effettuato il log dei 'chunk' recuperati durante
    la ricerca di similarità.
    """
    if chat_history is None:
        chat_history = []

    logging.info(f"Inizio elaborazione domanda: {question} per database: {db_name}")
    
    try:
        embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
        db_path = os.path.join(BASE_DB_PATH, f"faiss_index_{db_name}")  # Percorso corretto
        
        logging.info(f"Verifico esistenza database in: {db_path}")
        if not os.path.exists(db_path):
            logging.warning(f"Database {db_name} non trovato in {db_path}")
            return [
                {"role": "user", "content": question},
                {"role": "assistant", "content": f"Database non trovato in {db_path}"}
            ]
        
        # Carica l'indice FAISS
        vectorstore = FAISS.load_local(db_path, embeddings, allow_dangerous_deserialization=True)

        # Cerca i documenti (chunk) più simili
        relevant_docs = vectorstore.similarity_search(question, k=3)

        # Logga i chunk recuperati
        for idx, doc in enumerate(relevant_docs):
            logging.info(f"--- Chunk {idx+1} ---")
            logging.info(doc.page_content)
            logging.info("---------------------")

        # Prepara il contesto dai documenti
        context = "\n".join([doc.page_content for doc in relevant_docs])
        
        client = OpenAI(api_key=OPENAI_API_KEY)
        
        messages = [
            {"role": "system", "content": f"Usa questo contesto per rispondere: {context}"},
            {"role": "user", "content": question}
        ]
        
        # Esegui la chiamata a OpenAI
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            temperature=0,
            max_tokens=2048
        )
        
        answer = response.choices[0].message.content
        
        return [
            {"role": "user", "content": question},
            {"role": "assistant", "content": answer}
        ]

    except Exception as e:
        logging.error(f"Errore durante la generazione della risposta: {e}")
        return [
            {"role": "user", "content": question},
            {"role": "assistant", "content": f"Si è verificato un errore: {str(e)}"}
        ]


def delete_database(db_name):
    """
    Cancella il database FAISS corrispondente a 'db_name'.
    Restituisce un messaggio di stato e l'aggiornamento del dropdown in Gradio.
    """
    db_path = os.path.join(BASE_DB_PATH, f"faiss_index_{db_name}")  # Percorso corretto
    if not os.path.exists(db_path):
        return f"Il database {db_name} non esiste.", gr.Dropdown.update(choices=[])
    try:
        shutil.rmtree(db_path)
        logging.info(f"Database {db_name} eliminato con successo.")
        # Se hai una funzione list_databases(), usala per aggiornare la dropdown
        return f"Database {db_name} eliminato con successo.", gr.Dropdown.update(choices=[])
    except OSError as e:
        logging.error(f"Impossibile eliminare il database {db_name}: {e}")
        return f"Impossibile eliminare il database {db_name}: {e}", gr.Dropdown.update(choices=[])


if __name__ == "__main__":
    # Se esiste una funzione ensure_default_db(), decommenta:
    # ensure_default_db()
    
    # Qui potresti testare la funzione answer_question o avviare
    # il tuo server Gradio. Ad esempio:
    #
    # from app.interface import rag_chatbot
    # rag_chatbot.launch(share=True)
    
    pass