Spaces:
Running
Running
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 | |
# Se hai funzioni per gestire i database (list_databases, ensure_default_db, ecc.), | |
# importale dal modulo corretto: | |
# from app.document_handling import list_databases, ensure_default_db | |
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 = f"faiss_index_{db_name}" | |
if not os.path.exists(db_path): | |
logging.warning(f"Database {db_name} non trovato.") | |
return [ | |
{"role": "user", "content": question}, | |
{"role": "assistant", "content": "Database non trovato"} | |
] | |
# 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 = f"faiss_index_{db_name}" | |
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 | |