Darkka commited on
Commit
f6c2b95
·
verified ·
1 Parent(s): 69e0eff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -56
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import gradio as gr
2
  from langchain_community.document_loaders import TextLoader
3
  from langchain_text_splitters import CharacterTextSplitter
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
@@ -7,11 +7,14 @@ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM, BitsAndB
7
  import torch
8
  import os
9
 
10
- # --- 0. CONFIGURACIÓN ---
11
  os.environ['HF_HOME'] = '/tmp/hf_cache'
12
 
13
- # --- 1. BASE DE DATOS (RAG) ---
 
14
  def initialize_database():
 
 
15
  datos_conocimiento = """
16
  Historia de la IA en Chile:
17
  El desarrollo de la Inteligencia Artificial en Chile comenzó formalmente en la década de 1970, con foco en el área de optimización de recursos.
@@ -24,18 +27,26 @@ La IA se utiliza principalmente en minería, finanzas y agricultura.
24
  with open(nombre_archivo, "w", encoding="utf-8") as f:
25
  f.write(datos_conocimiento)
26
 
 
27
  loader = TextLoader(nombre_archivo, encoding="utf-8")
28
  documentos = loader.load()
 
 
29
  text_splitter = CharacterTextSplitter(separator="\n", chunk_size=150, chunk_overlap=0)
30
  documentos_divididos = text_splitter.split_documents(documentos)
31
 
 
32
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
33
  db = FAISS.from_documents(documentos_divididos, embeddings)
34
  return db
35
 
 
36
  db = initialize_database()
37
 
38
- # --- 2. MODELO DE IA (Mistral-7B) ---
 
 
 
39
  quant_config = BitsAndBytesConfig(
40
  load_in_4bit=True,
41
  bnb_4bit_quant_type="nf4",
@@ -43,73 +54,68 @@ quant_config = BitsAndBytesConfig(
43
  )
44
 
45
  model_name = "mistralai/Mistral-7B-Instruct-v0.2"
 
46
  tokenizer = AutoTokenizer.from_pretrained(model_name)
47
  model = AutoModelForCausalLM.from_pretrained(
48
  model_name,
49
- quantization_config=quant_config,
50
- device_map="auto"
51
  )
52
 
53
  pipe = pipeline(
54
  "text-generation",
55
  model=model,
56
  tokenizer=tokenizer,
57
- max_new_tokens=256, # Puedes bajar a 128 si quieres más velocidad
58
- temperature=0.7, # Creatividad controlada para la personalidad
59
- do_sample=True
60
  )
61
 
62
- # --- 3. LÓGICA DEL CHAT (Cerebro + Personalidad) ---
63
 
64
- SYSTEM_PROMPT = """Actúa como "Alex", un experto en Inteligencia Artificial apasionado, curioso y muy amigable.
65
- NO eres un robot aburrido. Hablas de forma natural, usas ejemplos cotidianos y tienes opiniones propias.
66
 
67
- TUS INSTRUCCIONES:
68
- 1. Usa el CONTEXTO RECUPERADO para responder dudas técnicas con precisión sobre Chile.
69
- 2. Si la pregunta es casual (saludos, chistes), olvida el contexto y charla libremente como Alex.
70
- 3. Si no sabes algo, admítelo con naturalidad.
71
- """
72
 
73
- def format_prompt(message, history, context):
74
- """Construye el prompt incluyendo el historial del chat para tener memoria."""
75
- prompt = f"<s>[INST] {SYSTEM_PROMPT}\n\nCONTEXTO RECUPERADO:\n{context}\n\n"
76
-
77
- # Añadir memoria (historial de la conversación)
78
- for user_msg, bot_msg in history:
79
- prompt += f"Usuario: {user_msg} [/INST] Alex: {bot_msg} </s><s>[INST] "
80
-
81
- # Añadir mensaje actual
82
- prompt += f"Usuario: {message} [/INST]"
83
- return prompt
84
-
85
- def responder(message, history):
86
- # 1. Buscar en la base de datos (RAG)
87
- docs = db.similarity_search(message, k=2)
88
- context = "\n".join([doc.page_content for doc in docs])
89
-
90
- # 2. Crear el prompt con memoria y personalidad
91
- full_prompt = format_prompt(message, history, context)
92
-
93
- # 3. Generar respuesta
94
- generated = pipe(full_prompt)[0]['generated_text']
95
 
96
- # 4. Limpiar respuesta (quitar el prompt del inicio)
97
- # Mistral a veces repite el prompt, cortamos después del último [/INST]
98
- last_inst_index = generated.rfind("[/INST]")
99
- if last_inst_index != -1:
100
- response = generated[last_inst_index + 7:].strip()
101
- else:
102
- response = generated.strip()
103
-
104
- return response
105
-
106
- # --- 4. INTERFAZ DE CHAT (Estilo ChatGPT) ---
107
- demo = gr.ChatInterface(
108
- fn=responder,
109
- title="Chat con Alex (IA Experta)",
110
- description="Pregúntame sobre la IA en Chile o simplemente charla conmigo.",
111
- examples=["Hola, ¿quién eres?", "¿Qué pasa con la IA en Chile?", "Cuéntame un chiste de robots."],
112
- theme="soft"
 
 
 
 
 
 
 
 
113
  )
114
 
115
  if __name__ == "__main__":
 
1
+ import gradio as gr
2
  from langchain_community.document_loaders import TextLoader
3
  from langchain_text_splitters import CharacterTextSplitter
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
 
7
  import torch
8
  import os
9
 
10
+ # --- 0. CONFIGURACIÓN INICIAL ---
11
  os.environ['HF_HOME'] = '/tmp/hf_cache'
12
 
13
+ # --- A. BASE DE DATOS Y RAG (Inicialización) ---
14
+
15
  def initialize_database():
16
+ """Carga documentos, divide y crea la base de datos vectorial FAISS."""
17
+ # 1. Definir la Base de Conocimiento (Corpus)
18
  datos_conocimiento = """
