ar12c commited on
Commit
cc881da
·
verified ·
1 Parent(s): 5e3dd78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +511 -487
app.py CHANGED
@@ -11,7 +11,7 @@ import math
11
  import unicodedata
12
  import requests
13
  from datetime import datetime
14
- from typing import Dict, List, Tuple, Optional, Any
15
 
16
  import torch
17
  import torch.nn as nn
@@ -26,8 +26,8 @@ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
26
  # Config
27
  # ---------------------
28
  SYSTEM_INSTRUCTION: str = (
29
- "You are a friendly, helpful, concise AI assistant named Okemo Language Model (OLM). "
30
- "Default to clear, short answers; elaborate only when asked."
31
  )
32
 
33
  ONLINE_LEARNING_EPOCHS: int = 5
@@ -35,14 +35,14 @@ CHECKPOINT_PATH: str = "checkpoint.pth"
35
 
36
  # Fallback defaults (used only when no checkpoint exists)
37
  DEFAULTS: Dict[str, Any] = {
38
- "d_model": 768,
39
- "n_head": 48,
40
- "d_ff": 768,
41
- "n_layers": 12,
42
- "dropout": 0.1,
43
- "max_length": 512,
44
- "k_sampling": 20,
45
- "LEARNING_RATE": 1e-6,
46
  }
47
 
48
  # Web search provider (Tavily). Keep key in environment.
@@ -55,573 +55,597 @@ WEB_TAG_RE = re.compile(r"<\s*web\s*>", flags=re.IGNORECASE)
55
  # Helpers
56
  # ---------------------
57
  def to_ascii(text: Optional[str]) -> str:
58
- """Normalize to NFKC and ensure str."""
59
- return unicodedata.normalize("NFKC", text or "")
60
 
61
  # Simple tokenizer: words or punctuation
62
  _TOKEN_RE = re.compile(r"\w+|[^\w\s]", flags=re.UNICODE)
63
 
64
  def tokenize(text: str) -> List[str]:
65
- """Lowercase, ASCII-normalized tokenization into words and punctuation units."""
66
- txt = to_ascii(text)
67
- return _TOKEN_RE.findall(txt.lower())
68
 
69
  def check_repetition(text: str, max_repeat: int = 2) -> bool:
70
- """Detect exact token repetition runs longer than max_repeat."""
71
- tokens = tokenize(text)
72
- if not tokens or max_repeat < 1:
73
- return False
74
- for i in range(len(tokens) - max_repeat):
75
- if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):
76
- return True
77
- return False
78
 
79
  # ---------------------
80
  # Vocabulary
81
  # ---------------------
82
  class Voc:
83
- """Lightweight vocabulary storing special tokens and bidirectional maps."""
84
-
85
- def __init__(self) -> None:
86
- self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"
87
- self.word2index: Dict[str, int] = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
88
- self.index2word: Dict[int, str] = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}
89
- self.n_words: int = 5
90
-
91
- @staticmethod
92
- def load_from_checkpoint(ckpt: Dict[str, Any]) -> "Voc":
93
- voc = Voc()
94
- if "voc_word2index" in ckpt and "voc_index2word" in ckpt:
95
- voc.word2index = ckpt["voc_word2index"]
96
- voc.index2word = ckpt["voc_index2word"]
97
- voc.n_words = len(voc.word2index)
98
- if "special_tokens" in ckpt:
99
- tokens = ckpt["special_tokens"]
100
- voc.PAD = tokens.get("PAD", voc.PAD)
101
- voc.SOS = tokens.get("SOS", voc.SOS)
102
- voc.EOS = tokens.get("EOS", voc.EOS)
103
- voc.UNK = tokens.get("UNK", voc.UNK)
104
- voc.SYSTEM = tokens.get("SYSTEM", voc.SYSTEM)
105
- return voc
106
-
107
- def add_sentence(self, sentence: str) -> None:
108
- for word in tokenize(sentence):
109
- if word not in self.word2index:
110
- idx = self.n_words
111
- self.word2index[word] = idx
112
- self.index2word[idx] = word
113
- self.n_words += 1
114
 
115
  # ---------------------
116
  # Model
117
  # ---------------------
118
  class PositionalEncoding(nn.Module):
119
- """Sinusoidal positional encoding used by Transformer."""
120
 
121
- def __init__(self, d_model: int, max_len: int = 5000) -> None:
122
- super().__init__()
123
- pe = torch.zeros(max_len, d_model)
124
- position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
125
- div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
126
- pe[:, 0::2] = torch.sin(position * div_term)
127
- pe[:, 1::2] = torch.cos(position * div_term)
128
- self.register_buffer("pe", pe.unsqueeze(0))
129
 
130
- def forward(self, x: torch.Tensor) -> torch.Tensor:
131
- return x + self.pe[:, : x.size(1), :]
132
 
133
  class GPT(nn.Module):
134
- """Minimal GPT-like model using nn.TransformerEncoder with weight tying."""
135
-
136
- def __init__(self, n_words: int, d_model: int, n_layers: int, n_head: int, d_ff: int, dropout: float = 0.1) -> None:
137
- super().__init__()
138
- self.embedding = nn.Embedding(n_words, d_model)
139
- self.pos = PositionalEncoding(d_model)
140
- self.norm = nn.LayerNorm(d_model)
141
- enc_layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)
142
- self.transformer = nn.TransformerEncoder(enc_layer, n_layers)
143
- self.fc = nn.Linear(d_model, n_words, bias=False)
144
- self.fc.weight = self.embedding.weight # weight tying
145
-
146
- def forward(
147
- self,
148
- x: torch.Tensor,
149
- mask: Optional[torch.Tensor] = None,
150
- key_padding_mask: Optional[torch.Tensor] = None,
151
- ) -> torch.Tensor:
152
- x = self.embedding(x)
153
- x = self.pos(x)
154
- x = self.norm(x)
155
- out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
156
- return self.fc(out)
157
 
158
  # ---------------------
159
  # Training utils
160
  # ---------------------
161
  def indexes_from_sentence(voc: Voc, sentence: str) -> List[int]:
162
- sanitized = " ".join(tokenize(sentence))
163
- prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)
164
- return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]
165
 
166
  def make_bool_causal_mask(sz: int, device: torch.device) -> torch.Tensor:
167
- return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
168
 
169
  # ---------------------
170
  # Device
171
  # ---------------------
172
  device: torch.device = torch.device(
173
- "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
174
  )
175
 
176
  # ---------------------
177
  # Checkpoint-aware init
178
  # ---------------------
