Question_And_Answer / knowledge_base.py
dschandra's picture
Update knowledge_base.py
31d430e verified
raw
history blame
1.34 kB
import requests
from transformers import pipeline
# Load the model and tokenizer using Hugging Face's pipeline
qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
def load_qa_model():
# Initialize any model settings or variables, if needed
return qa_pipeline
def get_answer_from_knowledge_base(question):
"""
This function uses a Hugging Face model (DistilBERT) for question answering
from a given context.
"""
try:
# Example: Using a static context for the model to search for answers
context = """
Andhra Pradesh (AP) is a state in southern India. The current Chief Minister of Andhra Pradesh is Y. S. Jagan Mohan Reddy.
He assumed office in May 2019. Jagan Mohan Reddy is from the Yuvajana Sramika Rythu Congress Party (YSRCP).
"""
# Using the question-answering pipeline from Hugging Face
result = qa_pipeline(question=question, context=context)
# Extract and return the answer from the result
if result['score'] > 0.1: # Only return answer if the model is confident
return result['answer']
else:
return None
except Exception as e:
print(f"Error occurred: {e}")
return "Sorry, I couldn't fetch data at the moment. Please try again later."