Spaces:
Running
Running
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +68 -56
src/streamlit_app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
-
import requests
|
| 4 |
import threading
|
|
|
|
| 5 |
|
| 6 |
import streamlit as st
|
| 7 |
import torch
|
|
@@ -72,11 +72,7 @@ DEFAULT_SYSTEM_PROMPT = (
|
|
| 72 |
)
|
| 73 |
|
| 74 |
SAMPLE_SYSTEM_PROMPT = DEFAULT_SYSTEM_PROMPT
|
| 75 |
-
|
| 76 |
-
SAMPLE_CONTEXT = (
|
| 77 |
-
"Teapot is an open-source AI assistant optimized for running on low-end cpu devices."
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
SAMPLE_ANSWER = "I am Teapot, an open-source AI assistant optimized for running on low-end cpu devices."
|
| 81 |
SAMPLE_PROMPT = f"{SAMPLE_CONTEXT}\n{SAMPLE_SYSTEM_PROMPT}\n{SAMPLE_QUESTION}\n"
|
| 82 |
|
|
@@ -106,6 +102,7 @@ if "messages" not in st.session_state:
|
|
| 106 |
if "seeded" not in st.session_state:
|
| 107 |
st.session_state.seeded = False
|
| 108 |
|
|
|
|
| 109 |
if (not st.session_state.seeded) and (len(st.session_state.messages) == 0):
|
| 110 |
st.session_state.messages = [SAMPLE_USER_MSG, SAMPLE_ASSISTANT_MSG]
|
| 111 |
st.session_state.seeded = True
|
|
@@ -215,13 +212,41 @@ def get_trace_id_if_available() -> str | None:
|
|
| 215 |
|
| 216 |
|
| 217 |
# =========================
|
| 218 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
# =========================
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
| 221 |
"""
|
| 222 |
-
|
|
|
|
| 223 |
"""
|
| 224 |
-
prompt = f"{context}\n{system_prompt}\n{question}\n"
|
| 225 |
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
| 226 |
|
| 227 |
streamer = TextIteratorStreamer(
|
|
@@ -238,52 +263,38 @@ def stream_answer_tokens(context: str, system_prompt: str, question: str):
|
|
| 238 |
streamer=streamer,
|
| 239 |
)
|
| 240 |
|
| 241 |
-
# Run generate in a background thread so we can iterate streamer in the main thread.
|
| 242 |
t = threading.Thread(target=model.generate, kwargs=gen_kwargs, daemon=True)
|
| 243 |
t.start()
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
| 248 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
# Wrap a traced function around the streaming loop (LangSmith will see a single run)
|
| 252 |
-
@traceable(name="teapot_answer_stream")
|
| 253 |
-
def traced_stream_answer(context: str, system_prompt: str, question: str):
|
| 254 |
-
for chunk in stream_answer_tokens(context, system_prompt, question):
|
| 255 |
-
yield chunk
|
| 256 |
-
else:
|
| 257 |
-
def traced_stream_answer(context: str, system_prompt: str, question: str):
|
| 258 |
-
for chunk in stream_answer_tokens(context, system_prompt, question):
|
| 259 |
-
yield chunk
|
| 260 |
|
| 261 |
|
| 262 |
-
|
| 263 |
-
# FEEDBACK HANDLER (attached to trace_id)
|
| 264 |
-
# =========================
|
| 265 |
-
def handle_feedback(idx: int):
|
| 266 |
-
val = st.session_state.get(f"fb_{idx}")
|
| 267 |
-
st.session_state.messages[idx]["feedback"] = val
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
key="thumb_rating",
|
| 278 |
-
score=score,
|
| 279 |
-
comment="thumbs_up" if score else "thumbs_down",
|
| 280 |
-
)
|
| 281 |
-
except Exception:
|
| 282 |
-
pass
|
| 283 |
|
| 284 |
|
| 285 |
# =========================
|
| 286 |
-
# INPUT FIRST (so
|
| 287 |
# =========================
|
| 288 |
query = st.chat_input("Ask a question...")
|
| 289 |
|
|
@@ -292,7 +303,9 @@ if query:
|
|
| 292 |
|
| 293 |
|
| 294 |
# =========================
|
| 295 |
-
# RENDER HISTORY
|
|
|
|
|
|
|
| 296 |
# =========================
|
| 297 |
for i, msg in enumerate(st.session_state.messages):
|
| 298 |
with st.chat_message(msg["role"]):
|
|
@@ -336,7 +349,6 @@ for i, msg in enumerate(st.session_state.messages):
|
|
| 336 |
|
| 337 |
# =========================
|
| 338 |
# GENERATE ONLY IF THIS RUN RECEIVED A NEW QUERY
|
| 339 |
-
# (We detect by: query is not None)
|
| 340 |
# =========================
|
| 341 |
if query:
|
| 342 |
question = query
|
|
@@ -349,25 +361,25 @@ if query:
|
|
| 349 |
prompt = f"{context}\n{system_prompt}\n{question}\n"
|
| 350 |
input_tokens = count_tokens(prompt)
|
| 351 |
|
| 352 |
-
#
|
| 353 |
with st.chat_message("assistant"):
|
|
|
|
| 354 |
msg_col, fb_col = st.columns([14, 1], vertical_alignment="center")
|
| 355 |
with msg_col:
|
| 356 |
placeholder = st.empty()
|
| 357 |
with fb_col:
|
| 358 |
st.feedback("thumbs", key="live_fb", disabled=True)
|
| 359 |
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
buf = ""
|
| 363 |
-
placeholder.markdown("") # ensures first token updates a visible element
|
| 364 |
-
for chunk in traced_stream_answer(context, system_prompt, question):
|
| 365 |
-
buf += chunk
|
| 366 |
-
placeholder.markdown(buf)
|
| 367 |
|
|
|
|
|
|
|
| 368 |
trace_id = get_trace_id_if_available()
|
| 369 |
gen_time = time.perf_counter() - start
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
| 371 |
tps = output_tokens / gen_time if gen_time > 0 else 0.0
|
| 372 |
|
| 373 |
# Row 2: inspect + metrics
|
|
@@ -394,7 +406,7 @@ if query:
|
|
| 394 |
st.session_state.messages.append(
|
| 395 |
{
|
| 396 |
"role": "assistant",
|
| 397 |
-
"content":
|
| 398 |
"context": context,
|
| 399 |
"system_prompt": system_prompt,
|
| 400 |
"question": question,
|
|
|
|
| 1 |
import os
|
| 2 |
import time
|
|
|
|
| 3 |
import threading
|
| 4 |
+
import requests
|
| 5 |
|
| 6 |
import streamlit as st
|
| 7 |
import torch
|
|
|
|
| 72 |
)
|
| 73 |
|
| 74 |
SAMPLE_SYSTEM_PROMPT = DEFAULT_SYSTEM_PROMPT
|
| 75 |
+
SAMPLE_CONTEXT = "Teapot is an open-source AI assistant optimized for running on low-end cpu devices."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
SAMPLE_ANSWER = "I am Teapot, an open-source AI assistant optimized for running on low-end cpu devices."
|
| 77 |
SAMPLE_PROMPT = f"{SAMPLE_CONTEXT}\n{SAMPLE_SYSTEM_PROMPT}\n{SAMPLE_QUESTION}\n"
|
| 78 |
|
|
|
|
| 102 |
if "seeded" not in st.session_state:
|
| 103 |
st.session_state.seeded = False
|
| 104 |
|
| 105 |
+
# Seed exactly once on first load
|
| 106 |
if (not st.session_state.seeded) and (len(st.session_state.messages) == 0):
|
| 107 |
st.session_state.messages = [SAMPLE_USER_MSG, SAMPLE_ASSISTANT_MSG]
|
| 108 |
st.session_state.seeded = True
|
|
|
|
| 212 |
|
| 213 |
|
| 214 |
# =========================
|
| 215 |
+
# FEEDBACK HANDLER (attached to trace_id)
|
| 216 |
+
# =========================
|
| 217 |
+
def handle_feedback(idx: int):
|
| 218 |
+
val = st.session_state.get(f"fb_{idx}")
|
| 219 |
+
st.session_state.messages[idx]["feedback"] = val
|
| 220 |
+
|
| 221 |
+
msg = st.session_state.messages[idx]
|
| 222 |
+
trace_id = msg.get("trace_id")
|
| 223 |
+
|
| 224 |
+
if ls_client and trace_id:
|
| 225 |
+
score = 1 if val == "👍" else 0
|
| 226 |
+
try:
|
| 227 |
+
ls_client.create_feedback(
|
| 228 |
+
trace_id=trace_id,
|
| 229 |
+
key="thumb_rating",
|
| 230 |
+
score=score,
|
| 231 |
+
comment="thumbs_up" if score else "thumbs_down",
|
| 232 |
+
)
|
| 233 |
+
except Exception:
|
| 234 |
+
pass
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# =========================
|
| 238 |
+
# STREAMING + LANGSMITH FIX
|
| 239 |
+
# - We do NOT trace a generator.
|
| 240 |
+
# - We stream to UI while returning a SINGLE final string.
|
| 241 |
# =========================
|
| 242 |
+
_UI_STREAM = {"placeholder": None} # set per-request
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _generate_with_streamer(prompt: str) -> str:
|
| 246 |
"""
|
| 247 |
+
Runs model.generate with a TextIteratorStreamer and updates a Streamlit placeholder
|
| 248 |
+
as chunks arrive. Returns the final full text.
|
| 249 |
"""
|
|
|
|
| 250 |
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
| 251 |
|
| 252 |
streamer = TextIteratorStreamer(
|
|
|
|
| 263 |
streamer=streamer,
|
| 264 |
)
|
| 265 |
|
|
|
|
| 266 |
t = threading.Thread(target=model.generate, kwargs=gen_kwargs, daemon=True)
|
| 267 |
t.start()
|
| 268 |
|
| 269 |
+
buf = ""
|
| 270 |
+
ph = _UI_STREAM.get("placeholder")
|
| 271 |
+
if ph is not None:
|
| 272 |
+
ph.markdown("") # ensure element exists before first chunk
|
| 273 |
|
| 274 |
+
for chunk in streamer:
|
| 275 |
+
buf += chunk
|
| 276 |
+
if ph is not None:
|
| 277 |
+
ph.markdown(buf)
|
| 278 |
|
| 279 |
+
return buf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
|
| 282 |
+
if traceable:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
@traceable(name="teapot_answer")
|
| 285 |
+
def traced_answer_streaming(context: str, system_prompt: str, question: str) -> str:
|
| 286 |
+
prompt = f"{context}\n{system_prompt}\n{question}\n"
|
| 287 |
+
return _generate_with_streamer(prompt)
|
| 288 |
|
| 289 |
+
else:
|
| 290 |
+
|
| 291 |
+
def traced_answer_streaming(context: str, system_prompt: str, question: str) -> str:
|
| 292 |
+
prompt = f"{context}\n{system_prompt}\n{question}\n"
|
| 293 |
+
return _generate_with_streamer(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
# =========================
|
| 297 |
+
# INPUT FIRST (so latest user msg renders immediately)
|
| 298 |
# =========================
|
| 299 |
query = st.chat_input("Ask a question...")
|
| 300 |
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
# =========================
|
| 306 |
+
# RENDER HISTORY
|
| 307 |
+
# Row 1: message + feedback
|
| 308 |
+
# Row 2: inspect + debug metrics
|
| 309 |
# =========================
|
| 310 |
for i, msg in enumerate(st.session_state.messages):
|
| 311 |
with st.chat_message(msg["role"]):
|
|
|
|
| 349 |
|
| 350 |
# =========================
|
| 351 |
# GENERATE ONLY IF THIS RUN RECEIVED A NEW QUERY
|
|
|
|
| 352 |
# =========================
|
| 353 |
if query:
|
| 354 |
question = query
|
|
|
|
| 361 |
prompt = f"{context}\n{system_prompt}\n{question}\n"
|
| 362 |
input_tokens = count_tokens(prompt)
|
| 363 |
|
| 364 |
+
# Assistant response (stream to UI, return full string for LangSmith)
|
| 365 |
with st.chat_message("assistant"):
|
| 366 |
+
# Row 1: message + feedback (disabled live)
|
| 367 |
msg_col, fb_col = st.columns([14, 1], vertical_alignment="center")
|
| 368 |
with msg_col:
|
| 369 |
placeholder = st.empty()
|
| 370 |
with fb_col:
|
| 371 |
st.feedback("thumbs", key="live_fb", disabled=True)
|
| 372 |
|
| 373 |
+
_UI_STREAM["placeholder"] = placeholder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
+
start = time.perf_counter()
|
| 376 |
+
answer = traced_answer_streaming(context, system_prompt, question)
|
| 377 |
trace_id = get_trace_id_if_available()
|
| 378 |
gen_time = time.perf_counter() - start
|
| 379 |
+
|
| 380 |
+
_UI_STREAM["placeholder"] = None # cleanup
|
| 381 |
+
|
| 382 |
+
output_tokens = count_tokens(answer)
|
| 383 |
tps = output_tokens / gen_time if gen_time > 0 else 0.0
|
| 384 |
|
| 385 |
# Row 2: inspect + metrics
|
|
|
|
| 406 |
st.session_state.messages.append(
|
| 407 |
{
|
| 408 |
"role": "assistant",
|
| 409 |
+
"content": answer,
|
| 410 |
"context": context,
|
| 411 |
"system_prompt": system_prompt,
|
| 412 |
"question": question,
|