-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprompt_builder.py
More file actions
executable file
·75 lines (53 loc) · 2.1 KB
/
prompt_builder.py
File metadata and controls
executable file
·75 lines (53 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import json
class PromptBuilder:
def __init__(self, prompt=None, prompt_type="chat_completion"):
if prompt is None:
prompt = []
self.prompt = prompt
self.prompt_type = prompt_type
@staticmethod
def load_from_file(file_path):
with open(file_path, "r") as fp:
content = fp.read()
try:
# Attempt to parse as JSON list (chat completion format)
prompts = json.loads(content)
if isinstance(prompts, list):
return PromptBuilder(prompts, "chat_completion")
raise ValueError("Unsupported prompt type!")
except json.JSONDecodeError:
return PromptBuilder(content, "completion")
def save_to_file(self, file_path):
with open(file_path, "w") as fp:
if self.prompt_type == "chat_completion":
json.dump(self.prompt, fp, ensure_ascii=False, indent=4)
elif prompt_type == "completion":
fp.write(self.prompt)
def append(self, prompt):
assert isinstance(prompt, list), "Prompt must be a list!"
self.prompt.append(prompt)
def format(self, **kwargs):
result = None
if self.prompt_type == "chat_completion":
result = []
for prompt in self.prompt:
result.append({
"role": prompt["role"],
"content": prompt["content"].format(**kwargs)
})
elif self.prompt_type == "completion":
result = self.prompt.format(**kwargs)
return result
def __str__(self):
return self.__repr__()
def __repr__(self):
if self.prompt_type == "chat_completion":
return json.dumps(self.prompt, indent=4)
elif self.prompt_type == "completion":
return self.prompt
def system(content):
return {"role": "system", "content": content}
def user(content):
return {"role": "user", "content": content}
def assistant(content):
return {"role": "assistant", "content": content}