179
  def load_checkpoint_or_defaults(path: str) -> Tuple[Dict[str, Any], Dict[str, Any], Voc, GPT, optim.Optimizer]:
180
- if os.path.exists(path):
181
- ckpt = torch.load(path, map_location=device)
182
- hp = {
183
- "d_model": ckpt.get("d_model", DEFAULTS["d_model"]),
184
- "n_head": ckpt.get("n_head", DEFAULTS["n_head"]),
185
- "d_ff": ckpt.get("d_ff", DEFAULTS["d_ff"]),
186
- "n_layers": ckpt.get("n_layers", DEFAULTS["n_layers"]),
187
- "dropout": ckpt.get("dropout", DEFAULTS["dropout"]),
188
- "max_length": ckpt.get("max_length", DEFAULTS["max_length"]),
189
- "k_sampling": ckpt.get("k_sampling", DEFAULTS["k_sampling"]),
190
- "LEARNING_RATE": ckpt.get("LEARNING_RATE", DEFAULTS["LEARNING_RATE"]),
191
- }
192
- voc = Voc.load_from_checkpoint(ckpt)
193
- model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)
194
- if ckpt.get("gpt_model_state_dict") is not None:
195
- model.load_state_dict(ckpt["gpt_model_state_dict"], strict=True)
196
- model.fc.weight = model.embedding.weight
197
- optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])
198
- if "optimizer_state_dict" in ckpt:
199
- try:
200
- optimizer.load_state_dict(ckpt["optimizer_state_dict"])
201
- except Exception as e:
202
- print(f"Warning: Failed to load optimizer state: {e}. Starting fresh.")
203
- return ckpt, hp, voc, model, optimizer
204
- else:
205
- print("WARNING: No checkpoint found. Initializing with defaults.")
206
- hp = DEFAULTS.copy()
207
- voc = Voc()
208
- model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)
209
- optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])
210
- return {}, hp, voc, model, optimizer
211
 
212
  checkpoint, HP, voc, gpt_model, optimizer = load_checkpoint_or_defaults(CHECKPOINT_PATH)
213
  criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
214
 
215
  # --- Added logic: Save initial state if no checkpoint was found to ensure .pth exists ---
216
  if not os.path.exists(CHECKPOINT_PATH):
217
- print("Saving initial checkpoint with default settings.")
218
- # The initial voc will only contain special tokens, but it's a valid starting point
219
- save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
220
  # ---------------------------------------------------------------------------------------
221
 
222
  # ---------------------
223
  # Save checkpoint
224
  # ---------------------
225
  def save_checkpoint(model: GPT, optimizer: optim.Optimizer, voc: Voc, path: str) -> None:
226
- print(f"Saving model checkpoint to {path}...")
227
- ckpt = {
228
- "voc_word2index": voc.word2index,
229
- "voc_index2word": voc.index2word,
230
- "gpt_model_state_dict": model.state_dict(),
231
- "optimizer_state_dict": optimizer.state_dict(),
232
- "d_model": HP["d_model"],
233
- "n_head": HP["n_head"],
234
- "d_ff": HP["d_ff"],
235
- "n_layers": HP["n_layers"],
236
- "dropout": HP["dropout"],
237
- "max_length": HP["max_length"],
238
- "k_sampling": HP["k_sampling"],
239
- "LEARNING_RATE": HP["LEARNING_RATE"],
240
- }
241
- try:
242
- torch.save(ckpt, path)
243
- print("Checkpoint saved successfully.")
244
- except Exception as e:
245
- print(f"ERROR: Failed to save checkpoint: {e}")
246
 
247
  # ---------------------
248
  # Web search (only with <WEB>)
249
  # ---------------------
250
  def perform_web_search(query: str) -> str:
251
- if not TAVILY_API_KEY:
252
- return ""
253
- try:
254
- resp = requests.post(
255
- "https://api.tavily.com/search",
256
- json={"api_key": TAVILY_API_KEY, "query": query, "include_answer": False, "max_results": 5},
257
- timeout=8,
258
- )
259
- resp.raise_for_status()
260
- data = resp.json()
261
- results = data.get("results", [])
262
- snippets: List[str] = []
263
- for r in results[:3]:
264
- title = (r.get("title") or "").strip()
265
- snippet = (r.get("content") or "").strip()
266
- url = (r.get("url") or "").strip()
267
- if title or snippet:
268
- snippets.append(f"{title}: {snippet} (Source: {url})")
269
- return to_ascii(" | ".join(snippets))
270
- except Exception as e:
271
- print(f"Search failed: {e}")
272
- return ""
273
 
274
  def should_search(user_text: str) -> bool:
275
- return bool(WEB_TAG_RE.search(user_text or ""))
276
 
277
  # ---------------------
278
  # Generation
279
  # ---------------------
280
- def generate_response(prompt: str, search_context: str = "", conversation_context: str = "") -> str:
281
- prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
282
- context_prefix = f"{conversation_context} " if conversation_context else ""
283
- full_input = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text}{prompt}"
284
- full_input = to_ascii(full_input)
285
-
286
- gpt_model.eval()
287
-
288
- initial_tokens = indexes_from_sentence(voc, full_input)
289
- input_tensor = torch.tensor(initial_tokens, dtype=torch.long, device=device).unsqueeze(0)
290
- generated: List[int] = []
291
- temperature = 0.8
292
- # min_tokens = 24 # The variable for forced generation is no longer used
293
- vocab_eos = voc.word2index[voc.EOS]
294
- vocab_pad = voc.word2index[voc.PAD]
295
-
296
- with torch.no_grad():
297
- for step in range(HP["max_length"]):
298
- L = input_tensor.size(1)
299
- causal = make_bool_causal_mask(L, device)
300
- padmask = (input_tensor == vocab_pad)
301
- logits = gpt_model(input_tensor, mask=causal, key_padding_mask=padmask)
302
- last = logits[:, -1, :].float() / max(temperature, 1e-3)
303
-
304
- k = max(1, int(HP["k_sampling"]))
305
- topk_vals, topk_idx = torch.topk(last, k)
306
- probs = F.softmax(topk_vals, dim=-1).float()
307
- pick_rel = torch.multinomial(probs, 1).item()
308
- candidate_id = topk_idx.squeeze(0)[pick_rel].item()
309
-
310
- # The logic that forces generation past min_tokens has been removed to improve generation quality.
311
- # if candidate_id == vocab_eos and step < min_tokens:
312
- # candidate_id = topk_idx.squeeze(0)[0].item()
313
-
314
- if candidate_id == vocab_eos:
315
- break
316
-
317
- generated.append(candidate_id)
318
- next_token = torch.tensor([[candidate_id]], device=device, dtype=torch.long)
319
- input_tensor = torch.cat([input_tensor, next_token], dim=1)
320
-
321
- words = [voc.index2word.get(t, voc.UNK) for t in generated]
322
- filtered_words = [w for w in words if w not in [voc.PAD, voc.SOS, voc.EOS, voc.UNK, voc.SYSTEM]]
323
-
324
- text = " ".join(filtered_words)
325
- text = to_ascii(text)
326
- text = re.sub(r"\s+([,.!?;:])", r"\1", text).strip()
327
- if not text or check_repetition(text):
328
- return "I got lost in the data tubes! Perhaps ask me something a little sillier? 🤪"
329
- return text
330
 
