Bhanuprasadchouki
commited on
Create CDH_chatbot_using_RAG.py
Browse files- CDH_chatbot_using_RAG.py +53 -0
CDH_chatbot_using_RAG.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from langchain_chroma import Chroma
|
3 |
+
from langchain_core.prompts import ChatPromptTemplate
|
4 |
+
from langchain_google_genai import GoogleGenerativeAI
|
5 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
6 |
+
|
7 |
+
# Configuration
|
8 |
+
GOOGLE_API_KEY = "AIzaSyB-7cKMdUpA5kTccpNxd72IT5CjeSgSmkc" # Replace with your API key
|
9 |
+
CHROMA_DB_DIR = "./chroma_db_" # Directory for ChromaDB
|
10 |
+
MODEL_NAME = "flax-sentence-embeddings/all_datasets_v4_MiniLM-L6"
|
11 |
+
|
12 |
+
# Initialize HuggingFace Embeddings
|
13 |
+
embeddings_model = HuggingFaceEmbeddings(model_name=MODEL_NAME)
|
14 |
+
|
15 |
+
# Initialize Chroma Database
|
16 |
+
db = Chroma(collection_name="vector_database",
|
17 |
+
embedding_function=embeddings_model,
|
18 |
+
persist_directory=CHROMA_DB_DIR)
|
19 |
+
|
20 |
+
# Initialize Google Generative AI
|
21 |
+
genai_model = GoogleGenerativeAI(api_key=GOOGLE_API_KEY, model="gemini-1.5-flash")
|
22 |
+
|
23 |
+
# Streamlit App
|
24 |
+
st.title("Question Answering with ChromaDB and Google GenAI")
|
25 |
+
st.write("Ask a question based on the context stored in the database.")
|
26 |
+
|
27 |
+
# Input Query
|
28 |
+
query = st.text_input("Enter your question:")
|
29 |
+
|
30 |
+
if query:
|
31 |
+
with st.spinner("Retrieving context and generating an answer..."):
|
32 |
+
# Retrieve Context from ChromaDB
|
33 |
+
docs_chroma = db.similarity_search_with_score(query, k=4)
|
34 |
+
context_text = "\n\n".join([doc.page_content for doc, _score in docs_chroma])
|
35 |
+
|
36 |
+
# Generate Answer
|
37 |
+
PROMPT_TEMPLATE = """
|
38 |
+
Answer the question based only on the following context:
|
39 |
+
{context}
|
40 |
+
Answer the question based on the above context: {question}.
|
41 |
+
Provide a detailed answer.
|
42 |
+
Don’t justify your answers.
|
43 |
+
Don’t give information not mentioned in the CONTEXT INFORMATION.
|
44 |
+
Do not say "according to the context" or "mentioned in the context" or similar.
|
45 |
+
"""
|
46 |
+
prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
|
47 |
+
prompt = prompt_template.format(context=context_text, question=query)
|
48 |
+
|
49 |
+
response_text = genai_model.invoke(prompt)
|
50 |
+
|
51 |
+
# Display Answer
|
52 |
+
st.subheader("Answer:")
|
53 |
+
st.write(response_text)
|