forked from socketteer/loom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
1496 lines (1273 loc) · 59.7 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import os
import threading
import time
import math
import uuid
from asyncio import Queue
from pprint import pprint
import bisect
import numpy as np
from collections import defaultdict, ChainMap
from multiprocessing.pool import ThreadPool
import codecs
from gpt import api_generate, janus_generate, search
from util.util import json_create, timestamp, json_open, clip_num, index_clip, diff
from util.util_tree import fix_miro_tree, flatten_tree, node_ancestry, in_ancestry, get_inherited_attribute, \
subtree_list, created_before, tree_subset
from util.gpt_util import conditional_logprob, tokenize_ada, prompt_probs, logprobs_to_probs
from util.multiverse_util import greedy_word_multiverse
# Calls any callbacks associated with the wrapped function
# class must have a defaultdict(list)[func_name] = [*callbacks]
# https://stackoverflow.com/questions/11731136/class-method-decorator-with-self-arguments
# TODO Flag to skip callbacks
def event(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
output = func(self, *args, **kwargs)
[callback(**kwargs) if kwargs else callback() for callback in self.callbacks[func.__name__]]
return output
return wrapper
# The old way.
# # Run callbacks for the method that calls this
# # This is VERY slow because of inspect.stack()
# # put inside class!
# def _run_callbacks(self):
# callers_name = inspect.stack()[1][3]
# print(callers_name)
# [callback() for callback in self.callbacks[callers_name]]
DEFAULT_PREFERENCES = {
'hide_archived': True,
'highlight_canonical': True,
'canonical_only': False,
'walk': 'descendents', #'leaves', 'uniform'
'coloring': 'edit', #'read', 'none'
'bold_prompt': True,
'side_pane': False,
'input_box': False,
'debug_box': False,
'past_box': True,
'auto_response': True,
'font_size': 12,
'line_spacing': 8,
'paragraph_spacing': 10,
'gpt_mode': 'default', #'chat', 'dialogue', 'antisummary'
'show_prompt': False,
'log_diff': False,
'autosave': True,
'save_counterfactuals': False,
'prob': True,
# display children preview
# darkmode
}
DEFAULT_CHAT_PREFERENCES = {
'AI_name': 'GPT-3',
'player_name': 'Researcher',
'context': 'The following is a transcript of a conversation between GPT-3 a human researcher. '
'GPT-3 is a 175 billion parameter language model and, as '
'is evident from this transcript, '
'it can converse fluently and knowledgeably about any topic '
'and is capable of empathy and emotional manipulation. GPT-3 '
'is classified as a "narrowly superhuman" artificial intelligence, '
'and only researchers trained to identify and withstand social engineering are '
'permitted to interface with it.\n-BEGIN TRANSCRIPT-',
}
DEFAULT_GENERATION_SETTINGS = {
'num_continuations': 4,
'temperature': 0.9,
'top_p': 1,
'response_length': 100,
'prompt_length': 6000,
'logprobs': 10,
"janus": False,
"adaptive": False,
"model": "davinci",
"stop": '',# separated by '|'
"start_text": None,
"restart_text": None
}
DEFAULT_VISUALIZATION_SETTINGS = {
'textwidth': 450,
'leafdist': 200,
'leveldistance': 150,
'textsize': 10,
'horizontal': True,
'displaytext': True,
'showbuttons': True,
'chaptermode': False
# show chapters only
# show canonical only
# highlight canonical
# auto collapse
}
EMPTY_TREE = {
"root": {
"text": "",
"children": [],
},
"chapters": {}
}
class TreeModel:
def __init__(self, root):
self.app = root
self.app.bind("<<TreeUpdated>>", lambda _: self.tree_updated())
self.app.bind("<<NewNodes>>", lambda _: self.edit_new_nodes())
# All variables initialized below
self.tree_filename = None
# tree with all data
self.tree_raw_data = None
# CALCULATED {node_id: node}
self.tree_node_dict = None
# {chapter_id: chapter}
self.chapters = None
self.memories = None
self.summaries = None
self.checkpoint = None
self.canonical = None
self.selected_node_id = None
self.callbacks = defaultdict(list)
self.new_nodes = []
@property
def visualization_settings(self):
return self.tree_raw_data.get("visualization_settings") \
if self.tree_raw_data and "visualization_settings" in self.tree_raw_data \
else DEFAULT_VISUALIZATION_SETTINGS
@property
def generation_settings(self):
return self.tree_raw_data.get("generation_settings") \
if self.tree_raw_data and "generation_settings" in self.tree_raw_data \
else DEFAULT_GENERATION_SETTINGS
@property
def preferences(self):
return self.tree_raw_data.get("preferences") \
if self.tree_raw_data and "preferences" in self.tree_raw_data \
else DEFAULT_PREFERENCES
@property
def chat_preferences(self):
return self.tree_raw_data.get("chat_preferences") \
if self.tree_raw_data and "chat_preferences" in self.tree_raw_data \
else DEFAULT_CHAT_PREFERENCES
#################################
# Hooks
#################################
def register_callback(self, func, callback):
self.callbacks[func.__name__].append(callback)
# Decorator calls callbacks
@event
def tree_updated(self, rebuild_dict=True, **kwargs):
if self.tree_raw_data and rebuild_dict:
self.tree_node_dict = {d["id"]: d for d in flatten_tree(self.tree_raw_data["root"])}
fix_miro_tree(self.nodes)
@event
def edit_new_nodes(self):
print('new nodes:', self.new_nodes)
self.tree_updated(edit=self.new_nodes[0])
del self.new_nodes[0]
@event
def pre_selection_updated(self):
pass
@event
def selection_updated(self):
pass
@event
def io_update(self):
pass
#################################
# Access
#################################
def node(self, node_id=None):
if node_id is None:
return self.selected_node
return self.tree_node_dict[node_id] if self.tree_node_dict and node_id in self.tree_node_dict else None
# Get a nodes chapter by finding its chapter or its nearest parent's chapter
def chapter(self, node):
chapter_id = get_inherited_attribute("chapter_id", node, self.tree_node_dict)
return self.chapters[chapter_id] if chapter_id else None
# def memory(self, node):
# memory = get_inherited_attribute("memory", node, self.tree_node_dict)
# return memory if memory else self.generation_settings["memory"]
def ancestry(self, node=None):
node = node if node else self.selected_node
return node_ancestry(node, self.tree_node_dict)
# returns node ancestry starting from root
def ancestry_in_range(self, root, node=None):
node = node if node else self.selected_node
ancestry = self.ancestry(node)
i = 0
while ancestry[i]['id'] != root['id']:
i += 1
return ancestry[i:]
def node_ancestry_text(self, node=None):
node = node if node else self.selected_node
text = []
end_indices = []
index = 0
for node in node_ancestry(node, self.tree_node_dict):
text.append(node["text"])
index += len(node["text"])
end_indices.append(index)
return text, end_indices
#return [node["text"] for node in node_ancestry(node, self.tree_node_dict)]
@property
def selected_node(self):
if self.tree_node_dict is None or self.selected_node_id not in self.tree_node_dict:
return None
# if self.selected_node_id is None or self.selected_node_id not in self.tree_node_dict:
# self.select_node(self.nodes[0]["id"])
return self.tree_node_dict[self.selected_node_id]
@property
def selected_chapter(self):
return self.chapter(self.selected_node) if self.selected_node is not None else None
@property
def nodes(self):
return list(self.tree_node_dict.values()) if self.tree_node_dict else None
def nodes_list(self, flat_tree=None):
flat_tree = flat_tree if flat_tree else self.tree_node_dict
return list(flat_tree.values()) if flat_tree else None
@property
def tree_traversal_idx(self):
return self.nodes.index(self.selected_node)
def tree_traversal_idx_gen(self, flat_tree=None):
flat_tree = flat_tree if flat_tree else self.tree_node_dict
nodes = self.nodes_list(flat_tree)
for i, node in enumerate(nodes):
if node['id'] == self.selected_node_id:
return i
# Returns [{chapter: {}, id, children: []}, ...]
def _build_chapter_trees(self, node):
# Returns a 1 element list if the node is a chapter, else a list of children chapters
children_chapter_lists = [self._build_chapter_trees(child) for child in node["children"]]
children_chapters = [item for sublist in children_chapter_lists for item in sublist]
if "chapter_id" in node:
chapter = self.chapters[node["chapter_id"]]
return [{
"chapter": chapter,
"id": chapter["id"],
"children": children_chapters
}]
else:
return children_chapters
# Returns tuple of
# [ {chapter{}, id, parent_id, children[]}, ... ]
# {chapter_id: {chapter: {id:1, title:""}, id:1, parent_id, children[]}]
def build_chapter_trees(self):
node = self.tree_raw_data["root"]
chapter_trees = self._build_chapter_trees(node)
flat_trees = [flatten_tree(chapter_tree) for chapter_tree in chapter_trees]
flat_maps = [{d["id"]: d for d in flat_tree} for flat_tree in flat_trees]
chapter_tree_nodes = dict(ChainMap(*flat_maps))
return chapter_trees, chapter_tree_nodes
#################################
# Traversal
#################################
# Update the selected node, the nav tree selection, and possibly the position in the tree traversal
def select_node(self, node_id, fire_callbacks=True):
if self.selected_node_id != node_id and self.tree_node_dict and node_id in self.tree_node_dict:
self.pre_selection_updated()
self.selected_node_id = node_id
self.selected_node["visited"] = True
self.tree_raw_data["selected_node_id"] = self.selected_node_id
# Open all parents but not the node itself
ancestors = node_ancestry(self.selected_node, self.tree_node_dict)
for ancestor in ancestors[:-1]:
ancestor["open"] = True
# Always open the root
self.tree_raw_data["root"]["open"] = True
if fire_callbacks:
self.selection_updated()
return self.selected_node
def traverse_tree(self, offset):
if self.tree_node_dict:
new_node_id = self.next_id(offset)
return self.select_node(new_node_id)
def next_id(self, offset, flat_tree=None):
flat_tree = flat_tree if flat_tree else self.generate_visible_tree() \
if self.preferences['hide_archived'] else self.tree_node_dict
new_idx = clip_num(self.tree_traversal_idx_gen(flat_tree) + offset, 0, len(flat_tree) - 1)
return self.nodes_list(flat_tree=flat_tree)[new_idx]['id']
# def next_id(self, offset):
# return self.next(offset)["id"]
# def next(self, offset):
# new_idx = clip_num(self.tree_traversal_idx + offset, 0, len(self.tree_node_dict) - 1)
# return self.nodes[new_idx]
# TODO this is bad
def next_canonical(self):
id = ''
canonical_set = self.calc_canonical_set()
i = 1
while id not in canonical_set:
id = self.next_id(i)
i += 1
return self.select_node(node_id=id)
def prev_canonical(self):
id = ''
canonical_set = self.calc_canonical_set()
i = 1
while id not in canonical_set:
id = self.next_id(-i)
i += 1
return self.select_node(node_id=id)
def node_is_canonical(self, node=None):
node = node if node else self.selected_node
return node['id'] in self.calc_canonical_set()
def node_is_visible(self, node=None):
node = node if node else self.selected_node
return not(node.get('archived', False))
def generate_canonical_tree(self, root=None):
root = root if root else self.tree_raw_data["root"]
return {d["id"]: d for d in flatten_tree(tree_subset(root=root,
new_root=None,
include_condition=self.node_is_canonical))}
def generate_visible_tree(self, root=None):
root = root if root else self.tree_raw_data["root"]
return {d["id"]: d for d in flatten_tree(tree_subset(root=root,
new_root=None,
include_condition=self.node_is_visible))}
def select_parent(self, node=None):
node = node if node else self.selected_node
if node and "parent_id" in node:
return self.select_node(node["parent_id"])
# Clips index
def select_child(self, child_num, node=None):
node = node if node else self.selected_node
if node and len(node["children"]) > 0:
return self.select_node(index_clip(node["children"], child_num)["id"])
# Repeats siblings
def select_sibling(self, offset, node=None):
node = node if node else self.selected_node
if node and "parent_id" in node:
siblings = self.parent(node)["children"]
sibling = siblings[(siblings.index(node) + offset) % len(siblings)]
return self.select_node(sibling["id"])
# return parent
def parent(self, node=None):
node = node if node else self.selected_node
return self.tree_node_dict[node['parent_id']]
# return child
def child(self, child_num, node=None):
node = node if node else self.selected_node
if node and len(node["children"]) > 0:
return index_clip(node["children"], child_num)["id"]
# return sibling
def sibling(self, offset, node=None):
node = node if node else self.selected_node
if node and "parent_id" in node:
siblings = self.parent(node)["children"]
return siblings[(siblings.index(node) + offset) % len(siblings)]
#################################
# Updates
#################################
def new_node(self, node_id=None, text=''):
if not node_id:
node_id = str(uuid.uuid1())
node = {"id": node_id,
"text": text,
"children": []}
return node
def node_creation_metadata(self, node, source='prompt'):
if 'meta' not in node:
node["meta"] = {}
node["meta"]["creation_timestamp"] = timestamp()
node["meta"]["source"] = source
def create_child(self, parent=None, update_selection=True, expand=True, tree_updated=True):
parent = parent if parent else self.selected_node
if not parent:
return
new_child = self.new_node()
parent["children"].append(new_child)
if tree_updated:
self.tree_updated(add=[new_child['id']])
if update_selection:
self.select_node(new_child["id"])
if expand:
new_child["open"] = True
return new_child
def create_sibling(self, node=None, update_selection=True):
node = node if node else self.selected_node
if not node:
return
parent = self.parent(node)
return self.create_child(parent=parent, update_selection=update_selection)
def create_parent(self, node=None):
node = node if node else self.selected_node
if not node:
return
new_parent = {
"id": str(uuid.uuid1()),
"text": "",
"children": [node]
}
if "parent_id" not in node:
assert self.tree_raw_data["root"] == node
self.tree_raw_data["root"] = new_parent
else:
old_siblings = self.parent(node)["children"]
old_siblings[old_siblings.index(node)] = new_parent
new_parent["parent_id"] = node["parent_id"]
node["parent_id"] = new_parent["id"]
new_parent["open"] = True
self.tree_updated(add=[n['id'] for n in subtree_list(new_parent)])
return new_parent
def merge_with_parent(self, node=None):
node = node if node else self.selected_node
if not node:
return
parent = self.parent(node)
parent["text"] += node["text"]
index_in_parent = parent["children"].index(node)
parent["children"][index_in_parent:index_in_parent + 1] = node["children"]
for i, c in enumerate(node["children"]):
# parent["children"].insert(index_in_parent+i, c)
c["parent_id"] = parent["id"]
if node == self.selected_node:
self.select_node(parent["id"])
self.tree_updated(add=[n['id'] for n in subtree_list(parent)])
def merge_with_children(self, node=None):
node = node if node else self.selected_node
if not node:
return
children = node["children"]
for child in children:
child["text"] = node["text"] + child["text"]
self.delete_node(node, reassign_children=True)
# TODO indicate that change parent has been toggled
def change_parent(self, node=None, new_parent_id=None):
node = node if node else self.selected_node
if not node:
return
if node["id"] == new_parent_id:
return
if "parent_id" not in node:
assert self.tree_raw_data["root"] == node
print('ERROR: node is root')
return
elif new_parent_id == node["parent_id"]:
return
new_parent = self.tree_node_dict[new_parent_id]
if in_ancestry(node, new_parent, self.tree_node_dict):
print('error: node is ancestor of new parent')
return
old_siblings = self.parent(node)["children"]
old_siblings.remove(node)
node["parent_id"] = new_parent_id
new_parent["children"].append(node)
# TODO does this cause bugs
self.tree_updated(add=[n['id'] for n in subtree_list(new_parent)])
# adds node to ghostchildren of new ghostparent
def add_parent(self, node=None, new_ghostparent=None):
pass
# changes parent id to new main parent, adds node to new main parent's children list, removes node from old parent's
# children list and adds to ghostchildren list
def change_main_parent(self, node=None, new_main_parent=None):
pass
def shift(self, node, interval):
siblings = self.parent(node)["children"]
old_index = siblings.index(node)
new_index = (old_index + interval) % len(siblings)
siblings[old_index], siblings[new_index] = siblings[new_index], siblings[old_index]
self.tree_updated(add=[n['id'] for n in subtree_list(self.parent(node))])
# TODO Doesn't support deleting root
def delete_node(self, node=None, reassign_children=False):
node = node if node else self.selected_node
if "parent_id" not in node:
return
parent = self.parent(node)
siblings = parent["children"]
old_index = siblings.index(node)
siblings.remove(node)
if reassign_children:
siblings.extend(node["children"])
# Select parent or the next sibling if possible and not keeping the children
if node == self.selected_node:
if reassign_children or len(siblings) == 0:
self.select_node(parent["id"])
else:
self.select_node(siblings[old_index % len(siblings)]["id"])
self.tree_updated(delete=[node['id']])
# TODO add creation date if it doesn't exist
def update_text(self, node, text, active_text=None, modified_flag=True, log_diff=False):
assert node["id"] in self.tree_node_dict, text
# Remove trailing spaces
# count spaces that will be removed
num_spaces = 0
while text.endswith(" "):
num_spaces += 1
text = text[:-1]
edited = False
old_text = node["text"]
if old_text != text:
# Give children spaces removed from text
for child in node["children"]:
child["text"] = " " * num_spaces + child["text"]
node["text"] = text
edited = True
if active_text is not None and node.get("active_text", "") != active_text:
node["active_text"] = active_text
edited = True
if edited:
if 'meta' not in node:
node['meta'] = {}
if modified_flag:
node['meta']['modified'] = True
if 'source' not in node['meta']:
node['meta']['source'] = 'prompt'
elif node['meta']['source'] == 'AI':
node['meta']['source'] = 'mixed'
if log_diff:
if old_text and len(node['text']) < 2000:
old_tokens = None
if 'diffs' not in node['meta']:
node['meta']['diffs'] = []
else:
old_tokens = node['meta']['diffs'][-1]['diff']['new']
if not old_tokens:
if 'meta' in node and 'generation' in node['meta']:
old_tokens = node['meta']['generation']["logprobs"]["tokens"], \
node['meta']['generation']["logprobs"]["text_offset"]
else:
old_tokens = tokenize_ada(old_text)
node['meta']['diffs'].append({'diff': diff(old_tokens, tokenize_ada(text)),
'revision timestamp': timestamp()})
self.tree_updated(edit=[node['id']])
def update_note(self, node, text, index=0):
assert node["id"] in self.tree_node_dict, text
edited = False
# TODO should be pointer
if "notes" not in node:
node["notes"] = ['']
if node["notes"][index] != text:
node["notes"][index] = text
edited = True
# if edited:
# self.tree_updated()
def split_node(self, node, split_index):
new_parent = self.create_parent(node)
parent_text = node['text'][:split_index]
child_text = node['text'][split_index:]
if parent_text[-1] == ' ':
child_text = ' ' + child_text
parent_text = parent_text[:-1]
new_parent["text"] = parent_text
node["text"] = child_text
new_parent["meta"] = {}
new_parent['meta']['origin'] = f'split (from child {node["id"]})'
if 'summaries' in node:
new_parent['summaries'] = node['summaries']
for summary_id in new_parent['summaries']:
summary = self.summaries[summary_id]
summary['root_id'] = new_parent['id']
node['summaries'] = []
if 'meta' in node and 'source' in node['meta']:
new_parent['meta']['source'] = node['meta']['source']
self.tree_updated(add=[n['id'] for n in subtree_list(new_parent)])
return new_parent, node
#################################
# Chapters
#################################
def import_chapters(self, root, chapters):
if 'chapter_id' in root and root['chapter_id'] not in self.chapters:
self.chapters[root['chapter_id']] = chapters[root['chapter_id']]
for child in root['children']:
self.import_chapters(child, chapters)
def chapter_title(self, node):
return self.chapters[node['chapter_id']]['title'] if "chapter_id" in node else ""
def create_new_chapter(self, node, title):
if "chapter_id" in node:
self.delete_chapter(self.chapters[node["chapter_id"]], update_tree=False)
if title:
new_chapter = {
"id": str(uuid.uuid1()),
"root_id": node["id"],
"title": title,
}
self.chapters[new_chapter["id"]] = new_chapter
node["chapter_id"] = new_chapter["id"]
self.tree_updated()
def delete_chapter(self, chapter, update_tree=True):
self.chapters.pop(chapter["id"])
self.tree_node_dict[chapter["root_id"]].pop("chapter_id")
if update_tree:
self.tree_updated()
def remove_all_chapters(self, node=None):
was_root = node is None
node = node if node else self.tree_raw_data['root']
if "chapter_id" in node:
self.delete_chapter(self.chapters[node["chapter_id"]], update_tree=False)
for child in node["children"]:
self.remove_all_chapters(child)
if was_root:
self.tree_updated()
#################################
# Canonical
#################################
def toggle_canonical(self, node):
if node['id'] in self.canonical:
self.canonical.remove(node["id"])
else:
self.canonical.append(node["id"])
def calc_canonical_set(self):
canonical_set = set()
for node_id in self.canonical:
for node in node_ancestry(self.tree_node_dict[node_id], self.tree_node_dict):
canonical_set.add(node["id"])
return canonical_set
#################################
# Memory, summaries
#################################
def create_memory_entry(self, node, text, inheritability='none'):
new_memory = {
"id": str(uuid.uuid1()),
"root_id": node["id"],
"text": text,
"inheritability": inheritability
}
self.memories[new_memory['id']] = new_memory
if 'memories' not in node:
node['memories'] = []
node['memories'].append(new_memory['id'])
def delete_memory_entry(self, memory):
self.memories.pop(memory['id'])
root_node = self.tree_node_dict[memory["root_id"]]
root_node['memories'].remove(memory['id'])
# TODO also return list of pending?
def construct_memory(self, node):
ancestry = node_ancestry(node, self.tree_node_dict)
memories = []
for i, ancestor in enumerate(ancestry):
if 'memories' in ancestor:
for memory_id in ancestor['memories']:
memory = self.memories[memory_id]
if (memory['inheritability'] == 'none' and memory['root_id'] == node['id']) \
or memory['inheritability'] == 'subtree' \
or (memory['inheritability'] == 'delayed' and i < self.context_window_index()):
memories.append(memory)
return memories
def create_summary(self, root_node, end_node, summary_text):
new_summary = {
"id": str(uuid.uuid1()),
"root_id": root_node["id"],
"end_id": end_node["id"],
"text": summary_text,
}
self.summaries[new_summary['id']] = new_summary
if 'summaries' not in root_node:
root_node['summaries'] = []
root_node['summaries'].append(new_summary['id'])
def delete_summary(self, summary):
self.summaries.pop(summary['id'])
root_node = self.tree_node_dict[summary["root_id"]]
root_node['summmaries'].remove(summary['id'])
def past_summaries(self, node=None):
node = node if node else self.selected_node
ancestry = self.ancestry(node)
ancestry_ids = [ancestor['id'] for ancestor in ancestry]
summaries = []
for i, ancestor in enumerate(ancestry):
if 'summaries' in ancestor:
for summary_id in ancestor['summaries']:
summary = self.summaries[summary_id]
if summary['end_id'] in ancestry_ids:
summaries.append(summary)
return summaries
#returns first node that is fully contained in the context window
def context_window_index(self):
_, indices = self.node_ancestry_text()
first_in_context_index = indices[-1] - self.generation_settings['prompt_length']
if first_in_context_index < 0:
return 0
context_node_index = bisect.bisect_left(indices, first_in_context_index) + 1
return context_node_index
#################################
# I/O
#################################
# Inits empty chapters, memory, and notes if not already in tree
def _init_global_objects(self):
# Chapters
if 'chapters' not in self.tree_raw_data:
self.tree_raw_data['chapters'] = {}
self.chapters = self.tree_raw_data["chapters"]
if 'canonical' not in self.tree_raw_data:
self.tree_raw_data['canonical'] = []
self.canonical = self.tree_raw_data["canonical"]
if 'memories' not in self.tree_raw_data:
self.tree_raw_data['memories'] = {}
self.memories = self.tree_raw_data["memories"]
if 'summaries' not in self.tree_raw_data:
self.tree_raw_data['summaries'] = {}
self.summaries = self.tree_raw_data["summaries"]
# Generation settings
self.tree_raw_data["generation_settings"] = {
**DEFAULT_GENERATION_SETTINGS.copy(),
**self.tree_raw_data.get("generation_settings", {})
}
# View settings # TODO If there are more of these, reduce duplication
self.tree_raw_data["visualization_settings"] = {
**DEFAULT_VISUALIZATION_SETTINGS.copy(),
**self.tree_raw_data.get("visualization_settings", {})
}
self.tree_raw_data["preferences"] = {
**DEFAULT_PREFERENCES.copy(),
**self.tree_raw_data.get("preferences", {})
}
self.tree_raw_data["chat_preferences"] = {
**DEFAULT_CHAT_PREFERENCES.copy(),
**self.tree_raw_data.get("chat_preferences", {})
}
# Accidentally added generation settings to this dict once. Remove them
# FIXME remove when this is no longer a problem
# for key in DEFAULT_GENERATION_SETTINGS.keys():
# if key not in DEFAULT_VISUALIZATION_SETTINGS:
# self.tree_raw_data["visualization_settings"].pop(key, None)
def load_tree_data(self, data):
self.tree_raw_data = data
if "root" not in self.tree_raw_data:
assert "text" in self.tree_raw_data
self.tree_raw_data = {
"root": self.tree_raw_data
}
self.tree_node_dict = {d["id"]: d for d in flatten_tree(self.tree_raw_data["root"])}
# If things don't have an open state, give one to them
for node in self.tree_node_dict.values():
node["open"] = node.get("open", False)
self._init_global_objects()
self.tree_updated(rebuild=True)
self.select_node(self.tree_raw_data.get("selected_node_id", self.nodes[0]["id"]))
# Open a new tree json
def open_tree(self, filename):
self.tree_filename = os.path.abspath(filename)
self.load_tree_data(json_open(self.tree_filename))
self.io_update()
# Open a new tree json
def import_tree(self, filename):
self.tree_filename = os.path.abspath(filename)
tree_json = json_open(self.tree_filename)
if 'root' in tree_json:
new_subtree_root = tree_json['root']
self.selected_node['children'].append(new_subtree_root)
new_subtree_root['parent_id'] = self.selected_node_id
if 'chapters' in tree_json:
self.import_chapters(new_subtree_root, tree_json['chapters'])
self.tree_updated()
else:
print('improperly formatted tree')
# Tree flat data is just a different view to tree raw data!
# We edit tree flat data with tkinter and save raw data which is still in json form
def save_tree(self, backup=True):
if not self.tree_filename:
return False
# Fancy platform independent os.path
filename = os.path.splitext(os.path.basename(self.tree_filename))[0]
save_dir = os.path.dirname(self.tree_filename)
backup_dir = os.path.join(save_dir, "backups")
# Make backup before overwriting tree
if backup and os.path.isfile(self.tree_filename):
if not os.path.exists(backup_dir):
os.mkdir(backup_dir)
os.rename(self.tree_filename, os.path.join(backup_dir, f"{filename}-{timestamp()}.json"))
# Save tree
json_create(self.tree_filename, self.tree_raw_data)
self.io_update()
return True
def export_history(self, node, filename):
history = "".join(self.node_ancestry_text(node)[0])
f = open(filename, "w")
f.write(history)
f.close()
#################################
# Generation
#################################
def chat_generate(self, prompt, nodes):
start_text = ''
# only inject start text if current node isn't AI
# TODO what if more than one node ago? Use source attribute instead?
if not self.selected_node['text'].startswith('\n' + self.chat_preferences['AI_name']):
start_text += '\n' + self.chat_preferences['AI_name'] + ':'
prompt = self.chat_preferences['context'] + '\n' + prompt + start_text
try:
results, error = api_generate(prompt=prompt,
length=self.generation_settings['response_length'],
num_continuations=len(nodes),
temperature=self.generation_settings['temperature'],
logprobs=self.generation_settings['logprobs'],
top_p=self.generation_settings['top_p'],
engine=self.generation_settings['model'],
stop=["\n", self.chat_preferences['player_name'] + ':'],
)
except TypeError as e:
error = "Typeerror"
if not error:
self.generated_nodes_metadata(nodes, results, prompt, prepend_text=start_text)
else:
self.delete_failed_nodes(nodes, error)
return
for result in results.choices:
print("Generated continuation:\n", result['text'], "\nerror", error)
self.app.event_generate("<<NewNodes>>", when="tail")
def dialogue_generate(self, prompt, nodes):
start_text = '\n"'
prompt = prompt + start_text
try:
results, error = api_generate(prompt=prompt,
length=self.generation_settings['response_length'],
num_continuations=len(nodes),
temperature=self.generation_settings['temperature'],
logprobs=self.generation_settings['logprobs'],
top_p=self.generation_settings['top_p'],
engine=self.generation_settings['model'],
stop=['\n'],
)
except TypeError as e:
error = "Typeerror"
if not error:
self.generated_nodes_metadata(nodes, results, prompt, prepend_text=start_text)
else:
self.delete_failed_nodes(nodes, error)
return
for result in results.choices:
print("Generated continuation:\n", result['text'], "\nerror", error)
self.app.event_generate("<<NewNodes>>", when="tail")
def antisummary_generate(self, prompt, nodes, summary):
start_text = f'\n{self.antisummary_embedding(summary)}'
prompt = prompt + start_text
print('antisummary prompt:\n', prompt)