331
  # ---------------------
332
  # Online learning (feedback)
333
  # ---------------------
334
  def online_update(
335
- model: GPT,
336
- input_sentence: str,
337
- target_response: str,
338
- max_seq_len: int,
339
- search_context: str = "",
340
- file_context: str = "",
341
- conversation_context: str = "",
342
  ) -> None:
343
- is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
344
- is_not_repetitive = not check_repetition(target_response, max_repeat=2)
345
- if not is_response_clean or not is_not_repetitive:
346
- print("Skipping online update: Target response is corrupted or highly repetitive.")
347
- return
348
-
349
- prefix_search = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
350
- prefix_file = f"Based on the attached file: {to_ascii(file_context)}. " if file_context else ""
351
- context_prefix = f"{conversation_context} " if conversation_context else ""
352
-
353
- full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_search}{prefix_file}{input_sentence}"
354
- full_prompt_text = to_ascii(full_prompt_text)
355
-
356
- prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
357
- sanitized_response = to_ascii(target_response)
358
- response_tokens = indexes_from_sentence(voc, sanitized_response)[1:]
359
-
360
- full_sequence_ids = prompt_tokens + response_tokens
361
- input_ids = full_sequence_ids[:-1]
362
- target_ids = full_sequence_ids[1:]
363
-
364
- if len(input_ids) < 2 or len(input_ids) != len(target_ids) or len(input_ids) > max_seq_len:
365
- print(f"Skipping online update. Sequence length: {len(input_ids)}")
366
- return
367
-
368
- input_tensor = torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0)
369
- target_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)
370
-
371
- L = input_tensor.size(1)
372
- model.train()
373
- causal = make_bool_causal_mask(L, device)
374
-
375
- last_loss = 0.0
376
- for _ in range(ONLINE_LEARNING_EPOCHS):
377
- optimizer.zero_grad()
378
- logits = model(input_tensor, mask=causal, key_padding_mask=None)
379
- loss = criterion(logits.squeeze(0), target_tensor)
380
- loss.backward()
381
- torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
382
- optimizer.step()
383
- last_loss = loss.item()
384
-
385
- model.eval()
386
- print(f"Online update done. Final Loss: {last_loss:.4f}")
387
 
388
  def process_feedback(history: List[List[Optional[str]]], rating: str) -> Tuple[List[List[Optional[str]]], str]:
389
- if not isinstance(history, list):
390
- return [], "Cannot process feedback: history not a list."
391
- if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):
392
- return history, "Cannot process feedback: No recent AI response found."
393
-
394
- last_user_message, last_ai_response = history[-1][0], history[-1][1]
395
-
396
- file_context_text = ""
397
- file_match = re.search(r"\(Attached: (.*?)\)", last_user_message or "")
398
- if file_match:
399
- file_name = file_match.group(1)
400
- file_context_text = f"The user provided a file named '{file_name}'."
401
-
402
- clean_user_message = to_ascii(last_user_message or "")
403
- clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()
404
- clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()
405
-
406
- search_context_text = ""
407
-
408
- if rating == "Good Response":
409
- conversation_context = ""
410
- if len(history) >= 2 and isinstance(history[-2], list) and len(history[-2]) == 2 and isinstance(history[-2][1], str):
411
- last_user, last_ai = history[-2][0], history[-2][1]
412
- conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
413
-
414
- online_update(
415
- gpt_model,
416
- clean_user_message,
417
- last_ai_response,
418
- HP["max_length"],
419
- search_context=search_context_text,
420
- file_context=file_context_text,
421
- conversation_context=conversation_context,
422
- )
423
- save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
424
- feedback_message = "Thanks for the Good Response rating! Learned from that turn. ✨"
425
- elif rating == "Bad Response":
426
- feedback_message = "Acknowledged Bad Response feedback. 🛠️"
427
- else:
428
- feedback_message = "Unknown rating received."
429
-
430
- return history, feedback_message
431
 
