Spaces:
Runtime error
Runtime error
Download backend.py from NLPChatBotTeam/ChatBot-NLP: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/NLPChatBotTeam/ChatBot-NLP/resolve/7a4ce4da4e8935c22a20f2b4b0ea5fa7d2119d38/backend.py
- Command line
-
hf download hf://spaces/NLPChatBotTeam/ChatBot-NLP@7a4ce4da4e8935c22a20f2b4b0ea5fa7d2119d38/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/NLPChatBotTeam/ChatBot-NLP/resolve/7a4ce4da4e8935c22a20f2b4b0ea5fa7d2119d38/backend.py
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() | |