ChatBot-NLP / backend.py
Mueble's picture
Update backend.py
167bb9a verified
Raw History Blame
1.16 kB
# backend.py
from sentence_transformers import SentenceTransformer
import chromadb
from chromadb.config import Settings
from huggingface_hub import InferenceClient
# Modelos
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Cargar índice persistente
chroma_client = chromadb.Client(Settings(anonymized_telemetry=False, persist_directory="chroma_db"))
collection = chroma_client.get_collection("batalla_ayacucho_rag")
# Función principal
def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
query_emb = embedding_model.encode(pregunta).tolist()
resultados = collection.query(query_embeddings=[query_emb], n_results=k)
contextos = resultados["documents"][0]
contexto = "\n\n".join(contextos)[:max_chars]
prompt = f"""Responde en español a la siguiente pregunta sobre historia peruana.
Contexto histórico:
{contexto}
Pregunta: {pregunta}
Respuesta:"""
respuesta = client.text_generation(
prompt=prompt,
max_new_tokens=512,
temperature=0.7,
top_p=0.95,
return_full_text=False
)
return respuesta.strip()