432
  def feedback_good(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:
433
- history_state, feedback_message = process_feedback(history_state, "Good Response")
434
- return history_state, feedback_message
435
 
436
  def feedback_bad(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:
437
- history_state, feedback_message = process_feedback(history_state, "Bad Response")
438
- return history_state, feedback_message
439
 
440
  def feedback_bad_with_prompt(history_state: List[List[Optional[str]]], suggested_prompt: str) -> Tuple[List[List[Optional[str]]], str]:
441
- log_path = "bad_feedback_log.txt"
442
- try:
443
- with open(log_path, "a", encoding="utf-8") as f:
444
- f.write(f"\n--- {datetime.now()} ---\nSuggested Prompt:\n{suggested_prompt}\n\n")
445
- except Exception as e:
446
- print(f"Failed to log feedback: {e}")
447
- process_feedback(history_state, "Bad Response")
448
- return history_state, f"Recorded:\n“{suggested_prompt}”"
449
 
450
  # ---------------------
451
  # Core request handling
452
  # ---------------------
453
  def _extract_file_context(uploaded_file: Optional[Any]) -> str:
454
- if not uploaded_file:
455
- return ""
456
- file_name = uploaded_file.name.split("/")[-1]
457
- return f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt about this file."
458
 
459
  def _build_conversation_context(history: List[List[Optional[str]]], is_instruction: bool) -> str:
460
- context_history = history[:-1] if not is_instruction else history
461
- if context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):
462
- last_user, last_ai = context_history[-1][0], context_history[-1][1]
463
- return f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
464
- return ""
465
 
466
  def _is_instruction_turn(user_message: str) -> bool:
467
- prefixes = ("please generate", "provide a much more detailed", "provide a different")
468
- return any((user_message or "").lower().startswith(p) for p in prefixes)
469
 
470
  def on_submit(
471
- user_message: str,
472
- history: Optional[List[List[Optional[str]]]],
473
- uploaded_file: Optional[Any],
474
- web_search_enabled_flag_unused: bool = True,
475
- ) -> Tuple[List[List[Optional[str]]], str]:
476
- history = history or []
477
-
478
- file_context = _extract_file_context(uploaded_file)
479
-
480
- is_instruction = _is_instruction_turn(user_message or "")
481
- clean_user_message = user_message or ""
482
- quoted_match = re.search(r':\s*"(.+?)"$', clean_user_message)
483
- if is_instruction and quoted_match:
484
- clean_user_message = quoted_match.group(1).strip()
485
- model_prompt = user_message
486
- else:
487
- model_prompt = user_message
488
-
489
- clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()
490
- clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()
491
-
492
- conversation_context = _build_conversation_context(history, is_instruction)
493
-
494
- search_context_text = ""
495
- if should_search(clean_user_message):
496
- query_for_search = WEB_TAG_RE.sub("", clean_user_message).strip()
497
- search_context_text = perform_web_search(query_for_search)
498
-
499
- # Modified to suppress "No Search" message
500
- display_search_result = (
501
- f"🔍 **Search Result Used:** {search_context_text}" if search_context_text
502
- else ""
503
- )
504
-
505
- final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt
506
- final_model_prompt = WEB_TAG_RE.sub("", final_model_prompt or "").strip()
507
-
508
- reply = generate_response(
509
- final_model_prompt,
510
- search_context=search_context_text,
511
- conversation_context=conversation_context,
512
- )
513
-
514
- if history and isinstance(history[-1], list) and len(history[-1]) == 2 and history[-1][1] is None:
515
- history[-1][1] = reply if isinstance(reply, str) else str(reply)
516
-
517
- return history, display_search_result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
 
519
  # ---------------------
520
  # Gradio app
521
  # ---------------------
522
  with gr.Blocks(title="OkemoLLM") as demo:
523
- gr.Markdown("# OkemoLLM (<WEB> gated web search, checkpoint-aware) 🌐")
524
- search_status_display = gr.Markdown("🔍 Search status will appear here.")
525
- chat = gr.Chatbot(height=500)
526
-
527
- with gr.Row():
528
- with gr.Column(scale=4):
529
- msg = gr.Textbox(
530
- placeholder='Type your message… Add "<WEB>" to use web search for this turn.',
531
- label="Message",
532
- elem_id="okemo-input-textbox"
533
- )
534
- uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")
535
- web_search_enabled_state = gr.Checkbox(label="Frontend Search Toggle (ignored; use <WEB>)", value=True)
536
-
537
- clear = gr.Button("Clear")
538
- send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")
539
-
540
- def add_user_message_to_history(message: str, history: Optional[List[List[Optional[str]]]], file_ref: Optional[Any], web_enabled: bool):
541
- history = history or []
542
- return history + [[message, None]], "..."
543
-
544
- msg.submit(
545
- add_user_message_to_history,
546
- [msg, chat, uploaded_file_state, web_search_enabled_state],
547
- [chat, search_status_display],
548
- queue=False
549
- ).then(
550
- on_submit,
551
- [msg, chat, uploaded_file_state, web_search_enabled_state],
552
- [chat, search_status_display],
553
- queue=False
554
- )
555
-
556
- send_trigger.click(
557
- add_user_message_to_history,
558
- [msg, chat, uploaded_file_state, web_search_enabled_state],
559
- [chat, search_status_display],
560
- queue=False
561
- ).then(
562
- on_submit,
563
- [msg, chat, uploaded_file_state, web_search_enabled_state],
564
- [chat, search_status_display],
565
- queue=False
566
- )
567
-
568
- clear.click(lambda: [], None, chat, queue=False)
569
-
570
- # Public API endpoints
571
- def chat_submit_api(
572
- msg_value: str,
573
- chat_value: Optional[List[List[Optional[str]]]],
574
- uploaded_file_value: Optional[Any],
575
- web_enabled_value: bool,
576
- ):
577
- updated_history = chat_value or []
578
- updated_history.append([msg_value, None])
579
- final_history, status_msg = on_submit(msg_value, updated_history, uploaded_file_value, web_enabled_value)
580
- return final_history, status_msg
581
-
582
- gr.Interface(
583
- fn=chat_submit_api,
584
- inputs=[
585
- gr.Textbox(label="Message"),
586
- gr.State(value=[]),
587
- gr.File(label="Uploaded File"),
588
- gr.Checkbox(label="Web Search Enabled (ignored; use <WEB>)", value=True),
589
- ],
590
- outputs=[
591
- gr.State(value=[]),
592
- gr.Textbox(visible=False),
593
- ],
594
- api_name="on_submit",
595
- live=False,
596
- allow_flagging="never",
597
- )
598
-
599
- gr.Interface(
600
- fn=feedback_good,
601
- inputs=[gr.State(value=[])],
602
- outputs=[gr.State(value=[]), gr.Textbox()],
603
- api_name="feedback_good",
604
- live=False,
605
- allow_flagging="never",
606
- )
607
-
608
- gr.Interface(
609
- fn=feedback_bad,
610
- inputs=[gr.State(value=[])],
611
- outputs=[gr.State(value=[]), gr.Textbox()],
612
- api_name="feedback_bad",
613
- live=False,
614
- allow_flagging="never",
615
- )
616
-
617
- gr.Interface(
618
- fn=feedback_bad_with_prompt,
619
- inputs=[gr.State(value=[]), gr.Textbox(label="Suggested Prompt")],
620
- outputs=[gr.State(value=[]), gr.Textbox()],
621
- api_name="feedback_bad_with_prompt",
622
- live=False,
623
- allow_flagging="never",
624
- )
625
 
626
  if __name__ == "__main__":
627
- demo.queue(api_open=True).launch(ssr_mode=False)
 
11
  import unicodedata
12
  import requests
13
  from datetime import datetime
14
+ from typing import Dict, List, Tuple, Optional, Any, Iterator
15
 
16
  import torch
17
  import torch.nn as nn
 
26
  # Config
27
  # ---------------------
28
  SYSTEM_INSTRUCTION: str = (
29
+     "You are a friendly, helpful, concise AI assistant named Okemo Language Model (OLM). "
30
+     "Default to clear, short answers; elaborate only when asked."
31
  )
32
 
33
  ONLINE_LEARNING_EPOCHS: int = 5
 
35
 
36
  # Fallback defaults (used only when no checkpoint exists)
37
  DEFAULTS: Dict[str, Any] = {
38
+     "d_model": 768,
39
+     "n_head": 48,
40
+     "d_ff": 768,
41
+     "n_layers": 12,
42
+     "dropout": 0.1,
43
+     "max_length": 512,
44
+     "k_sampling": 20,
45
+     "LEARNING_RATE": 1e-6,
46
  }
47
 
48
  # Web search provider (Tavily). Keep key in environment.
 
55
  # Helpers
56
  # ---------------------
57
  def to_ascii(text: Optional[str]) -> str:
58
+     """Normalize to NFKC and ensure str."""
59
+     return unicodedata.normalize("NFKC", text or "")
60
 
61
  # Simple tokenizer: words or punctuation
62
  _TOKEN_RE = re.compile(r"\w+|[^\w\s]", flags=re.UNICODE)
63
 
64
  def tokenize(text: str) -> List[str]:
65
+     """Lowercase, ASCII-normalized tokenization into words and punctuation units."""
66
+     txt = to_ascii(text)
67
+     return _TOKEN_RE.findall(txt.lower())
68
 
69
  def check_repetition(text: str, max_repeat: int = 2) -> bool:
70
+     """Detect exact token repetition runs longer than max_repeat."""
71
+     tokens = tokenize(text)
72
+     if not tokens or max_repeat < 1:
73
+         return False
74
+     for i in range(len(tokens) - max_repeat):
75
+         if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):
76
+             return True
77
+     return False
78
 
