howard9963 commited on
Commit
a674033
·
verified ·
1 Parent(s): 622282a

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -1
app.py CHANGED
@@ -184,7 +184,31 @@ def safe_parse_json(text: str) -> dict:
184
  if "'" in repaired and '"' not in repaired:
185
  repaired = repaired.replace("'", '"')
186
  return _json.loads(repaired)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
 
 
 
 
 
 
188
  def call_llm(messages: List[dict], model: str, logs: List[str]) -> dict:
189
  """
190
  保留原名稱 call_llm,但改為本地 LLaMA。
@@ -220,7 +244,7 @@ def call_llm(messages: List[dict], model: str, logs: List[str]) -> dict:
220
  print("torch.no_grad")
221
  # 解碼生成內容後
222
  full_text = _hf_tok.decode(out_ids[0], skip_special_tokens=True)
223
- gen_text = full_text.replace(prompt,"",1).strip()
224
  logs.append(f"[LOCAL LLM] raw_len={len(gen_text)}")
225
  logs.append(f"[LOCAL LLM] gen_text={gen_text}")
226
  logs.append(f"[LOCAL LLM] prompt={prompt}")
 
184
  if "'" in repaired and '"' not in repaired:
185
  repaired = repaired.replace("'", '"')
186
  return _json.loads(repaired)
187
+ def extract_model_reply(full_text, prompt):
188
+ """
189
+ 從模型完整輸出中,移除 prompt 和任何 system、assistant 等前置內容
190
+ """
191
+ try:
192
+ # 如果模型有把 prompt 或 system 一起回顯,先找最後一次 user 提問位置
193
+ markers = ["user", "User", "使用者", prompt.strip()]
194
+ last_pos = -1
195
+ for m in markers:
196
+ pos = full_text.rfind(m)
197
+ if pos > last_pos:
198
+ last_pos = pos
199
+
200
+ # 從最後 marker 後面開始取內容
201
+ if last_pos != -1:
202
+ reply = full_text[last_pos + len(markers[-1]):]
203
+ else:
204
+ reply = full_text
205
 
206
+ # 移除多餘空白與換行
207
+ return reply.strip()
208
+ except Exception as e:
209
+ print(f"[extract_model_reply 錯誤] {e}")
210
+ return full_text.strip()
211
+
212
  def call_llm(messages: List[dict], model: str, logs: List[str]) -> dict:
213
  """
214
  保留原名稱 call_llm,但改為本地 LLaMA。
 
244
  print("torch.no_grad")
245
  # 解碼生成內容後
246
  full_text = _hf_tok.decode(out_ids[0], skip_special_tokens=True)
247
+ gen_text = extract_model_reply(full_text, prompt)
248
  logs.append(f"[LOCAL LLM] raw_len={len(gen_text)}")
249
  logs.append(f"[LOCAL LLM] gen_text={gen_text}")
250
  logs.append(f"[LOCAL LLM] prompt={prompt}")