Spaces:
Running
on
Zero
Running
on
Zero
Add internet search feature
Browse files- app.py +95 -101
- requirements.txt +1 -0
app.py
CHANGED
@@ -1,10 +1,9 @@
|
|
1 |
import streamlit as st
|
2 |
from llama_cpp import Llama
|
3 |
from huggingface_hub import hf_hub_download
|
4 |
-
import os
|
5 |
-
import
|
6 |
-
import
|
7 |
-
import re
|
8 |
|
9 |
# ----- Custom CSS for pretty formatting of internal reasoning -----
|
10 |
CUSTOM_CSS = """
|
@@ -33,8 +32,40 @@ st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
|
|
33 |
# ----- Set a threshold for required free storage (in bytes) -----
|
34 |
REQUIRED_SPACE_BYTES = 5 * 1024 ** 3 # 5 GB
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
# ----- Available models -----
|
37 |
MODELS = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
"Qwen2.5-7B-Instruct (Q2_K)": {
|
39 |
"repo_id": "Qwen/Qwen2.5-7B-Instruct-GGUF",
|
40 |
"filename": "qwen2.5-7b-instruct-q2_k.gguf",
|
@@ -76,22 +107,16 @@ MODELS = {
|
|
76 |
with st.sidebar:
|
77 |
st.header("⚙️ Settings")
|
78 |
selected_model_name = st.selectbox("Select Model", list(MODELS.keys()))
|
79 |
-
|
80 |
-
max_tokens = st.slider("Max tokens", 64,
|
81 |
temperature = st.slider("Temperature", 0.1, 2.0, 0.7)
|
82 |
top_k = st.slider("Top-K", 1, 100, 40)
|
83 |
top_p = st.slider("Top-P", 0.1, 1.0, 0.95)
|
84 |
repeat_penalty = st.slider("Repetition Penalty", 1.0, 2.0, 1.1)
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
if f.endswith(".gguf"):
|
90 |
-
os.remove(os.path.join("models", f))
|
91 |
-
st.success("Model cache cleared.")
|
92 |
-
except Exception as e:
|
93 |
-
st.error(f"Failed to clear models: {e}")
|
94 |
-
|
95 |
if st.button("📦 Show Disk Usage"):
|
96 |
try:
|
97 |
usage = shutil.disk_usage(".")
|
@@ -101,49 +126,22 @@ with st.sidebar:
|
|
101 |
except Exception as e:
|
102 |
st.error(f"Disk usage error: {e}")
|
103 |
|
104 |
-
# -----
|
105 |
selected_model = MODELS[selected_model_name]
|
106 |
model_path = os.path.join("models", selected_model["filename"])
|
107 |
|
108 |
-
#
|
109 |
-
if "model_name" not in st.session_state:
|
110 |
-
st.session_state.model_name = None
|
111 |
-
if "llm" not in st.session_state:
|
112 |
-
st.session_state.llm = None
|
113 |
-
if "chat_history" not in st.session_state:
|
114 |
-
st.session_state.chat_history = []
|
115 |
-
if "pending_response" not in st.session_state:
|
116 |
-
st.session_state.pending_response = False
|
117 |
-
|
118 |
-
# ----- Ensure model directory exists -----
|
119 |
os.makedirs("models", exist_ok=True)
|
120 |
|
121 |
-
# -----
|
122 |
-
def cleanup_old_models():
|
123 |
-
for f in os.listdir("models"):
|
124 |
-
if f.endswith(".gguf") and f != selected_model["filename"]:
|
125 |
-
try:
|
126 |
-
os.remove(os.path.join("models", f))
|
127 |
-
except Exception as e:
|
128 |
-
st.warning(f"Couldn't delete old model {f}: {e}")
|
129 |
-
|
130 |
-
def download_model():
|
131 |
-
with st.spinner(f"Downloading {selected_model['filename']}..."):
|
132 |
-
hf_hub_download(
|
133 |
-
repo_id=selected_model["repo_id"],
|
134 |
-
filename=selected_model["filename"],
|
135 |
-
local_dir="./models",
|
136 |
-
local_dir_use_symlinks=False, # Deprecated parameter; harmless warning.
|
137 |
-
)
|
138 |
-
|
139 |
def try_load_model(path):
|
140 |
try:
|
141 |
return Llama(
|
142 |
model_path=path,
|
143 |
-
n_ctx=
|
144 |
-
n_threads=
|
145 |
-
n_threads_batch=
|
146 |
-
n_batch=
|
147 |
n_gpu_layers=0,
|
148 |
use_mlock=False,
|
149 |
use_mmap=True,
|
@@ -152,15 +150,21 @@ def try_load_model(path):
|
|
152 |
except Exception as e:
|
153 |
return str(e)
|
154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
def validate_or_download_model():
|
156 |
-
# Download model if not present locally.
|
157 |
if not os.path.exists(model_path):
|
158 |
free_space = shutil.disk_usage(".").free
|
159 |
if free_space < REQUIRED_SPACE_BYTES:
|
160 |
-
st.info("Insufficient storage
|
161 |
-
cleanup_old_models()
|
162 |
download_model()
|
163 |
-
|
164 |
result = try_load_model(model_path)
|
165 |
if isinstance(result, str):
|
166 |
st.warning(f"Initial load failed: {result}\nAttempting re-download...")
|
@@ -168,10 +172,6 @@ def validate_or_download_model():
|
|
168 |
os.remove(model_path)
|
169 |
except Exception:
|
170 |
pass
|
171 |
-
free_space = shutil.disk_usage(".").free
|
172 |
-
if free_space < REQUIRED_SPACE_BYTES:
|
173 |
-
st.info("Insufficient storage detected on re-download attempt. Cleaning up old models to free up space.")
|
174 |
-
cleanup_old_models()
|
175 |
download_model()
|
176 |
result = try_load_model(model_path)
|
177 |
if isinstance(result, str):
|
@@ -180,6 +180,16 @@ def validate_or_download_model():
|
|
180 |
return result
|
181 |
return result
|
182 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
# ----- Load model if changed -----
|
184 |
if st.session_state.model_name != selected_model_name:
|
185 |
if st.session_state.llm is not None:
|
@@ -194,37 +204,51 @@ llm = st.session_state.llm
|
|
194 |
st.title(f"🧠 {selected_model['description']} (Streamlit + GGUF)")
|
195 |
st.caption(f"Powered by `llama.cpp` | Model: {selected_model['filename']}")
|
196 |
|
197 |
-
#
|
198 |
for chat in st.session_state.chat_history:
|
199 |
with st.chat_message(chat["role"]):
|
200 |
st.markdown(chat["content"])
|
201 |
-
# For assistant messages, if there's completed internal reasoning, display it behind an expander.
|
202 |
-
if chat.get("role") == "assistant" and chat.get("thinking"):
|
203 |
-
with st.expander("🧠 Model's Internal Reasoning"):
|
204 |
-
for t in chat["thinking"]:
|
205 |
-
st.markdown(t.strip())
|
206 |
|
207 |
-
# ----- Chat input
|
208 |
user_input = st.chat_input("Ask something...")
|
209 |
|
210 |
if user_input:
|
211 |
if st.session_state.pending_response:
|
212 |
st.warning("Please wait for the assistant to finish responding.")
|
213 |
else:
|
|
|
214 |
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
215 |
with st.chat_message("user"):
|
216 |
st.markdown(user_input)
|
217 |
|
218 |
st.session_state.pending_response = True
|
219 |
|
220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
trimmed_history = st.session_state.chat_history[-(MAX_TURNS * 2):]
|
222 |
-
messages = [{"role": "system", "content":
|
223 |
|
224 |
-
#
|
225 |
with st.chat_message("assistant"):
|
226 |
visible_placeholder = st.empty()
|
227 |
-
thinking_placeholder = st.empty()
|
228 |
full_response = ""
|
229 |
stream = llm.create_chat_completion(
|
230 |
messages=messages,
|
@@ -240,41 +264,11 @@ if user_input:
|
|
240 |
if "choices" in chunk:
|
241 |
delta = chunk["choices"][0]["delta"].get("content", "")
|
242 |
full_response += delta
|
243 |
-
|
244 |
-
# Determine if there is an open (in-progress) <think> block
|
245 |
-
open_think = re.search(r"<think>([^<]*)$", full_response, flags=re.DOTALL)
|
246 |
-
in_progress = open_think.group(1).strip() if open_think else ""
|
247 |
-
|
248 |
-
# Create the visible response by removing any complete <think>...</think> blocks,
|
249 |
-
# and also removing any in-progress (unclosed) <think> content.
|
250 |
visible_response = re.sub(r"<think>.*?</think>", "", full_response, flags=re.DOTALL)
|
251 |
visible_response = re.sub(r"<think>.*$", "", visible_response, flags=re.DOTALL)
|
252 |
visible_placeholder.markdown(visible_response)
|
253 |
|
254 |
-
|
255 |
-
if in_progress:
|
256 |
-
# You can further format in_progress as you like; here we wrap it in a styled div.
|
257 |
-
thinking_html = f"""
|
258 |
-
<div class="chat-assistant">
|
259 |
-
<strong>Internal Reasoning (in progress):</strong>
|
260 |
-
<br>{in_progress}
|
261 |
-
</div>
|
262 |
-
"""
|
263 |
-
thinking_placeholder.markdown(thinking_html, unsafe_allow_html=True)
|
264 |
-
else:
|
265 |
-
thinking_placeholder.empty()
|
266 |
-
|
267 |
-
# After streaming completes:
|
268 |
-
# Extract all completed <think> blocks (the final internal reasoning that was closed)
|
269 |
-
final_thinking = re.findall(r"<think>(.*?)</think>", full_response, flags=re.DOTALL)
|
270 |
-
# The final visible response: remove any <think> blocks or any in-progress open block.
|
271 |
-
final_visible = re.sub(r"<think>.*?</think>", "", full_response, flags=re.DOTALL)
|
272 |
-
final_visible = re.sub(r"<think>.*$", "", final_visible, flags=re.DOTALL)
|
273 |
-
|
274 |
-
st.session_state.chat_history.append({
|
275 |
-
"role": "assistant",
|
276 |
-
"content": final_visible,
|
277 |
-
"thinking": final_thinking
|
278 |
-
})
|
279 |
-
|
280 |
st.session_state.pending_response = False
|
|
|
|
1 |
import streamlit as st
|
2 |
from llama_cpp import Llama
|
3 |
from huggingface_hub import hf_hub_download
|
4 |
+
import os, gc, shutil, re
|
5 |
+
from itertools import islice
|
6 |
+
from duckduckgo_search import DDGS # Latest class-based interface :contentReference[oaicite:0]{index=0}
|
|
|
7 |
|
8 |
# ----- Custom CSS for pretty formatting of internal reasoning -----
|
9 |
CUSTOM_CSS = """
|
|
|
32 |
# ----- Set a threshold for required free storage (in bytes) -----
|
33 |
REQUIRED_SPACE_BYTES = 5 * 1024 ** 3 # 5 GB
|
34 |
|
35 |
+
# ----- Function to perform DuckDuckGo search and retrieve concise context -----
|
36 |
+
def retrieve_context(query, max_results=2, max_chars_per_result=150):
|
37 |
+
"""
|
38 |
+
Query DuckDuckGo for the given search query and return a concatenated context string.
|
39 |
+
Uses the DDGS().text() generator (with region, safesearch, and timelimit parameters)
|
40 |
+
and limits the results using islice. Each result's title and snippet are combined into context.
|
41 |
+
"""
|
42 |
+
try:
|
43 |
+
with DDGS() as ddgs:
|
44 |
+
results_gen = ddgs.text(query, region="wt-wt", safesearch="off", timelimit="y")
|
45 |
+
results = list(islice(results_gen, max_results))
|
46 |
+
context = ""
|
47 |
+
if results:
|
48 |
+
for i, result in enumerate(results, start=1):
|
49 |
+
title = result.get("title", "No Title")
|
50 |
+
snippet = result.get("body", "")[:max_chars_per_result]
|
51 |
+
context += f"Result {i}:\nTitle: {title}\nSnippet: {snippet}\n\n"
|
52 |
+
return context.strip()
|
53 |
+
except Exception as e:
|
54 |
+
st.error(f"Error during retrieval: {e}")
|
55 |
+
return ""
|
56 |
+
|
57 |
# ----- Available models -----
|
58 |
MODELS = {
|
59 |
+
"Qwen2.5-0.5B-Instruct (Q4_K_M)": {
|
60 |
+
"repo_id": "Qwen/Qwen2.5-0.5B-Instruct-GGUF",
|
61 |
+
"filename": "qwen2.5-0.5b-instruct-q4_k_m.gguf",
|
62 |
+
"description": "Qwen2.5-0.5B-Instruct (Q4_K_M)"
|
63 |
+
},
|
64 |
+
"Gemma-3.1B-it (Q4_K_M)": {
|
65 |
+
"repo_id": "unsloth/gemma-3-1b-it-GGUF",
|
66 |
+
"filename": "gemma-3-1b-it-Q4_K_M.gguf",
|
67 |
+
"description": "Gemma-3.1B-it (Q4_K_M)"
|
68 |
+
},
|
69 |
"Qwen2.5-7B-Instruct (Q2_K)": {
|
70 |
"repo_id": "Qwen/Qwen2.5-7B-Instruct-GGUF",
|
71 |
"filename": "qwen2.5-7b-instruct-q2_k.gguf",
|
|
|
107 |
with st.sidebar:
|
108 |
st.header("⚙️ Settings")
|
109 |
selected_model_name = st.selectbox("Select Model", list(MODELS.keys()))
|
110 |
+
system_prompt_base = st.text_area("System Prompt", value="You are a helpful assistant.", height=80)
|
111 |
+
max_tokens = st.slider("Max tokens", 64, 1024, 256, step=32) # Adjust for lower memory usage
|
112 |
temperature = st.slider("Temperature", 0.1, 2.0, 0.7)
|
113 |
top_k = st.slider("Top-K", 1, 100, 40)
|
114 |
top_p = st.slider("Top-P", 0.1, 1.0, 0.95)
|
115 |
repeat_penalty = st.slider("Repetition Penalty", 1.0, 2.0, 1.1)
|
116 |
|
117 |
+
# Checkbox to enable the DuckDuckGo search feature (disabled by default)
|
118 |
+
enable_search = st.checkbox("Enable Web Search", value=False)
|
119 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
if st.button("📦 Show Disk Usage"):
|
121 |
try:
|
122 |
usage = shutil.disk_usage(".")
|
|
|
126 |
except Exception as e:
|
127 |
st.error(f"Disk usage error: {e}")
|
128 |
|
129 |
+
# ----- Define selected model and path -----
|
130 |
selected_model = MODELS[selected_model_name]
|
131 |
model_path = os.path.join("models", selected_model["filename"])
|
132 |
|
133 |
+
# Ensure model directory exists
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
os.makedirs("models", exist_ok=True)
|
135 |
|
136 |
+
# ----- Helper functions for model management -----
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
def try_load_model(path):
|
138 |
try:
|
139 |
return Llama(
|
140 |
model_path=path,
|
141 |
+
n_ctx=512, # Reduced context window to save memory
|
142 |
+
n_threads=1, # Fewer threads for resource-constrained environments
|
143 |
+
n_threads_batch=1,
|
144 |
+
n_batch=2, # Lower batch size to conserve memory
|
145 |
n_gpu_layers=0,
|
146 |
use_mlock=False,
|
147 |
use_mmap=True,
|
|
|
150 |
except Exception as e:
|
151 |
return str(e)
|
152 |
|
153 |
+
def download_model():
|
154 |
+
with st.spinner(f"Downloading {selected_model['filename']}..."):
|
155 |
+
hf_hub_download(
|
156 |
+
repo_id=selected_model["repo_id"],
|
157 |
+
filename=selected_model["filename"],
|
158 |
+
local_dir="./models",
|
159 |
+
local_dir_use_symlinks=False,
|
160 |
+
)
|
161 |
+
|
162 |
def validate_or_download_model():
|
|
|
163 |
if not os.path.exists(model_path):
|
164 |
free_space = shutil.disk_usage(".").free
|
165 |
if free_space < REQUIRED_SPACE_BYTES:
|
166 |
+
st.info("Insufficient storage. Consider cleaning up old models.")
|
|
|
167 |
download_model()
|
|
|
168 |
result = try_load_model(model_path)
|
169 |
if isinstance(result, str):
|
170 |
st.warning(f"Initial load failed: {result}\nAttempting re-download...")
|
|
|
172 |
os.remove(model_path)
|
173 |
except Exception:
|
174 |
pass
|
|
|
|
|
|
|
|
|
175 |
download_model()
|
176 |
result = try_load_model(model_path)
|
177 |
if isinstance(result, str):
|
|
|
180 |
return result
|
181 |
return result
|
182 |
|
183 |
+
# ----- Session state initialization -----
|
184 |
+
if "model_name" not in st.session_state:
|
185 |
+
st.session_state.model_name = None
|
186 |
+
if "llm" not in st.session_state:
|
187 |
+
st.session_state.llm = None
|
188 |
+
if "chat_history" not in st.session_state:
|
189 |
+
st.session_state.chat_history = []
|
190 |
+
if "pending_response" not in st.session_state:
|
191 |
+
st.session_state.pending_response = False
|
192 |
+
|
193 |
# ----- Load model if changed -----
|
194 |
if st.session_state.model_name != selected_model_name:
|
195 |
if st.session_state.llm is not None:
|
|
|
204 |
st.title(f"🧠 {selected_model['description']} (Streamlit + GGUF)")
|
205 |
st.caption(f"Powered by `llama.cpp` | Model: {selected_model['filename']}")
|
206 |
|
207 |
+
# Render existing chat history
|
208 |
for chat in st.session_state.chat_history:
|
209 |
with st.chat_message(chat["role"]):
|
210 |
st.markdown(chat["content"])
|
|
|
|
|
|
|
|
|
|
|
211 |
|
212 |
+
# ----- Chat input and integrated RAG with memory optimizations -----
|
213 |
user_input = st.chat_input("Ask something...")
|
214 |
|
215 |
if user_input:
|
216 |
if st.session_state.pending_response:
|
217 |
st.warning("Please wait for the assistant to finish responding.")
|
218 |
else:
|
219 |
+
# Append the user query to chat history
|
220 |
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
221 |
with st.chat_message("user"):
|
222 |
st.markdown(user_input)
|
223 |
|
224 |
st.session_state.pending_response = True
|
225 |
|
226 |
+
# Only retrieve search context if search feature is enabled
|
227 |
+
if enable_search:
|
228 |
+
retrieved_context = retrieve_context(user_input, max_results=2, max_chars_per_result=150)
|
229 |
+
else:
|
230 |
+
retrieved_context = ""
|
231 |
+
st.sidebar.markdown("### Retrieved Context" if enable_search else "Web Search Disabled")
|
232 |
+
st.sidebar.text(retrieved_context or "No context found.")
|
233 |
+
|
234 |
+
# Build an augmented system prompt that includes the retrieved context if available
|
235 |
+
if retrieved_context:
|
236 |
+
augmented_prompt = (
|
237 |
+
"Use the following recent web search context to help answer the query:\n\n"
|
238 |
+
f"{retrieved_context}\n\nUser Query: {user_input}"
|
239 |
+
)
|
240 |
+
else:
|
241 |
+
augmented_prompt = f"User Query: {user_input}"
|
242 |
+
full_system_prompt = system_prompt_base.strip() + "\n\n" + augmented_prompt
|
243 |
+
|
244 |
+
# Limit conversation history to the last 2 turns
|
245 |
+
MAX_TURNS = 2
|
246 |
trimmed_history = st.session_state.chat_history[-(MAX_TURNS * 2):]
|
247 |
+
messages = [{"role": "system", "content": full_system_prompt}] + trimmed_history
|
248 |
|
249 |
+
# Generate response with the LLM in a streaming fashion
|
250 |
with st.chat_message("assistant"):
|
251 |
visible_placeholder = st.empty()
|
|
|
252 |
full_response = ""
|
253 |
stream = llm.create_chat_completion(
|
254 |
messages=messages,
|
|
|
264 |
if "choices" in chunk:
|
265 |
delta = chunk["choices"][0]["delta"].get("content", "")
|
266 |
full_response += delta
|
267 |
+
# Clean internal reasoning markers before display
|
|
|
|
|
|
|
|
|
|
|
|
|
268 |
visible_response = re.sub(r"<think>.*?</think>", "", full_response, flags=re.DOTALL)
|
269 |
visible_response = re.sub(r"<think>.*$", "", visible_response, flags=re.DOTALL)
|
270 |
visible_placeholder.markdown(visible_response)
|
271 |
|
272 |
+
st.session_state.chat_history.append({"role": "assistant", "content": full_response})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
273 |
st.session_state.pending_response = False
|
274 |
+
gc.collect() # Trigger garbage collection to free memory
|
requirements.txt
CHANGED
@@ -5,3 +5,4 @@ llama-cpp-python
|
|
5 |
llama-cpp-agent
|
6 |
huggingface_hub
|
7 |
streamlit
|
|
|
|
5 |
llama-cpp-agent
|
6 |
huggingface_hub
|
7 |
streamlit
|
8 |
+
duckduckgo_search
|