79
  # ---------------------
80
  # Vocabulary
81
  # ---------------------
82
  class Voc:
83
+     """Lightweight vocabulary storing special tokens and bidirectional maps."""
84
+
85
+     def __init__(self) -> None:
86
+         self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"
87
+         self.word2index: Dict[str, int] = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
88
+         self.index2word: Dict[int, str] = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}
89
+         self.n_words: int = 5
90
+
91
+     @staticmethod
92
+     def load_from_checkpoint(ckpt: Dict[str, Any]) -> "Voc":
93
+         voc = Voc()
94
+         if "voc_word2index" in ckpt and "voc_index2word" in ckpt:
95
+             voc.word2index = ckpt["voc_word2index"]
96
+             voc.index2word = ckpt["voc_index2word"]
97
+             voc.n_words = len(voc.word2index)
98
+         if "special_tokens" in ckpt:
99
+             tokens = ckpt["special_tokens"]
100
+             voc.PAD = tokens.get("PAD", voc.PAD)
101
+             voc.SOS = tokens.get("SOS", voc.SOS)
102
+             voc.EOS = tokens.get("EOS", voc.EOS)
103
+             voc.UNK = tokens.get("UNK", voc.UNK)
104
+             voc.SYSTEM = tokens.get("SYSTEM", voc.SYSTEM)
105
+         return voc
106
+
107
+     def add_sentence(self, sentence: str) -> None:
108
+         for word in tokenize(sentence):
109
+             if word not in self.word2index:
110
+                 idx = self.n_words
111
+                 self.word2index[word] = idx
112
+                 self.index2word[idx] = word
113
+                 self.n_words += 1
114
 
115
  # ---------------------
116
  # Model
117
  # ---------------------
118
  class PositionalEncoding(nn.Module):
119
+     """Sinusoidal positional encoding used by Transformer."""
120
 
121
+     def __init__(self, d_model: int, max_len: int = 5000) -> None:
122
+         super().__init__()
123
+         pe = torch.zeros(max_len, d_model)
124
+         position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
125
+         div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
126
+         pe[:, 0::2] = torch.sin(position * div_term)
127
+         pe[:, 1::2] = torch.cos(position * div_term)
128
+         self.register_buffer("pe", pe.unsqueeze(0))
129
 
130
+     def forward(self, x: torch.Tensor) -> torch.Tensor:
131
+         return x + self.pe[:, : x.size(1), :]
132
 
133
  class GPT(nn.Module):
134
+     """Minimal GPT-like model using nn.TransformerEncoder with weight tying."""
135
+
136
+     def __init__(self, n_words: int, d_model: int, n_layers: int, n_head: int, d_ff: int, dropout: float = 0.1) -> None:
137
+         super().__init__()
138
+         self.embedding = nn.Embedding(n_words, d_model)
139
+         self.pos = PositionalEncoding(d_model)
140
+         self.norm = nn.LayerNorm(d_model)
141
+         enc_layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)
142
+         self.transformer = nn.TransformerEncoder(enc_layer, n_layers)
143
+         self.fc = nn.Linear(d_model, n_words, bias=False)
144
+         self.fc.weight = self.embedding.weight  # weight tying
145
+
146
+     def forward(
147
+         self,
148
+         x: torch.Tensor,
149
+         mask: Optional[torch.Tensor] = None,
150
+         key_padding_mask: Optional[torch.Tensor] = None,
151
+     ) -> torch.Tensor:
152
+         x = self.embedding(x)
153
+         x = self.pos(x)
154
+         x = self.norm(x)
155
+         out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
156
+         return self.fc(out)
157
 
158
  # ---------------------
159
  # Training utils
160
  # ---------------------
161
  def indexes_from_sentence(voc: Voc, sentence: str) -> List[int]:
162
+     sanitized = " ".join(tokenize(sentence))
163
+     prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)
164
+     return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]
165
 
166
  def make_bool_causal_mask(sz: int, device: torch.device) -> torch.Tensor:
167
+     return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
168
 
169
  # ---------------------
170
  # Device
171
  # ---------------------
172
  device: torch.device = torch.device(
173
+     "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
174
  )
175
 
176
  # ---------------------
177
  # Checkpoint-aware init
178
  # ---------------------
179
  def load_checkpoint_or_defaults(path: str) -> Tuple[Dict[str, Any], Dict[str, Any], Voc, GPT, optim.Optimizer]:
180
+     if os.path.exists(path):
181
+         ckpt = torch.load(path, map_location=device)
182
+         hp = {
183
+             "d_model": ckpt.get("d_model", DEFAULTS["d_model"]),
184
+             "n_head": ckpt.get("n_head", DEFAULTS["n_head"]),
185
+             "d_ff": ckpt.get("d_ff", DEFAULTS["d_ff"]),
186
+             "n_layers": ckpt.get("n_layers", DEFAULTS["n_layers"]),
187
+             "dropout": ckpt.get("dropout", DEFAULTS["dropout"]),
188
+             "max_length": ckpt.get("max_length", DEFAULTS["max_length"]),
189
+             "k_sampling": ckpt.get("k_sampling", DEFAULTS["k_sampling"]),
190
+             "LEARNING_RATE": ckpt.get("LEARNING_RATE", DEFAULTS["LEARNING_RATE"]),
191
+         }
192
+         voc = Voc.load_from_checkpoint(ckpt)
193
+         model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)
194
+         if ckpt.get("gpt_model_state_dict") is not None:
195
+             model.load_state_dict(ckpt["gpt_model_state_dict"], strict=True)
196
+         model.fc.weight = model.embedding.weight
197
+         optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])
198
+         if "optimizer_state_dict" in ckpt:
199
+             try:
200
+                 optimizer.load_state_dict(ckpt["optimizer_state_dict"])
201
+             except Exception as e:
202
+                 print(f"Warning: Failed to load optimizer state: {e}. Starting fresh.")
203
+         return ckpt, hp, voc, model, optimizer
204
+     else:
205
+         print("WARNING: No checkpoint found. Initializing with defaults.")
206
+         hp = DEFAULTS.copy()
207
+         voc = Voc()
208
+         model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)
209
+         optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])
210
+         return {}, hp, voc, model, optimizer
211
 
