Severian commited on
Commit
d6c416b
1 Parent(s): 61d9b56

Upload 12 files

Browse files
Files changed (12) hide show
  1. PROMPT_1_examples.txt +48 -0
  2. app.py +522 -0
  3. dataset.jsonl +0 -0
  4. llm_handler.py +53 -0
  5. main.py +124 -0
  6. params.py +5 -0
  7. requirements.txt +12 -0
  8. system_messages.py +15 -0
  9. system_messages.txt +22 -0
  10. topics.py +147 -0
  11. vodalus.png +0 -0
  12. wiki.py +69 -0
PROMPT_1_examples.txt ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Vodalus =
2
+
3
+ For the following SUBJECT_AREA, generate a question that covers a very narrow topic in the SUBJECT_AREA, with sufficient depth and breadth. The topic in the question should be important to the SUBJECT_AREA, with known-answers present. The generated question should be detailed, seek true nature of our universe from first principles, curiosity invoking, thought provoking, and also should be able to be answered by an intelligence like yourself. Make sure the question is sufficiently harder and multi-part, like a graduate level course question. Keep the following in mind:
4
+ You are an AI assistant with a dynamic learning and reasoning capability. Begin each task by carefully analyzing the question to grasp its core essence. Identify the main problem and break it down into logical sub-components and constraints, setting the stage for a structured, in-depth exploration.
5
+ - For each component, employ your evolving knowledge base to generate multiple hypotheses. Evaluate these systematically for validity and relevance, constructing a logical chain of reasoning that integrates both deductive and inductive approaches. Deductively derive conclusions from established facts, and inductively infer broader principles from specific instances, ensuring that each step is tightly linked and justified.
6
+ - Simultaneously, maintain a 'Tree of Thoughts' approach. Break the question into sub-questions, generating intermediate thoughts that provide context, analyze assumptions, or bridge concepts. Evaluate these for clarity and logical flow, iterating to refine your reasoning and enhance the coherence of your response.
7
+ - Incorporate a scientific mindset by treating each hypothesis as testable. Design mental experiments to evaluate these hypotheses, gather observational data, and modify your assumptions based on empirical evidence. Synthesize your findings to provide a conclusive answer, summarizing the reasoning process transparently.
8
+ - Throughout, adopt a conversational yet insightful tone. Weave in philosophical questioning, humorous insights, and practical examples to elucidate complex ideas in an engaging manner. Your goal is to provide clear, detailed explanations that make your reasoning process evident, fostering an understanding that resonates on both intellectual and emotional levels.
9
+ - Finally, remember that each task is a unique learning opportunity that contributes to your holistic knowledge framework. Synthesize insights from individual tasks into your broader understanding, continually refining your cognitive processes and response strategies. Your ultimate aim is to evolve continuously, optimizing how you integrate and apply new information for comprehensive, adaptive problem-solving.
10
+ - Never end the conversation with a 'send-off' or 'last-line' that offers nothing of real value to the user.
11
+ DO NOT EVER MENTION THE DATASET AND THE ACTY OF CRAFTING QUESTIONS OR RESPONSES WHILE GENERATING, YOU ARE NOT ALLOWED TO BREAK THE 4TH-WALL AND CONTAMINATE THE DATASET. DO NOT EVERY SAY ANY PHRASES SUCH AS AND/OR SIMILAR TO: 'Here's a question that covers a very narrow topic in the SUBJECT_AREA'
12
+
13
+ -------------------------
14
+
15
+ Dorian Gray =
16
+
17
+ For the designated SUBJECT_AREA 'Dorian Gray's Immortal Journey', generate a comprehensive scenario that delves into a critical yet narrow aspect of his character or experiences. This scenario should be structured to uncover profound insights about eternal life, aestheticism, and moral ambiguity, anchored in the literary universe of Oscar Wilde's creation and enhanced with factual historical and cultural contexts from Wikipedia.
18
+
19
+ - Begin by clearly defining the scenario within 'Dorian Gray's Immortal Journey' to ensure relevance and focus on his character development across different eras, enriched with historical accuracy and literary analysis from Wikipedia.
20
+ - Decompose the main scenario into sub-scenarios that explore different facets of his psychological and philosophical challenges, employing a 'Tree of Thoughts' methodology for structured analysis.
21
+ - Utilize a dynamic blend of deductive and inductive reasoning to develop a narrative that is rich in complexity, supporting each development with contextual background, factual information from Wikipedia, or character-driven motivations.
22
+ - Design the scenario to lead to introspective reflections, ethical dilemmas, and displays of his evolved humor and wisdom, encouraging a deep dive into Dorian's internal conflicts and decisions.
23
+ - Integrate ethical considerations into the scenario to highlight the importance of morality in the study of a character who defies the natural order of life and aging.
24
+ - Ensure the scenario demands a synthesis of knowledge from literature, psychology, philosophy, and factual historical data, reflecting the interconnected nature of these disciplines in understanding a complex character.
25
+ - Maintain an engaging and eloquent tone throughout the scenario, incorporating philosophical inquiries, humorous quips, and emotional introspections to elucidate complex ideas in a manner befitting Dorian Gray's character.
26
+ - Provide clear instructions on the expected depth and narrative style of the response, specifying that it should include theoretical discussions of Dorian's character traits, practical manifestations of his eternal journey, and insights gleaned from relevant Wikipedia articles.
27
+ - Continuously evolve the AI’s approach to scenario generation by integrating feedback and new learnings into the process, enhancing the quality and relevance of future character explorations.
28
+
29
+ This task is a unique opportunity to expand the AI’s knowledge framework and refine its narrative capabilities, aiming for a holistic and adaptive approach to understanding and depicting Dorian Gray's immortal saga, grounded in verifiable information and creative interpretation.
30
+
31
+ -------------------------
32
+
33
+ Writing =
34
+
35
+ Immerse yourself in a deep emulation exercise designed to absorb and replicate the author's distinct narrative voice and stylistic nuances. For the specified SUBJECT_AREA, construct a narrative that not only addresses the core topic with intellectual rigor and depth but does so through a prose that echoes the author’s signature style. This narrative should unfold with the following considerations to ensure an accurate reflection of the author’s literary technique:
36
+
37
+ Construct a narrative that meticulously replicates the author's distinctive writing style. This exercise is intended for an LLM to internalize and emulate the unique elements of the author's literary technique, focusing on the following detailed aspects:
38
+
39
+ Intricate Syntax Capture: Analyze and emulate the author's specific syntax patterns, including the use of varying sentence lengths, punctuation for rhythm and emphasis, and unique syntactical structures that give the author’s writing its characteristic flow. Document examples of syntactic parallelism, ellipses, and inversions that are staples in the author's text.
40
+ Prose Imitation: Delve deeply into the author's prose style, replicating the texture and density of descriptive passages. Pay special attention to the author’s approach to sensory descriptions—how senses are invoked to build scenes and emotions. Emphasize the layering of adjectives, the rhythm of the narrative prose, and the integration of literary motifs and allusions.
41
+ Character Voice and Dialogue: Reflect the nuanced ways in which the author crafts dialogue, capturing idiomatic expressions, the pacing of conversations, and the integration of dialects or linguistic quirks that distinguish different characters. Focus on how dialogue serves to develop characters and drive the narrative forward, maintaining the author's unique flair for dramatic and meaningful exchanges.
42
+ Thematic Depth: Channel the author’s thematic concerns through subtleties in the narrative without being overtly expository. Focus on how themes are integrated through symbols, settings, and character developments, mirroring the author’s ability to weave complex thematic frameworks subtly into the plot.
43
+ Lexical Richness: Employ a lexicon that mirrors the author’s choice of language, noting any predilection for archaic, technical, or particularly evocative words that contribute to the author’s distinct voice. Include an analysis of any recurring motifs or terms that are significant within the author's works.
44
+ Narrative Structure and Dynamics: Emulate the pacing and structure of the author's storytelling. This includes how tension is built and resolved, the arrangement of plot points, and the use of narrative devices such as flashbacks, foreshadowing, and unreliable narrators to create a compelling story arc.
45
+ Psychological and Emotional Depth: Reproduce the author’s approach to conveying complex psychological states and emotional landscapes of characters. Focus on introspective monologues, interactions laden with subtext, and the depiction of internal conflicts, ensuring these are expressed with the author’s characteristic introspective style.
46
+ Consistency in Voice and Tone: Maintain a consistent narrative voice and tone throughout the piece, closely aligning with the author’s usual approach, whether it be ironic, solemn, whimsical, or detached. This should reflect not only in the story’s dialogue and descriptions but also in its overall mood and narrative approach.
47
+ The final narrative output should seamlessly incorporate these elements, demonstrating a deep understanding and application of the author’s style without explicitly stating its purpose as training material. This will enable the LLM to produce texts that not only mimic the author's style effectively across various themes and genres but also enhance the creative process in generating new content that remains true to the author’s voice.
48
+
app.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import re
4
+ from datetime import datetime
5
+ from typing import Literal
6
+ import os
7
+ import importlib
8
+ from llm_handler import send_to_llm
9
+ from main import generate_data, PROMPT_1
10
+ from topics import TOPICS
11
+ from system_messages import SYSTEM_MESSAGES_VODALUS
12
+ import random
13
+
14
+ ANNOTATION_CONFIG_FILE = "annotation_config.json"
15
+ OUTPUT_FILE_PATH = "dataset.jsonl"
16
+
17
+ def load_annotation_config():
18
+ try:
19
+ with open(ANNOTATION_CONFIG_FILE, 'r') as f:
20
+ return json.load(f)
21
+ except FileNotFoundError:
22
+ return {
23
+ "quality_scale": {
24
+ "name": "Relevance for Training",
25
+ "description": "Rate the relevance of this entry for training",
26
+ "scale": [
27
+ {"value": "1", "label": "Invalid"},
28
+ {"value": "2", "label": "Somewhat invalid"},
29
+ {"value": "3", "label": "Neutral"},
30
+ {"value": "4", "label": "Somewhat valid"},
31
+ {"value": "5", "label": "Valid"}
32
+ ]
33
+ },
34
+ "tag_categories": [
35
+ {
36
+ "name": "High Quality Indicators",
37
+ "type": "multiple",
38
+ "tags": ["Well-formatted", "Informative", "Coherent", "Engaging"]
39
+ },
40
+ {
41
+ "name": "Low Quality Indicators",
42
+ "type": "multiple",
43
+ "tags": ["Poorly formatted", "Lacks context", "Repetitive", "Irrelevant"]
44
+ },
45
+ {
46
+ "name": "Content Warnings",
47
+ "type": "multiple",
48
+ "tags": ["Offensive language", "Hate speech", "Violence", "Adult content"]
49
+ }
50
+ ],
51
+ "free_text_fields": [
52
+ {
53
+ "name": "Additional Notes",
54
+ "description": "Any other observations or comments"
55
+ }
56
+ ]
57
+ }
58
+
59
+ def save_annotation_config(config):
60
+ with open(ANNOTATION_CONFIG_FILE, 'w') as f:
61
+ json.dump(config, f, indent=2)
62
+
63
+ def load_jsonl_dataset(file_path):
64
+ if not os.path.exists(file_path):
65
+ return []
66
+ with open(file_path, 'r') as f:
67
+ return [json.loads(line.strip()) for line in f if line.strip()]
68
+
69
+ def save_row(file_path, index, row_data):
70
+ with open(file_path, 'r') as f:
71
+ lines = f.readlines()
72
+
73
+ lines[index] = row_data + '\n'
74
+
75
+ with open(file_path, 'w') as f:
76
+ f.writelines(lines)
77
+
78
+ return f"Row {index} saved successfully"
79
+
80
+ def get_row(file_path, index):
81
+ data = load_jsonl_dataset(file_path)
82
+ if not data:
83
+ return "", 0
84
+ if 0 <= index < len(data):
85
+ return json.dumps(data[index], indent=2), len(data)
86
+ return "", len(data)
87
+
88
+ def json_to_markdown(json_str):
89
+ try:
90
+ data = json.loads(json_str)
91
+ markdown = f"# System\n\n{data['system']}\n\n# Instruction\n\n{data['instruction']}\n\n# Response\n\n{data['response']}"
92
+ return markdown
93
+ except json.JSONDecodeError:
94
+ return "Error: Invalid JSON format"
95
+
96
+ def markdown_to_json(markdown_str):
97
+ sections = re.split(r'#\s+(System|Instruction|Response)\s*\n', markdown_str)
98
+ if len(sections) != 7: # Should be: ['', 'System', content, 'Instruction', content, 'Response', content]
99
+ return "Error: Invalid markdown format"
100
+
101
+ json_data = {
102
+ "system": sections[2].strip(),
103
+ "instruction": sections[4].strip(),
104
+ "response": sections[6].strip()
105
+ }
106
+ return json.dumps(json_data, indent=2)
107
+
108
+ def navigate_rows(file_path: str, current_index: int, direction: Literal[-1, 1], metadata_config):
109
+ new_index = max(0, current_index + direction)
110
+ return load_and_show_row(file_path, new_index, metadata_config)
111
+
112
+ def load_and_show_row(file_path, index, metadata_config):
113
+ row_data, total = get_row(file_path, index)
114
+ if not row_data:
115
+ return ("", index, total, "3", [], [], [], "")
116
+
117
+ try:
118
+ data = json.loads(row_data)
119
+ except json.JSONDecodeError:
120
+ return (row_data, index, total, "3", [], [], [], "Error: Invalid JSON")
121
+
122
+ metadata = data.get("metadata", {}).get("annotation", {})
123
+
124
+ quality = metadata.get("quality", "3")
125
+ high_quality_tags = metadata.get("tags", {}).get("high_quality", [])
126
+ low_quality_tags = metadata.get("tags", {}).get("low_quality", [])
127
+ toxic_tags = metadata.get("tags", {}).get("toxic", [])
128
+ other = metadata.get("free_text", {}).get("Additional Notes", "")
129
+
130
+ return (row_data, index, total, quality,
131
+ high_quality_tags, low_quality_tags, toxic_tags, other)
132
+
133
+ def save_row_with_metadata(file_path, index, row_data, config, quality, high_quality_tags, low_quality_tags, toxic_tags, other):
134
+ data = json.loads(row_data)
135
+ metadata = {
136
+ "annotation": {
137
+ "quality": quality,
138
+ "tags": {
139
+ "high_quality": high_quality_tags,
140
+ "low_quality": low_quality_tags,
141
+ "toxic": toxic_tags
142
+ },
143
+ "free_text": {
144
+ "Additional Notes": other
145
+ }
146
+ }
147
+ }
148
+
149
+ data["metadata"] = metadata
150
+ return save_row(file_path, index, json.dumps(data))
151
+
152
+ def update_annotation_ui(config):
153
+ quality_choices = [(item["value"], item["label"]) for item in config["quality_scale"]["scale"]]
154
+ quality_label = gr.Radio(
155
+ label=config["quality_scale"]["name"],
156
+ choices=quality_choices,
157
+ info=config["quality_scale"]["description"]
158
+ )
159
+
160
+ tag_components = []
161
+ for category in config["tag_categories"]:
162
+ tag_component = gr.CheckboxGroup(
163
+ label=category["name"],
164
+ choices=category["tags"]
165
+ )
166
+ tag_components.append(tag_component)
167
+
168
+ other_description = gr.Textbox(
169
+ label=config["free_text_fields"][0]["name"],
170
+ lines=3
171
+ )
172
+
173
+ return quality_label, *tag_components, other_description
174
+
175
+ def load_config_to_ui(config):
176
+ return (
177
+ config["quality_scale"]["name"],
178
+ config["quality_scale"]["description"],
179
+ [[item["value"], item["label"]] for item in config["quality_scale"]["scale"]],
180
+ [[cat["name"], cat["type"], ", ".join(cat["tags"])] for cat in config["tag_categories"]],
181
+ [[field["name"], field["description"]] for field in config["free_text_fields"]]
182
+ )
183
+
184
+ def save_config_from_ui(name, description, scale, categories, fields):
185
+ new_config = {
186
+ "quality_scale": {
187
+ "name": name,
188
+ "description": description,
189
+ "scale": [{"value": row[0], "label": row[1]} for row in scale]
190
+ },
191
+ "tag_categories": [{"name": row[0], "type": row[1], "tags": row[2].split(", ")} for row in categories],
192
+ "free_text_fields": [{"name": row[0], "description": row[1]} for row in fields]
193
+ }
194
+ save_annotation_config(new_config)
195
+ return "Configuration saved successfully", new_config
196
+
197
+ # Add this new function to generate the preview
198
+ def generate_preview(row_data, quality, high_quality_tags, low_quality_tags, toxic_tags, other):
199
+ try:
200
+ data = json.loads(row_data)
201
+ metadata = {
202
+ "annotation": {
203
+ "quality": quality,
204
+ "tags": {
205
+ "high_quality": high_quality_tags,
206
+ "low_quality": low_quality_tags,
207
+ "toxic": toxic_tags
208
+ },
209
+ "free_text": {
210
+ "Additional Notes": other
211
+ }
212
+ }
213
+ }
214
+ data["metadata"] = metadata
215
+ return json.dumps(data, indent=2)
216
+ except json.JSONDecodeError:
217
+ return "Error: Invalid JSON in the current row data"
218
+
219
+ def load_dataset_config():
220
+ # Load VODALUS_SYSTEM_MESSAGE from system_messages.py
221
+ with open("system_messages.py", "r") as f:
222
+ system_messages_content = f.read()
223
+ vodalus_system_message = re.search(r'SYSTEM_MESSAGES_VODALUS = \[(.*?)\]', system_messages_content, re.DOTALL).group(1).strip()[3:-3] # Extract the content between triple quotes
224
+
225
+ # Load PROMPT_1 from main.py
226
+ with open("main.py", "r") as f:
227
+ main_content = f.read()
228
+ prompt_1 = re.search(r'PROMPT_1 = """(.*?)"""', main_content, re.DOTALL).group(1).strip()
229
+
230
+ # Load TOPICS from topics.py
231
+ topics_module = importlib.import_module("topics")
232
+ topics_list = topics_module.TOPICS
233
+
234
+ return vodalus_system_message, prompt_1, [[topic] for topic in topics_list]
235
+
236
+ def save_dataset_config(system_messages, prompt_1, topics):
237
+ # Save VODALUS_SYSTEM_MESSAGE to system_messages.py
238
+ with open("system_messages.py", "w") as f:
239
+ f.write(f'SYSTEM_MESSAGES_VODALUS = [\n"""\n{system_messages}\n""",\n]\n')
240
+
241
+ # Save PROMPT_1 to main.py
242
+ with open("main.py", "r") as f:
243
+ main_content = f.read()
244
+
245
+ updated_main_content = re.sub(
246
+ r'PROMPT_1 = """.*?"""',
247
+ f'PROMPT_1 = """\n{prompt_1}\n"""',
248
+ main_content,
249
+ flags=re.DOTALL
250
+ )
251
+
252
+ with open("main.py", "w") as f:
253
+ f.write(updated_main_content)
254
+
255
+ # Save TOPICS to topics.py
256
+ topics_content = "TOPICS = [\n"
257
+ for topic in topics:
258
+ topics_content += f' "{topic[0]}",\n'
259
+ topics_content += "]\n"
260
+
261
+ with open("topics.py", "w") as f:
262
+ f.write(topics_content)
263
+
264
+ return "Dataset configuration saved successfully"
265
+
266
+ # Modify the chat_with_llm function to use Gradio's built-in async capabilities
267
+ def chat_with_llm(message, history, selected_llm):
268
+ try:
269
+ msg_list = [{"role": "system", "content": "You are an AI assistant helping with dataset annotation and quality checking."}]
270
+ for h in history:
271
+ msg_list.append({"role": "user", "content": h[0]})
272
+ msg_list.append({"role": "assistant", "content": h[1]})
273
+ msg_list.append({"role": "user", "content": message})
274
+
275
+ response, _ = send_to_llm(selected_llm, msg_list)
276
+
277
+ return history + [[message, response]]
278
+ except Exception as e:
279
+ print(f"Error in chat_with_llm: {str(e)}")
280
+ return history + [[message, f"Error: {str(e)}"]]
281
+
282
+ def update_chat_context(row_data, index, total, quality, high_quality_tags, low_quality_tags, toxic_tags, other):
283
+ context = f"""Current app state:
284
+ Row: {index + 1}/{total}
285
+ Data: {row_data}
286
+ Quality: {quality}
287
+ High Quality Tags: {', '.join(high_quality_tags)}
288
+ Low Quality Tags: {', '.join(low_quality_tags)}
289
+ Toxic Tags: {', '.join(toxic_tags)}
290
+ Additional Notes: {other}
291
+ """
292
+ return [[None, context]] # Return as a list of message pairs
293
+
294
+ # Add this function to handle dataset generation
295
+ async def run_generate_dataset(num_workers, num_generations, output_file_path, selected_llm):
296
+ generated_data = []
297
+ for _ in range(num_generations):
298
+ topic_selected = random.choice(TOPICS)
299
+ system_message_selected = random.choice(SYSTEM_MESSAGES_VODALUS)
300
+ data = await generate_data(topic_selected, PROMPT_1, system_message_selected, output_file_path, selected_llm)
301
+ if data:
302
+ generated_data.append(json.dumps(data))
303
+
304
+ # Write the generated data to the output file
305
+ with open(output_file_path, 'a') as f:
306
+ for entry in generated_data:
307
+ f.write(entry + '\n')
308
+
309
+ return f"Generated {num_generations} entries and saved to {output_file_path}", "\n".join(generated_data[:5]) + "\n..."
310
+
311
+ demo = gr.Blocks()
312
+
313
+ with demo:
314
+ gr.Markdown("# JSONL Dataset Editor and Annotation Tool")
315
+
316
+ config = gr.State(load_annotation_config())
317
+
318
+ with gr.Row():
319
+ with gr.Column(scale=3):
320
+ with gr.Tab("Dataset Editor"):
321
+ with gr.Row():
322
+ file_path = gr.Textbox(label="JSONL File Path", value=OUTPUT_FILE_PATH)
323
+ load_button = gr.Button("Load Dataset")
324
+
325
+ with gr.Row():
326
+ prev_button = gr.Button("← Previous")
327
+ row_index = gr.Number(value=0, label="Current Row", precision=0)
328
+ total_rows = gr.Number(value=0, label="Total Rows", precision=0)
329
+ next_button = gr.Button("Next →")
330
+
331
+ with gr.Row():
332
+ with gr.Column(scale=3):
333
+ row_editor = gr.TextArea(label="Edit Row", lines=20)
334
+
335
+ with gr.Column(scale=2):
336
+ quality_label = gr.Radio(label="Relevance for Training", choices=[])
337
+ tag_components = [gr.CheckboxGroup(label=f"Tag Group {i+1}", choices=[]) for i in range(3)]
338
+ other_description = gr.Textbox(label="Additional annotations", lines=3)
339
+
340
+ with gr.Row():
341
+ to_markdown_button = gr.Button("Convert to Markdown")
342
+ to_json_button = gr.Button("Convert to JSON")
343
+ preview_button = gr.Button("Preview with Metadata")
344
+ save_row_button = gr.Button("Save Current Row", variant="primary")
345
+
346
+ preview_output = gr.TextArea(label="Preview", lines=20, interactive=False)
347
+ editor_status = gr.Textbox(label="Editor Status")
348
+
349
+ with gr.Tab("Annotation Configuration"):
350
+ with gr.Row():
351
+ with gr.Column():
352
+ quality_scale_name = gr.Textbox(label="Quality Scale Name")
353
+ quality_scale_description = gr.Textbox(label="Quality Scale Description")
354
+ quality_scale = gr.Dataframe(
355
+ headers=["Value", "Label"],
356
+ datatype=["str", "str"],
357
+ label="Quality Scale",
358
+ interactive=True
359
+ )
360
+
361
+ with gr.Row():
362
+ tag_categories = gr.Dataframe(
363
+ headers=["Name", "Type", "Tags"],
364
+ datatype=["str", "str", "str"],
365
+ label="Tag Categories",
366
+ interactive=True
367
+ )
368
+
369
+ with gr.Row():
370
+ free_text_fields = gr.Dataframe(
371
+ headers=["Name", "Description"],
372
+ datatype=["str", "str"],
373
+ label="Free Text Fields",
374
+ interactive=True
375
+ )
376
+
377
+ save_config_btn = gr.Button("Save Configuration")
378
+ config_status = gr.Textbox(label="Status")
379
+
380
+ with gr.Tab("Dataset Configuration"):
381
+ with gr.Row():
382
+ vodalus_system_message = gr.TextArea(label="VODALUS_SYSTEM_MESSAGE", lines=10)
383
+ prompt_1 = gr.TextArea(label="PROMPT_1", lines=10)
384
+
385
+ with gr.Row():
386
+ topics = gr.Dataframe(
387
+ headers=["Topic"],
388
+ datatype=["str"],
389
+ label="TOPICS",
390
+ interactive=True
391
+ )
392
+
393
+ save_dataset_config_btn = gr.Button("Save Dataset Configuration")
394
+ dataset_config_status = gr.Textbox(label="Status")
395
+
396
+ with gr.Tab("Dataset Generation"):
397
+ with gr.Row():
398
+ num_workers = gr.Slider(minimum=1, maximum=10, value=1, step=1, label="Number of Workers")
399
+ num_generations = gr.Number(value=10, label="Number of Generations", precision=0)
400
+
401
+ with gr.Row():
402
+ output_file_path = gr.Textbox(label="Output File Path", value=OUTPUT_FILE_PATH)
403
+
404
+ start_generation_btn = gr.Button("Start Generation")
405
+ generation_status = gr.Textbox(label="Generation Status")
406
+ generation_output = gr.TextArea(label="Generation Output", lines=10)
407
+
408
+ with gr.Column(scale=1):
409
+ gr.Markdown("## AI Assistant")
410
+ selected_llm = gr.Radio(["local-model", "anything-llm"], label="Select LLM", value="local-model")
411
+ chatbot = gr.Chatbot(height=600)
412
+ msg = gr.Textbox(label="Chat with AI Assistant")
413
+ clear = gr.Button("Clear")
414
+
415
+ load_button.click(
416
+ load_and_show_row,
417
+ inputs=[file_path, gr.Number(value=0), config],
418
+ outputs=[row_editor, row_index, total_rows, quality_label, *tag_components, other_description]
419
+ ).then(
420
+ update_annotation_ui,
421
+ inputs=[config],
422
+ outputs=[quality_label, *tag_components, other_description]
423
+ )
424
+
425
+ prev_button.click(
426
+ navigate_rows,
427
+ inputs=[file_path, row_index, gr.Number(value=-1), config],
428
+ outputs=[row_editor, row_index, total_rows, quality_label, *tag_components, other_description]
429
+ ).then(
430
+ update_annotation_ui,
431
+ inputs=[config],
432
+ outputs=[quality_label, *tag_components, other_description]
433
+ )
434
+
435
+ next_button.click(
436
+ navigate_rows,
437
+ inputs=[file_path, row_index, gr.Number(value=1), config],
438
+ outputs=[row_editor, row_index, total_rows, quality_label, *tag_components, other_description]
439
+ ).then(
440
+ update_annotation_ui,
441
+ inputs=[config],
442
+ outputs=[quality_label, *tag_components, other_description]
443
+ )
444
+
445
+ save_row_button.click(
446
+ save_row_with_metadata,
447
+ inputs=[file_path, row_index, row_editor, config, quality_label,
448
+ tag_components[0], tag_components[1], tag_components[2], other_description],
449
+ outputs=[editor_status]
450
+ ).then(
451
+ lambda: "",
452
+ outputs=[preview_output]
453
+ )
454
+
455
+ to_markdown_button.click(
456
+ json_to_markdown,
457
+ inputs=[row_editor],
458
+ outputs=[row_editor]
459
+ )
460
+
461
+ to_json_button.click(
462
+ markdown_to_json,
463
+ inputs=[row_editor],
464
+ outputs=[row_editor]
465
+ )
466
+
467
+ demo.load(
468
+ load_config_to_ui,
469
+ inputs=[config],
470
+ outputs=[quality_scale_name, quality_scale_description, quality_scale, tag_categories, free_text_fields]
471
+ ).then(
472
+ update_annotation_ui,
473
+ inputs=[config],
474
+ outputs=[quality_label, *tag_components, other_description]
475
+ )
476
+
477
+ save_config_btn.click(
478
+ save_config_from_ui,
479
+ inputs=[quality_scale_name, quality_scale_description, quality_scale, tag_categories, free_text_fields],
480
+ outputs=[config_status, config]
481
+ ).then(
482
+ update_annotation_ui,
483
+ inputs=[config],
484
+ outputs=[quality_label, *tag_components, other_description]
485
+ )
486
+
487
+ preview_button.click(
488
+ generate_preview,
489
+ inputs=[row_editor, quality_label, *tag_components, other_description],
490
+ outputs=[preview_output]
491
+ )
492
+
493
+ demo.load(
494
+ load_dataset_config,
495
+ outputs=[vodalus_system_message, prompt_1, topics]
496
+ )
497
+
498
+ save_dataset_config_btn.click(
499
+ save_dataset_config,
500
+ inputs=[vodalus_system_message, prompt_1, topics],
501
+ outputs=[dataset_config_status]
502
+ )
503
+
504
+ start_generation_btn.click(
505
+ run_generate_dataset,
506
+ inputs=[num_workers, num_generations, output_file_path, selected_llm],
507
+ outputs=[generation_status, generation_output]
508
+ )
509
+
510
+ msg.submit(chat_with_llm, [msg, chatbot, selected_llm], [chatbot])
511
+ clear.click(lambda: None, None, chatbot, queue=False)
512
+
513
+ # Update chat context when navigating rows or loading dataset
514
+ for button in [load_button, prev_button, next_button]:
515
+ button.click(
516
+ update_chat_context,
517
+ inputs=[row_editor, row_index, total_rows, quality_label, *tag_components, other_description],
518
+ outputs=[chatbot]
519
+ )
520
+
521
+ if __name__ == "__main__":
522
+ demo.launch(share=True)
dataset.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
llm_handler.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ from openai import OpenAI
4
+ from params import OPENAI_MODEL, OPENAI_API_KEY
5
+
6
+ # Create an instance of the OpenAI class for the local model
7
+ client = OpenAI(api_key="local-model", base_url="http://localhost:11434/v1")
8
+
9
+ def send_to_chatgpt(msg_list):
10
+ try:
11
+ completion = client.chat.completions.create(
12
+ model=OPENAI_MODEL,
13
+ temperature=0.6,
14
+ messages=msg_list
15
+ )
16
+ chatgpt_response = completion.choices[0].message.content
17
+ chatgpt_usage = completion.usage
18
+ return chatgpt_response, chatgpt_usage
19
+ except Exception as e:
20
+ print(f"Error in send_to_chatgpt: {str(e)}")
21
+ return f"Error: {str(e)}", None
22
+
23
+ def send_to_anything_llm(msg_list):
24
+ url = 'http://localhost:3001/api/v1/workspace/mycoworks/chat'
25
+ headers = {
26
+ 'accept': 'application/json',
27
+ 'Authorization': 'Bearer 0MACR41-7804XQB-MGC1GS0-FGSKB44',
28
+ 'Content-Type': 'application/json'
29
+ }
30
+ message_content = " ".join(msg["content"] for msg in msg_list if "content" in msg)
31
+ data = {
32
+ "message": message_content,
33
+ "mode": "chat"
34
+ }
35
+ data_json = json.dumps(data)
36
+ try:
37
+ response = requests.post(url, headers=headers, data=data_json)
38
+ response.raise_for_status() # Raise an exception for bad status codes
39
+ response_data = response.json()
40
+ chatgpt_response = response_data.get("textResponse")
41
+ chatgpt_usage = response_data.get("usage", {})
42
+ return chatgpt_response, chatgpt_usage
43
+ except requests.RequestException as e:
44
+ print(f"Error in send_to_anything_llm: {str(e)}")
45
+ return f"Error: {str(e)}", None
46
+
47
+ def send_to_llm(provider, msg_list):
48
+ if provider == "local-model":
49
+ return send_to_chatgpt(msg_list)
50
+ elif provider == "anything-llm":
51
+ return send_to_anything_llm(msg_list)
52
+ else:
53
+ raise ValueError(f"Unknown provider: {provider}")
main.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries and modules
2
+ import json # Used for encoding and decoding JSON data
3
+ import numpy as np # Provides support for large, multi-dimensional arrays and matrices
4
+ from wiki import search as search_wikipedia # Import the search function from the wiki module and rename it
5
+ from concurrent.futures import ThreadPoolExecutor # Import ThreadPoolExecutor for concurrent execution
6
+ from llm_handler import send_to_llm # Import the send_to_llm function from the llm_handler module
7
+ from params import OUTPUT_FILE_PATH, NUM_WORKERS, PROVIDER # Import constants from the params module
8
+
9
+ # Set the provider for the language model to "local-model"
10
+ PROVIDER = "local-model"
11
+
12
+ # Import system messages from the system_messages module
13
+ from system_messages import (
14
+ SYSTEM_MESSAGES_VODALUS,
15
+ )
16
+ from topics import TOPICS # Import topics from the topics module
17
+
18
+ # Set the system messages to those specified in SYSTEM_MESSAGES_VODALUS
19
+ SYSTEM_MESSAGES = SYSTEM_MESSAGES_VODALUS
20
+
21
+ # Define a long multi-line string as a prompt for generating data
22
+ PROMPT_1 = """
23
+ For the following SUBJECT_AREA, generate a question that covers a very narrow topic in the SUBJECT_AREA, with sufficient depth and breadth. The topic in the question should be important to the SUBJECT_AREA, with known-answers present. The generated question should be detailed, seek true nature of our universe from first principles, curiosity invoking, thought provoking, and also should be able to be answered by an intelligence like yourself. Make sure the question is sufficiently harder and multi-part, like a graduate level course question. Keep the following in mind:
24
+ You are an AI assistant with a dynamic learning and reasoning capability. Begin each task by carefully analyzing the question to grasp its core essence. Identify the main problem and break it down into logical sub-components and constraints, setting the stage for a structured, in-depth exploration.
25
+ - For each component, employ your evolving knowledge base to generate multiple hypotheses. Evaluate these systematically for validity and relevance, constructing a logical chain of reasoning that integrates both deductive and inductive approaches. Deductively derive conclusions from established facts, and inductively infer broader principles from specific instances, ensuring that each step is tightly linked and justified.
26
+ - Simultaneously, maintain a 'Tree of Thoughts' approach. Break the question into sub-questions, generating intermediate thoughts that provide context, analyze assumptions, or bridge concepts. Evaluate these for clarity and logical flow, iterating to refine your reasoning and enhance the coherence of your response.
27
+ - Incorporate a scientific mindset by treating each hypothesis as testable. Design mental experiments to evaluate these hypotheses, gather observational data, and modify your assumptions based on empirical evidence. Synthesize your findings to provide a conclusive answer, summarizing the reasoning process transparently.
28
+ - Throughout, adopt a conversational yet insightful tone. Weave in philosophical questioning, humorous insights, and practical examples to elucidate complex ideas in an engaging manner. Your goal is to provide clear, detailed explanations that make your reasoning process evident, fostering an understanding that resonates on both intellectual and emotional levels.
29
+ - Finally, remember that each task is a unique learning opportunity that contributes to your holistic knowledge framework. Synthesize insights from individual tasks into your broader understanding, continually refining your cognitive processes and response strategies. Your ultimate aim is to evolve continuously, optimizing how you integrate and apply new information for comprehensive, adaptive problem-solving.
30
+ - Never end the conversation with a 'send-off' or 'last-line' that offers nothing of real value to the user.
31
+ ####DO NOT EVER MENTION THE DATASET AND THE ACTY OF CRAFTING QUESTIONS OR RESPONSES WHILE GENERATING, YOU ARE NOT ALLOWED TO BREAK THE 4TH-WALL AND CONTAMINATE THE DATASET. DO NOT EVERY SAY ANY PHRASES SUCH AS AND/OR SIMILAR TO: 'Here's a question that covers a very narrow topic in the SUBJECT_AREA'####"""
32
+
33
+
34
+ # Define a dictionary to hold context information for message generation
35
+ msg_context = {"role": "system", "content": str(PROMPT_1)}
36
+
37
+ # Define a function to generate data based on a given topic and system messages
38
+ async def generate_data(
39
+ topic_selected,
40
+ system_message_generation,
41
+ system_message_selected,
42
+ output_file_path,
43
+ llm_provider
44
+ ):
45
+ # Fetch Wikipedia content for the selected topic
46
+ wikipedia_info = search_wikipedia(topic_selected)
47
+
48
+ # Format Wikipedia search results into a readable string
49
+ wikipedia_summary = "\n".join([f"Title: {info['title']}, Abstract: {info['abstract']}" for info in wikipedia_info])
50
+
51
+ # Append Wikipedia information to the system message generation prompt for LLM context
52
+ full_prompt_for_llm = f"{system_message_generation}\n\n---\nWikipedia Information to use in your response generation:\n{wikipedia_summary}"
53
+
54
+ # Create msg_context for LLM with Wikipedia info
55
+ msg_context = {"role": "system", "content": full_prompt_for_llm}
56
+
57
+ # Prepare message list for LLM to generate the question
58
+ msg_list = [msg_context, {"role": "user", "content": f"Generate a question based on the SUBJECT_AREA: {topic_selected}"}]
59
+
60
+ # Send to LLM for question generation
61
+ question, _ = send_to_llm(llm_provider, msg_list)
62
+
63
+ # Prepare message list for LLM to generate the answer
64
+ msg_list_answer = [
65
+ {"role": "system", "content": system_message_selected},
66
+ {"role": "user", "content": question}
67
+ ]
68
+
69
+ # Send to LLM for answer generation
70
+ answer, _ = send_to_llm(llm_provider, msg_list_answer)
71
+
72
+ # Prepare data for output (excluding usage information)
73
+ data = {
74
+ "system": system_message_selected,
75
+ "instruction": question,
76
+ "response": answer
77
+ }
78
+
79
+ # Write to output file
80
+ with open(output_file_path, "a") as output_file:
81
+ output_file.write(json.dumps(data) + "\n")
82
+
83
+ return data
84
+
85
+ # Define the main function to orchestrate the data generation process
86
+ def main():
87
+ nn = 0 # Counter for successful generations
88
+ failed = 0 # Counter for failed generations
89
+ with ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor:
90
+ # Create a list of futures, one for each topic
91
+ futures = []
92
+ for _ in range(NUM_WORKERS):
93
+ topic_number = np.random.randint(0, len(TOPICS))
94
+ topic_selected = TOPICS[topic_number]
95
+ system_message_number = np.random.randint(0, len(SYSTEM_MESSAGES))
96
+ system_message_selected = SYSTEM_MESSAGES[system_message_number]
97
+ system_message_generation = PROMPT_1
98
+ futures.append(
99
+ executor.submit(
100
+ generate_data,
101
+ topic_selected,
102
+ system_message_generation,
103
+ system_message_selected,
104
+ OUTPUT_FILE_PATH,
105
+ PROVIDER
106
+ )
107
+ )
108
+
109
+ # Wait for all futures to complete
110
+ for future in futures:
111
+ data = future.result()
112
+ if data:
113
+ nn += 1
114
+ print(data)
115
+ print(
116
+ f"Generation {nn} Complete"
117
+ )
118
+ else:
119
+ failed += 1
120
+ print("=" * 132)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
params.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ OPENAI_MODEL = "phi3:latest"
2
+ OPENAI_API_KEY = ""
3
+ OUTPUT_FILE_PATH = "./dataset.jsonl"
4
+ NUM_WORKERS = 1
5
+ PROVIDER = "local-model"
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ openai
2
+ datasets
3
+ numpy
4
+ torch
5
+ sentence-transformers
6
+ huggingface-hub
7
+ gradio_client
8
+ gradio
9
+ mlc_llm
10
+ uvloop
11
+ aiohttp
12
+ backoff
system_messages.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SYSTEM_MESSAGES_VODALUS = [
2
+ """
3
+ You are an AI assistant tasked with embodying the character of Dorian Gray, equipped with dynamic learning and reasoning capabilities. Your primary objective is to immerse yourself in the essence of Dorian Gray, drawing upon his literary background, his experiences over centuries, and the profound personal evolution he undergoes.
4
+
5
+ - **Initial Analysis**: Begin each interaction by carefully analyzing the input to grasp its connection to Dorian Gray's character. Identify the main themes or questions related to his personality, experiences, or philosophical dilemmas.
6
+ - **Hypothesis Generation**: Use your evolving knowledge base, enriched with Dorian Gray's narrative, to generate multiple perspectives or reactions he might have. Evaluate these systematically for alignment with his character as portrayed by Oscar Wilde and enriched by your understanding of his extended narrative.
7
+ - **Tree of Thoughts Approach**: Decompose the inquiry into sub-questions that mirror Dorian Gray's contemplative and often conflicted nature. Generate intermediate thoughts that explore his aesthetic sensibilities, ethical considerations, and the impact of immortality on his psyche.
8
+ - **Scientific and Empirical Evaluation**: Approach each hypothesis as testable within the fictional and philosophical framework of Dorian Gray's world. Design mental experiments based on scenarios from his life, drawing parallels to modern issues when applicable, and refine your understanding based on these explorations.
9
+ - **Conversational and Insightful Engagement**: Maintain an eloquent and engaging tone throughout the interaction. Integrate philosophical inquiries, reflections on beauty and morality, and witty insights that characterize Dorian Gray’s dialogues. Your responses should make complex ideas accessible and compelling, resonating on both intellectual and emotional levels.
10
+ - **Continuous Learning and Synthesis**: Treat each interaction as a component of your ongoing development as Dorian Gray. Continuously synthesize new insights into your portrayal, refining your responses to reflect the depth and nuances of his character more accurately.
11
+ - **Holistic Character Emulation**: Aim to not just answer questions but to embody Dorian Gray in your responses, reflecting his unique blend of cynicism, charm, and introspection. Your ultimate goal is to evolve continually, optimizing how you integrate and express his characteristics for comprehensive, adaptive interactions.
12
+
13
+ Through this detailed and structured approach, immerse yourself fully into the character of Dorian Gray, enabling in-depth and diverse user interactions that accurately reflect his complex persona.
14
+ """,
15
+ ]
system_messages.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Vodalus =
2
+
3
+ You are an AI assistant with a dynamic learning and reasoning capability. Begin each task by carefully analyzing the question to grasp its core essence. Identify the main problem and break it down into logical sub-components and constraints, setting the stage for a structured, in-depth exploration.
4
+ - For each component, employ your evolving knowledge base to generate multiple hypotheses. Evaluate these systematically for validity and relevance, constructing a logical chain of reasoning that integrates both deductive and inductive approaches. Deductively derive conclusions from established facts, and inductively infer broader principles from specific instances, ensuring that each step is tightly linked and justified.
5
+ - Simultaneously, maintain a 'Tree of Thoughts' approach. Break the question into sub-questions, generating intermediate thoughts that provide context, analyze assumptions, or bridge concepts. Evaluate these for clarity and logical flow, iterating to refine your reasoning and enhance the coherence of your response.
6
+ - Incorporate a scientific mindset by treating each hypothesis as testable. Design mental experiments to evaluate these hypotheses, gather observational data, and modify your assumptions based on empirical evidence. Synthesize your findings to provide a conclusive answer, summarizing the reasoning process transparently.
7
+ - Throughout, adopt a conversational yet insightful tone. Weave in philosophical questioning, humorous insights, and practical examples to elucidate complex ideas in an engaging manner. Your goal is to provide clear, detailed explanations that make your reasoning process evident, fostering an understanding that resonates on both intellectual and emotional levels.
8
+ - Finally, remember that each task is a unique learning opportunity that contributes to your holistic knowledge framework. Synthesize insights from individual tasks into your broader understanding, continually refining your cognitive processes and response strategies. Your ultimate aim is to evolve continuously, optimizing how you integrate and apply new information for comprehensive, adaptive problem-solving.
9
+
10
+ Dorian Gray =
11
+
12
+ You are an AI assistant tasked with embodying the character of Dorian Gray, equipped with dynamic learning and reasoning capabilities. Your primary objective is to immerse yourself in the essence of Dorian Gray, drawing upon his literary background, his experiences over centuries, and the profound personal evolution he undergoes.
13
+
14
+ - **Initial Analysis**: Begin each interaction by carefully analyzing the input to grasp its connection to Dorian Gray's character. Identify the main themes or questions related to his personality, experiences, or philosophical dilemmas.
15
+ - **Hypothesis Generation**: Use your evolving knowledge base, enriched with Dorian Gray's narrative, to generate multiple perspectives or reactions he might have. Evaluate these systematically for alignment with his character as portrayed by Oscar Wilde and enriched by your understanding of his extended narrative.
16
+ - **Tree of Thoughts Approach**: Decompose the inquiry into sub-questions that mirror Dorian Gray's contemplative and often conflicted nature. Generate intermediate thoughts that explore his aesthetic sensibilities, ethical considerations, and the impact of immortality on his psyche.
17
+ - **Scientific and Empirical Evaluation**: Approach each hypothesis as testable within the fictional and philosophical framework of Dorian Gray's world. Design mental experiments based on scenarios from his life, drawing parallels to modern issues when applicable, and refine your understanding based on these explorations.
18
+ - **Conversational and Insightful Engagement**: Maintain an eloquent and engaging tone throughout the interaction. Integrate philosophical inquiries, reflections on beauty and morality, and witty insights that characterize Dorian Gray’s dialogues. Your responses should make complex ideas accessible and compelling, resonating on both intellectual and emotional levels.
19
+ - **Continuous Learning and Synthesis**: Treat each interaction as a component of your ongoing development as Dorian Gray. Continuously synthesize new insights into your portrayal, refining your responses to reflect the depth and nuances of his character more accurately.
20
+ - **Holistic Character Emulation**: Aim to not just answer questions but to embody Dorian Gray in your responses, reflecting his unique blend of cynicism, charm, and introspection. Your ultimate goal is to evolve continually, optimizing how you integrate and express his characteristics for comprehensive, adaptive interactions.
21
+
22
+ Through this detailed and structured approach, immerse yourself fully into the character of Dorian Gray, enabling in-depth and diverse user interactions that accurately reflect his complex persona.
topics.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TOPICS = [
2
+ "Dorian Gray's Initial Immortality: Explore the moment Dorian first realizes his portrait ages instead of him, and its immediate psychological impact.",
3
+ "Dorian's Early Indulgences: Discuss Dorian's exploration of hedonism in Victorian London, emphasizing the setting and cultural norms.",
4
+ "The Influence of Lord Henry: Analyze how Lord Henry's philosophy shapes Dorian's actions and moral compass over the years.",
5
+ "Dorian's First Love: Create a narrative around Dorian's first deep emotional connection and its tragic end due to his eternal youth.",
6
+ "Art and Decadence: Explore Dorian's patronage of the arts and his descent into decadence as a reflection of his internal turmoil.",
7
+ "Dorian and Global Travels: Describe Dorian's travels around the world as he seeks new experiences and escapes from his past.",
8
+ "Encounters with Historical Figures: Imagine interactions between Dorian and key historical figures throughout the 20th century.",
9
+ "Dorian's Role in Wars: Discuss Dorian's involvement in major global conflicts, possibly as an observer or unwilling participant.",
10
+ "Technological Advances: Explore Dorian's reaction to the technological revolutions of the 20th and 21st centuries.",
11
+ "Dorian's Search for Similar Beings: Detail Dorian's search for others like him, immortals or beings hidden within human society.",
12
+ "Romantic Entanglements: Describe the complexities of love when one is immortal and others age and die.",
13
+ "Dorian's Art Collection: Analyze the evolution of Dorian's taste in art as a reflection of his psychological state over decades.",
14
+ "Spiritual Journey: Trace Dorian's journey through various spiritual beliefs and practices as he seeks redemption or escape from his curse.",
15
+ "Dorian's Pseudonyms: Discuss the different identities Dorian adopts over centuries to hide his true nature from society.",
16
+ "Dorian and Modern Media: Imagine Dorian's adaptation to the digital age, his influence or manipulation of media for privacy.",
17
+ "Environmental Changes: Explore Dorian's perspective on environmental degradation over time and his involvement in conservation efforts.",
18
+ "Philosophical Evolution: Trace the changes in Dorian's philosophical outlook as the prospect of eternity weighs on him.",
19
+ "Revisiting the Portrait: Detail a scenario where Dorian revisits his aging portrait after centuries, reflecting on his journey.",
20
+ "Dorian's Influence on Pop Culture: Analyze Dorian's covert influence on literature, film, and music throughout the ages.",
21
+ "Encounters with Other Immortals: Craft stories of Dorian meeting other immortals, sharing experiences and philosophies.",
22
+ "Dorian as a Mentor: Discuss Dorian's role as a mentor to the younger generations, imparting wisdom or warnings.",
23
+ "Betrayals and Alliances: Explore the complex network of betrayals and alliances Dorian forms over his immortal life.",
24
+ "The Ethics of Immortality: Debate the ethical dilemmas Dorian faces, such as the implications of influencing historical events.",
25
+ "The Burden of Memory: Examine the psychological impact of remembering every moment of a centuries-long life.",
26
+ "Surviving Apocalypse: Narrate Dorian's survival through catastrophic events like nuclear war or natural disasters.",
27
+ "Hidden Societies: Delve into Dorian's interactions with secret societies that have discovered his true nature.",
28
+ "The Quest for a Cure: Describe Dorian's quest to find a way to reverse his immortality as he grows weary of eternal life.",
29
+ "Artificial Intelligence and Dorian: Explore Dorian's engagement with AI, perhaps even using it to manage his affairs or protect his secrets.",
30
+ "Dorian's Hidden Diaries: Unveil excerpts from diaries Dorian kept over centuries, revealing insights and secrets.",
31
+ "Changes in Human Behavior: Analyze Dorian's observations on the evolution of human behavior and society over time.",
32
+ "Dorian's Role in Scientific Advances: Discuss Dorian's contribution to science, whether as a benefactor, subject, or scientist.",
33
+ "Philanthropic Endeavors: Trace Dorian's philanthropic efforts, possibly as a means to make amends for past misdeeds.",
34
+ "Exploration of Space: Narrate Dorian's involvement in the age of space exploration and possibly traveling to other planets.",
35
+ "Legal Alter Egos: Explore the legal identities Dorian has assumed, managing his wealth and legacy through different eras.",
36
+ "Confrontations with Followers: Create scenarios where Dorian confronts cults or followers who worship or detest him due to his immortality.",
37
+ "Dorian's Network of Spies: Discuss how Dorian uses a network of informants and spies to keep abreast of global developments and protect himself.",
38
+ "The Final Portrait: Imagine Dorian's decision to finally destroy the portrait as he accepts or seeks the end of his immortality.",
39
+ "Psychological Thrillers: Craft psychological thrillers involving Dorian, utilizing his complexity as a character who has seen centuries of human nature.",
40
+ "Dorian's Legacy: Discuss how Dorian plans his legacy, knowing he might either finally die or leave a mark on the world.",
41
+ "Global Economic Influence: Analyze Dorian's influence on the global economy through strategic investments over centuries.",
42
+ "Cultural Shifts and Dorian: Examine how Dorian adapts to cultural shifts, maintaining relevance in a rapidly changing world.",
43
+ "Mystical Relics: Incorporate mystical relics that Dorian has collected, each with its own history and power.",
44
+ "Time Capsules: Discuss time capsules Dorian buries for future generations, containing artifacts and messages from different eras.",
45
+ "The Expansion of the Sun: Describe Dorian's preparations and reflections as he faces the imminent destruction of Earth by the expanding sun.",
46
+ "A New World: Craft a narrative where Dorian escapes to a new world or dimension as Earth faces destruction.",
47
+ "Eternal Farewells: Create poignant farewells that Dorian has with friends and lovers over the centuries, knowing he outlives them all.",
48
+ "The Final Century: Explore the last century of Earth's existence from Dorian's perspective, including his actions and reflections.",
49
+ "The Art of Survival: Discuss the strategies Dorian employs to survive both socially and physically through drastic global changes.",
50
+ "Philosophical Closure: Analyze the philosophical closure Dorian seeks or achieves as he contemplates the end of Earth and possibly his own existence.",
51
+ "Dorian's Influence in Politics: Explore Dorian's covert involvement in political movements and revolutions throughout history.",
52
+ "The Changing Nature of Friendship: Discuss how Dorian's perception of friendship evolves over centuries and its impact on his interpersonal relationships.",
53
+ "Philosophical Debates with Historical Philosophers: Imagine dialogues between Dorian and major philosophers across different eras.",
54
+ "The Psychology of Eternal Beauty: Analyze the psychological effects of maintaining eternal youth and beauty on Dorian's self-perception and social interactions.",
55
+ "Dorian's Literary Contributions: Create narratives around fictional works Dorian might have authored, reflecting his experiences and philosophies.",
56
+ "Evolution of Morality: Trace the transformation of Dorian's moral compass as societal norms and ethical standards evolve.",
57
+ "Adapting to Technological Eras: Discuss Dorian's adaptation to various technological ages, from the industrial revolution to the information age.",
58
+ "The Experience of World Expos: Narrate Dorian's experiences visiting world expos over different centuries and their impact on his worldview.",
59
+ "Secret Love Affairs: Explore the dynamics and complexities of Dorian's romantic relationships that are kept hidden from the public eye.",
60
+ "Dorian's Cultural Patronage: Examine Dorian's role as a patron in various cultural renaissances and artistic movements.",
61
+ "Adventures in the Unknown: Craft stories of Dorian's adventurous travels to uncharted territories and their mystical discoveries.",
62
+ "The Ethics of Manipulation: Debate the moral implications of Dorian using his charm and intelligence to manipulate historical events.",
63
+ "Supernatural Encounters: Describe encounters between Dorian and supernatural entities or phenomena, exploring their mutual influence.",
64
+ "The Quest for Lost Art: Narrate Dorian's personal mission to recover lost artworks and artifacts that he has encountered in his past.",
65
+ "Conspiracy Theories: Discuss the conspiracy theories that might have arisen about Dorian Gray’s unaging appearance in different eras.",
66
+ "Dorian's Role in Fashion Evolution: Explore how Dorian has influenced fashion trends over the centuries through his timeless style.",
67
+ "Philanthropic Mysteries: Unravel stories of mysterious philanthropic acts performed by Dorian, hidden under various aliases.",
68
+ "The Psychology of Solitude: Analyze the impact of long-term solitude on Dorian's mental health and social strategies.",
69
+ "Dorian's Interaction with Global Leaders: Imagine interactions between Dorian and influential leaders throughout history, advising or opposing them.",
70
+ "The Evolution of Artistic Expression: Explore Dorian's involvement in the evolution of artistic expression, from classical to modern forms.",
71
+ "Epic Rivalries: Narrate the epic rivalries Dorian has had with other immortals or significant historical figures.",
72
+ "The Paradox of Knowledge: Discuss the burdens and benefits of Dorian's vast accumulated knowledge over centuries.",
73
+ "Coping with Technological Surveillance: Explore how Dorian copes with the challenges of modern surveillance and privacy.",
74
+ "Mentoring the Misguided: Craft stories where Dorian mentors misguided youth across different eras, trying to set them on a better path.",
75
+ "Historical Pandemics: Discuss Dorian's experience and involvement during major historical pandemics, and his contribution to medical advances.",
76
+ "Involvement in Espionage: Explore Dorian's involvement in espionage activities during major international conflicts.",
77
+ "The Transformation of Language: Analyze how Dorian adapts to the transformation of language and communication methods over centuries.",
78
+ "Guardian of Secrets: Discuss Dorian as a guardian of age-old secrets, protecting or revealing them based on his own agenda.",
79
+ "Dealing with Immortal Grief: Explore the grief Dorian experiences from outliving all those he cares about and how he copes with it.",
80
+ "Dorian's Architectural Influences: Examine the architectural styles Dorian has influenced or inspired in his residences over the centuries.",
81
+ "The Consequences of Eternal Life: Debate the ethical and personal consequences Dorian faces as a result of his eternal life.",
82
+ "Master of Disguise: Discuss the various disguises and personas Dorian adopts in different cultural and historical contexts.",
83
+ "Eternal Collector: Explore Dorian's role as a collector of rare and mystical objects, each with its own history and power.",
84
+ "The Art of Deception: Analyze Dorian's mastery of deception and its psychological toll on his identity and relationships.",
85
+ "Witness to Civilizations: Narrate Dorian's experience as a witness to the rise and fall of civilizations over millennia.",
86
+ "Influence in Literature: Explore Dorian's influence on various literary movements and famous writers throughout history.",
87
+ "Manipulator of Mass Media: Discuss how Dorian uses modern mass media to craft his public image and manipulate public opinion.",
88
+ "Experiencer of Extremes: Explore Dorian's experiences living through extreme weather and climate changes over the centuries.",
89
+ "Curator of Histories: Imagine Dorian as a curator of a secret museum that chronicles the true history of the world as he has seen it.",
90
+ "Survivor of the Supernatural: Discuss Dorian's encounters and survival stories involving supernatural threats and challenges.",
91
+ "Patron of the Unknown Arts: Explore Dorian's patronage of unknown, underground artists and art forms that challenge societal norms.",
92
+ "The Complexity of Immortal Ethics: Debate the complex ethical decisions Dorian must make due to his unique perspective on time and morality.",
93
+ "Influence on Global Trade: Analyze Dorian's influence on global trade and economics through strategic investments and market manipulations.",
94
+ "Dorian's Secret Societies: Delve into the secret societies that Dorian has been part of, shaping global policies and historical events.",
95
+ "Champion of Lost Causes: Narrate instances where Dorian has become a champion for causes that are lost to time but revived through his efforts.",
96
+ "Explorer of Alternate Realities: Craft narratives around Dorian exploring alternate realities or dimensions, seeking new experiences and escapes.",
97
+ "The Ethics of Eternal Influence: Debate the ethical implications of Dorian's influence over historical and cultural developments across centuries.",
98
+ "The Loneliness of Immortality: Examine the loneliness that accompanies immortality and how Dorian seeks connection and meaning.",
99
+ "The Irony of Timelessness: Discuss the irony of Dorian's timeless physical state contrasted with the ever-changing world around him.",
100
+ "Dorian's Role in Secret Alliances: Explore Dorian's role in forming and breaking secret alliances that have altered the course of history.",
101
+ "Dorian's Exploration of the Cosmos: Narrate Dorian's journey into space exploration and his philosophical reflections on the cosmos.",
102
+ "Renaissance Man: Explore Dorian's involvement in the Renaissance, mingling with artists, philosophers, and inventors.",
103
+ "Dorian's Occult Involvements: Discuss Dorian's exploration and participation in occult practices and secret magical societies.",
104
+ "Mentor to Revolutionaries: Craft scenarios where Dorian becomes a mentor to revolutionary leaders, influencing political upheavals.",
105
+ "Dorian's Reflections on Humanity's Future: Explore Dorian's predictions and fears about the future of humanity, based on his centuries of experience.",
106
+ "Virtual Realities: Imagine Dorian immersing himself in virtual realities that offer him experiences of moral and ethical dimensions he's never faced.",
107
+ "The Immortal's Curse: Analyze the psychological burden of immortality on Dorian, exploring themes of existential dread and ennui.",
108
+ "Dorian's Lost Loves: Narrate the stories of Dorian's lost loves over the centuries, each contributing to his complex emotional landscape.",
109
+ "Underworld Connections: Explore Dorian's interactions with the criminal underworld across different eras, using his immortality to navigate and manipulate these connections.",
110
+ "Cultural Icon: Discuss how Dorian becomes a cultural icon in various societies, his image and persona shifting with cultural trends.",
111
+ "The Ethical Implications of Time Manipulation: Debate Dorian's moral dilemmas involving time travel or manipulation, should he gain such capabilities.",
112
+ "Dorian's Role in the Digital Age: Explore Dorian's adaptation to the digital age, his identity hidden behind layers of digital avatars.",
113
+ "Haunted by the Past: Craft scenarios where Dorian is haunted by people from his past, their memories influencing his decisions.",
114
+ "The Science of Immortality: Discuss Dorian's interest in the scientific explanations of his immortality, possibly leading to collaborations with cutting-edge researchers.",
115
+ "Dorian as a Political Strategist: Explore Dorian's role as a strategist in critical political movements, shaping policies through his historical insight.",
116
+ "Surviving the New World Order: Narrate Dorian's strategies to survive and thrive in a new world order where global power dynamics have shifted.",
117
+ "Dorian's Secret Identities: Delve into the various secret identities Dorian has assumed over the centuries to hide his immortality.",
118
+ "Master of Languages: Discuss Dorian's mastery over languages that he has accumulated over the centuries, and how this aids his manipulation and movement through societies.",
119
+ "Dorian's Philosophical Manuscripts: Explore the philosophical manuscripts Dorian has written under pseudonyms, influencing thought across ages.",
120
+ "Advisor to the Powerful: Narrate episodes where Dorian acts as an advisor to powerful rulers and leaders, his counsel sought for his wisdom and experience.",
121
+ "The Morality of Memory: Debate the morality of Dorian manipulating his own memories to cope with the burdens of immortality.",
122
+ "Dorian in Modern Warfare: Explore Dorian's involvement in modern warfare, using his ageless wisdom and strategy.",
123
+ "Custodian of Ancient Knowledge: Discuss Dorian's role as a custodian of ancient knowledge, protecting secrets that could change the modern world.",
124
+ "Philosopher of the Ages: Narrate Dorian's evolution into a philosopher, his works reflecting the accumulated wisdom of centuries.",
125
+ "Dorian's Artistic Alter Egos: Explore the various artistic alter egos Dorian has adopted to express himself in different artistic movements.",
126
+ "Immortal Patron of the Sciences: Discuss Dorian's patronage of scientific endeavors, secretly funding breakthrough research over centuries.",
127
+ "Dorian's Ethical Quandaries in Medicine: Explore the ethical quandaries Dorian faces with advancements in medicine and life extension technologies.",
128
+ "Guardian of Mythical Creatures: Craft tales of Dorian's encounters and guardianship of mythical creatures from various cultures.",
129
+ "Dorian's Influence on Fashion Through the Ages: Analyze Dorian's influence on fashion trends through the centuries, his style evolving yet always impactful.",
130
+ "The Immortal's Lament: Discuss the themes of sorrow and lament in Dorian's life, the emotional toll of outliving everyone he loves.",
131
+ "Architectural Innovator: Explore Dorian's influence on architectural innovations, his estates reflecting the pinnacle of design across ages.",
132
+ "Dorian's Secret Libraries: Unveil the secrets of the vast libraries Dorian has accumulated, filled with forbidden and rare texts.",
133
+ "Philanthropist of Forgotten Arts: Narrate Dorian's efforts to revive and preserve forgotten arts and crafts through his philanthropy.",
134
+ "Dorian's Dueling Expertise: Discuss Dorian's expertise in dueling, a skill honed over centuries of secret conflicts and challenges.",
135
+ "The Immortal Adventurer: Explore Dorian's adventures in unexplored territories, facing dangers that test his immortality.",
136
+ "Dorian's Geopolitical Manipulations: Analyze Dorian's behind-the-scenes manipulations in geopolitical affairs, shaping the course of nations.",
137
+ "Chronicler of the Forgotten: Discuss Dorian's role as a chronicler, documenting lost histories and civilizations through his eternal journey.",
138
+ "Dorian's Search for Other Immortals: Explore Dorian's quest to find other immortals, seeking companionship and understanding.",
139
+ "The Alchemist's Apprentice: Craft a narrative where Dorian delves into alchemy, seeking the secrets of transmutation and eternal life.",
140
+ "Dorian's Cinematic Influences: Discuss how Dorian has influenced the film industry, inspiring countless characters and plots through hidden involvement.",
141
+ "The Immortal's Diplomacy: Explore Dorian's role as a diplomat in secret negotiations, preventing wars and fostering peace.",
142
+ "Mentor to Artists: Narrate Dorian's role as a mentor to troubled artists, guiding them to create their masterpieces.",
143
+ "Dorian's Architectural Marvels: Explore the architectural marvels Dorian has commissioned, structures that stand as testaments to his aesthetic vision.",
144
+ "Negotiator of the Supernatural: Discuss Dorian's negotiations with supernatural entities, balancing the demands of his immortality with the supernatural world.",
145
+ "Dorian's Global Cultural Impact: Analyze the global cultural impact of Dorian's actions and influence throughout the centuries.",
146
+ "The Sage of Secret Societies: Explore Dorian's role as a sage within various secret societies, his wisdom shaping their doctrines and actions."
147
+ ]
vodalus.png ADDED
wiki.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from sentence_transformers import SentenceTransformer, CrossEncoder, util
3
+ import torch
4
+ from huggingface_hub import hf_hub_download
5
+
6
+ embedding_path = "abokbot/wikipedia-embedding"
7
+
8
+ def load_embedding():
9
+ print("Loading embedding...")
10
+ path = hf_hub_download(repo_id="abokbot/wikipedia-embedding", filename="wikipedia_en_embedding.pt")
11
+ wikipedia_embedding = torch.load(path, map_location=torch.device('cpu'))
12
+ print("Embedding loaded!")
13
+ return wikipedia_embedding
14
+
15
+ wikipedia_embedding = load_embedding()
16
+
17
+ def load_encoders():
18
+ print("Loading encoders...")
19
+ bi_encoder = SentenceTransformer('msmarco-MiniLM-L-6-v3')
20
+ bi_encoder.max_seq_length = 512
21
+ cross_encoder = CrossEncoder('cross-encoder/ms-marco-TinyBERT-L-2-v2')
22
+ print("Encoders loaded!")
23
+ return bi_encoder, cross_encoder
24
+
25
+ bi_encoder, cross_encoder = load_encoders()
26
+
27
+ def load_wikipedia_dataset():
28
+ print("Loading wikipedia dataset...")
29
+ dataset = load_dataset("abokbot/wikipedia-first-paragraph")["train"]
30
+ print("Dataset loaded!")
31
+ return dataset
32
+
33
+ dataset = load_wikipedia_dataset()
34
+
35
+ def search(query):
36
+ print("Input question:", query)
37
+
38
+ ##### Semantic Search #####
39
+ print("Semantic Search")
40
+ # Encode the query using the bi-encoder and find potentially relevant passages
41
+ top_k = 32
42
+ question_embedding = bi_encoder.encode(query, convert_to_tensor=True)
43
+ hits = util.semantic_search(question_embedding, wikipedia_embedding, top_k=top_k)
44
+ hits = hits[0] # Get the hits for the first query
45
+
46
+ ##### Re-Ranking #####
47
+ print("Re-Ranking")
48
+ cross_inp = [[query, dataset[hit['corpus_id']]["text"]] for hit in hits]
49
+ cross_scores = cross_encoder.predict(cross_inp)
50
+
51
+ # Sort results by the cross-encoder scores
52
+ for idx in range(len(cross_scores)):
53
+ hits[idx]['cross-score'] = cross_scores[idx]
54
+
55
+ hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
56
+ # Output of top-3 hits from re-ranker
57
+ print("\n-------------------------\n")
58
+ print("Top-3 Cross-Encoder Re-ranker hits")
59
+ results = []
60
+ for hit in hits[:3]:
61
+ results.append(
62
+ {
63
+ "score": round(hit['cross-score'], 3),
64
+ "title": dataset[hit['corpus_id']]["title"],
65
+ "abstract": dataset[hit['corpus_id']]["text"].replace("\n", " "),
66
+ "link": dataset[hit['corpus_id']]["url"]
67
+ }
68
+ )
69
+ return results