Sistema completo de Retrieval-Augmented Generation (RAG) con interfaz web e API para responder preguntas basadas en una base de conocimiento.
Este proyecto implementa un sistema RAG que:
| Componente | Modelo | Tamaño |
|---|---|---|
| Embeddings | MongoDB/mdbr-leaf-ir | ~90 MB |
| Lenguaje | PleIAs/Pleias-RAG-350M | ~707 MB |
Ambos modelos optimizados para CPU en entornos serverless.
🌐 Abre el Chat RAG en Hugging Face Spaces
# 1. Clonar repositorio
git clone https://github.com/Soren-Madsen/Practica-Final-RA3-Analisis-predictivo-de-informacion.git
cd Practica-Final-RA3-Analisis-predictivo-de-informacion.
# 2. Crear entorno virtual
python -m venv .venv
source .venv/bin/activate # En Windows: .venv\Scripts\activate
# 3. Instalar dependencias
pip install -r requirements.txt
# 4. Ejecutar la aplicación
python app.py
Abre tu navegador en http://localhost:7860
python app.py
Luego accede a http://localhost:7860 y:
Parámetros:
from rag_engine import preguntar
# Hacer una pregunta
respuesta = preguntar("What is the hospital email?", top_k=1, umbral=0.55)
print(respuesta)
# Output: "The hospital email is [email protected]."
# Ejecutar ejemplos de prueba
python rag_engine.py
from gradio_client import Client
client = Client("SorenMad/ChatRAG2")
result = client.predict(
query="Where is the hospital located?",
top_k=1,
umbral=0.55,
api_name="/ask"
)
print(result[0]) # Respuesta
print(result[1]) # Documentos recuperados
O ejecuta:
python tests/test_api.py
recuperar_documentos(consulta, top_k=2, umbral=0.4)Recupera documentos relevantes basados en similitud semántica.
Parámetros:
consulta (str): Pregunta del usuariotop_k (int): Número máximo de documentos a retornarumbral (float): Similitud mínima (0.0 - 1.0)Retorna: Lista de textos de documentos relevantes
docs = recuperar_documentos("What is the hospital email?", top_k=2, umbral=0.4)
# Output: ['Document 1 text', 'Document 2 text']
generar_respuesta(consulta, documentos_recuperados)Genera una respuesta usando los documentos como contexto.
Parámetros:
consulta (str): Pregunta originaldocumentos_recuperados (list): Documentos del paso anteriorRetorna: String con la respuesta generada
respuesta = generar_respuesta("What is the email?", docs)
# Output: "The hospital email is [email protected]."
preguntar(consulta, top_k=2, umbral=0.4)Función completa que combina recuperación y generación.
respuesta = preguntar("What are the working hours?")
# Output: "The hospital's working hours are 7:00 AM - 8:00 PM daily."
├── app.py # Interfaz Gradio (web)
├── rag_engine.py # Motor RAG principal
├── documents.json # Base de conocimiento
├── requirements.txt # Dependencias Python
├── README.md # Este archivo
├── LICENSE # Licencia MIT
├── tests/
│ └── test_api.py # Tests de API remota
└── teoria/
└── crud_flask.py # Código teórico (referencia)
Input: "What is the hospital email?"
Output: "The hospital email is [email protected]."
Input: "What are the working hours?"
Output: "The hospital's working hours are 7:00 AM - 8:00 PM daily."
Input: "Where is the hospital located?"
Output: "The hospital is located at xyz, abc, 1234, Nepal."
El proyecto está ya desplegado y funcionando en:
Crear un Space en Hugging Face
Clonar y actualizar el Space
git clone https://huggingface.co/spaces/tu-usuario/tu-space
cd tu-space
cp app.py rag_engine.py documents.json requirements.txt .
Push de cambios
git add .
git commit -m "Deploy Chat RAG"
git push
El Space se actualizará automáticamente.
Para máxima precisión:
preguntar(consulta, top_k=2, umbral=0.55)
Para máxima cobertura:
preguntar(consulta, top_k=5, umbral=0.40)
Para respuestas rápidas:
preguntar(consulta, top_k=1, umbral=0.60)
Para usar otros modelos, edita rag_engine.py:
# Cambiar modelo de embeddings
embedding_model = SentenceTransformer("tu-modelo-aqui")
# Cambiar modelo de lenguaje
language_model = AutoModelForCausalLM.from_pretrained("tu-modelo-aqui")
┌─────────────────┐
│ Pregunta │
└────────┬────────┘
│
▼
┌─────────────────────────────┐
│ 1. RECUPERACIÓN │
│ (Embedding + Similitud) │
└────────┬────────────────────┘
│
▼ Documentos relevantes
┌─────────────────────────────┐
│ 2. GENERACIÓN │
│ (LLM + Contexto) │
└────────┬────────────────────┘
│
▼
┌──────────┐
│ Respuesta│
└──────────┘
Recuperación:
Generación:
Ver requirements.txt para versiones exactas.
Este proyecto está bajo la licencia MIT. Ver archivo LICENSE para más detalles.
Soren Madsen
Última actualización: Marzo 2026
Estado: ✅ Producción - Fully Functional
Sistema completo de Retrieval-Augmented Generation (RAG) con interfaz web e API para responder preguntas basadas en una base de conocimiento.
Este proyecto implementa un sistema RAG que:
| Componente | Modelo | Tamaño |
|---|---|---|
| Embeddings | MongoDB/mdbr-leaf-ir | ~90 MB |
| Lenguaje | PleIAs/Pleias-RAG-350M | ~707 MB |
Ambos modelos optimizados para CPU en entornos serverless.
🌐 Abre el Chat RAG en Hugging Face Spaces
# 1. Clonar repositorio
git clone https://github.com/Soren-Madsen/Practica-Final-RA3-Analisis-predictivo-de-informacion.git
cd Practica-Final-RA3-Analisis-predictivo-de-informacion.
# 2. Crear entorno virtual
python -m venv .venv
source .venv/bin/activate # En Windows: .venv\Scripts\activate
# 3. Instalar dependencias
pip install -r requirements.txt
# 4. Ejecutar la aplicación
python app.py
Abre tu navegador en http://localhost:7860
python app.py
Luego accede a http://localhost:7860 y:
Parámetros:
from rag_engine import preguntar
# Hacer una pregunta
respuesta = preguntar("What is the hospital email?", top_k=1, umbral=0.55)
print(respuesta)
# Output: "The hospital email is [email protected]."
# Ejecutar ejemplos de prueba
python rag_engine.py
from gradio_client import Client
client = Client("SorenMad/ChatRAG2")
result = client.predict(
query="Where is the hospital located?",
top_k=1,
umbral=0.55,
api_name="/ask"
)
print(result[0]) # Respuesta
print(result[1]) # Documentos recuperados
O ejecuta:
python tests/test_api.py
recuperar_documentos(consulta, top_k=2, umbral=0.4)Recupera documentos relevantes basados en similitud semántica.
Parámetros:
consulta (str): Pregunta del usuariotop_k (int): Número máximo de documentos a retornarumbral (float): Similitud mínima (0.0 - 1.0)Retorna: Lista de textos de documentos relevantes
docs = recuperar_documentos("What is the hospital email?", top_k=2, umbral=0.4)
# Output: ['Document 1 text', 'Document 2 text']
generar_respuesta(consulta, documentos_recuperados)Genera una respuesta usando los documentos como contexto.
Parámetros:
consulta (str): Pregunta originaldocumentos_recuperados (list): Documentos del paso anteriorRetorna: String con la respuesta generada
respuesta = generar_respuesta("What is the email?", docs)
# Output: "The hospital email is [email protected]."
preguntar(consulta, top_k=2, umbral=0.4)Función completa que combina recuperación y generación.
respuesta = preguntar("What are the working hours?")
# Output: "The hospital's working hours are 7:00 AM - 8:00 PM daily."
├── app.py # Interfaz Gradio (web)
├── rag_engine.py # Motor RAG principal
├── documents.json # Base de conocimiento
├── requirements.txt # Dependencias Python
├── README.md # Este archivo
├── LICENSE # Licencia MIT
├── tests/
│ └── test_api.py # Tests de API remota
└── teoria/
└── crud_flask.py # Código teórico (referencia)
Input: "What is the hospital email?"
Output: "The hospital email is [email protected]."
Input: "What are the working hours?"
Output: "The hospital's working hours are 7:00 AM - 8:00 PM daily."
Input: "Where is the hospital located?"
Output: "The hospital is located at xyz, abc, 1234, Nepal."
El proyecto está ya desplegado y funcionando en:
Crear un Space en Hugging Face
Clonar y actualizar el Space
git clone https://huggingface.co/spaces/tu-usuario/tu-space
cd tu-space
cp app.py rag_engine.py documents.json requirements.txt .
Push de cambios
git add .
git commit -m "Deploy Chat RAG"
git push
El Space se actualizará automáticamente.
Para máxima precisión:
preguntar(consulta, top_k=2, umbral=0.55)
Para máxima cobertura:
preguntar(consulta, top_k=5, umbral=0.40)
Para respuestas rápidas:
preguntar(consulta, top_k=1, umbral=0.60)
Para usar otros modelos, edita rag_engine.py:
# Cambiar modelo de embeddings
embedding_model = SentenceTransformer("tu-modelo-aqui")
# Cambiar modelo de lenguaje
language_model = AutoModelForCausalLM.from_pretrained("tu-modelo-aqui")
┌─────────────────┐
│ Pregunta │
└────────┬────────┘
│
▼
┌─────────────────────────────┐
│ 1. RECUPERACIÓN │
│ (Embedding + Similitud) │
└────────┬────────────────────┘
│
▼ Documentos relevantes
┌─────────────────────────────┐
│ 2. GENERACIÓN │
│ (LLM + Contexto) │
└────────┬────────────────────┘
│
▼
┌──────────┐
│ Respuesta│
└──────────┘
Recuperación:
Generación:
Ver requirements.txt para versiones exactas.
Este proyecto está bajo la licencia MIT. Ver archivo LICENSE para más detalles.
Soren Madsen
Última actualización: Marzo 2026
Estado: ✅ Producción - Fully Functional