212
  checkpoint, HP, voc, gpt_model, optimizer = load_checkpoint_or_defaults(CHECKPOINT_PATH)
213
  criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
214
 
215
  # --- Added logic: Save initial state if no checkpoint was found to ensure .pth exists ---
216
  if not os.path.exists(CHECKPOINT_PATH):
217
+     print("Saving initial checkpoint with default settings.")
218
+     # The initial voc will only contain special tokens, but it's a valid starting point
219
+     save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
220
  # ---------------------------------------------------------------------------------------
221
 
222
  # ---------------------
223
  # Save checkpoint
224
  # ---------------------
225
  def save_checkpoint(model: GPT, optimizer: optim.Optimizer, voc: Voc, path: str) -> None:
226
+     print(f"Saving model checkpoint to {path}...")
227
+     ckpt = {
228
+         "voc_word2index": voc.word2index,
229
+         "voc_index2word": voc.index2word,
230
+         "gpt_model_state_dict": model.state_dict(),
231
+         "optimizer_state_dict": optimizer.state_dict(),
232
+         "d_model": HP["d_model"],
233
+         "n_head": HP["n_head"],
234
+         "d_ff": HP["d_ff"],
235
+         "n_layers": HP["n_layers"],
236
+         "dropout": HP["dropout"],
237
+         "max_length": HP["max_length"],
238
+         "k_sampling": HP["k_sampling"],
239
+         "LEARNING_RATE": HP["LEARNING_RATE"],
240
+     }
241
+     try:
242
+         torch.save(ckpt, path)
243
+         print("Checkpoint saved successfully.")
244
+     except Exception as e:
245
+         print(f"ERROR: Failed to save checkpoint: {e}")
246
 
247
  # ---------------------
248
  # Web search (only with <WEB>)
249
  # ---------------------
250
  def perform_web_search(query: str) -> str:
251
+     if not TAVILY_API_KEY:
252
+         return ""
253
+     try:
254
+         resp = requests.post(
255
+             "https://api.tavily.com/search",
256
+             json={"api_key": TAVILY_API_KEY, "query": query, "include_answer": False, "max_results": 5},
257
+             timeout=8,
258
+         )
259
+         resp.raise_for_status()
260
+         data = resp.json()
261
+         results = data.get("results", [])
262
+         snippets: List[str] = []
263
+         for r in results[:3]:
264
+             title = (r.get("title") or "").strip()
265
+             snippet = (r.get("content") or "").strip()
266
+             url = (r.get("url") or "").strip()
267
+             if title or snippet:
268
+                 snippets.append(f"{title}: {snippet} (Source: {url})")
269
+         return to_ascii(" | ".join(snippets))
270
+     except Exception as e:
271
+         print(f"Search failed: {e}")
272
+         return ""
273
 
274
  def should_search(user_text: str) -> bool:
275
+     return bool(WEB_TAG_RE.search(user_text or ""))
276
 
277
  # ---------------------
278
  # Generation
279
  # ---------------------
280
+ def generate_response(prompt: str, search_context: str = "", conversation_context: str = "") -> Iterator[str]:
281
+     """Generator function that yields the generated word tokens."""
282
+     prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
283
+     context_prefix = f"{conversation_context} " if conversation_context else ""
284
+     full_input = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text}{prompt}"
285
+     full_input = to_ascii(full_input)
286
+
287
+     gpt_model.eval()
288
+
289
+     initial_tokens = indexes_from_sentence(voc, full_input)
290
+     input_tensor = torch.tensor(initial_tokens, dtype=torch.long, device=device).unsqueeze(0)
291
+     generated_token_ids: List[int] = [] # Use this to check for repetition later
292
+     temperature = 0.8
293
+     vocab_eos = voc.word2index[voc.EOS]
294
+     vocab_pad = voc.word2index[voc.PAD]
295
+
296
+     with torch.no_grad():
297
+         for step in range(HP["max_length"]):
298
+             L = input_tensor.size(1)
299
+             causal = make_bool_causal_mask(L, device)
300
+             padmask = (input_tensor == vocab_pad)
301
+             logits = gpt_model(input_tensor, mask=causal, key_padding_mask=padmask)
302
+             last = logits[:, -1, :].float() / max(temperature, 1e-3)
303
+
304
+             k = max(1, int(HP["k_sampling"]))
305
+             topk_vals, topk_idx = torch.topk(last, k)
306
+             probs = F.softmax(topk_vals, dim=-1).float()
307
+             pick_rel = torch.multinomial(probs, 1).item()
308
+             candidate_id = topk_idx.squeeze(0)[pick_rel].item()
309
+
310
+             if candidate_id == vocab_eos:
311
+                 break
312
+
313
+             generated_token_ids.append(candidate_id)
314
+             next_token = torch.tensor([[candidate_id]], device=device, dtype=torch.long)
315
+             input_tensor = torch.cat([input_tensor, next_token], dim=1)
316
+            
317
+             # Yield the generated word token for streaming
318
+             word = voc.index2word.get(candidate_id, voc.UNK)
319
+             if word not in [voc.PAD, voc.SOS, voc.EOS, voc.UNK, voc.SYSTEM]:
320
+                 yield word + " " # Yield with space for cleaner UI streaming
 
 
 
 
 
 
 
 
 
321
 
322
  # ---------------------
323
  # Online learning (feedback)
324
  # ---------------------
325
  def online_update(
326
+     model: GPT,
327
+     input_sentence: str,
328
+     target_response: str,
329
+     max_seq_len: int,
330
+     search_context: str = "",
331
+     file_context: str = "",
332
+     conversation_context: str = "",
333
  ) -> None:
