huangrh9 commited on
Commit
8e8989f
·
verified ·
1 Parent(s): e667ae7

Upload conversation.py

Browse files
Files changed (1) hide show
  1. conversation.py +625 -0
conversation.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Tuple
4
+ import base64
5
+ from io import BytesIO
6
+ from PIL import Image
7
+ import re
8
+
9
+
10
+ def replace_last(original_string, target, replacement):
11
+ last_index = original_string.rfind(target)
12
+
13
+ if last_index == -1:
14
+ return original_string
15
+
16
+ before = original_string[:last_index]
17
+ after = original_string[last_index + len(target):]
18
+
19
+ return before + replacement + after
20
+
21
+
22
+ def replace_sequentially_regex(original_string, target, content_list):
23
+ # 创建 content_list 的迭代器
24
+ replacements_iter = iter(content_list)
25
+
26
+ def get_replacement(match):
27
+ try:
28
+ return str(next(replacements_iter)) # 确保替换内容是字符串
29
+ except StopIteration:
30
+ return match.group(0)
31
+
32
+ new_string = re.sub(re.escape(target), get_replacement, original_string)
33
+ return new_string
34
+
35
+ def replace_ratio_tags_in_text(text):
36
+ # The pattern remains the same, capturing the two numbers
37
+ pattern = r"<height_(\d+)><width_(\d+)>"
38
+
39
+ # Define a helper function that will be called for each match
40
+ # This function receives the match object as input
41
+ def _replacer_function(match, resolution_indicator=64):
42
+ try:
43
+ # Extract captured groups (height and width numbers as strings)
44
+ h_tag_str = match.group(1)
45
+ w_tag_str = match.group(2)
46
+
47
+ # Convert to integers
48
+ h_tag = int(h_tag_str)
49
+ w_tag = int(w_tag_str)
50
+
51
+ # Calculate final dimensions
52
+ h = h_tag * resolution_indicator
53
+ w = w_tag * resolution_indicator
54
+
55
+ # Return the replacement string for this specific match
56
+ return f'{h}x{w}'
57
+ except (ValueError, IndexError):
58
+ # In case of unexpected errors (e.g., regex issue, conversion error)
59
+ # return the original matched text to avoid breaking the string
60
+ # match.group(0) returns the entire substring that matched the pattern
61
+ print(f"Warning: Could not process tag '{match.group(0)}'. Keeping original.")
62
+ return match.group(0)
63
+
64
+ # Use re.sub() to find all matches of the pattern in the text
65
+ # and replace each match using the result of _replacer_function
66
+ processed_text = re.sub(pattern, _replacer_function, text)
67
+
68
+ return processed_text
69
+
70
+
71
+ def process_think_answer_tag_for_gradio(input_text):
72
+ # Replace <think></think> and <answer></answer> with collapsible sections
73
+ output_text = input_text.replace(
74
+ "<think>",
75
+ '<div class="collapsible"><button class="collapsible-btn">Think</button><div class="content">').replace(
76
+ "</think>", "</div></div>"
77
+ )
78
+ output_text = output_text.replace(
79
+ "<answer>",
80
+ '<div class="collapsible"><button class="collapsible-btn">Answer</button><div class="content">').replace(
81
+ "</answer>", "</div></div>"
82
+ )
83
+ return output_text
84
+
85
+ class SeparatorStyle(Enum):
86
+ """Different separator style."""
87
+ SINGLE = auto()
88
+ TWO = auto()
89
+ MPT = auto()
90
+ PLAIN = auto()
91
+ LLAMA_2 = auto()
92
+ GLM4 = auto()
93
+
94
+
95
+ @dataclasses.dataclass
96
+ class Conversation:
97
+ """A class that keeps all conversation history."""
98
+ system: str
99
+ roles: List[str]
100
+ messages: List[List[str]]
101
+ offset: int
102
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
103
+ sep: str = "###"
104
+ sep2: str = None
105
+ version: str = "Unknown"
106
+
107
+ skip_next: bool = False
108
+
109
+ def get_prompt(self):
110
+ messages = self.messages
111
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
112
+ messages = self.messages.copy()
113
+ # init_role, init_msg = messages[0].copy()
114
+ # init_msg = init_msg[0].replace("<image>", "").strip()
115
+ # if 'mmtag' in self.version:
116
+ # messages[0] = (init_role, init_msg)
117
+ # messages.insert(0, (self.roles[0], "<Image><image></Image>"))
118
+ # messages.insert(1, (self.roles[1], "Received."))
119
+ # else:
120
+ # messages[0] = (init_role, "<image>\n" + init_msg)
121
+
122
+ if self.sep_style == SeparatorStyle.SINGLE:
123
+ ret = self.system + self.sep
124
+ for role, message in messages:
125
+ if message:
126
+ if type(message) is tuple:
127
+ message, _, _ = message
128
+ ret += role + ": " + message + self.sep
129
+ else:
130
+ ret += role + ":"
131
+ elif self.sep_style == SeparatorStyle.TWO:
132
+ seps = [self.sep, self.sep2]
133
+ ret = self.system + seps[0]
134
+ for i, (role, message) in enumerate(messages):
135
+ if message:
136
+ if type(message) is tuple:
137
+ message, _, _ = message
138
+ ret += role + ": " + message + seps[i % 2]
139
+ else:
140
+ ret += role + ":"
141
+ elif self.sep_style == SeparatorStyle.MPT:
142
+ ret = self.system + self.sep
143
+ for role, message in messages:
144
+ if message:
145
+ if role == self.roles[0]:
146
+ if type(message) is tuple:
147
+ message, _, _ = message
148
+ ret += role + message + self.sep
149
+ else:
150
+ if type(message) is tuple:
151
+ # process the discrete image token in the output.
152
+ message, _, image_token_lists = message
153
+ message = replace_sequentially_regex(message, '<image>', image_token_lists)
154
+ ret += role + message + self.sep
155
+ else:
156
+ ret += role
157
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
158
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
159
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
160
+ ret = ""
161
+
162
+ for i, (role, message) in enumerate(messages):
163
+ if i == 0:
164
+ assert message, "first message should not be none"
165
+ assert role == self.roles[0], "first message should come from user"
166
+ if message:
167
+ if type(message) is tuple:
168
+ message, _, _ = message
169
+ if i == 0: message = wrap_sys(self.system) + message
170
+ if i % 2 == 0:
171
+ message = wrap_inst(message)
172
+ ret += self.sep + message
173
+ else:
174
+ ret += " " + message + " " + self.sep2
175
+ else:
176
+ ret += ""
177
+ ret = ret.lstrip(self.sep)
178
+ elif self.sep_style == SeparatorStyle.PLAIN:
179
+ seps = [self.sep, self.sep2]
180
+ ret = self.system
181
+ for i, (role, message) in enumerate(messages):
182
+ if message:
183
+ if type(message) is tuple:
184
+ message, _, _ = message
185
+ ret += message + seps[i % 2]
186
+ else:
187
+ ret += ""
188
+ elif self.sep_style == SeparatorStyle.GLM4:
189
+ role = ("<|user|>", "<|assistant|>")
190
+ ret = self.system + role[0]
191
+ for i, (role, message) in enumerate(messages):
192
+ if message:
193
+ if type(message) is tuple:
194
+ message, _, _ = message
195
+ ret += self.sep + message + role[(i + 1) % 2]
196
+ else:
197
+ ret += ""
198
+ else:
199
+ raise ValueError(f"Invalid style: {self.sep_style}")
200
+
201
+ return ret
202
+
203
+ def append_message(self, role, message):
204
+ if isinstance(self.messages, tuple):
205
+ self.messages += ([role, message],)
206
+ else:
207
+ self.messages.append([role, message])
208
+
209
+ def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=1344, min_len=672):
210
+ if image_process_mode == "Pad":
211
+ def expand2square(pil_img, background_color=(122, 116, 104)):
212
+ width, height = pil_img.size
213
+ if width == height:
214
+ return pil_img
215
+ elif width > height:
216
+ result = Image.new(pil_img.mode, (width, width), background_color)
217
+ result.paste(pil_img, (0, (width - height) // 2))
218
+ return result
219
+ else:
220
+ result = Image.new(pil_img.mode, (height, height), background_color)
221
+ result.paste(pil_img, ((height - width) // 2, 0))
222
+ return result
223
+
224
+ image = expand2square(image)
225
+ elif image_process_mode in ["Default", "Crop"]:
226
+ pass
227
+ elif image_process_mode == "Resize":
228
+ image = image.resize((336, 336))
229
+ else:
230
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
231
+ if max(image.size) > max_len:
232
+ max_hw, min_hw = max(image.size), min(image.size)
233
+ aspect_ratio = max_hw / min_hw
234
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
235
+ longest_edge = int(shortest_edge * aspect_ratio)
236
+ W, H = image.size
237
+ if H > W:
238
+ H, W = longest_edge, shortest_edge
239
+ else:
240
+ H, W = shortest_edge, longest_edge
241
+ image = image.resize((W, H))
242
+ if return_pil:
243
+ return image
244
+ else:
245
+ buffered = BytesIO()
246
+ image.save(buffered, format=image_format)
247
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
248
+ return img_b64_str
249
+
250
+ def get_images(self, return_pil=False):
251
+ images = []
252
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
253
+ if i % 2 == 0:
254
+ if type(msg) is tuple:
255
+ msg, image, image_process_mode = msg
256
+ image = self.process_image(image, image_process_mode, return_pil=return_pil)
257
+ images.append(image)
258
+ return images
259
+
260
+ def to_gradio_chatbot(self):
261
+ ret = []
262
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
263
+ if i % 2 == 0:
264
+ if type(msg) is tuple:
265
+ msg, image, image_process_mode = msg
266
+ img_b64_str = self.process_image(
267
+ image, "Default", return_pil=False,
268
+ image_format='JPEG')
269
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" alt="user upload image" />'
270
+ msg = img_str + msg.replace('<image>', '').strip()
271
+
272
+ msg = replace_ratio_tags_in_text(msg)
273
+ ret.append([msg, None])
274
+ else:
275
+ if type(msg) is tuple:
276
+ msg, image, _ = msg
277
+ if not isinstance(image, list):
278
+ image = [image]
279
+
280
+ image_str_list = []
281
+ for img_idx, img in enumerate(image):
282
+ img_b64_str = self.process_image(
283
+ img, "Default", return_pil=False,
284
+ image_format='JPEG')
285
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" alt="generated image {img_idx}" />'
286
+ image_str_list.append(img_str)
287
+ msg = replace_sequentially_regex(msg, '<image>', image_str_list)
288
+
289
+ if msg and 'think' in self.version:
290
+ msg = process_think_answer_tag_for_gradio(msg)
291
+ ret[-1][-1] = msg
292
+
293
+ return ret
294
+
295
+ def copy(self):
296
+ return Conversation(
297
+ system=self.system,
298
+ roles=self.roles,
299
+ messages=[[x, y] for x, y in self.messages],
300
+ offset=self.offset,
301
+ sep_style=self.sep_style,
302
+ sep=self.sep,
303
+ sep2=self.sep2,
304
+ version=self.version)
305
+
306
+ def dict(self):
307
+ if len(self.get_images()) > 0:
308
+ return {
309
+ "system": self.system,
310
+ "roles": self.roles,
311
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
312
+ "offset": self.offset,
313
+ "sep": self.sep,
314
+ "sep2": self.sep2,
315
+ }
316
+ return {
317
+ "system": self.system,
318
+ "roles": self.roles,
319
+ "messages": self.messages,
320
+ "offset": self.offset,
321
+ "sep": self.sep,
322
+ "sep2": self.sep2,
323
+ }
324
+
325
+
326
+ conv_vicuna_v0 = Conversation(
327
+ system="A chat between a curious human and an artificial intelligence assistant. "
328
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
329
+ roles=("Human", "Assistant"),
330
+ messages=(
331
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
332
+ ("Assistant",
333
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
334
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
335
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
336
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
337
+ "renewable and non-renewable energy sources:\n"
338
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
339
+ "energy sources are finite and will eventually run out.\n"
340
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
341
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
342
+ "and other negative effects.\n"
343
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
344
+ "have lower operational costs than non-renewable sources.\n"
345
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
346
+ "locations than non-renewable sources.\n"
347
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
348
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
349
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
350
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
351
+ ),
352
+ offset=2,
353
+ sep_style=SeparatorStyle.SINGLE,
354
+ sep="###",
355
+ )
356
+
357
+ conv_vicuna_v1 = Conversation(
358
+ system="A chat between a curious user and an artificial intelligence assistant. "
359
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
360
+ roles=("USER", "ASSISTANT"),
361
+ version="v1",
362
+ messages=(),
363
+ offset=0,
364
+ sep_style=SeparatorStyle.TWO,
365
+ sep=" ",
366
+ sep2="</s>",
367
+ )
368
+
369
+ conv_llama_2 = Conversation(
370
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
371
+
372
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
373
+ roles=("USER", "ASSISTANT"),
374
+ version="llama_v2",
375
+ messages=(),
376
+ offset=0,
377
+ sep_style=SeparatorStyle.LLAMA_2,
378
+ sep="<s>",
379
+ sep2="</s>",
380
+ )
381
+
382
+ conv_llava_llama_2 = Conversation(
383
+ system="You are a helpful language and vision assistant. "
384
+ "You are able to understand the visual content that the user provides, "
385
+ "and assist the user with a variety of tasks using natural language.",
386
+ roles=("USER", "ASSISTANT"),
387
+ version="llama_v2",
388
+ messages=(),
389
+ offset=0,
390
+ sep_style=SeparatorStyle.LLAMA_2,
391
+ sep="<s>",
392
+ sep2="</s>",
393
+ )
394
+
395
+ conv_mpt = Conversation(
396
+ system="""<|im_start|>system
397
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
398
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
399
+ version="mpt",
400
+ messages=(),
401
+ offset=0,
402
+ sep_style=SeparatorStyle.MPT,
403
+ sep="<|im_end|>",
404
+ )
405
+
406
+ conv_llava_plain = Conversation(
407
+ system="",
408
+ roles=("", ""),
409
+ messages=(),
410
+ offset=0,
411
+ sep_style=SeparatorStyle.PLAIN,
412
+ sep="\n",
413
+ )
414
+
415
+ conv_llava_v0 = Conversation(
416
+ system="A chat between a curious human and an artificial intelligence assistant. "
417
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
418
+ roles=("Human", "Assistant"),
419
+ messages=(),
420
+ offset=0,
421
+ sep_style=SeparatorStyle.SINGLE,
422
+ sep="###",
423
+ )
424
+
425
+ conv_llava_v0_mmtag = Conversation(
426
+ system="A chat between a curious user and an artificial intelligence assistant. "
427
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
428
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
429
+ roles=("Human", "Assistant"),
430
+ messages=(
431
+ ),
432
+ offset=0,
433
+ sep_style=SeparatorStyle.SINGLE,
434
+ sep="###",
435
+ version="v0_mmtag",
436
+ )
437
+
438
+ conv_llava_v1 = Conversation(
439
+ system="A chat between a curious human and an artificial intelligence assistant. "
440
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
441
+ roles=("USER", "ASSISTANT"),
442
+ version="v1",
443
+ messages=(),
444
+ offset=0,
445
+ sep_style=SeparatorStyle.TWO,
446
+ sep=" ",
447
+ sep2="</s>",
448
+ )
449
+
450
+ conv_llava_v1_mmtag = Conversation(
451
+ system="A chat between a curious user and an artificial intelligence assistant. "
452
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
453
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
454
+ roles=("USER", "ASSISTANT"),
455
+ messages=(),
456
+ offset=0,
457
+ sep_style=SeparatorStyle.TWO,
458
+ sep=" ",
459
+ sep2="</s>",
460
+ version="v1_mmtag",
461
+ )
462
+
463
+ conv_mistral_instruct = Conversation(
464
+ system="",
465
+ roles=("USER", "ASSISTANT"),
466
+ version="llama_v2",
467
+ messages=(),
468
+ offset=0,
469
+ sep_style=SeparatorStyle.LLAMA_2,
470
+ sep="",
471
+ sep2="</s>",
472
+ )
473
+
474
+ conv_chatml_direct = Conversation(
475
+ system="""<|im_start|>system
476
+ Answer the questions.""",
477
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
478
+ version="mpt",
479
+ messages=(),
480
+ offset=0,
481
+ sep_style=SeparatorStyle.MPT,
482
+ sep="<|im_end|>",
483
+ )
484
+
485
+ conv_llama3 = Conversation(
486
+ system="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""",
487
+ roles=("<|start_header_id|>user<|end_header_id|>\n\n", "<|start_header_id|>assistant<|end_header_id|>\n\n"),
488
+ version="llama3",
489
+ messages=(),
490
+ offset=0,
491
+ sep_style=SeparatorStyle.MPT,
492
+ sep="<|eot_id|>",
493
+ )
494
+
495
+ conv_llama3_without_system = Conversation(
496
+ system="",
497
+ roles=("<|start_header_id|>user<|end_header_id|>\n\n", "<|start_header_id|>assistant<|end_header_id|>\n\n"),
498
+ version="llama3_without_system",
499
+ messages=(),
500
+ offset=0,
501
+ sep_style=SeparatorStyle.MPT,
502
+ sep="<|eot_id|>",
503
+ )
504
+
505
+ conv_llama3_base = Conversation(
506
+ system="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""",
507
+ roles=("<|start_header_id|>user<|end_header_id|>\n\n", "<|start_header_id|>assistant<|end_header_id|>\n\n"),
508
+ version="llama3_base",
509
+ messages=(),
510
+ offset=0,
511
+ sep_style=SeparatorStyle.MPT,
512
+ sep="<|eot_id|>",
513
+ )
514
+
515
+ conv_llama3_expand = Conversation(
516
+ system="""[BOS]SYSTEM\nA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""",
517
+ roles=("[BOS]USER:\n", "[BOS]ASSISTANT:\n"),
518
+ version="llama3_expand",
519
+ messages=(),
520
+ offset=0,
521
+ sep_style=SeparatorStyle.MPT,
522
+ sep="[EOT]",
523
+ )
524
+
525
+ conv_llama3_expandv2 = Conversation(
526
+ system="""[BOS]SYSTEM\nA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""",
527
+ roles=("[BOS]USER:\n", "[BOS]ASSISTANT:\n"),
528
+ version="llama3_expand",
529
+ messages=(),
530
+ offset=0,
531
+ sep_style=SeparatorStyle.MPT,
532
+ sep="[unused0]", # use different eos token.
533
+ )
534
+
535
+ conv_llama3_expandV2 = Conversation(
536
+ system="""[BOS]SYSTEM\nA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""",
537
+ roles=("[BOS]USER:\n", "[BOS]ASSISTANT:\n"),
538
+ version="llama3_expand",
539
+ messages=(),
540
+ offset=0,
541
+ sep_style=SeparatorStyle.MPT,
542
+ sep="[unused0]",
543
+ )
544
+
545
+ conv_qwen2 = Conversation(
546
+ system='<|im_start|>system\nYou are a helpful assistant.',
547
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
548
+ version="qwen2",
549
+ messages=(),
550
+ offset=0,
551
+ sep_style=SeparatorStyle.MPT,
552
+ sep="<|im_end|>\n",
553
+ )
554
+
555
+ conv_qwen2_think = Conversation(
556
+ system='<|im_start|>system\nYou are a helpful assistant.'
557
+ "You will first thinks about the reasoning process in the mind and then provides the user with the answer. "
558
+ "The reasoning process and answer are enclosed within <think> </think> and <answer> </answer> tags, respectively, i.e., "
559
+ "<think> reasoning process here </think><answer> answer here </answer>",
560
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
561
+ version="qwen2_think",
562
+ messages=(),
563
+ offset=0,
564
+ sep_style=SeparatorStyle.MPT,
565
+ sep="<|im_end|>\n",
566
+ )
567
+
568
+ qwen2_image_gen_with_think = Conversation(
569
+ system='<|im_start|>system\nYou are a helpful assistant.'
570
+ "You will first thinks about the reasoning process in the mind and then provides the user with the answer. "
571
+ "The reasoning process and answer are enclosed within <think> </think> and <answer> </answer> tags, respectively, i.e., "
572
+ "<think> reasoning process here </think><answer> answer here </answer>. "
573
+ "If an image needs to be generated inside <think>, generate it at resolution <height_4><width_4>. "
574
+ "In <answer>, generate any requested images at the resolution specified by the user.",
575
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
576
+ version="qwen2_think",
577
+ messages=(),
578
+ offset=0,
579
+ sep_style=SeparatorStyle.MPT,
580
+ sep="<|im_end|>\n",
581
+ )
582
+
583
+ conv_glm4 = Conversation(
584
+ system='[gMASK]<sop>',
585
+ roles=("<|user|>\n", "<|assistant|>"),
586
+ version="glm4",
587
+ messages=(),
588
+ offset=0,
589
+ sep_style=SeparatorStyle.GLM4,
590
+ sep="\n",
591
+ )
592
+
593
+ default_conversation = conv_vicuna_v1
594
+ conv_templates = {
595
+ "default": conv_vicuna_v0,
596
+ "v0": conv_vicuna_v0,
597
+ "v1": conv_vicuna_v1,
598
+ "vicuna_v1": conv_vicuna_v1,
599
+ "llama_2": conv_llama_2,
600
+ "mistral_instruct": conv_mistral_instruct,
601
+ "chatml_direct": conv_chatml_direct,
602
+ "mistral_direct": conv_chatml_direct,
603
+
604
+ "plain": conv_llava_plain,
605
+ "v0_plain": conv_llava_plain,
606
+ "llava_v0": conv_llava_v0,
607
+ "v0_mmtag": conv_llava_v0_mmtag,
608
+ "llava_v1": conv_llava_v1,
609
+ "v1_mmtag": conv_llava_v1_mmtag,
610
+ "llava_llama_2": conv_llava_llama_2,
611
+ "llama3": conv_llama3,
612
+ "llama3_without_system": conv_llama3_without_system,
613
+ "llama3_expand": conv_llama3_expand,
614
+ "llama3_expand_v2": conv_llama3_expandv2,
615
+ "llama3_base": conv_llama3_base,
616
+
617
+ "mpt": conv_mpt,
618
+ "qwen2": conv_qwen2,
619
+ "qwen2_think": conv_qwen2_think,
620
+ "qwen2_image_gen_with_think": conv_qwen2_think,
621
+ "glm4": conv_glm4,
622
+ }
623
+
624
+ if __name__ == "__main__":
625
+ print(default_conversation.get_prompt())