importitertoolsimportjsonimportuuidfromtypingimportTYPE_CHECKING,Iterable,TypeVarfromkaniimportKaniifTYPE_CHECKING:from.base_kaniimportBaseKaniT=TypeVar("T")defcreate_kani_id()->str:"""Create a unique identifier for a kani."""returnstr(uuid.uuid4())# ===== title =====# thin class for typing
[docs]classAutogenerateTitle:""" A sentinel class to tell ReDel to automatically generate a session title. Do not construct manually - use the singleton ``redel.AUTOGENERATE_TITLE``. """def__repr__(self):return"<AUTOGENERATE_TITLE>"
AUTOGENERATE_TITLE=AutogenerateTitle()asyncdefgenerate_conversation_title(ai:"BaseKani"):"""Given an kani, create a title for its current conversation state."""helper=Kani(ai.engine)chat_history="\n".join(f"{msg.role.value}: {msg.text}"formsginai.chat_historyifmsg.text)title=awaithelper.chat_round_str("Here is the start of a conversation:\n"f"{chat_history}\n\n""Come up with a short (~5 words), descriptive title for this conversation.\n\nReply with your answer only and"" be specific.")returntitle.strip(' "')defbatched(iterable:Iterable[T],n:int)->Iterable[tuple[T,...]]:# batched('ABCDEFG', 3) --> ABC DEF Gifn<1:raiseValueError("n must be at least one")it=iter(iterable)whilebatch:=tuple(itertools.islice(it,n)):yieldbatch
[docs]defread_jsonl(fp)->Iterable[dict]:""" Yield JSON objects from the JSONL file at the given path. .. note:: This function returns an iterator, not a list -- to read a full JSONL file into memory, use ``list(read_jsonl(...))``. """withopen(fp,encoding="utf-8")asf:forlineinf:yieldjson.loads(line)