334
+     is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
335
+     is_not_repetitive = not check_repetition(target_response, max_repeat=2)
336
+     if not is_response_clean or not is_not_repetitive:
337
+         print("Skipping online update: Target response is corrupted or highly repetitive.")
338
+         return
339
+
340
+     prefix_search = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
341
+     prefix_file = f"Based on the attached file: {to_ascii(file_context)}. " if file_context else ""
342
+     context_prefix = f"{conversation_context} " if conversation_context else ""
343
+
344
+     full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_search}{prefix_file}{input_sentence}"
345
+     full_prompt_text = to_ascii(full_prompt_text)
346
+
347
+     prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
348
+     sanitized_response = to_ascii(target_response)
349
+     response_tokens = indexes_from_sentence(voc, sanitized_response)[1:]
350
+
351
+     full_sequence_ids = prompt_tokens + response_tokens
352
+     input_ids = full_sequence_ids[:-1]
353
+     target_ids = full_sequence_ids[1:]
354
+
355
+     if len(input_ids) < 2 or len(input_ids) != len(target_ids) or len(input_ids) > max_seq_len:
356
+         print(f"Skipping online update. Sequence length: {len(input_ids)}")
357
+         return
358
+
359
+     input_tensor = torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0)
360
+     target_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)
361
+
362
+     L = input_tensor.size(1)
363
+     model.train()
364
+     causal = make_bool_causal_mask(L, device)
365
+
366
+     last_loss = 0.0
367
+     for _ in range(ONLINE_LEARNING_EPOCHS):
368
+         optimizer.zero_grad()
369
+         logits = model(input_tensor, mask=causal, key_padding_mask=None)
370
+         loss = criterion(logits.squeeze(0), target_tensor)
371
+         loss.backward()
372
+         torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
373
+         optimizer.step()
374
+         last_loss = loss.item()
375
+
376
+     model.eval()
377
+     print(f"Online update done. Final Loss: {last_loss:.4f}")
378
 
379
  def process_feedback(history: List[List[Optional[str]]], rating: str) -> Tuple[List[List[Optional[str]]], str]:
380
+     if not isinstance(history, list):
381
+         return [], "Cannot process feedback: history not a list."
382
+     if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):
383
+         return history, "Cannot process feedback: No recent AI response found."
384
+
385
+     last_user_message, last_ai_response = history[-1][0], history[-1][1]
386
+
387
+     file_context_text = ""
388
+     file_match = re.search(r"\(Attached: (.*?)\)", last_user_message or "")
389
+     if file_match:
390
+         file_name = file_match.group(1)
391
+         file_context_text = f"The user provided a file named '{file_name}'."
392
+
393
+     clean_user_message = to_ascii(last_user_message or "")
394
+     clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()
395
+     clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()
396
+
397
+     search_context_text = ""
398
+
399
+     if rating == "Good Response":
400
+         conversation_context = ""
401
+         if len(history) >= 2 and isinstance(history[-2], list) and len(history[-2]) == 2 and isinstance(history[-2][1], str):
402
+             last_user, last_ai = history[-2][0], history[-2][1]
403
+             conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
404
+
405
+         online_update(
406
+             gpt_model,
407
+             clean_user_message,
408
+             last_ai_response,
409
+             HP["max_length"],
410
+             search_context=search_context_text,
411
+             file_context=file_context_text,
412
+             conversation_context=conversation_context,
413
+         )
414
+         save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
415
+         feedback_message = "Thanks for the Good Response rating! Learned from that turn. ✨"
416
+     elif rating == "Bad Response":
417
+         feedback_message = "Acknowledged Bad Response feedback. 🛠️"
418
+     else:
419
+         feedback_message = "Unknown rating received."
420
+
421
+     return history, feedback_message
422
 
