Gems234 commited on
Commit
846ecc9
·
verified ·
1 Parent(s): 3505c55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -60
app.py CHANGED
@@ -64,40 +64,24 @@ def get_conv_names():
64
  with lock:
65
  return list(conversations.keys())
66
 
67
- # Format de prompt Alpaca OPTIMISÉ
68
- def build_alpaca_prompt(instruction, input_text="", output_text=""):
69
- """Format Alpaca optimisé pour la vitesse"""
70
- if input_text:
71
- return f"### Instruction:\n{instruction}\n\n### Input:\n{input_text}\n\n### Response:\n{output_text}"
72
- else:
73
- return f"### Instruction:\n{instruction}\n\n### Response:\n{output_text}"
74
-
75
  def build_conversation_prompt(history, new_message):
76
- """Prompt optimisé pour la vitesse avec format Alpaca léger"""
77
-
78
- # System prompt seulement au début (plus court)
79
- system_prompt = "Tu es Alisia, assistante IA compétente. Réponds en français de façon concise."
80
 
81
- # Construire l'historique de façon optimisée
82
- conversation_parts = []
83
-
84
- # Ajouter l'historique seulement s'il y en a
85
- if history:
86
- for user_msg, assistant_msg in history:
87
- conv_part = build_alpaca_prompt(user_msg, "", assistant_msg)
88
- conversation_parts.append(conv_part)
89
 
90
- # Ajouter le nouveau message
91
- current_prompt = build_alpaca_prompt(new_message, "", "")
 
92
 
93
- # Combiner tout le prompt
94
- full_prompt = f"{system_prompt}\n\n" if not history else ""
95
- full_prompt += "\n\n".join(conversation_parts)
96
- if conversation_parts:
97
- full_prompt += "\n\n"
98
- full_prompt += current_prompt
99
 
100
- return full_prompt
101
 
102
  def send_message_stream(user_message, displayed_history, current_chat_name):
103
  global stop_generation
@@ -115,29 +99,31 @@ def send_message_stream(user_message, displayed_history, current_chat_name):
115
  local_hist.append((str(user_message), ""))
116
  yield local_hist, ""
117
 
118
- # Construction OPTIMISÉE du prompt
119
  formatted_prompt = build_conversation_prompt(local_hist[:-1], str(user_message))
120
  partial = ""
121
 
122
- # PARAMÈTRES DE RÉACTIVITÉ ULTRA-RAPIDE
123
  last_update = time.time()
124
  token_count = 0
125
- min_tokens = 1 # Minimum réduit pour plus de réactivité
126
- max_delay = 0.08 # Réduit à 80ms pour plus de vitesse
127
 
128
  try:
129
- # Paramètres de génération OPTIMISÉS
130
  stream = llm.create_completion(
131
  prompt=formatted_prompt,
132
  stream=True,
133
- max_tokens=768, # Réduit pour plus de vitesse
134
  temperature=0.7,
135
- top_p=0.85, # Légèrement réduit
136
- repeat_penalty=1.15, # Augmenté pour éviter la répétition
137
- stop=["### Instruction:", "### Response:", "\n\n", "<|endoftext|>", "###"],
138
- top_k=40 # Ajouté pour la vitesse
 
139
  )
140
 
 
141
  for chunk in stream:
142
  if stop_generation.is_set():
143
  break
@@ -145,27 +131,34 @@ def send_message_stream(user_message, displayed_history, current_chat_name):
145
  if "choices" in chunk and chunk["choices"]:
146
  token = chunk["choices"][0].get("text", "")
147
  if token:
148
- partial += token
149
  token_count += 1
150
 
151
- # STRATÉGIE ULTRA-RAPIDE
 
 
 
152
  should_update = (
153
  token_count >= min_tokens or
154
- time.time() - last_update > max_delay or
155
- token in [".", "!", "?", "\n"]
156
  )
157
 
158
- if should_update:
159
- cleaned = clean_output(partial)
160
- local_hist[-1] = (str(user_message), cleaned)
161
- yield local_hist, ""
162
- last_update = time.time()
 
 
 
163
  token_count = 0
164
 
165
- # DERNIER FLUSH - Garantit que tout est affiché
166
- if partial:
167
- cleaned = clean_output(partial)
168
- local_hist[-1] = (str(user_message), cleaned)
 
169
  yield local_hist, ""
170
 
171
  except Exception as e:
@@ -389,7 +382,7 @@ with gr.Blocks(css=css, title="Alisia Chat - Ultra Rapide", theme=gr.themes.Soft
389
  menu_btn = gr.Button("☰", elem_classes="hamburger")
390
  gr.Markdown("### 💬 Alisia <span class='alisia-badge'>AI Assistant</span>", elem_id="title")
391
  gr.HTML("<div style='flex:1'></div>")
392
- gr.Markdown("<small style='color:#94a3b8'>llama.cpp optimisé</small>")
393
 
394
  with gr.Row():
395
  with gr.Column(scale=1, visible=True, elem_id="leftcol") as left_column:
@@ -410,12 +403,12 @@ with gr.Blocks(css=css, title="Alisia Chat - Ultra Rapide", theme=gr.themes.Soft
410
  "🗑️ Effacer chat",
411
  elem_classes="clear-btn"
412
  )
413
- gr.Markdown("## 🚀 Mode Ultra-Rapide", elem_classes="conversation-header")
414
  gr.Markdown("""
415
  <div style="color: #94a3b8; font-size: 14px;">
416
- Streaming hybride<br>
417
- ✅ Réactivité 80ms<br>
418
- Format Alpaca optimisé
419
  </div>
420
  """, elem_classes="conversation-subheader")
421
 
@@ -515,9 +508,9 @@ with gr.Blocks(css=css, title="Alisia Chat - Ultra Rapide", theme=gr.themes.Soft
515
  # LANCEMENT
516
  # -------------------------
517
  if __name__ == "__main__":
518
- print("🚀 Lancement de l'interface ULTRA-RAPIDE...")
519
- print("⏱️ Mode streaming optimisé (80ms)")
520
- print("🎯 Format Alpaca accéléré")
521
  demo.launch(
522
  share=True,
523
  server_name="0.0.0.0",
 
64
  with lock:
65
  return list(conversations.keys())
66
 
67
+ # FORMAT ULTRA-MINIMALISTE POUR MAXIMUM DE VITESSE
 
 
 
 
 
 
 
68
  def build_conversation_prompt(history, new_message):
69
+ """Format ultra-optimisé pour la vitesse maximale"""
 
 
 
70
 
71
+ # System prompt très court, seulement au début
72
+ if not history:
73
+ prompt = "Tu es Alisia, assistante IA. Réponds en français.\n\n"
74
+ else:
75
+ prompt = ""
 
 
 
76
 
77
+ # Historique formaté de façon minimaliste
78
+ for i, (user_msg, assistant_msg) in enumerate(history):
79
+ prompt += f"Q: {user_msg}\nA: {assistant_msg}\n\n"
80
 
81
+ # Nouveau message
82
+ prompt += f"Q: {new_message}\nA:"
 
 
 
 
83
 
84
+ return prompt
85
 
86
  def send_message_stream(user_message, displayed_history, current_chat_name):
87
  global stop_generation
 
99
  local_hist.append((str(user_message), ""))
100
  yield local_hist, ""
101
 
102
+ # Construction ULTRA-RAPIDE du prompt
103
  formatted_prompt = build_conversation_prompt(local_hist[:-1], str(user_message))
104
  partial = ""
105
 
106
+ # PARAMÈTRES DE RÉACTIVITÉ MAXIMALE
107
  last_update = time.time()
108
  token_count = 0
109
+ min_tokens = 1 # Mise à jour après chaque token
110
+ max_delay = 0.05 # Seulement 50ms entre les updates!
111
 
112
  try:
113
+ # Paramètres de génération ULTRA-OPTIMISÉS
114
  stream = llm.create_completion(
115
  prompt=formatted_prompt,
116
  stream=True,
117
+ max_tokens=512, # Réduit au maximum pour la vitesse
118
  temperature=0.7,
119
+ top_p=0.9,
120
+ repeat_penalty=1.1,
121
+ stop=["Q:", "A:", "\n\n", "<|endoftext|>", "###", "Instruction:", "Response:"],
122
+ top_k=40,
123
+ min_p=0.05 # Ajouté pour la vitesse
124
  )
125
 
126
+ buffer = ""
127
  for chunk in stream:
128
  if stop_generation.is_set():
129
  break
 
131
  if "choices" in chunk and chunk["choices"]:
132
  token = chunk["choices"][0].get("text", "")
133
  if token:
134
+ buffer += token
135
  token_count += 1
136
 
137
+ # STRATÉGIE ULTRA-RAPIDE - mise à jour immédiate
138
+ current_time = time.time()
139
+ time_since_update = current_time - last_update
140
+
141
  should_update = (
142
  token_count >= min_tokens or
143
+ time_since_update >= max_delay or
144
+ token in ["\n", ".", "!", "?", ","]
145
  )
146
 
147
+ if should_update and buffer.strip():
148
+ cleaned = clean_output(buffer)
149
+ if cleaned: # Only update if we have meaningful content
150
+ current_response = local_hist[-1][1] + cleaned
151
+ local_hist[-1] = (str(user_message), current_response)
152
+ yield local_hist, ""
153
+ buffer = "" # Clear buffer after updating
154
+ last_update = current_time
155
  token_count = 0
156
 
157
+ # Final update with any remaining content
158
+ if buffer.strip():
159
+ cleaned = clean_output(buffer)
160
+ current_response = local_hist[-1][1] + cleaned
161
+ local_hist[-1] = (str(user_message), current_response)
162
  yield local_hist, ""
163
 
164
  except Exception as e:
 
382
  menu_btn = gr.Button("☰", elem_classes="hamburger")
383
  gr.Markdown("### 💬 Alisia <span class='alisia-badge'>AI Assistant</span>", elem_id="title")
384
  gr.HTML("<div style='flex:1'></div>")
385
+ gr.Markdown("<small style='color:#94a3b8'>Mode Turbo Activé</small>")
386
 
387
  with gr.Row():
388
  with gr.Column(scale=1, visible=True, elem_id="leftcol") as left_column:
 
403
  "🗑️ Effacer chat",
404
  elem_classes="clear-btn"
405
  )
406
+ gr.Markdown("## 🚀 Mode Turbo", elem_classes="conversation-header")
407
  gr.Markdown("""
408
  <div style="color: #94a3b8; font-size: 14px;">
409
+ Format minimaliste<br>
410
+ ✅ Réactivité 50ms<br>
411
+ Optimisation max
412
  </div>
413
  """, elem_classes="conversation-subheader")
414
 
 
508
  # LANCEMENT
509
  # -------------------------
510
  if __name__ == "__main__":
511
+ print("🚀 Lancement du mode TURBO...")
512
+ print("⏱️ Réactivité maximale (50ms)")
513
+ print("🎯 Format ultra-minimaliste")
514
  demo.launch(
515
  share=True,
516
  server_name="0.0.0.0",