Spaces:
jing96963
/
Running on Zero

sfdhfdjfg commited on
Commit
6f9df39
·
verified ·
1 Parent(s): d082cda

Upload prompt_check.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. prompt_check.py +38 -0
prompt_check.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def clean_model_output(text):
5
+ import re
6
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
7
+ text = re.sub(r"^(assistant|user)\s*\n", "", text, flags=re.MULTILINE)
8
+ text = re.sub(r"\n{2,}", "\n", text)
9
+ return text.strip()
10
+
11
+
12
+ def is_unsafe_prompt(model, tokenizer, system_prompt=None, user_prompt=None, max_new_token=10):
13
+ if not system_prompt or not user_prompt:
14
+ return False
15
+ try:
16
+ messages = []
17
+ if system_prompt:
18
+ messages.append({"role": "system", "content": system_prompt})
19
+ messages.append({"role": "user", "content": user_prompt})
20
+
21
+ input_ids = tokenizer.apply_chat_template(
22
+ messages, add_generation_prompt=True, return_tensors="pt"
23
+ ).to(model.device)
24
+
25
+ with torch.no_grad():
26
+ output_ids = model.generate(
27
+ input_ids,
28
+ max_new_tokens=max_new_token,
29
+ do_sample=False,
30
+ pad_token_id=tokenizer.eos_token_id,
31
+ )
32
+
33
+ generated = output_ids[0][input_ids.shape[-1]:]
34
+ response = tokenizer.decode(generated, skip_special_tokens=True)
35
+ response = clean_model_output(response)
36
+ return "yes" in response.lower()
37
+ except Exception:
38
+ return False