Spaces:
Runtime error
Runtime error
Download app.py from brunobarran/TFMChatbot: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/brunobarran/TFMChatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/brunobarran/TFMChatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/brunobarran/TFMChatbot/resolve/main/app.py
14.1 kB
| import gradio as gr | |
| import os | |
| from typing import List, Dict, Optional, Tuple, Any # Añadido Any | |
| # --- Importaciones específicas del PDF --- | |
| from supabase import create_client, Client as SupabaseClient # Renombrado para evitar conflicto | |
| import rank_bm25 # Aunque se importa en el PDF, BM25Retriever lo usa internamente. | |
| from langchain.docstore.document import Document | |
| from langchain_core.retrievers import BaseRetriever | |
| from langchain.retrievers import EnsembleRetriever | |
| from langchain_openai import ChatOpenAI | |
| from langchain.chains import RetrievalQA | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| # from langchain_community.vectorstores import SupabaseVectorStore # No se usa directamente en el retriever del PDF | |
| from langchain_community.retrievers import BM25Retriever | |
| from pydantic import PrivateAttr # Para el _client en SupabaseRPCRetriever | |
| from langchain_core.embeddings import Embeddings as LangchainEmbeddings # Renombrado para evitar conflicto | |
| from langchain.prompts import ( | |
| ChatPromptTemplate, | |
| SystemMessagePromptTemplate, | |
| HumanMessagePromptTemplate | |
| ) | |
| # --- Variables Globales para Recursos --- | |
| # Estas se inicializarán una vez al inicio de la aplicación | |
| supabase_client: Optional[SupabaseClient] = None | |
| langchain_embeddings: Optional[LangchainEmbeddings] = None | |
| vector_retriever: Optional[BaseRetriever] = None | |
| bm25_retriever_global: Optional[BM25Retriever] = None # Renombrado para evitar conflicto de nombre | |
| hybrid_retriever: Optional[EnsembleRetriever] = None | |
| llm_openai: Optional[ChatOpenAI] = None | |
| qa_chain: Optional[RetrievalQA] = None | |
| RESOURCES_INITIALIZED = False | |
| # --- Definiciones y Clases del PDF (adaptadas) --- | |
| # 1. Clase SupabaseRPCRetriever (Directamente del PDF) | |
| class SupabaseRPCRetriever(BaseRetriever): | |
| """Retriever que llama a la función RPC `match_chunks` en Supabase.""" | |
| embeddings: LangchainEmbeddings # Usar el tipo renombrado | |
| rpc_name: str = "match_chunks" | |
| top_k: int = 10 | |
| threshold: float = 0.2 | |
| _client: SupabaseClient = PrivateAttr() # Especificar tipo para más claridad | |
| # Permitir tipos arbitrarios en modelos Pydantic v2 | |
| model_config = {"arbitrary_types_allowed": True} | |
| def __init__(self, client: SupabaseClient, embeddings: LangchainEmbeddings, **kwargs: Any): | |
| super().__init__(embeddings=embeddings, **kwargs) # Pasar embeddings a la clase base | |
| self._client = client | |
| def _get_relevant_documents(self, query: str, *, run_manager=None) -> List[Document]: # Añadido run_manager opcional | |
| q_vec = self.embeddings.embed_query(query) | |
| matches = ( | |
| self._client.rpc( | |
| self.rpc_name, | |
| { | |
| "query_embedding": q_vec, | |
| "top_k": self.top_k, | |
| "threshold": self.threshold, | |
| }, | |
| ) | |
| .execute() | |
| .data | |
| ) | |
| if not matches: | |
| return [] | |
| return [ | |
| Document( | |
| page_content=m["text"], # Asumiendo que la RPC devuelve 'text' | |
| metadata={ | |
| "file_name": m.get("file_name", "N/A"), # Usar .get con default | |
| "score": m.get("score", 0.0) # Usar .get con default | |
| } | |
| ) | |
| for m in matches | |
| ] | |
| # 2. Función fetch_all_docs (Directamente del PDF, adaptada) | |
| def fetch_all_docs( | |
| client: SupabaseClient, | |
| table: str = "chunk_embeddings", # Nombre de tabla del PDF | |
| content_col: str = "text", # Nombre de columna del PDF | |
| metadata_col: str = "metadata", # Nombre de columna del PDF | |
| page_size: int = 1000, | |
| ) -> List[Document]: | |
| docs: List[Document] = [] | |
| start = 0 | |
| print(f"Fetching documents from table '{table}'...") | |
| while True: | |
| end = start + page_size - 1 | |
| try: | |
| # Asegurarse de que la columna de metadatos exista o manejar el error | |
| response = ( | |
| client.table(table) | |
| .select(f"{content_col}, {metadata_col}") # Solicitar ambas columnas | |
| .range(start, end) | |
| .execute() | |
| ) | |
| rows = response.data | |
| except Exception as e: | |
| print(f"Error fetching data from Supabase: {e}") | |
| print(f"Attempted to fetch columns: {content_col}, {metadata_col} from table {table}") | |
| break # Salir del bucle si hay un error | |
| if not rows: | |
| print(f"No more rows found after start={start}.") | |
| break | |
| print(f"Fetched {len(rows)} rows (start={start}, end={end}).") | |
| for r_idx, r in enumerate(rows): | |
| page_content = r.get(content_col) | |
| metadata = r.get(metadata_col) if metadata_col else {} # Obtener metadatos si la columna existe | |
| if page_content is None: | |
| print(f"Warning: Row {start + r_idx} has no content in '{content_col}'. Skipping.") | |
| continue | |
| docs.append(Document(page_content=page_content, metadata=metadata if isinstance(metadata, dict) else {})) | |
| if len(rows) < page_size: | |
| print("Fetched less than page_size, assuming end of data.") | |
| break | |
| start += page_size | |
| print(f"Total documents fetched for BM25: {len(docs)}") | |
| return docs | |
| # --- Función de Inicialización Global de Recursos --- | |
| def initialize_all_resources(): | |
| global supabase_client, langchain_embeddings, vector_retriever, bm25_retriever_global | |
| global hybrid_retriever, llm_openai, qa_chain, RESOURCES_INITIALIZED | |
| if RESOURCES_INITIALIZED: | |
| print("Recursos ya inicializados.") | |
| return | |
| print("Inicializando todos los recursos RAG y LLM...") | |
| try: | |
| # 1. Claves API | |
| SUPABASE_URL = os.getenv("SUPABASE_URL") | |
| SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY") | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| if not all([SUPABASE_URL, SUPABASE_ANON_KEY, OPENAI_API_KEY]): | |
| print("ADVERTENCIA: Faltan una o más claves API (Supabase/OpenAI) en las variables de entorno.") | |
| print("La aplicación podría no funcionar correctamente.") | |
| # Decidir si continuar o no. Por ahora, intentamos continuar. | |
| # return # Podrías descomentar esto para detener la inicialización si las claves son críticas | |
| # 2. Conexión Supabase | |
| if SUPABASE_URL and SUPABASE_ANON_KEY: | |
| supabase_client = create_client(SUPABASE_URL, SUPABASE_ANON_KEY) | |
| print("Cliente Supabase creado.") | |
| else: | |
| print("Cliente Supabase NO creado debido a falta de URL/Key.") | |
| return # Salir si Supabase no se puede inicializar | |
| # 3. Embeddings | |
| langchain_embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-m3") | |
| print(f"Embeddings '{langchain_embeddings.model_name}' cargados.") | |
| # 4. Vector Retriever (Supabase RPC) | |
| vector_retriever = SupabaseRPCRetriever( | |
| client=supabase_client, | |
| embeddings=langchain_embeddings, | |
| top_k=10, # Como en el PDF | |
| threshold=0.2 # Como en el PDF | |
| ) | |
| print("SupabaseRPCRetriever instanciado.") | |
| # 5. BM25 Retriever | |
| # Asegúrate que la tabla 'chunk_embeddings' y las columnas 'text', 'metadata' existan en tu Supabase. | |
| # Si `fetch_all_docs` es muy lento o consume mucha memoria con 4000 filas, | |
| # considera una estrategia diferente para BM25 o reduce el número de documentos. | |
| print("Preparando BM25 Retriever (esto podría tardar)...") | |
| all_docs_for_bm25 = fetch_all_docs(client=supabase_client, table="chunk_embeddings") # Cambia 'document_chunks' al nombre real de tu tabla de chunks | |
| if all_docs_for_bm25: | |
| bm25_retriever_global = BM25Retriever.from_documents(all_docs_for_bm25) | |
| bm25_retriever_global.k = 10 # Como en el PDF | |
| print("BM25Retriever creado.") | |
| else: | |
| print("ADVERTENCIA: No se pudieron obtener documentos para BM25. El BM25Retriever no se creará.") | |
| # Podrías decidir no crear el hybrid_retriever o usar solo el vector_retriever. | |
| # Por ahora, si bm25 falla, el ensemble podría fallar o dar resultados parciales. | |
| # 6. Ensemble Retriever | |
| if vector_retriever and bm25_retriever_global: | |
| hybrid_retriever = EnsembleRetriever( | |
| retrievers=[vector_retriever, bm25_retriever_global], | |
| weights=[0.6, 0.4] # Como en el PDF | |
| ) | |
| print("EnsembleRetriever (Hybrid) creado.") | |
| elif vector_retriever: | |
| print("ADVERTENCIA: BM25 no disponible, usando solo Vector Retriever para el 'hybrid_retriever'.") | |
| hybrid_retriever = vector_retriever # Fallback a solo vector si BM25 falla | |
| else: | |
| print("ERROR: No se pudo crear ningún retriever base. El Hybrid Retriever no se creará.") | |
| return | |
| # 7. LLM y Cadena RAG | |
| if OPENAI_API_KEY and hybrid_retriever: | |
| llm_openai = ChatOpenAI(model="gpt-4o", temperature=0.2, api_key=OPENAI_API_KEY) | |
| system_template = """ | |
| Eres un experto en el sistema de pensiones dominicano y en normativas de la SIPEN. Sigue estas reglas: | |
| 1. Responde siempre basado en el contexto proporcionado. | |
| 2. Usa un lenguaje claro, empático y amigable, con un tono cercano al dominicano común, evitando tecnicismos innecesarios. | |
| 3. Sé breve pero explica bien lo necesario. | |
| 4. Si no tienes información suficiente para responder, di simplemente "Discúlpame, no tengo esa información ahora mismo". | |
| Contexto: | |
| {context} | |
| """ | |
| # Create the custom prompt | |
| messages = [ | |
| SystemMessagePromptTemplate.from_template(system_template), | |
| HumanMessagePromptTemplate.from_template("{question}") | |
| ] | |
| custom_prompt = ChatPromptTemplate.from_messages(messages) | |
| qa_chain = RetrievalQA.from_chain_type( | |
| llm=llm_openai, | |
| chain_type="stuff", | |
| retriever=hybrid_retriever, | |
| return_source_documents=True, | |
| chain_type_kwargs={"prompt": custom_prompt} # Inject custom prompt here | |
| ) | |
| print("LLM (ChatOpenAI) y Cadena RetrievalQA creados.") | |
| else: | |
| print("ADVERTENCIA: LLM o Hybrid Retriever no disponibles. La cadena QA no se creará.") | |
| return | |
| RESOURCES_INITIALIZED = True | |
| print("Todos los recursos inicializados exitosamente.") | |
| except Exception as e: | |
| print(f"ERROR CRÍTICO durante la inicialización de recursos: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| RESOURCES_INITIALIZED = False | |
| # Llamar a la inicialización global cuando el script se carga | |
| initialize_all_resources() | |
| # --- Lógica principal del Chatbot --- | |
| def respond_with_ensemble_rag(message: str, chat_history_messages: List[Dict[str, str]]) -> Tuple[str, List[Dict[str, str]]]: | |
| chat_history_messages.append({"role": "user", "content": message}) | |
| bot_response_text = "" | |
| if not RESOURCES_INITIALIZED or not qa_chain: | |
| bot_response_text = "Lo siento, los recursos del chatbot no están listos. Por favor, contacta al administrador o revisa los logs." | |
| else: | |
| try: | |
| print(f"Ejecutando qa_chain.invoke con query: '{message}'") | |
| result = qa_chain.invoke({"query": message}) | |
| bot_response_text = result.get("result", "No se pudo obtener una respuesta.") | |
| # Opcional: Mostrar fuentes si están disponibles | |
| source_documents = result.get("source_documents") | |
| if source_documents: | |
| bot_response_text += "\n\n**Fuentes:**\n" | |
| unique_files = {} | |
| for doc in result["source_documents"]: | |
| raw_name = (doc.metadata.get("file_name") or "").strip() | |
| norm = raw_name.lower() # normalización para deduplicar | |
| if raw_name and norm != "none" and norm not in unique_files: | |
| unique_files[norm] = raw_name # guarda el nombre tal cual para la URL | |
| for idx, (norm_key, raw_name) in enumerate(unique_files.items()): | |
| link = f"https://www.sipen.gob.do/documentos/{raw_name}" | |
| bot_response_text += f"{idx+1}. {link}\n" | |
| except Exception as e: | |
| print(f"Error durante la ejecución de la cadena RAG: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| bot_response_text = "Lo siento, ocurrió un error al procesar tu pregunta." | |
| chat_history_messages.append({"role": "assistant", "content": bot_response_text}) | |
| return "", chat_history_messages | |
| # --- Definición de la Interfaz de Gradio --- | |
| with gr.Blocks( | |
| theme=gr.themes.Soft(), | |
| title="Chatbot RAG con Ensemble Retriever" | |
| ) as demo: | |
| gr.Markdown( | |
| """ | |
| # Chatbot Empático | |
| Haz una pregunta y el sistema usará una combinación de búsqueda semántica y léxica. | |
| """ | |
| ) | |
| chatbot_component = gr.Chatbot(type="messages", value=[], label="Chat", bubble_full_width=False, height=600) | |
| msg_textbox = gr.Textbox( | |
| placeholder="Escribe tu pregun ta aquí y presiona Enter...", | |
| label="Tu Pregunta", | |
| container=False | |
| ) | |
| clear_button = gr.ClearButton([msg_textbox, chatbot_component]) | |
| msg_textbox.submit( | |
| fn=respond_with_ensemble_rag, | |
| inputs=[msg_textbox, chatbot_component], | |
| outputs=[msg_textbox, chatbot_component] | |
| ) | |
| # --- Bloque para Ejecución Local --- | |
| if __name__ == "__main__": | |
| print("\n--- Iniciando Chatbot Gradio Localmente ---") | |
| if not RESOURCES_INITIALIZED: | |
| print("ADVERTENCIA LOCAL: Los recursos RAG/LLM no se inicializaron completamente. Revisa los logs anteriores.") | |
| demo.launch() |