songff commited on
Commit
aa73958
·
verified ·
1 Parent(s): f58738a

Create tokenization.py

Browse files
Files changed (1) hide show
  1. tokenization.py +53 -0
tokenization.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedTokenizerFast
2
+
3
+ class SinglePOTokenizer(PreTrainedTokenizerFast):
4
+ def __init__(self, *args, **kwargs):
5
+ super().__init__(*args, **kwargs)
6
+
7
+ def get_context(
8
+ self,
9
+ raw_instruction,
10
+ rule_description,
11
+ ):
12
+ prompt = "You are an expert prompt engineer." + " "
13
+ prompt += "Please help me optimize this prompt to get better response:\n\n[The Start of Raw Prompt]\n{}\n[The End of Raw Prompt]".format(raw_instruction)
14
+ prompt += "\n\nYou should optimize this prompt by {}".format(rule_description)
15
+
16
+ context = self.apply_chat_template(
17
+ [
18
+ {
19
+ "role": "user",
20
+ "content": prompt,
21
+ }
22
+ ],
23
+ add_generation_prompt=True,
24
+ tokenize=False,
25
+ ) + "The Optimized Prompt:\n\n[The Start of Optimized Prompt"
26
+
27
+ return context
28
+
29
+ def parse_output(
30
+ self,
31
+ output_text,
32
+ raw_instruction = "", # recommend to provide, so when some error happened, we can still use the raw instruction
33
+ ):
34
+ better_instruction = "The Optimized Prompt:\n\n[The Start of Optimized Prompt" + output_text
35
+
36
+ if "[The Start of Optimized Prompt]" in better_instruction:
37
+ better_instruction = better_instruction[better_instruction.index("[The Start of Optimized Prompt]") + len("[The Start of Optimized Prompt]"):]
38
+ if better_instruction.startswith("\n"):
39
+ better_instruction = better_instruction[1:]
40
+ if "[The End of Optimized Prompt]" in better_instruction:
41
+ better_instruction = better_instruction[:better_instruction.index("[The End of Optimized Prompt]")]
42
+ if better_instruction.endswith("\n"):
43
+ better_instruction = better_instruction[:-1]
44
+ if "The Optimized Prompt:" in better_instruction: # almost error happened
45
+ better_instruction = better_instruction[:better_instruction.index("The Optimized Prompt:")]
46
+
47
+ if better_instruction.strip() == "": # some error may happen in optimization, so use the raw instruction
48
+ better_instruction = raw_instruction
49
+
50
+ if "The Optimized" in better_instruction: # still some error happened
51
+ better_instruction = raw_instruction
52
+
53
+ return better_instruction