Se cambia el prompt tamplate de question_generator el cual generaba un error al volver a preguntar pues respondia en ingles.
This commit is contained in:
parent
9227a4201f
commit
e43e001185
3
app.py
3
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
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -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
|
||||
@ -98,8 +120,9 @@ class LangChainTools:
|
||||
# model_huggingface = (
|
||||
# "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
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user