423
  def feedback_good(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:
424
+     history_state, feedback_message = process_feedback(history_state, "Good Response")
425
+     return history_state, feedback_message
426
 
427
  def feedback_bad(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:
428
+     history_state, feedback_message = process_feedback(history_state, "Bad Response")
429
+     return history_state, feedback_message
430
 
431
  def feedback_bad_with_prompt(history_state: List[List[Optional[str]]], suggested_prompt: str) -> Tuple[List[List[Optional[str]]], str]:
432
+     log_path = "bad_feedback_log.txt"
433
+     try:
434
+         with open(log_path, "a", encoding="utf-8") as f:
435
+             f.write(f"\n--- {datetime.now()} ---\nSuggested Prompt:\n{suggested_prompt}\n\n")
436
+     except Exception as e:
437
+         print(f"Failed to log feedback: {e}")
438
+     process_feedback(history_state, "Bad Response")
439
+     return history_state, f"Recorded:\n“{suggested_prompt}”"
440
 
441
  # ---------------------
442
  # Core request handling
443
  # ---------------------
444
  def _extract_file_context(uploaded_file: Optional[Any]) -> str:
445
+     if not uploaded_file:
446
+         return ""
447
+     file_name = uploaded_file.name.split("/")[-1]
448
+     return f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt about this file."
449
 
450
  def _build_conversation_context(history: List[List[Optional[str]]], is_instruction: bool) -> str:
451
+     context_history = history[:-1] if not is_instruction else history
452
+     if context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):
453
+         last_user, last_ai = context_history[-1][0], context_history[-1][1]
454
+         return f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
455
+     return ""
456
 
457
  def _is_instruction_turn(user_message: str) -> bool:
458
+     prefixes = ("please generate", "provide a much more detailed", "provide a different")
459
+     return any((user_message or "").lower().startswith(p) for p in prefixes)
460
 
461
  def on_submit(
462
+     user_message: str,
463
+     history: Optional[List[List[Optional[str]]]],
464
+     uploaded_file: Optional[Any],
465
+     web_search_enabled_flag_unused: bool = True,
466
+ ) -> Iterator[Tuple[List[List[Optional[str]]], str]]:
467
+     """Handles the request and yields incremental updates for streaming."""
468
+     history = history or []
469
+
470
+     file_context = _extract_file_context(uploaded_file)
471
+
472
+     is_instruction = _is_instruction_turn(user_message or "")
473
+     clean_user_message = user_message or ""
474
+     quoted_match = re.search(r':\s*"(.+?)"$', clean_user_message)
475
+     if is_instruction and quoted_match:
476
+         clean_user_message = quoted_match.group(1).strip()
477
+         model_prompt = user_message
478
+     else:
479
+         model_prompt = user_message
480
+
481
+     clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()
482
+     clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()
483
+
484
+     conversation_context = _build_conversation_context(history, is_instruction)
485
+
486
+     search_context_text = ""
487
+     if should_search(clean_user_message):
488
+         query_for_search = WEB_TAG_RE.sub("", clean_user_message).strip()
489
+         search_context_text = perform_web_search(query_for_search)
490
+
491
+     display_search_result = (
492
+         f"🔍 **Search Result Used:** {search_context_text}" if search_context_text
493
+         else ""
494
+     )
495
+
496
+     final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt
497
+     final_model_prompt = WEB_TAG_RE.sub("", final_model_prompt or "").strip()
498
+
499
+     # --- Streaming Logic ---
500
+     response_generator = generate_response(
501
+         final_model_prompt,
502
+         search_context=search_context_text,
503
+         conversation_context=conversation_context,
504
+     )
505
+
506
+     full_reply_text = ""
507
+     status_message = display_search_result or "Thinking..."
508
+     last_user_message = history[-1][0] if history and history[-1][0] else clean_user_message
509
+
510
+     for token in response_generator:
511
+         full_reply_text += token
512
+
513
+         # Update the last message in history with the partial response
514
+         if history and history[-1][1] is None:
515
+             history[-1][1] = full_reply_text
516
+         elif history:
517
+             # Ensure we don't accidentally lose the user message if it was stripped before submit
518
+             history[-1][0] = last_user_message
519
+             history[-1][1] = full_reply_text
520
+        
521
+         # Yield the current state for streaming to the frontend
522
+         yield history, status_message
523
+
524
+     # --- Final Formatting and Completion ---
525
+    
526
+     # Final formatting/cleanup
527
+     full_reply_text = to_ascii(full_reply_text)
528
+     full_reply_text = re.sub(r"\s+([,.!?;:])", r"\1", full_reply_text).strip()
529
+    
530
+     # Final checks
531
+     if not full_reply_text or check_repetition(full_reply_text):
532
+         final_reply = "I got lost in the data tubes! Perhaps ask me something a little sillier? 🤪"
533
+         status_message = display_search_result or "Error: Response was blocked."
534
+     else:
535
+         final_reply = full_reply_text
536
+         status_message = display_search_result or "Response complete."
537
+    
538
+     # Final update to history (in case of an error or final cleanup)
539
+     if history:
540
+         history[-1][1] = final_reply
541
+    
542
+     yield history, status_message
543
 
544
  # ---------------------
545
  # Gradio app
546
  # ---------------------
547
  with gr.Blocks(title="OkemoLLM") as demo:
548
+     gr.Markdown("# OkemoLLM (<WEB> gated web search, checkpoint-aware) 🌐")
549
+     search_status_display = gr.Markdown("🔍 Search status will appear here.")
550
+     chat = gr.Chatbot(height=500)
551
+
552
+     with gr.Row():
553
+         with gr.Column(scale=4):
554
+             msg = gr.Textbox(
555
+                 placeholder='Type your message… Add "<WEB>" to use web search for this turn.',
556
+                 label="Message",
557
+                 elem_id="okemo-input-textbox"
558
+             )
559
+         uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")
560
+         web_search_enabled_state = gr.Checkbox(label="Frontend Search Toggle (ignored; use <WEB>)", value=True)
561
+
562
+     clear = gr.Button("Clear")
563
+     send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")
564
+
565
+     def add_user_message_to_history(message: str, history: Optional[List[List[Optional[str]]]], file_ref: Optional[Any], web_enabled: bool):
566
+         history = history or []
567
+         return history + [[message, None]], "..."
568
+
569
+     msg.submit(
570
+         add_user_message_to_history,
571
+         [msg, chat, uploaded_file_state, web_search_enabled_state],
572
+         [chat, search_status_display],
573
+         queue=False
574
+     ).then(
575
+         on_submit,
576
+         [msg, chat, uploaded_file_state, web_search_enabled_state],
577
+         [chat, search_status_display] # REMOVED: queue=False to enable streaming
578
+     )
579
+
580
+     send_trigger.click(
581
+         add_user_message_to_history,
582
+         [msg, chat, uploaded_file_state, web_search_enabled_state],
583
+         [chat, search_status_display],
584
+         queue=False
585
+     ).then(
586
+         on_submit,
587
+         [msg, chat, uploaded_file_state, web_search_enabled_state],
588
+         [chat, search_status_display] # REMOVED: queue=False to enable streaming
589
+     )
590
+
591
+     clear.click(lambda: [], None, chat, queue=False)
592
+
593
+     # Public API endpoints
594
+     def chat_submit_api(
595
+         msg_value: str,
596
+         chat_value: Optional[List[List[Optional[str]]]],
597
+         uploaded_file_value: Optional[Any],
598
+         web_enabled_value: bool,
599
+     ):
600
+         updated_history = chat_value or []
601
+         updated_history.append([msg_value, None])
602
+         # Call generator and return the final state
603
+         final_history, status_msg = list(on_submit(msg_value, updated_history, uploaded_file_value, web_enabled_value))[-1]
604
+         return final_history, status_msg
605
+
606
+     gr.Interface(
607
+         fn=chat_submit_api,
608
+         inputs=[
609
+             gr.Textbox(label="Message"),
610
+             gr.State(value=[]),
611
+             gr.File(label="Uploaded File"),
612
+             gr.Checkbox(label="Web Search Enabled (ignored; use <WEB>)", value=True),
613
+         ],
614
+         outputs=[
615
+             gr.State(value=[]),
616
+             gr.Textbox(visible=False),
617
+         ],
618
+         api_name="on_submit",
619
+         live=False,
620
+         allow_flagging="never",
621
+     )
622
+
623
+     gr.Interface(
624
+         fn=feedback_good,
625
+         inputs=[gr.State(value=[])],
626
+         outputs=[gr.State(value=[]), gr.Textbox()],
627
+         api_name="feedback_good",
628
+         live=False,
629
+         allow_flagging="never",
630
+     )
631
+
632
+     gr.Interface(
633
+         fn=feedback_bad,
634
+         inputs=[gr.State(value=[])],
635
+         outputs=[gr.State(value=[]), gr.Textbox()],
636
+         api_name="feedback_bad",
637
+         live=False,
638
+         allow_flagging="never",
639
+     )
640
+
641
+     gr.Interface(
642
+         fn=feedback_bad_with_prompt,
643
+         inputs=[gr.State(value=[]), gr.Textbox(label="Suggested Prompt")],
644
+         outputs=[gr.State(value=[]), gr.Textbox()],
645
+         api_name="feedback_bad_with_prompt",
646
+         live=False,
647
+         allow_flagging="never",
648
+     )
 
649
 
650
  if __name__ == "__main__":
651
+     demo.queue(api_open=True).launch(ssr_mode=False)