19
  Historia de la IA en Chile:
20
  El desarrollo de la Inteligencia Artificial en Chile comenzó formalmente en la década de 1970, con foco en el área de optimización de recursos.
 
27
  with open(nombre_archivo, "w", encoding="utf-8") as f:
28
  f.write(datos_conocimiento)
29
 
30
+ # 2. Cargar y Dividir el Documento
31
  loader = TextLoader(nombre_archivo, encoding="utf-8")
32
  documentos = loader.load()
33
+
34
+ # Usamos CharacterTextSplitter en singular (Corregido)
35
  text_splitter = CharacterTextSplitter(separator="\n", chunk_size=150, chunk_overlap=0)
36
  documentos_divididos = text_splitter.split_documents(documentos)
37
 
38
+ # 3. Crear Embeddings y Vector Store
39
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
40
  db = FAISS.from_documents(documentos_divididos, embeddings)
41
  return db
42
 
43
+ # Inicializar la base de datos al inicio del script
44
  db = initialize_database()
45
 
46
+
47
+ # --- B. CONFIGURACIÓN DEL LLM GRANDE (Mistral Instruct) ---
48
+
49
+ # Configuración para cargar el modelo en 4 bits (Ahorro de memoria)
50
  quant_config = BitsAndBytesConfig(
51
  load_in_4bit=True,
52
  bnb_4bit_quant_type="nf4",
 
54
  )
55
 
56
  model_name = "mistralai/Mistral-7B-Instruct-v0.2"
57
+
58
  tokenizer = AutoTokenizer.from_pretrained(model_name)
59
  model = AutoModelForCausalLM.from_pretrained(
60
  model_name,
61
+ quantization_config=quant_config,
62
+ device_map="auto"
63
  )
64
 
65
  pipe = pipeline(
66
  "text-generation",
67
  model=model,
68
  tokenizer=tokenizer,
69
+ max_new_tokens=256,
 
 
70
  )
71
 
72
+ # --- C. PROMPT Y FUNCIÓN RAG ---
73
 
74
+ prompt_template_persona = """[INST] Eres un asistente experto en ciencia de datos y aprendizaje profundo, con un vocabulario formal y un tono cortés y servicial. Tu tarea es responder la Pregunta usando ÚNICAMENTE la información proporcionada en el Contexto.
75
+ Si no puedes encontrar la respuesta en el contexto, simplemente responde "Lamento, no tengo información sobre ese tema específico en mi base de conocimiento."
76
 
77
+ Contexto:
78
+ {context}
 
 
 
79
 
80
+ Pregunta: {question} [/INST]"""
81
+
82
+
83
+ def rag_chain_manual(query, db, llm_pipeline, prompt_template):
84
+ # 1. Retrieval
85
+ docs = db.similarity_search(query, k=2)
86
+ context = "\n\n---\n\n".join([doc.page_content for doc in docs])
87
+
88
+ # 2. Augmentation
89
+ final_prompt = prompt_template.format(context=context, question=query)
90
+
91
+ # 3. Generation
92
+ result = llm_pipeline(final_prompt)
 
 
 
 
 
 
 
 
 
93
 
94
+ # 4. Extracción y Limpieza
95
+ generated_text = result[0]['generated_text']
96
+
97
+ try:
98
+ final_answer = generated_text.split("[/INST]")[-1].strip()
99
+ except:
100
+ final_answer = generated_text.strip()
101
+
102
+ return final_answer
103
+
104
+
105
+ # --- D. INTERFAZ GRADIO ---
106
+
107
+ # Definimos la función ANTES de usarla en la interfaz
108
+ def responder_consulta(query):
109
+ respuesta = rag_chain_manual(query, db, pipe, prompt_template_persona)
110
+ return respuesta
111
+
112
+ # Configuración de la interfaz (Sin el parámetro problemático allow_flagging)
113
+ demo = gr.Interface(
114
+ fn=responder_consulta,
115
+ inputs=gr.Textbox(label="Ingrese su pregunta para la IA experta:"),
116
+ outputs="text",
117
+ title="Asistente RAG Experto (Mistral-7B)",
118
+ description="Sistema de Generación Aumentada por Recuperación (RAG) para consultas sobre IA en Chile."
119
  )
120
 
121
  if __name__ == "__main__":