From e43e001185fd1ad8e424f7bb226573d1b265bef6 Mon Sep 17 00:00:00 2001 From: mongar Date: Wed, 1 May 2024 20:19:13 -0500 Subject: [PATCH] Se cambia el prompt tamplate de question_generator el cual generaba un error al volver a preguntar pues respondia en ingles. --- app.py | 3 + .../data_level0.bin | Bin 6284000 -> 6284000 bytes .../length.bin | Bin 4000 -> 4000 bytes .../__pycache__/lc_tools.cpython-311.pyc | Bin 8341 -> 9156 bytes langchain_tools/lc_tools.py | 48 +++++-- pruebas_open_source.py | 119 +++++------------- 6 files changed, 72 insertions(+), 98 deletions(-) diff --git a/app.py b/app.py index 2bcfdf6..2ecfd5e 100644 --- a/app.py +++ b/app.py @@ -51,6 +51,9 @@ if pdf_name: # Cargamos el modelo de embeddings embedding_model = langChainTools.load_embedding_opnai() + # Cargamos el modelo de embeddings + # embedding_model = langChainTools.load_embedding_hf() + # Creamos el vector store docstorage = langChainTools.create_vector_strore( docs_split, pdf_name, embedding_model diff --git a/embeddings/el_espejo_como_no-lugar/a9e94886-c385-464d-ad7b-244f5af91cc8/data_level0.bin b/embeddings/el_espejo_como_no-lugar/a9e94886-c385-464d-ad7b-244f5af91cc8/data_level0.bin index ea3192e8ec5112eb8b4f2a7bde5d13bbb95e6ac0..6c9e4319f24dd1f83b12bb1b4f9d6f0f4e448e1a 100644 GIT binary patch delta 22221 zcmeHP2~bt%6@K6UUl0)FfubTVpsXT_E2tp2popj_BI1e*qH&1}DkhCL#{4GQ*ybi$ zvzWvMGm}o2+%)Mjoi4VuYi8QCNt>pVHkt12q|3C^HeIym+^2+R-hDpc-FG|XIlj@k z_rL$W|M}1P&hnpg-nx2SyhXp~U)6LB9yvj7Ir*B_e)+l!KRxm*RIa$;pGxec=2*MP9S|6nT_VcskILp_-*J>G#221^ z@dG?v{uoK;GDX$;N9;bFcIvc=my>m5Pps8;p81vCK!>lpAVq#~k$U;M+ zj4GVtky@;YUC`qb2V(4u)pGG29on6b{oY|J_(2KAm8~=I>}Wu4d-$hzZ$`oN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_OKbY2cWwm{zk7`K2qZBT&*PtW|Ct(r*;y zEAEpGv)W$N_MZE5xA&fMXL&Lc%_KtX$}HM;UORB%-EL3RTLx;s>?V%Aa{j9klfwC|RwY)LGRcC`Mp6bF3d`1dJiyKLTQlD9 z>QoG2$>WYke;(|4r|w0?z+EwD?LEfYE`ZMHzQ=_WR7j9$Ag7hGn8>T%PagJfbDpZyA`<{slJmBj!d+tyvHn5ClTyHhweq0CG?o76I)<4 zD3C2Df5?D=l%Y8$P7za3aoF&@GOK}z3%x<23M_I8jIC`xOeTAUO8_lr(u}=y0~ksd zA7XVwHh1?eqwZ=!|M7ht7&iEmqxTHKhU$v8Pl@6=TRmi;nz)j}1t?b63~HC4xezhv z>vBH7XV}lBi`?PD>V9E0EP8_>n-j&w^rd%kwQj_V`y(EIyG1pGQGb9Jzov*sagJ>aW(EKj9#ni%GMCcmg$ z^&qRHkW)Huk@=wSw;Ag;=U3U{M8MVXAv7y(HqN=z2vLqh{w7*d_5R+WTvNooTsY^* zYI|iBSVyM+qI;C&22fj0roCoShFVl~>F$$g;!LX5^er_#52GhkbIP#Q6pZ?A@p&P) z1qeuK8-D4@*xuJw(hB*ApL6-eqSj})dmW$la6Ypq(VI?v{|K{$WG9{vpg8Xzxl`)I zgv!m_(};zRpX0JID_XSv=r^t22OE!n*Vp%eeEnT#e%;yo;O64FYub%|2&|HC3_9d)4-v7TQ2Z|v8 delta 6149 zcmeIwF%1A93;@9d1@*t8fS`dL2dxu82f5)5e6H4M^_n{)dZj#IfB^;=V1NMz7+`<_ W1{h#~0R|XgfB^;=VBiA-BX+y*C$8QA diff --git a/embeddings/el_espejo_como_no-lugar/a9e94886-c385-464d-ad7b-244f5af91cc8/length.bin b/embeddings/el_espejo_como_no-lugar/a9e94886-c385-464d-ad7b-244f5af91cc8/length.bin index 1dc89f8e47e591af4c36a35046077f0ba1d1ef9d..79e7c5ddc2f56102f648b8c450eead51082fa6be 100644 GIT binary patch literal 4000 zcmeHJ`CCuv8}7sON&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M`W8%?ex%AYuXw06x?Ov;Y7A diff --git a/langchain_tools/__pycache__/lc_tools.cpython-311.pyc b/langchain_tools/__pycache__/lc_tools.cpython-311.pyc index be078b147d4e1fa99de9251244c11456f454864c..9fe1ebf951d5418e108046b497d26c7c8836ae5b 100644 GIT binary patch delta 2225 zcmZ{leQXp(6u@`y_U^XZ`zZFV*Sj9=LR-o~TRsFTrIuDGAc`Om!G>hBy_vgi*^le& zT@h$4QHV9+56Q&%@duHZR1G9zNHl&0Bm5~zW6tE<#Dr*+e~*BFh+=%RM++F3-2Hau z&6_uG-+Mdr_Tbg+;g3QgiG%jzjkVeD+s=d=`3q+{PIV#<)#@>$VYq?kJlu8;1y6D) zH0$BG^YE{>;W!HH?XKU`a#=AGD%VlJndxov6&4;dpEAsE=1d2ROe-5cCGK`-+0 zY2-c04g0WvEHJNx1S}#SuE`3>e^QtQ@%i~FZdgJA(62=zFos(kQ07hHFH}=Rn6RQS-O3U4tW0N@6bN)uY8QQ2(JS_6t+)i_=PR29(!SY>m|TD z9O9>V)YD&LlUs&%QV%Ll z`)F2q@c^Mu2j%Gw8=D1eW^h-5sHUB@h=GZ{O4ao)BX8nD*NAH4u8FmdAK?itgB@=s zUv#1-=&8DP3@dmc0o&4EM=~sgb;VQ->;$X*!$(w-vz-uZ0&_}rnD&qexIzv#0@FT{ zV16}@R`Z&Lyp9$}6g96Y1?w<2$x^1<%FqU|S$1XCND_L^BHdEaeMgkh>@k^63(bc{ zv+YcMH{b+U33F}F@pGblJ=Q-Xl^f*`+UMfSXM*L#s*AC?#-5qb?=9=f@g?O%dpX%r z2?(-ulLOplm=Q{1suJYtqNPadoY+cImu?7edid3JJkZHE(6fP!{tnoNET_K&T0nd^ zkmQrJQS9e?=>hQ@K6NQt)6Dy#pp&CLQghUOC#SZ6jXWl5p-3=^(YzGj(7?>Z8T^2> z;Kqi;m|zg#NV;w)Rvw$GW(y#w#({n-t@9s(q5UlVSZJXQwcUJ*4%JqCq#302P;l8` z?)~>z`*J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5l^uo^KmqI7Ewgpqsbiaji*4ybBsH>Td^&U&JN!7c4hv- zHwNa^tGMzl04~|6xF}DEUsL#y(48gp47=g zQf%kOX`dL@_8gu7h2vf2k0XvF77#k%Q{sDYeB8XFjRZ`bTjHWNDsE^;lj(3*i`>Pe zh!2kJoe1~02w*!%BE8LUsugG}zPuY10~S)^#lg=z@gaLL$K^~ns}+|oi?RHHhjvq* v#=Ka#U&bHO6nrJ>RW{9C(BP>O=Px3z=5NomBE=wuy!Ym|ukYMv)lcv@{()U^ diff --git a/langchain_tools/lc_tools.py b/langchain_tools/lc_tools.py index 6027dc6..1d3fee4 100644 --- a/langchain_tools/lc_tools.py +++ b/langchain_tools/lc_tools.py @@ -9,6 +9,7 @@ import streamlit as st from dotenv import load_dotenv from langchain.chains import RetrievalQAWithSourcesChain, ConversationalRetrievalChain from langchain_community.llms import HuggingFaceEndpoint +from langchain_community.embeddings import HuggingFaceEmbeddings class LangChainTools: @@ -33,6 +34,27 @@ class LangChainTools: return self.embedding_model + def load_embedding_hf(self): + """Esta funcion carga un modelo de embedding de OpenAI + + Returns: + _type_: Retorno a un objetito de tipo embedding de OpenAI + """ + + huggingfacehub_api_token = "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" + + model_name = "sentence-transformers/all-mpnet-base-v2" + model_kwargs = {"device": "cpu"} + encode_kwargs = {"normalize_embeddings": False} + + self.embedding_model = HuggingFaceEmbeddings( + model_name=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs, + ) + + return self.embedding_model + @st.cache_resource def create_vector_strore( _self, _docs_split: list, _file_name: str, _embedding_model @@ -96,10 +118,11 @@ class LangChainTools: """ # model_huggingface = "google/gemma-1.1-7b-it" # Es buena y funciona en espanol # model_huggingface = ( - # "google/gemma-1.1-2b-it" # Es buena y funciona en espanol funciona rapido + # "google/gemma-1.1-2b-it" # Es buena y funciona en espanol funciona rapido # ) - # model_huggingface = 'tiiuae/falcon-7b-instruct' - # model_huggingface = 'mistralai/Mistral-7B-Instruct-v0.2' + # model_huggingface = "tiiuae/falcon-7b-instruct" + # model_huggingface = "mistralai/Mistral-7B-Instruct-v0.2" + # model_huggingface = 'mistralai/Mixtral-8x7B-Instruct-v0.1' huggingfacehub_api_token = "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" model_huggingface = "mistralai/Mixtral-8x7B-Instruct-v0.1" # Es buena y funciona en espanol funciona rapido @@ -108,8 +131,8 @@ class LangChainTools: llm = HuggingFaceEndpoint( repo_id=model_huggingface, huggingfacehub_api_token=huggingfacehub_api_token, - temperature=0.5, - max_new_tokens=500, + temperature=0.1, + max_new_tokens=1000, ) return llm @@ -120,7 +143,7 @@ class LangChainTools: Returns: _type_: Retorno a un prompt template de LangChain. """ - template = """Responde a la siguiente pregunta utilizando los documentos proporcionados y citando las fuentes relevantes entre corchetes []: + template = """Responde en español la siguiente pregunta utilizando los documentos proporcionados y citando las fuentes relevantes entre corchetes []: Pregunta: {question} @@ -213,12 +236,21 @@ class LangChainTools: return_source_documents=True, # Devuelve los documentos fuente ) - template = """Utiliza los siguientes fragmentos de contexto para responder la pregunta al final. Si no sabes la respuesta, simplemente di que no sabes, no intentes inventar una respuesta. La respuesta dala con un formateo de markdown. Responde a la pregunta siempre en español. - + template = """Utiliza los siguientes fragmentos de contexto para responder en español la pregunta al final. Si no sabes la respuesta, simplemente di que no sabes, no intentes inventar una respuesta. + {context} Pregunta: {question} Respuesta:""" + + # template = """Utiliza los siguientes fragmentos de contexto como ejemplo para responder la pregunta al final. Organiza tu respuesta de manera clara y concisa, proporcionando información relevante y evitando divagaciones innecesarias. + + # {context} + + # Pregunta: {question} + # Respuesta en español:""" + conversation.combine_docs_chain.llm_chain.prompt.template = template + conversation.question_generator.prompt.template = "Dado el siguiente diálogo y una pregunta de seguimiento, reformula la pregunta de seguimiento para que sea una pregunta independiente, en su idioma original.\n\nHistorial del chat:\n{chat_history}\nPregunta de seguimiento: {question}\nPregunta independiente:" return conversation diff --git a/pruebas_open_source.py b/pruebas_open_source.py index ed40bd0..327b115 100644 --- a/pruebas_open_source.py +++ b/pruebas_open_source.py @@ -1,24 +1,19 @@ +# from langchain_tools.lc_tools import LangChainTools from langchain_community.llms import HuggingFaceEndpoint -from langchain.chains import LLMChain -from langchain.memory import ConversationBufferMemory -from langchain_core.prompts import PromptTemplate -from langchain_openai import OpenAIEmbeddings -# model_huggingface = 'google/gemma-1.1-7b-it' # Es buena y funciona en espanol +# Instanciamos la clase LangChainTools que contiene herramientras LangChain +# langChainTools = LangChainTools() -# model_huggingface = 'tiiuae/falcon-7b-instruct' -# model_huggingface = 'mistralai/Mistral-7B-Instruct-v0.2' -# model_huggingface = "google/gemma-7b" +# model_huggingface = "google/gemma-1.1-7b-it" # Es buena y funciona en espanol # model_huggingface = ( -# "mistralai/Mixtral-8x7B-Instruct-v0.1" # Es muy buena y funciona en espanol +# "google/gemma-1.1-2b-it" # Es buena y funciona en espanol funciona rapido # ) - +# model_huggingface = 'tiiuae/falcon-7b-instruct' +model_huggingface = "mistralai/Mistral-7B-Instruct-v0.2" huggingfacehub_api_token = "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" -model_huggingface = ( - "google/gemma-1.1-2b-it" # Es buena y funciona en espanol funciona rapido -) +# model_huggingface = "mistralai/Mixtral-8x22B-Instruct-v0.1" # Es buena y funciona en espanol funciona rapido # Define the LLM llm = HuggingFaceEndpoint( @@ -26,36 +21,21 @@ llm = HuggingFaceEndpoint( huggingfacehub_api_token=huggingfacehub_api_token, temperature=0.5, max_new_tokens=500, -) +) # Cargamos el modelo LLM desde LangChainllm llm = langChainTools.load_llm_open_source() +# respuesta = llm.invoke("Cual es el sentido de la vida?") -# for chunk in llm.stream("Como se construye un ensayo?"): -# print(chunk, end="", flush=True) +# print(respuesta) -# question = "Como se construye un ensayo?" -# output = llm.invoke(question) - -# print(output) - - -# prompt = PromptTemplate( -# input_variables=["chat_history", "human_input"], template=template -# ) -# memory = ConversationBufferMemory(memory_key="chat_history") - -# llm = OpenAI() -# llm_chain = LLMChain( -# llm=llm, -# prompt=promptas st +import streamlit as st +from chats.streamlit_tools import import_file # ,clear_cache +from streamlit_extras.add_vertical_space import add_vertical_space from langchain_tools.pdf_tools import PdfLangChain from langchain_tools.lc_tools import LangChainTools -from langchain_community.llms import HuggingFaceEndpoint -from langchain.chains.question_answering import load_qa_chain -from langchain.memory import ConversationBufferMemory -from langchain_core.prompts import PromptTemplate +from chats.chat_tools import MessageManager -# Inicializamos la clase PdfLangChain -pdfLangChain = PdfLangChain("1.TC_Malamud, Se está muriendo la democracia.pdf") -pdf_name = pdfLangChain.file_name + +pdf_name = "1.TC_Malamud, Se está muriendo la democracia.pdf" +pdfLangChain = PdfLangChain(pdf_name) # Cargamos el documento PDF docs: list = pdfLangChain.load_pdf() @@ -67,62 +47,21 @@ docs_split: list = pdfLangChain.split_docs(docs) langChainTools = LangChainTools() # Cargamos el modelo de embeddings -embedding_model = langChainTools.load_embedding_opnai() +# embedding_model = langChainTools.load_embedding_opnai() + +# Cargamos el modelo de embeddings +embedding_model = langChainTools.load_embedding_hf() # Creamos el vector store docstorage = langChainTools.create_vector_strore(docs_split, pdf_name, embedding_model) +# Cargamos el modelo LLM desde LangChain +llm = langChainTools.load_llm_open_source() -template = """Tu eres un chatbot y tienes una conversacion con un humano quien te \ -hara preguntas y tu deberas responder con base al context y al chat_history. Si no \ -conocer la respuesta, solo repsonde que no sabes como responder. - - -{context} - -{chat_history} -Human: {question} -Chatbot:""" - -prompt = PromptTemplate( - input_variables=["chat_history", "human_input", "context"], template=template -) -memory = ConversationBufferMemory(memory_key="chat_history", input_key="question") -chain = load_qa_chain( - llm, - chain_type="stuff", - memory=memory, - prompt=prompt, - verbose=True, +# Creamos la cadena que integra Vectorstroe, el LLM para hacer consultas.Para este caso la cadena tene el parametro de memoria. +qa = langChainTools.define_retrieval_qa_memory( + llm, docstorage, pdf_name, embedding_model ) +# qa.question_generator.prompt.template = "Dado el siguiente diálogo y una pregunta de seguimiento, reformula la pregunta de seguimiento para que sea una pregunta independiente, en su idioma original.\n\nHistorial del chat:\n{chat_history}\nPregunta de seguimiento: {question}\nPregunta independiente:" -query = "cuales son los elementos clave del texto?" -# documents = docstorage.similarity_search(query) -# respuesta = chain.invoke( -# {"question": f"{prompt}", "input_documents": documents}, return_only_outputs=False -# ) -# chain({"input_documents": documents, "human_input": query}, return_only_outputs=True) -# print(documents) -# print(respuesta["output_text"]) - - -from langchain.chains import RetrievalQAWithSourcesChain, ConversationalRetrievalChain - -chain = ConversationalRetrievalChain.from_llm(llm, docstorage.as_retriever()) - -print(dir(chain)) - -print(chain) - -# template = f"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:" - -template = "Utiliza los siguientes fragmentos de contexto para responder la pregunta al final. Si no sabes la respuesta, simplemente di que no sabes, no intentes inventar una respuesta.\n\n{context}\n\nQuestion: {question}\nRespuesta útil:" - -# Define el nuevo template que deseas utilizar -new_template = "Este es un nuevo template que reemplazará al anterior.\n\n{context}\n\nPregunta: {question}\nRespuesta útil:" - -# Accede al prompt del LLMChain en combine_docs_chain y actualiza su template -chain.combine_docs_chain.llm_chain.prompt.template = template -print("\n\n") -# Imprime la instancia de clase para verificar que se haya actualizado el template -print(chain) +print(qa)