Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from openai import OpenAI
|
4 |
+
from langchain.memory import ConversationBufferMemory
|
5 |
+
from langchain.vectorstores import FAISS
|
6 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
7 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
8 |
+
from langchain.document_loaders import PyPDFLoader, TextLoader
|
9 |
+
import tempfile
|
10 |
+
|
11 |
+
# Page configuration
|
12 |
+
st.set_page_config(page_title="DeepSeek RAG Chatbot", page_icon="π€", layout="wide")
|
13 |
+
|
14 |
+
# App title and description
|
15 |
+
st.title("π€ DeepSeek RAG Chatbot")
|
16 |
+
st.subheader("A chatbot that uses your documents to give informed answers")
|
17 |
+
|
18 |
+
# Set up API key input
|
19 |
+
if 'DEEPSEEK_API_KEY' not in st.session_state:
|
20 |
+
api_key = st.text_input("Enter your DeepSeek API Key:", type="password")
|
21 |
+
if api_key:
|
22 |
+
st.session_state['DEEPSEEK_API_KEY'] = api_key
|
23 |
+
os.environ['DEEPSEEK_API_KEY'] = api_key
|
24 |
+
st.success("API Key saved!")
|
25 |
+
st.rerun()
|
26 |
+
|
27 |
+
# Initialize session state variables
|
28 |
+
if 'memory' not in st.session_state:
|
29 |
+
st.session_state.memory = ConversationBufferMemory(return_messages=True)
|
30 |
+
if 'chat_history' not in st.session_state:
|
31 |
+
st.session_state.chat_history = []
|
32 |
+
if 'vectorstore' not in st.session_state:
|
33 |
+
st.session_state.vectorstore = None
|
34 |
+
if 'client' not in st.session_state and 'DEEPSEEK_API_KEY' in st.session_state:
|
35 |
+
try:
|
36 |
+
# Initialize DeepSeek client for chat
|
37 |
+
st.session_state.client = OpenAI(
|
38 |
+
api_key=st.session_state['DEEPSEEK_API_KEY'],
|
39 |
+
base_url="https://api.deepseek.com"
|
40 |
+
)
|
41 |
+
|
42 |
+
# Initialize small HuggingFace embeddings model
|
43 |
+
# Using paraphrase-MiniLM-L3-v2 - a smaller version with only 22MB size
|
44 |
+
st.session_state.embeddings = HuggingFaceEmbeddings(
|
45 |
+
model_name="sentence-transformers/paraphrase-MiniLM-L3-v2"
|
46 |
+
)
|
47 |
+
|
48 |
+
st.success("Models loaded successfully!")
|
49 |
+
except Exception as e:
|
50 |
+
st.error(f"Error initializing API: {str(e)}")
|
51 |
+
|
52 |
+
# Function to process uploaded documents
|
53 |
+
def process_documents(uploaded_files):
|
54 |
+
temp_dir = tempfile.mkdtemp()
|
55 |
+
for file in uploaded_files:
|
56 |
+
file_path = os.path.join(temp_dir, file.name)
|
57 |
+
with open(file_path, "wb") as f:
|
58 |
+
f.write(file.getbuffer())
|
59 |
+
|
60 |
+
# Load documents based on file type
|
61 |
+
documents = []
|
62 |
+
for file in uploaded_files:
|
63 |
+
if file.name.endswith('.pdf'):
|
64 |
+
loader = PyPDFLoader(os.path.join(temp_dir, file.name))
|
65 |
+
documents.extend(loader.load())
|
66 |
+
elif file.name.endswith('.txt'):
|
67 |
+
loader = TextLoader(os.path.join(temp_dir, file.name))
|
68 |
+
documents.extend(loader.load())
|
69 |
+
|
70 |
+
# Split documents into chunks
|
71 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
72 |
+
chunk_size=1000,
|
73 |
+
chunk_overlap=200
|
74 |
+
)
|
75 |
+
document_chunks = text_splitter.split_documents(documents)
|
76 |
+
|
77 |
+
# Create or update vector store
|
78 |
+
if st.session_state.vectorstore is None:
|
79 |
+
st.session_state.vectorstore = FAISS.from_documents(
|
80 |
+
document_chunks,
|
81 |
+
st.session_state.embeddings
|
82 |
+
)
|
83 |
+
else:
|
84 |
+
# Add new documents to existing vectorstore
|
85 |
+
st.session_state.vectorstore.add_documents(document_chunks)
|
86 |
+
|
87 |
+
return len(document_chunks)
|
88 |
+
|
89 |
+
# Function to retrieve relevant context from vector database
|
90 |
+
def retrieve_context(query, k=3):
|
91 |
+
if st.session_state.vectorstore is None:
|
92 |
+
return ""
|
93 |
+
|
94 |
+
docs = st.session_state.vectorstore.similarity_search(query, k=k)
|
95 |
+
context = "\n\n".join([doc.page_content for doc in docs])
|
96 |
+
return context
|
97 |
+
|
98 |
+
# Main application layout
|
99 |
+
if 'DEEPSEEK_API_KEY' in st.session_state:
|
100 |
+
# Create a two-column layout
|
101 |
+
col1, col2 = st.columns([3, 1])
|
102 |
+
|
103 |
+
with col2:
|
104 |
+
st.header("Document Upload")
|
105 |
+
uploaded_files = st.file_uploader(
|
106 |
+
"Upload your documents",
|
107 |
+
accept_multiple_files=True,
|
108 |
+
type=["pdf", "txt"]
|
109 |
+
)
|
110 |
+
|
111 |
+
if uploaded_files:
|
112 |
+
if st.button("Process Documents"):
|
113 |
+
with st.spinner("Processing documents..."):
|
114 |
+
num_chunks = process_documents(uploaded_files)
|
115 |
+
st.success(f"Successfully processed {len(uploaded_files)} documents into {num_chunks} chunks!")
|
116 |
+
|
117 |
+
st.header("RAG Settings")
|
118 |
+
k_documents = st.slider("Number of documents to retrieve", min_value=1, max_value=10, value=3)
|
119 |
+
|
120 |
+
# Clear conversation button
|
121 |
+
if st.button("Clear Conversation"):
|
122 |
+
st.session_state.memory = ConversationBufferMemory(return_messages=True)
|
123 |
+
st.session_state.chat_history = []
|
124 |
+
st.success("Conversation cleared!")
|
125 |
+
st.rerun()
|
126 |
+
|
127 |
+
# Clear knowledge base button
|
128 |
+
if st.button("Clear Knowledge Base"):
|
129 |
+
st.session_state.vectorstore = None
|
130 |
+
st.success("Knowledge base cleared!")
|
131 |
+
|
132 |
+
with col1:
|
133 |
+
# Display chat history
|
134 |
+
for message in st.session_state.chat_history:
|
135 |
+
with st.chat_message(message["role"]):
|
136 |
+
st.write(message["content"])
|
137 |
+
|
138 |
+
# User input
|
139 |
+
user_input = st.chat_input("Type your message here...")
|
140 |
+
|
141 |
+
if user_input:
|
142 |
+
# Add user message to chat history
|
143 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
144 |
+
|
145 |
+
# Display user message
|
146 |
+
with st.chat_message("user"):
|
147 |
+
st.write(user_input)
|
148 |
+
|
149 |
+
# Get model response
|
150 |
+
with st.chat_message("assistant"):
|
151 |
+
with st.spinner("Thinking..."):
|
152 |
+
try:
|
153 |
+
# Retrieve relevant context from vector database
|
154 |
+
context = retrieve_context(user_input, k=k_documents)
|
155 |
+
|
156 |
+
# Prepare chat history for DeepSeek API
|
157 |
+
system_prompt = "You are a helpful assistant with access to a knowledge base."
|
158 |
+
if context:
|
159 |
+
system_prompt += f"\n\nRelevant information from knowledge base:\n{context}\n\nUse this information to answer the user's question. If the information doesn't contain the answer, just say that you don't know based on the available information."
|
160 |
+
|
161 |
+
messages = [{"role": "system", "content": system_prompt}]
|
162 |
+
for msg in st.session_state.chat_history:
|
163 |
+
messages.append({"role": msg["role"], "content": msg["content"]})
|
164 |
+
|
165 |
+
# Call DeepSeek API
|
166 |
+
response = st.session_state.client.chat.completions.create(
|
167 |
+
model="deepseek-chat",
|
168 |
+
messages=messages,
|
169 |
+
stream=False
|
170 |
+
)
|
171 |
+
|
172 |
+
assistant_response = response.choices[0].message.content
|
173 |
+
st.write(assistant_response)
|
174 |
+
|
175 |
+
# Add assistant response to chat history
|
176 |
+
st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
|
177 |
+
|
178 |
+
except Exception as e:
|
179 |
+
st.error(f"Error: {str(e)}")
|
180 |
+
|
181 |
+
# Sidebar with info
|
182 |
+
with st.sidebar:
|
183 |
+
st.header("About")
|
184 |
+
st.markdown("""
|
185 |
+
This RAG chatbot uses:
|
186 |
+
- π¦ LangChain for memory and document processing
|
187 |
+
- π FAISS for vector storage and retrieval
|
188 |
+
- π§ HuggingFace for lightweight embeddings (paraphrase-MiniLM-L3-v2)
|
189 |
+
- π€ DeepSeek API for AI responses
|
190 |
+
- π₯οΈ Streamlit for the web interface
|
191 |
+
|
192 |
+
The chatbot can:
|
193 |
+
- Upload and process PDF and text documents
|
194 |
+
- Retrieve relevant information from documents
|
195 |
+
- Generate informed responses using your documents
|
196 |
+
- Maintain conversation context
|
197 |
+
""")
|