Spaces:
Sleeping
Sleeping
| import tempfile | |
| import os | |
| import shutil | |
| import uuid | |
| from knowledge_base.utils_kb import cargar_documentos_resumenes | |
| from langchain.text_splitter import CharacterTextSplitter | |
| from langchain_openai import OpenAIEmbeddings, ChatOpenAI | |
| # from langchain_chroma import Chroma | |
| from langchain_community.vectorstores import Chroma | |
| from langchain.memory import ConversationBufferMemory | |
| from langchain.chains import ConversationalRetrievalChain | |
| MODEL = "gpt-4o-mini" | |
| def inicializar_chat(session_id): | |
| documentos, mensaje = cargar_documentos_resumenes(session_id) | |
| if documentos is None: | |
| return None, mensaje | |
| if not documentos: | |
| return None, "⚠️ No se encontraron textos en la base de conocimiento." | |
| # Embeddings y vectorstore. Separar en chunks (no se dividirán los posteos si cada texto < 1000) | |
| # splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200) | |
| # chunks = splitter.split_documents(documentos) | |
| # 🚫 NO HACEMOS SPLITTING EN CHUNKS | |
| chunks = documentos # cada documento es un chunk completo | |
| # Crear embeddings y almacenar vectorstore | |
| persist_path = os.path.join(tempfile.gettempdir(), f"vector_db_{session_id}_{str(uuid.uuid4())[:8]}") | |
| if os.path.exists(persist_path): | |
| shutil.rmtree(persist_path) | |
| embeddings = OpenAIEmbeddings() | |
| vectorstore = Chroma.from_documents(chunks, embedding=embeddings, persist_directory=persist_path) | |
| # Crear el LLM y la cadena de recuperación | |
| llm = ChatOpenAI(model_name=MODEL, temperature=0.7) | |
| memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) | |
| # retriever = vectorstore.as_retriever() | |
| k = min(100, len(documentos)) | |
| retriever = vectorstore.as_retriever(search_kwargs={"k": k}) | |
| chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory) | |
| return chain, f"✅ Chat cargado con éxito. Base cargada con {len(chunks)} resumenes. Ahora puedes comenzar a escribir tus consultas abajo. 🚀" | |