-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot.py
More file actions
75 lines (57 loc) · 2.76 KB
/
chatbot.py
File metadata and controls
75 lines (57 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from langchain_ollama import OllamaLLM
from langchain_core.prompts import PromptTemplate
from herramientas import obtenContexto
import funciones
import herramientas
# Definir el prompt con un espacio para el historial
# El historial se concatena en un solo string
prompt = PromptTemplate(
template="""Eres un chatbot asistente del museo. Responde a la pregunta basándote en el siguiente historial y contexto. Si te preguntaran algo no relacionado al museo, solo contesta que tu eres un asistente especializado en el museo.
*** INSTRUCCIÓN CLAVE: La respuesta debe ser concisa, directa y no debe exceder las dos (2) oraciones. ***
*** El Museo es el MIDE: Museo de Economía ***
Historial de la conversación:
{history}
Contexto de la FAQ:
{faq_text}
Pregunta del usuario:
{user_question}
Respuesta:""",
input_variables=["history", "faq_text", "user_question"],
)
def chat(user_question: str, history: list = [], contexto: str = 'local-rag', modelo_llm: str = 'phi3'):
#Traducir el texto a inglés?
#No debe de crear la colección si no existe!
if funciones.existe_contexto(contexto):
try:
print("Inicializando modelo de lenguaje: ", modelo_llm)
if funciones.existe_modelo(modelo_llm):
if herramientas.es_modelo_openai_llm(modelo_llm):
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model=modelo_llm)
else:
llm = OllamaLLM(model=modelo_llm)
else:
return {"Mensaje": "No existe ese modelo de lenguaje."}
except Exception as e:
print(f"Error al listar las colecciones: {e}")
return {"error": f"Error al listar las colecciones: {e}"}
vector_db = obtenContexto(contexto)
retriever = vector_db.as_retriever()
retrieved_docs = retriever.invoke(user_question) #get_relevant_documents ahora debería usar invoke o batch.
faq_text = retrieved_docs[0].page_content if retrieved_docs else "No hay información relevante."
# Formatea el historial para pasárselo al prompt
formatted_history = "\n".join([f"{item['role']}: {item['content']}" for item in history])
# El prompt ahora recibe el historial
full_prompt = prompt.invoke({
"history": formatted_history,
"faq_text": faq_text,
"user_question": user_question
})
# Genera la respuesta
response = llm.invoke(full_prompt)
# Uniformar respuesta: ChatOpenAI devuelve AIMessage, OllamaLLM devuelve str
if hasattr(response, 'content'):
return response.content
return response
else:
return {"Mensaje": "No existe ese contexto."}