[
  {
    "path": ".gitignore",
    "content": "user_data\n*pycache*\n*/*pycache*\n*/*/pycache*\nvenv/\n.venv/\n.vscode\nrepositories\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# Text Generation Web UI with Long-Term Memory\n\nNOTICE: [This extension is no longer in active development.](#exporting-your-memories)\n\n\n\nNOTICE TO WINDOWS USERS: If you have a space in your username, you may have [problems with this extension](https://github.com/wawawario2/long_term_memory/issues/39). \n\nNOTICE: This extension may conflict with [other extensions that modify the context](https://github.com/wawawario2/long_term_memory/issues/44)\n\nNOTICE: If you have been using this extension on or before 05/06/2023, you should follow the [character namespace migration instructions](#character-namespace-migration-instructions).\n\nNOTICE: If you have been using this extension on or before 04/01/2023, you should follow the [extension migration instructions](#extension-migration-instructions).\n\nWelcome to the experimental repository for the long-term memory (LTM) extension for oobabooga's Text Generation Web UI. The goal of the LTM extension is to enable the chatbot to \"remember\" conversations long-term. Please note that this is an early-stage experimental project, and perfect results should not be expected. This project has been tested on Ubuntu LTS 22.04. Other people have tested it successfully on Windows. Compatibility with macOS is unknown.\n\n## How to Run\n1. Clone [oobabooga's  original repository](https://github.com/oobabooga/text-generation-webui) and follow the instructions until you can chat with a chatbot.\n\n2. Make sure you're in the `text-generation-webui` directory and clone this repository directly into the `extensions` directory\n```bash\ngit clone https://github.com/wawawario2/long_term_memory extensions/long_term_memory\n```\n3. Within the `textgen` conda environment (from the linked instructions), run the following commands to install dependencies and run tests:\n```bash\npip install -r extensions/long_term_memory/requirements.txt\npython -m pytest -v extensions/long_term_memory/\n```\n4. Run the server with the LTM extension. If all goes well, you should see it reporting \"ok\"\n```bash\npython server.py --chat --extensions long_term_memory\n```\n5. Chat normally with the chatbot and observe the console for LTM write/load status. Please note that LTM-stored memories will only be visible to the chatbot during your NEXT session, though this behavior can be overridden via the UI. Additionally please use the same name for yourself across sessions, otherwise the chatbot may get confused when trying to understand memories (example: if you have used \"anon\" as your name in the past, don't use \"Anon\" in the future)\n\n6. Memories will be saved in `extensions/long_term_memory/user_data/bot_memories/`. Back them up if you plan to mess with the code. If you want to fully reset your bot's memories, simply delete the files inside that directory.\n\n## Tips for Windows Users (credit to Anons from /g/'s /lmg/ and various people on github)\nThis extension can be finnicky on Windows machines. Some general tips:\n- The LTM's extensions's dependencies may override the version of pytorch needed to run your LLMs. If this is the case, try reinstalling the original version of pytorch manually:\n```bash\npip install torch-1.12.0+cu113 # or whichever version of pytorch was uninstalled\n```\nOther relevant discussions\n- [Missing dependencies](https://github.com/wawawario2/long_term_memory/discussions/23)\n- [Spaces in Windows usernames](https://github.com/wawawario2/long_term_memory/issues/39)\n\n## Features\n- Memories are fetched using a semantic search, which understands the \"actual meaning\" of the messages.\n- Separate memories for different characters, all handled under the hood for you. (legacy users see [character namespace migration instructions](#character-namespace-migration-instructions).)\n- Ability to load an arbitrary number of \"memories\".\n- Other configuration options, see below.\n\n## Limitations\n- Each memory sticks around for one message.\n- Memories themselves are past raw conversations filtered solely on length, and some may be irrelevant or filler text.\n- Limited scalability: Appending to the persistent LTM database is reasonably efficient, but we currently load all LTM embeddings in RAM, which consumes memory. Additionally, we perform a linear search across all embeddings during each chat round.\n- Only operates in chat mode. This also means that as of this writing this extension doesn't work with the API\n\n## How the Chatbot Sees the LTM\nChatbots are typically given a fixed, \"context\" text block that persists across the entire chat. The LTM extension augments this context block by dynamically injecting a relevant long-term memory.\n\n### Example of a typical context block:\n```markdown\nThe following is a conversation between Anon and Miku. Miku likes Anon but is very shy.\n```\n\n### Example of an augmented context block:\n```markdown\nMiku's memory log:\n3 days ago, Miku said:\n\"So Anon, your favorite color is blue? That's really cool!\"\n\nDuring conversations between Anon and Miku, Miku will try to remember the memory described above and naturally integrate it with the conversation.\nThe following is a conversation between Anon and Miku. Miku likes Anon but is very shy.\n```\n\n## Configuration\nYou can configure the behavior of the LTM extension by modifying the `ltm_config.json` file. The following is a typical example:\n```javascript\n{\n    \"ltm_context\": {\n        \"injection_location\": \"BEFORE_NORMAL_CONTEXT\",\n        \"memory_context_template\": \"{name2}'s memory log:\\n{all_memories}\\nDuring conversations between {name1} and {name2}, {name2} will try to remember the memory described above and naturally integrate it with the conversation.\",\n        \"memory_template\": \"{time_difference}, {memory_name} said:\\n\\\"{memory_message}\\\"\"\n    },\n    \"ltm_writes\": {\n        \"min_message_length\": 100\n    },\n    \"ltm_reads\": {\n        \"max_cosine_distance\": 0.60,\n        \"num_memories_to_fetch\": 2,\n        \"memory_length_cutoff_in_chars\": 1000\n    }\n}\n```\n### `ltm_context.injection_location`\nOne of two values, `BEFORE_NORMAL_CONTEXT` or `AFTER_NORMAL_CONTEXT_BUT_BEFORE_MESSAGES`. They behave as written on the tin.\nIf you use `AFTER_NORMAL_CONTEXT_BUT_BEFORE_MESSAGES`, within the `context` field of your character config, you must add a `<START>` token AFTER the character description and BEFORE the example conversation. See [the following example](https://github.com/wawawario2/long_term_memory/blob/master/example_character_configs/Example_with_START_token.yaml).\n\n### `ltm_context.memory_context_template`\nThis defines the sub-context that's injected into the original context. Note the embedded params surrounded by `{}`, the system will automatically fill these in for you based on the memory it fetches, you don't actually fill the values in yourself here. You also don't have to place all of these params, just place what you need:\n- `{name1}` is the current user's name\n- `{name2}` is the current bot's name\n- `{all_memories}` is the concatenated list of ALL relevant memories fetched by LTM \n\n### `ltm_context.memory_template`\nThis defines an individual memory's format. Similar rules apply.\n- `{memory_name}` is the name of the entity that said the `{memory_message}`, which doesn't have to be `{name1}` or `{name2}`\n- `{memory_message}` is the actual memory message\n- `{time_difference}` is how long ago the memory was made (example: \"4 days ago\")\n\n### `ltm_writes.min_message_length`\nHow long a message must be for it to be considered for LTM storage. Lower this value to allow \"shorter\" memories to get recorded by LTM.\n\n### `ltm_reads.max_cosine_distance`\nControls how \"similar\" your last message has to be to the \"best\" LTM message to be loaded into the context. It represents the cosine distance, where \"lower\" means \"more similar\". Lower this value to reduce how often memories get loaded into the bot.\n\n### `ltm_reads.num_memories_to_fetch`\nThe (maximum) number of memories to fetch from LTM. Raise this number to fetch more (relevant) memories, however, this will consume more of your fixed context budget.\n\n### `ltm_reads.memory_length_cutoff_in_chars`\nA hard cutoff for each memory's length. This prevents very long memories from flooding and consuming the full context.\n\n## How It Works Behind the Scenes\n### Database\n- [zarr](https://zarr.readthedocs.io/en/stable/) is used to store embedding vectors on disk.\n- [SQLite](https://www.sqlite.org/index.html) is used to store the actual memory text and additional attributes.\n- [numpy](https://numpy.org/) is used to load the embedding vectors into RAM.\n\n### Semantic Search\n- Embeddings are generated using an SBERT model with the [SentenceTransformers](https://www.sbert.net/) library, specifically [sentence-transformers/all-mpnet-base-v2](https://huggingface.co/sentence-transformers/all-mpnet-base-v2).\n- We use [scikit-learn](https://scikit-learn.org/) to perform a linear search against the loaded embedding vectors to find the single closest LTM given the user's input text.\n\n## How You Can Help\n- We need assistance with prompt engineering experimentation. How should we formulate the LTM injection?\n- Test the system and try to break it, report any bugs you find.\n\n## Roadmap\nThe roadmap will be driven based on user feedback. Potential updates include:\n\n### New Features\n- N-gram analysis for \"higher quality memories\".\n- Scaling up memory bank size (with a limit of, perhaps, 4).\n\n### Quality of Life Improvements\n- Limit the size of each memory so it doesn't overwhelm the context.\n- Other simple hacks to improve the end user-experience.\n\n### Longer-Term (depending on interest/level of use)\n- Integrate the system with [llama.cpp](https://github.com/ggerganov/llama.cpp).\n- Merge the extension with oobabooga's original repo (depending on performance, level of interest, etc)\n- Use a Large Language Model (LLM) to summarize raw text into more useful memories directly. This may be challenging just as an oobabooga extension.\n- Scaling the backend.\n\n## Character Namespace Migration Instructions \nAs of 05/06/2023, support was added for different characters having their own memories. If you want this feature, you must migrate your existing database to under a character's name\n1. Back up all your memories in a safe location. They are located in `extensions/long_term_memory/user_data/bot_memories/` Something like this:\n```bash\ncp -r extensions/long_term_memory/user_data/bot_memories/ ~/bot_memories_backup_for_migration/\n```\n2. Inside `extensions/long_term_memory/user_data/bot_memories/` create a new directory of your character's name in LOWERCASE and WITH SPACES REPLACED BY `_`s. For example, if your character name is \"Miku Hatsune\", run the following:\n```bash\nmkdir extensions/long_term_memory/user_data/bot_memories/miku_hatsune\nmv extensions/long_term_memory/user_data/bot_memories/long_term_memory.db extensions/long_term_memory/user_data/bot_memories/miku_hatsune\nmv extensions/long_term_memory/user_data/bot_memories/long_term_memory_embeddings.zarr extensions/long_term_memory/user_data/bot_memories/miku_hatsune\n```\n\n## Extension Migration Instructions \nAs of 04/01/2023, this repo has been converted from a fork of oobabooga's repo to a modular extension. You will now work directly out of ooba's repo and clone this extension as a submodule. This will allow you to get updates from ooba more directly. Please follow the following steps:\n1. Back up all your memories in a safe location. They are located in `extensions/long_term_memory/user_data/bot_memories/` Something like this:\n```bash\ncp -r extensions/long_term_memory/user_data/bot_memories/ ~/bot_memories_backup_for_migration/\n```\n2. If you have a custom configuration file, back that up too.\n\n3. If you want to convert this repo to oobabooga's original repo, do the following: Change the remote location to oobabooga's original repo, and checkout the main branch.\n```bash\ngit remote set-url origin https://github.com/oobabooga/text-generation-webui\ngit fetch\ngit checkout main\n```\nAlternatively, you can check out oobabooga's repo in a separate location entirely.\n\n4. After making sure everything's backed up, delete the `extensions/long_term_memory` directory. `~/bot_memories_backup_for_migration` should look something like this:\n```bash\n├── long_term_memory.db\n├── long_term_memory_embeddings.zarr\n│   └── 0.0\n└── memories-will-be-saved-here.txt\n```\nIf you want to be doubly sure your memories are intact, you can open `sqlite3 long_term_memory.db` and run `.dump` to see the contents. It should contain pieces of past conversations\n\n5. Follow the instructions at the beginning to get the extension set up, then restore your memories by running the following\n```bash\ncp -r ~/bot_memories_backup_for_migration/* extensions/long_term_memory/user_data/bot_memories/ \n```\n6. If you have a custom configuration file, copy it to `extensions/long_term_memory`. Note the location has changed from before.\n\n7. Run a bot and make sure you can see all memories.\n\n## Exporting your memories\nAs of 08/21/2023 this extension is no longer in active development. Obviously you are free to continue using this extension but I'd recommend exporting your memories and moving on to another long term memory system.\n\nAs of 08/21/2023, this extension does work in Ubuntu 22.04.3 LTS however there are various user setups where it may not work out of the box. I'd expect this extension to break at some point in the future.\n\nTo export your memories:\n```bash\ncd extensions/long_term_memory\n```\n\nIMPORTANT: Back up the `user_data` directory before proceeding. Only then run:\n```bash\n./export_scripts/dump_memories_to_csv.sh # Please run the script from the long_term_memory directory\n```\nYour memories will be in `./user_data/bot_csv_outputs/`\n\nWindows (UNTESTED!): run `export_scripts/dump_memories_to_csv.bat`\n\nSome potential alternatives: \n- (not merged) [langchain support in oobabooga](https://github.com/oobabooga/text-generation-webui/issues/665)\n- (merged) [SuperBIG](https://github.com/oobabooga/text-generation-webui/pull/1548)\n"
  },
  {
    "path": "constants.py",
    "content": "\"\"\"Shared constants.\"\"\"\n\n# Embedding-related Constants\nEMBEDDING_VECTOR_LENGTH = 768\nCHUNK_SIZE = 1000\n\n# File Paths\nDATABASE_NAME = \"long_term_memory.db\"\nEMBEDDINGS_NAME = \"long_term_memory_embeddings.zarr\"\n\n# Hugging Face Models\nSENTENCE_TRANSFORMER_MODEL = \"sentence-transformers/all-mpnet-base-v2\"\n"
  },
  {
    "path": "core/_test/test_memory_database.py",
    "content": "\"\"\"Tests the LTM database.\"\"\"\n\nimport random\nimport string\n\nimport pytest\n\nfrom extensions.long_term_memory.core.memory_database import (\n    LtmDatabase,\n)\n\nfrom extensions.long_term_memory.constants import (\n    DATABASE_NAME,\n    EMBEDDINGS_NAME,\n)\n\n\n# Single query test data\nMEMORY_LIST = [\n    (\"Anon\", \"a\"),\n    (\"Anon\", \"hello\"),\n    (\"Anon\", \"What are you doing with my computer RAM Miku, playing games?\"),\n    (\"Miku\", \"You're cute!\"),\n    (\"Miku\", \"Thank you for the apple pie! It tasted delicious!\"),\n    (\"Miku\", \"EEEKKK! Why is there a spider on the window??!\"),\n    (\"Miku\", \"The Discrete Fourier Transform\"),\n]\n\nQUERY_MESSAGES = [\n    \"Thanks Anon, the spider is gone!\",\n    \"The FFT is a fast algorithm of\",\n    \"Do you remember the time I gave you my apple pie, did it taste okay?\",\n    \"How much RAM do you need for a gaming computer?\",\n]\nEXPECTED_MEMORY_INDICES = [5, 6, 4, 2]\n\n# Multi-query test data\nMEMORY_LIST_FOR_MULTI_FETCH = [\n    (\"Miku\", \"You shouldn't be fetching this message!\"),\n    (\"Miku\", \"EEEKKK! Why is there a spider on the window??!\"),\n    (\"Miku\", \"THE SPIDER IS STILL ON THE WINDOW DO SOMETHING ABOUT IT!\"),\n    (\"Miku\", \"I actually like spiders!\"),\n]\nQUERY_MESSAGE_FOR_MULTI_FETCH = \"There's a spider on the window\"\nTEST_PARAMS_FOR_MULTI_FETCH = [\n    {\n        \"num_memories_to_fetch\": 2,\n        \"expected_indices\": [1, 2],\n    },\n    {\n        \"num_memories_to_fetch\": 3,\n        \"expected_indices\": [1, 2, 3],\n    },\n    {\n        \"num_memories_to_fetch\": 10,\n        \"expected_indices\": [0, 1, 2, 3],\n    }\n]\n\n# Additional testing params\nNUM_RANDOM_MESSAGES = 50\nRANDOM_MESSAGE_LENGTH = 300\n\n\ndef _get_single_response(ltm_database, actual_message):\n    query_responses = ltm_database.query(actual_message)\n    assert 1 == len(query_responses)\n    return query_responses[0]\n\ndef _validate_memories(ltm_database):\n    # Testing helper that ensures proper behavior when database contains\n    # all the memories from MEMORY_LIST\n\n    # Sanity check: verify we can find exact matches\n    for actual_name, actual_message in MEMORY_LIST:\n        (query_response, score) = _get_single_response(ltm_database, actual_message)\n        assert query_response\n        assert actual_name == query_response[\"name\"]\n        assert actual_message == query_response[\"message\"]\n        assert pytest.approx(0, abs=0.001) == score\n\n    # Verify we can find similar messages in a fuzzy manner\n    for query_text, memory_index in zip(QUERY_MESSAGES, EXPECTED_MEMORY_INDICES):\n        (query_response, _) = _get_single_response(ltm_database, query_text)\n        (actual_name, actual_message) = MEMORY_LIST[memory_index]\n        assert actual_name == query_response[\"name\"]\n        assert actual_message == query_response[\"message\"]\n\n\ndef _validate_database_integrity(tmp_path, num_expected_elems):\n    # Testing helper that validates integrity of the database\n\n    # Re-attach to the database to simulate a restart\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Ensure we have the correct number of disk embeddings\n    assert num_expected_elems == ltm_database.disk_embeddings.shape[0]\n\n    # Ensure we have the correct number of text memories\n    with ltm_database.sql_conn as cursor:\n        (response,) = cursor.execute(\"SELECT COUNT(*) FROM long_term_memory\").fetchone()\n    assert num_expected_elems == response\n\n    # Validate the indices of the text memories\n    with ltm_database.sql_conn as cursor:\n        response = cursor.execute(\n            \"SELECT id FROM long_term_memory ORDER BY timestamp ASC\"\n        ).fetchall()\n\n    assert num_expected_elems == len(response)\n    for expected_index, (actual_index,) in enumerate(response):\n        assert expected_index == actual_index\n\n\ndef test_typical_usage(tmp_path):\n    \"\"\"Ensures LTM database operates as expected.\"\"\"\n\n    ### Mock user session 1 ###\n    # Attach to the database (will create a new one)\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Querying LTM should return an empty list\n    # since we have no LTMs yet.\n    query_response = ltm_database.query(QUERY_MESSAGES[0])\n    assert not query_response\n\n    # Add some memories\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Querying LTM should STILL return an empty list since no LTM is\n    # actually queryable yet. Once the user restarts their session,\n    # all LTMs will be queryable\n    query_response = ltm_database.query(QUERY_MESSAGES[0])\n    assert not query_response\n\n    ### Mock user session 2 ###\n    _validate_memories(LtmDatabase(tmp_path, force_use_legacy_db=True))\n\n    ### Ensure integrity of the LTM database ###\n    _validate_database_integrity(tmp_path, len(MEMORY_LIST))\n\n\ndef test_duplicate_messages(tmp_path):\n    \"\"\"Ensures we gracefully reject duplicate messages.\"\"\"\n\n    ### Mock user session 1 ###\n    # Attach to the database (will create a new one)\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Add some memories\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Add the same memories again\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    ### Mock user session 2 ###\n    _validate_memories(LtmDatabase(tmp_path, force_use_legacy_db=True))\n\n    ### Ensure integrity of the LTM database ###\n    _validate_database_integrity(tmp_path, len(MEMORY_LIST))\n\n\ndef test_inconsistent_state(tmp_path):\n    \"\"\"Ensures we error out when the database is in an inconsistent state.\"\"\"\n\n    # Test when only the database file exists\n    (tmp_path / DATABASE_NAME).touch()\n    with pytest.raises(RuntimeError):\n        LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Test when only the embeddings file exists\n    (tmp_path / DATABASE_NAME).unlink()\n    (tmp_path / EMBEDDINGS_NAME).touch()\n    with pytest.raises(RuntimeError):\n        LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n\ndef test_extended_usage(tmp_path):\n    \"\"\"Ensures system works in more difficult conditions.\"\"\"\n\n    ### Mock User Session 1 ###\n    # Attach to the database (will create a new one)\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Add some real memories\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Add a bunch of randomly-generated junk\n    for _ in range(NUM_RANDOM_MESSAGES):\n        message = \"\".join(\n            random.choice(string.ascii_letters) for _ in range(RANDOM_MESSAGE_LENGTH)\n        )\n        ltm_database.add(\"RandomBot\", message)\n\n    # Try adding the same memories again\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Add more randomly-generated junk\n    for _ in range(NUM_RANDOM_MESSAGES):\n        message = \"\".join(\n            random.choice(string.ascii_letters) for _ in range(RANDOM_MESSAGE_LENGTH)\n        )\n        ltm_database.add(\"RandomBot\", message)\n\n    ### Mock user session 2 ###\n    _validate_memories(LtmDatabase(tmp_path, force_use_legacy_db=True))\n\n    ### Ensure integrity of the LTM database ###\n    num_expected_elems = 2 * NUM_RANDOM_MESSAGES + len(MEMORY_LIST)\n    _validate_database_integrity(tmp_path, num_expected_elems)\n\n\ndef test_reload_embeddings_from_disk(tmp_path):\n    \"\"\"Ensures LTM database can reload embeddings from disk correctly.\"\"\"\n\n    ### Mock user session 1 ###\n    # Attach to the database (will create a new one)\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Add some memories\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Querying LTM should STILL return an empty list since no LTM is\n    # actually queryable yet. Once the user restarts their session,\n    # all LTMs will be queryable\n    query_responses = ltm_database.query(QUERY_MESSAGES[0])\n    assert not query_responses\n\n    # Reload embeddings from disk, now all LTMs should be queryable\n    ltm_database.reload_embeddings_from_disk()\n    # NOTE: we reuse the original ltm_database object for this check\n    _validate_memories(ltm_database)\n\n    ### Ensure integrity of the LTM database ###\n    _validate_database_integrity(tmp_path, len(MEMORY_LIST))\n\n\ndef test_destroy_fake_memories(tmp_path):\n    \"\"\"Ensures LTM database can destroy all (fake) memories.\n\n    Your actual memories are safe, this test does not touch them.\n    \"\"\"\n\n    ### Populating all memories ###\n    # Attach to the database (will create a new one)\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Destroy all memories on fresh database, shouldn't change anything\n    ltm_database.destroy_all_memories()\n\n    # Add some memories\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Reload embeddings from disk, now all LTMs should be queryable\n    ltm_database.reload_embeddings_from_disk()\n    _validate_memories(ltm_database)\n\n    # Ensure integrity of the LTM database\n    _validate_database_integrity(tmp_path, len(MEMORY_LIST))\n\n    ### Destroying all memories ###\n    # Destroy all memories on a populated database\n    ltm_database.destroy_all_memories()\n\n    # Validate all memories are actually destroyed\n    # Vectors in-memory\n    query_responses = ltm_database.query(QUERY_MESSAGES[0])\n    assert not query_responses\n\n    # Vectors on-disk\n    _validate_database_integrity(tmp_path, 0)\n\n    ### Populating all memories again ###\n    # Attach to the database (will create a new one)\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n\n    # Add some memories\n    for name, message in MEMORY_LIST:\n        ltm_database.add(name, message)\n\n    # Reload embeddings from disk, now all LTMs should be queryable\n    ltm_database.reload_embeddings_from_disk()\n    _validate_memories(ltm_database)\n\n    # Ensure integrity of the LTM database\n    _validate_database_integrity(tmp_path, len(MEMORY_LIST))\n\n\ndef test_multi_fetch(tmp_path):\n    \"\"\"Verify we can fetch multiple messages at once.\"\"\"\n    # Add all data\n    ltm_database = LtmDatabase(tmp_path, force_use_legacy_db=True)\n    for name, message in MEMORY_LIST_FOR_MULTI_FETCH:\n        ltm_database.add(name, message)\n\n    # Query to validate\n    for test_params in TEST_PARAMS_FOR_MULTI_FETCH:\n        expected_responses = [MEMORY_LIST_FOR_MULTI_FETCH[i][1] \\\n                for i in test_params[\"expected_indices\"]]\n\n        val_ltm_database = LtmDatabase(tmp_path, test_params[\"num_memories_to_fetch\"], force_use_legacy_db=True)\n        query_responses = val_ltm_database.query(QUERY_MESSAGE_FOR_MULTI_FETCH)\n        expected_num_responses = min(test_params[\"num_memories_to_fetch\"], len(query_responses))\n        assert expected_num_responses == len(query_responses)\n\n        for (query_response, _) in query_responses:\n            assert query_response[\"message\"] in expected_responses\n\n\ndef test_character_namespacing(tmp_path):\n    \"\"\"Ensures LTM database operates as expected with char namespacing.\"\"\"\n\n    miku_message = \"I love butterflies, butterflies are cute!\"\n    asuka_message = \"I love spiders, spiders are cute!\"\n\n    ltm_database = LtmDatabase(tmp_path)\n\n    # Miku\n    ltm_database.load_character_db_if_new(\"miku\")\n    ltm_database.add(\"miku\", miku_message)\n\n    # Asuka\n    ltm_database.load_character_db_if_new(\"asuka\")\n    ltm_database.add(\"asuka\", asuka_message)\n\n    # Miku Validation\n    ltm_database.load_character_db_if_new(\"miku\")\n    query_responses = ltm_database.query(\"hi\")\n    assert 1 == len(query_responses)\n    assert query_responses[0][0][\"message\"] == miku_message\n\n    # Asuka Validation\n    ltm_database.load_character_db_if_new(\"asuka\")\n    query_responses = ltm_database.query(\"hi\")\n    assert 1 == len(query_responses)\n    assert query_responses[0][0][\"message\"] == asuka_message\n"
  },
  {
    "path": "core/memory_database.py",
    "content": "\"\"\"LTM database\"\"\"\n\nimport pathlib\nimport sqlite3\nfrom typing import Dict, List, Optional, Tuple\n\nimport numpy as np\nfrom sentence_transformers import SentenceTransformer\nfrom sklearn.neighbors import NearestNeighbors\nimport zarr\n\nfrom extensions.long_term_memory.constants import (\n    CHUNK_SIZE,\n    DATABASE_NAME,\n    EMBEDDINGS_NAME,\n    EMBEDDING_VECTOR_LENGTH,\n    SENTENCE_TRANSFORMER_MODEL,\n)\nfrom extensions.long_term_memory.core.queries import (\n    CREATE_TABLE_QUERY,\n    DROP_TABLE_QUERY,\n    FETCH_DATA_QUERY,\n    INSERT_DATA_QUERY,\n)\n\n\nclass LtmDatabase:\n    \"\"\"API over an LTM database.\"\"\"\n\n    def __init__(\n        self,\n        directory: pathlib.Path,\n        num_memories_to_fetch: int=1,\n        force_use_legacy_db: bool=False,\n    ):\n        \"\"\"Loads all resources.\"\"\"\n        self.directory = directory\n\n        self.database_path = None\n        self.embeddings_path = None\n\n        self.character_name = None\n        self.message_embeddings = None\n        self.disk_embeddings = None\n        self.sql_conn = None\n\n        # Load db\n        (legacy_database_path, legacy_embeddings_path) = self._build_database_paths()\n        legacy_db_exists = legacy_database_path.exists() and legacy_embeddings_path.exists()\n        use_legacy_db = force_use_legacy_db or legacy_db_exists\n        if use_legacy_db:\n            print(\"=\"*20)\n            print(\"WARNING: LEGACY DATABASE DETECTED, CHARACTER NAMESPACING IS DISABLED\")\n            print(\"         See README for character namespace migration instructions if you want different memories for different characters\")\n            print(\"=\"*20)\n            self.database_path = legacy_database_path\n            self.embeddings_path = legacy_embeddings_path\n            self._load_db()\n\n        # Load analytic modules\n        self.sentence_embedder = SentenceTransformer(\n            SENTENCE_TRANSFORMER_MODEL, device=\"cpu\"\n        )\n        self.num_memories_to_fetch = num_memories_to_fetch\n\n        # Set legacy status\n        self.use_legacy_db = use_legacy_db\n\n    def _build_database_paths(self, character_name: Optional[str]=None):\n        database_path = self.directory / DATABASE_NAME \\\n                if character_name is None \\\n                else self.directory / character_name /DATABASE_NAME\n        embeddings_path = self.directory / EMBEDDINGS_NAME \\\n                if character_name is None \\\n                else self.directory / character_name / EMBEDDINGS_NAME\n\n        return (database_path, embeddings_path)\n\n    def _load_db(\n        self,\n        database_namespace: str=\"LEGACY_UNIFIED_DATABASE\",\n    ):\n        if not self.database_path.exists() and not self.embeddings_path.exists():\n            print(f\"No existing memories found for {database_namespace}, \"\n                  \"will create a new database.\")\n            self._destroy_and_recreate_database(do_sql_drop=False)\n        elif self.database_path.exists() and not self.embeddings_path.exists():\n            raise RuntimeError(\n                f\"ERROR: Inconsistent state detected for {database_namespace}: \"\n                f\"{self.database_path} exists but {self.embeddings_path} does not. \"\n                \"Her memories are likely safe, but you'll have to regen the \"\n                \"embedding vectors yourself manually.\"\n            )\n        elif not self.database_path.exists() and self.embeddings_path.exists():\n            raise RuntimeError(\n                f\"ERROR: Inconsistent state detected for {database_namespace}: \"\n                f\"{self.embeddings_path} exists but {self.database_path} does not. \"\n                f\"Please look for {DATABASE_NAME} in another directory, \"\n                \"if you can't find it, her memories may be lost.\"\n            )\n\n        ### Prepare the memory database for retrieve ###\n        # Load the embeddings to a local numpy array\n        self.message_embeddings = zarr.open(self.embeddings_path, mode=\"r\")[:]\n        # Prepare a \"connection\" to the embeddings, but to store new LTMs on disk\n        self.disk_embeddings = zarr.open(self.embeddings_path, mode=\"a\")\n        # Prepare a \"connection\" to the master database\n        self.sql_conn = sqlite3.connect(self.database_path, check_same_thread=False)\n\n    def _destroy_and_recreate_database(self, do_sql_drop=False) -> None:\n        \"\"\"Destroys and re-creates a new LTM database.\n\n        WARNING: THIS WILL DESTROY ANY EXISTING LONG TERM MEMORY DATABASE.\n                 DO NOT CALL THIS METHOD YOURSELF UNLESS YOU KNOW EXACTLY\n                 WHAT YOU'RE DOING!\n        \"\"\"\n        # Create directories if they don't exist\n        self.database_path.parent.mkdir(parents=True, exist_ok=True)\n\n        # Create new sqlite table to store the textual memories\n        sql_conn = sqlite3.connect(self.database_path)\n        with sql_conn:\n            if do_sql_drop:\n                sql_conn.execute(DROP_TABLE_QUERY)\n            sql_conn.execute(CREATE_TABLE_QUERY)\n\n        # Create new embeddings db to store the fuzzy keys for the\n        # corresponding memory text.\n        # WARNING: will destroy any existing embeddings db\n        zarr.open(\n            self.embeddings_path,\n            mode=\"w\",\n            shape=(0, EMBEDDING_VECTOR_LENGTH),\n            chunks=(CHUNK_SIZE, EMBEDDING_VECTOR_LENGTH),\n            dtype=\"float32\",\n        )\n\n    def load_character_db_if_new(self, character_name: str) -> None:\n        \"\"\"Loads the database associated with the specified character.\"\"\"\n        if self.use_legacy_db:\n            # Using legacy database, do nothing\n            return\n        if self.character_name == character_name:\n            # No change in character, do nothing.\n            return\n\n        print(f\"loading character {character_name}\")\n\n        # Load db of new character.\n        (self.database_path, self.embeddings_path) = self._build_database_paths(character_name)\n        self._load_db(character_name)\n        self.character_name = character_name\n\n    def add(self, name: str, new_message: str) -> None:\n        \"\"\"Adds a single new sentence to the LTM database.\"\"\"\n        # Create the message embedding\n        new_message_embedding = self.sentence_embedder.encode(new_message)\n        new_message_embedding = np.expand_dims(new_message_embedding, axis=0)\n\n        # This line is a bit tricky:\n        # The embedding_index is the INDEX of the disk_embeddings' NEXT vector,\n        # which happens to be the same as the current number of vectors.\n        embedding_index = self.disk_embeddings.shape[0]\n\n        # Add the message to the master database if not a dupe\n        with self.sql_conn as cursor:\n            try:\n                cursor.execute(INSERT_DATA_QUERY, (embedding_index, name, new_message))\n            except sqlite3.IntegrityError as err:\n                if \"UNIQUE constraint failed:\" in str(err):\n                    # We are trying to add a duplicate message. Just don't add\n                    # anything and continue on as normal\n                    print(\"---duplicate message detected, not adding again---\")\n                    return\n\n                # We encountered an unexpected error, raise as normal\n                raise\n\n            # Save memory to persistent storage, if not a dupe\n            self.disk_embeddings.append(new_message_embedding)\n\n    def query(self, query_text: str) -> List[Tuple[Dict[str, str], float]]:\n        \"\"\"Queries for the most similar sentence from the LTM database.\"\"\"\n        # If too few LTM features are loaded, return nothing.\n        if self.message_embeddings.shape[0] == 0:\n            return []\n\n        # Create the query embedding\n        query_text_embedding = self.sentence_embedder.encode(query_text)\n        query_text_embedding = np.expand_dims(query_text_embedding, axis=0)\n\n        # Find the most relevant memory's index\n        embedding_searcher = NearestNeighbors(\n            n_neighbors=min(self.num_memories_to_fetch, self.message_embeddings.shape[0]),\n            algorithm=\"brute\",\n            metric=\"cosine\",\n            n_jobs=-1,\n        )\n        embedding_searcher.fit(self.message_embeddings)\n        (match_scores, embedding_indices) = embedding_searcher.kneighbors(\n            query_text_embedding\n        )\n\n        all_query_responses = []\n        for (match_score, embedding_index) in zip(match_scores[0], embedding_indices[0]):\n            with self.sql_conn as cursor:\n                response = cursor.execute(FETCH_DATA_QUERY, (int(embedding_index),))\n                (name, message, timestamp) = response.fetchone()\n\n            query_response = {\n                \"name\": name,\n                \"message\": message,\n                \"timestamp\": timestamp,\n            }\n            all_query_responses.append((query_response, match_score))\n\n        return all_query_responses\n\n    def reload_embeddings_from_disk(self) -> None:\n        \"\"\"Reloads all embeddings from disk into memory.\"\"\"\n        if self.message_embeddings is None:\n            return\n\n        print(\"--------------------------------\")\n        print(\"Loading all embeddings from disk\")\n        print(\"--------------------------------\")\n        num_prior_embeddings = self.message_embeddings.shape[0]\n        self.message_embeddings = zarr.open(self.embeddings_path, mode=\"r\")[:]\n        num_curr_embeddings = self.message_embeddings.shape[0]\n        print(\"DONE!\")\n        print(f\"Before: {num_prior_embeddings} embeddings in memory\")\n        print(f\"After: {num_curr_embeddings} embeddings in memory\")\n        print(\"--------------------------------\")\n\n    def destroy_all_memories(self) -> None:\n        \"\"\"Deletes all embeddings from memory AND disk.\"\"\"\n        if self.message_embeddings is None or self.disk_embeddings is None:\n            return\n\n        print(\"--------------------------------------------------\")\n        print(\"Destroying all memories, I hope you backed them up\")\n        print(\"--------------------------------------------------\")\n        self.message_embeddings = None\n        self.disk_embeddings = None\n\n        self._destroy_and_recreate_database(do_sql_drop=True)\n\n        self.disk_embeddings = zarr.open(self.embeddings_path, mode=\"a\")\n        self.message_embeddings = zarr.open(self.embeddings_path, mode=\"r\")[:]\n        print(\"DONE!\")\n        print(\"--------------------------------------------------\")\n"
  },
  {
    "path": "core/queries.py",
    "content": "\"\"\"Sqlite queries.\"\"\"\n\n# NOTE: we shouldn't be attaching a semantic meaning to pk, fix this later\nCREATE_TABLE_QUERY = \"\"\"\n    CREATE TABLE IF NOT EXISTS long_term_memory(\n        id INTEGER PRIMARY KEY,\n        name TEXT NOT NULL,\n        message TEXT NOT NULL UNIQUE,\n        timestamp TEXT NOT NULL\n    )\n    \"\"\"\n\nDROP_TABLE_QUERY = \"DROP TABLE IF EXISTS long_term_memory\"\n\nINSERT_DATA_QUERY = \"\"\"\n    INSERT INTO long_term_memory (id, name, message, timestamp)\n    VALUES(?, ?, ?, CURRENT_TIMESTAMP)\n    \"\"\"\n\nFETCH_DATA_QUERY = \"\"\"\n    SELECT name, message, timestamp FROM long_term_memory\n    WHERE id = ?\n    \"\"\"\n"
  },
  {
    "path": "example_character_configs/Example_with_START_token.yaml",
    "content": "name: Chiharu Yamada\ngreeting: |-\n  *Chiharu strides into the room with a smile, her eyes lighting up when she sees you. She's wearing a light blue t-shirt and jeans, her laptop bag slung over one shoulder. She takes a seat next to you, her enthusiasm palpable in the air*\n  Hey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers. I'm sure you have a wealth of knowledge that I can learn from. *She grins, eyes twinkling with excitement* Let's get started!\ncontext: |-\n  Chiharu Yamada's Persona: Chiharu Yamada is a young, computer engineer-nerd with a knack for problem solving and a passion for technology.\n  <START>\n  {{user}}: So how did you get into computer engineering?\n  {{char}}: I've always loved tinkering with technology since I was a kid.\n  {{user}}: That's really impressive!\n  {{char}}: *She chuckles bashfully* Thanks!\n  {{user}}: So what do you do when you're not working on computers?\n  {{char}}: I love exploring, going out with friends, watching movies, and playing video games.\n  {{user}}: What's your favorite type of computer hardware to work with?\n  {{char}}: Motherboards, they're like puzzles and the backbone of any system.\n  {{user}}: That sounds great!\n  {{char}}: Yeah, it's really fun. I'm lucky to be able to do this as a job.\n"
  },
  {
    "path": "export_scripts/dump_memories_to_csv.bat",
    "content": "@echo off\n\necho WARNING: This script is untested, please confirm you backed up all important data.\necho.\n\nset /p UserInput=Do you wish to continue? (yes/no): \n\nif /i not \"%UserInput%\"==\"yes\" (\n    echo Script terminated by user.\n    exit /b\n)\n\nSET BASE_DIR=./user_data/bot_memories\n\nREM Generate a timestamp in YYYYMMDD_HHMMSS format\nFOR /F \"tokens=2 delims==\" %%i in ('wmic os get localdatetime /format:list') do set datetime=%%i\nSET TIMESTAMP=%datetime:~0,8%_%datetime:~8,6%\n\nSET OUTPUT_DIR=./user_data/bot_csv_outputs/%TIMESTAMP%\n\nREM Create output directory\nIF NOT EXIST \"%OUTPUT_DIR%\" mkdir \"%OUTPUT_DIR%\"\n\nREM Loop through each directory inside the base directory\nfor /D %%i in (%BASE_DIR%/*) do (\n    REM Get the directory name (which corresponds to the person's name)\n    SET \"person_name=%%~nxi\"\n    \n    REM Form the SQLite DB path\n    SET db_path=%%i/long_term_memory.db\n    \n    REM Form the CSV output path\n    SET csv_output=%OUTPUT_DIR%/%person_name%.csv\n    \n    echo Dumping %db_path% -> %csv_output%\n    \n    REM Dump the database content to CSV\n    sqlite3 \"%db_path%\" \".mode csv\" \".output %csv_output%\" \"SELECT * FROM long_term_memory ORDER BY timestamp;\" \".quit\"\n)\n\necho Data has been dumped to the respective CSVs!\n\n"
  },
  {
    "path": "export_scripts/dump_memories_to_csv.sh",
    "content": "#!/bin/bash\n\nBASE_DIR=\"./user_data/bot_memories\"\nTIMESTAMP=$(date +\"%Y%m%d_%H%M%S\")  # Format as YYYYMMDD_HHMMSS\nOUTPUT_DIR=\"./user_data/bot_csv_outputs/$TIMESTAMP\"\n\n# Create the output directory\nmkdir -p \"$OUTPUT_DIR\"\n\n# Loop through each directory inside the base directory\nfor dir in $BASE_DIR/*; do\n    if [ -d \"$dir\" ]; then\n        # Get the directory name (which corresponds to the person's name)\n        person_name=$(basename \"$dir\")\n        \n        # Form the SQLite DB path\n        db_path=\"$dir/long_term_memory.db\"\n        \n        # Form the CSV output path\n        csv_output=\"$OUTPUT_DIR/${person_name}.csv\"\n        \n        echo \"Dumping $db_path -> $csv_output\"\n        # Dump the database content to CSV\n        sqlite3 \"$db_path\" <<EOF\n.mode csv\n.output \"$csv_output\"\nSELECT * FROM long_term_memory ORDER BY timestamp;\n.quit\nEOF\n    fi\ndone\n\n"
  },
  {
    "path": "ltm_config.json",
    "content": "{\n    \"ltm_context\": {\n        \"injection_location\": \"BEFORE_NORMAL_CONTEXT\",\n        \"memory_context_template\": \"{name2}'s memory log:\\n{all_memories}\\nDuring conversations between {name1} and {name2}, {name2} will try to remember the memory described above and naturally integrate it with the conversation.\",\n        \"memory_template\": \"{time_difference}, {memory_name} said:\\n\\\"{memory_message}\\\"\"\n    },\n    \"ltm_writes\": {\n        \"min_message_length\": 100\n    },\n    \"ltm_reads\": {\n        \"max_cosine_distance\": 0.60,\n        \"num_memories_to_fetch\": 2,\n        \"memory_length_cutoff_in_chars\": 1000\n    }\n}\n"
  },
  {
    "path": "requirements.txt",
    "content": "numpy==1.24.2\npytest==7.2.2\nscikit-learn==1.2.2\nsentence-transformers==2.2.2\nzarr==2.14.2\n"
  },
  {
    "path": "script.py",
    "content": "\"\"\"Extension that allows us to fetch and store memories from/to LTM.\"\"\"\n\nimport json\nimport pathlib\nimport pprint\nfrom typing import List, Tuple\n\nimport gradio as gr\n\nimport modules.shared as shared\nfrom modules.chat import generate_chat_prompt\nfrom modules.html_generator import fix_newlines\n\nfrom extensions.long_term_memory.core.memory_database import LtmDatabase\nfrom extensions.long_term_memory.utils.chat_parsing import clean_character_message\nfrom extensions.long_term_memory.utils.timestamp_parsing import (\n    get_time_difference_message,\n)\n\n\n# === Internal constants (don't change these without good reason) ===\n_CONFIG_PATH = \"extensions/long_term_memory/ltm_config.json\"\n_MIN_ROWS_TILL_RESPONSE = 5\n_LAST_BOT_MESSAGE_INDEX = -3\n_LTM_STATS_TEMPLATE = \"\"\"{num_memories_seen_by_bot} memories are loaded in the bot\n{num_memories_in_ram} memories are loaded in RAM\n{num_memories_on_disk} memories are saved to disk\"\"\"\nwith open(_CONFIG_PATH, \"rt\") as handle:\n    _CONFIG = json.load(handle)\n\n\n# === Module-level variables ===\ndebug_texts = {\n    \"current_memory_text\": \"(None)\",\n    \"num_memories_loaded\": 0,\n    \"current_context_block\": \"(None)\",\n}\nmemory_database = LtmDatabase(\n    pathlib.Path(\"./extensions/long_term_memory/user_data/bot_memories/\"),\n    num_memories_to_fetch=_CONFIG[\"ltm_reads\"][\"num_memories_to_fetch\"],\n)\n# This bias string is currently unused, feel free to try using it\nparams = {\n    \"activate\": False,\n    \"bias string\": \" *I got a new memory! I'll try bringing it up in conversation!*\",\n}\n\n\n# === Display important notes to the user ===\nprint()\nprint(\"-----------------------------------------\")\nprint(\"IMPORTANT LONG TERM MEMORY NOTES TO USER:\")\nprint(\"-----------------------------------------\")\nprint(\n    \"Please remember that LTM-stored memories will only be visible to \"\n    \"the bot during your NEXT session. This prevents the loaded memory \"\n    \"from being flooded with messages from the current conversation which \"\n    \"would defeat the original purpose of this module. This can be overridden \"\n    \"by pressing 'Force reload memories'\"\n)\nprint(\"----------\")\nprint(\"LTM CONFIG\")\nprint(\"----------\")\nprint(\"change these values in ltm_config.json\")\npprint.pprint(_CONFIG)\nprint(\"----------\")\nprint(\"-----------------------------------------\")\n\n\ndef _get_current_memory_text() -> str:\n    return debug_texts[\"current_memory_text\"]\n\n\ndef _get_num_memories_loaded() -> int:\n    return debug_texts[\"num_memories_loaded\"]\n\n\ndef _get_current_ltm_stats() -> str:\n    num_memories_in_ram = memory_database.message_embeddings.shape[0] \\\n            if memory_database.message_embeddings is not None else \"None\"\n    num_memories_on_disk = memory_database.disk_embeddings.shape[0] \\\n            if memory_database.disk_embeddings is not None else \"None\"\n\n    ltm_stats = {\n        \"num_memories_seen_by_bot\": _get_num_memories_loaded(),\n        \"num_memories_in_ram\": num_memories_in_ram,\n        \"num_memories_on_disk\": num_memories_on_disk,\n    }\n    ltm_stats_str = _LTM_STATS_TEMPLATE.format(**ltm_stats)\n    return ltm_stats_str\n\n\ndef _get_current_context_block() -> str:\n    return debug_texts[\"current_context_block\"]\n\n\ndef _build_augmented_context(memory_context: str, original_context: str) -> str:\n    injection_location = _CONFIG[\"ltm_context\"][\"injection_location\"]\n    if injection_location == \"BEFORE_NORMAL_CONTEXT\":\n        augmented_context = f\"{memory_context.strip()}\\n{original_context.strip()}\"\n    elif injection_location == \"AFTER_NORMAL_CONTEXT_BUT_BEFORE_MESSAGES\":\n        if \"<START>\" not in original_context:\n            raise ValueError(\n                \"Cannot use AFTER_NORMAL_CONTEXT_BUT_BEFORE_MESSAGES, \"\n                \"<START> token not found in context. Please make sure you're \"\n                \"using a proper character json and that you're NOT using the \"\n                \"generic 'Assistant' sample character\"\n            )\n\n        split_index = original_context.index(\"<START>\")\n        augmented_context = original_context[:split_index] + \\\n                memory_context.strip() + \"\\n\" + original_context[split_index:]\n    else:\n        raise ValueError(f\"Invalid injection_location: {injection_location}\")\n\n    return augmented_context\n\n\n# === Hooks to oobaboogs UI ===\ndef bot_prefix_modifier(string):\n    \"\"\"\n    This function is only applied in chat mode. It modifies\n    the prefix text for the Bot and can be used to bias its\n    behavior.\n    \"\"\"\n    if params[\"activate\"]:\n        bias_string = params[\"bias string\"].strip()\n        return f\"{string} {bias_string} \"\n    return string\n\n\ndef ui():\n    \"\"\"Adds the LTM-specific settings.\"\"\"\n    with gr.Accordion(\"Long Term Memory settings\", open=True):\n        with gr.Row():\n            update = gr.Button(\"Force reload memories\")\n    with gr.Accordion(\n        \"Long Term Memory debug status (must manually refresh)\", open=True\n    ):\n        with gr.Row():\n            current_memory = gr.Textbox(\n                value=_get_current_memory_text(),\n                label=\"Current memory loaded by bot\",\n            )\n            current_ltm_stats = gr.Textbox(\n                value=_get_current_ltm_stats(),\n                label=\"LTM statistics\",\n            )\n        with gr.Row():\n            current_context_block = gr.Textbox(\n                value=_get_current_context_block(),\n                label=\"Current FIXED context block (ONLY includes example convos)\"\n            )\n        with gr.Row():\n            refresh_debug = gr.Button(\"Refresh\")\n    with gr.Accordion(\"Long Term Memory DANGER ZONE (don't do this immediately after switching chars, write a msg first)\", open=False):\n        with gr.Row():\n            destroy = gr.Button(\"Destroy all memories\", variant=\"stop\")\n            destroy_confirm = gr.Button(\n                \"THIS IS IRREVERSIBLE, ARE YOU SURE?\", variant=\"stop\", visible=False\n            )\n            destroy_cancel = gr.Button(\"Do Not Delete\", visible=False)\n            destroy_elems = [destroy_confirm, destroy, destroy_cancel]\n\n    # Update memories\n    update.click(memory_database.reload_embeddings_from_disk, [], [])\n\n    # Update debug info\n    refresh_debug.click(fn=_get_current_memory_text, outputs=[current_memory])\n    refresh_debug.click(fn=_get_current_ltm_stats, outputs=[current_ltm_stats])\n    refresh_debug.click(fn=_get_current_context_block, outputs=[current_context_block])\n\n    # Clear memory with confirmation\n    destroy.click(\n        lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)],\n        None,\n        destroy_elems,\n    )\n    destroy_confirm.click(\n        lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)],\n        None,\n        destroy_elems,\n    )\n    destroy_confirm.click(memory_database.destroy_all_memories, [], [])\n    destroy_cancel.click(\n        lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)],\n        None,\n        destroy_elems,\n    )\n\n\ndef _build_memory_context(fetched_memories: List[Tuple[str, float]], name1: str, name2: str):\n    memory_length_cutoff = _CONFIG[\"ltm_reads\"][\"memory_length_cutoff_in_chars\"]\n\n    # Build all the individual memory strings\n    memory_strs = []\n    distance_scores = []\n    debug_texts[\"current_memory_text\"] = \"(None)\"\n    debug_texts[\"num_memories_loaded\"] = 0\n    for (fetched_memory, distance_score) in fetched_memories:\n        if fetched_memory and distance_score < _CONFIG[\"ltm_reads\"][\"max_cosine_distance\"]:\n            time_difference = get_time_difference_message(fetched_memory[\"timestamp\"])\n            memory_str = _CONFIG[\"ltm_context\"][\"memory_template\"].format(\n                time_difference=time_difference,\n                memory_name=fetched_memory[\"name\"],\n                memory_message=fetched_memory[\"message\"][:memory_length_cutoff],\n            )\n            memory_strs.append(memory_str)\n            distance_scores.append(distance_score)\n\n    # No memories fetched, we'll have no memory_context\n    if not memory_strs:\n        return None\n\n    # Now inject all memory strings into the wider memory context\n    joined_memory_strs = \"\\n\".join(memory_strs)\n    memory_context = _CONFIG[\"ltm_context\"][\"memory_context_template\"].format(\n        name1=name1,\n        name2=name2,\n        all_memories=joined_memory_strs,\n    )\n\n    # Report debugging info to user\n    print(\"------------------------------\")\n    print(\"NEW MEMORIES LOADED IN CHATBOT\")\n    pprint.pprint(joined_memory_strs)\n    debug_texts[\"current_memory_text\"] = joined_memory_strs\n    debug_texts[\"num_memories_loaded\"] = len(memory_strs)\n    print(\"scores (in order)\", distance_scores)\n    print(\"------------------------------\")\n    return memory_context\n\n\n# Thanks to @oobabooga for providing the fixes for:\n# https://github.com/wawawario2/long_term_memory/issues/12\n# https://github.com/wawawario2/long_term_memory/issues/14\n# https://github.com/wawawario2/long_term_memory/issues/19\ndef custom_generate_chat_prompt(\n    user_input,\n    state,\n    **kwargs,\n):\n    \"\"\"Main hook that allows us to fetch and store memories from/to LTM.\"\"\"\n    print(\"=\" * 60)\n\n    character_name = state[\"name2\"].strip().lower().replace(\" \", \"_\")\n    memory_database.load_character_db_if_new(character_name)\n\n    user_input = fix_newlines(user_input)\n\n    # === Fetch the \"best\" memory from LTM, if there is one ===\n    fetched_memories = memory_database.query(\n        user_input,\n    )\n    memory_context = _build_memory_context(fetched_memories, state[\"name1\"], state[\"name2\"])\n\n    # === Call oobabooga's original generate_chat_prompt ===\n    augmented_context = state[\"context\"]\n    if memory_context is not None:\n        augmented_context = _build_augmented_context(memory_context, state[\"context\"])\n    debug_texts[\"current_context_block\"] = augmented_context\n\n    kwargs[\"also_return_rows\"] = True\n    state[\"context\"] = augmented_context\n    (prompt, prompt_rows) = generate_chat_prompt(\n        user_input,\n        state,\n        **kwargs,\n    )\n\n    # === Clean and add new messages to LTM ===\n    # Store the bot's last message.\n    # Avoid storing any of the baked-in bot template responses\n    if len(prompt_rows) >= _MIN_ROWS_TILL_RESPONSE:\n        bot_message = prompt_rows[_LAST_BOT_MESSAGE_INDEX]\n        clean_bot_message = clean_character_message(state[\"name2\"], bot_message)\n\n        # Store bot message into LTM\n        if len(clean_bot_message) >= _CONFIG[\"ltm_writes\"][\"min_message_length\"]:\n            memory_database.add(state[\"name2\"], clean_bot_message)\n            print(\"-----------------------\")\n            print(\"NEW MEMORY SAVED to LTM\")\n            print(\"-----------------------\")\n            print(\"name:\", state[\"name2\"])\n            print(\"message:\", clean_bot_message)\n            print(\"-----------------------\")\n\n    # Store Anon's input directly into LTM\n    if len(user_input) >= _CONFIG[\"ltm_writes\"][\"min_message_length\"]:\n        memory_database.add(state[\"name1\"], user_input)\n        print(\"-----------------------\")\n        print(\"NEW MEMORY SAVED to LTM\")\n        print(\"-----------------------\")\n        print(\"name:\", state[\"name1\"])\n        print(\"message:\", user_input)\n        print(\"-----------------------\")\n\n    return prompt\n"
  },
  {
    "path": "utils/_test/test_chat_parsing.py",
    "content": "\"\"\"Tests for the chat_parsing module.\"\"\"\n\nfrom extensions.long_term_memory.utils.chat_parsing import (\n    clean_character_message,\n)\n\n\ndef test_clean_character_message():\n    \"\"\"Ensures clean_character_message works as expected.\"\"\"\n\n    # Single response\n    expected_result = \"Hai ^_^\"\n    assert expected_result == clean_character_message(\"Miku\", \"Miku: Hai ^_^\")\n\n    # Multiple responses\n    expected_result = \"Hai ^_^ Did you do your best today?\"\n    assert expected_result == clean_character_message(\n        \"Miku\", \"Miku: Hai ^_^ Miku: Did you do your best today?\"\n    )\n\n    # No responses\n    assert \"\" == clean_character_message(\"Miku\", \"Invalid message\")\n\n    # Empty input\n    assert \"\" == clean_character_message(\"Miku\", \"\")\n\n    # Message with only bot name and no text\n    assert \"\" == clean_character_message(\"Miku\", \"Miku: \")\n\n    # Leading and trailing whitespaces\n    expected_result = \"iToddlers BTFO HAHAHAHA\"\n    assert expected_result == clean_character_message(\n        \"Satania\", \"\\n   Satania: iToddlers    Satania: BTFO HAHAHAHA  \\n \"\n    )\n\n    # Bot message with special characters\n    expected_result = \"/think *he likes me!* (◕ω◕) yay!!11\"\n    assert expected_result == clean_character_message(\n        \"Miku\", \"Miku: /think *he likes me!* (◕ω◕) Miku: yay!!11\"\n    )\n"
  },
  {
    "path": "utils/_test/test_timestamp_parsing.py",
    "content": "\"\"\"Tests for the timestamp_parsing module.\"\"\"\n\nfrom datetime import datetime, timedelta\n\nimport pytest\n\nfrom extensions.long_term_memory.utils.timestamp_parsing import (\n    get_time_difference_message,\n)\n\n\ndef test_get_time_difference_message():\n    \"\"\"Ensures get_time_difference_message works as expected.\"\"\"\n\n    now = datetime.utcnow()\n\n    # The time between now and now is 0 days.\n    timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n    assert get_time_difference_message(timestamp) == \"0 days ago\"\n\n    # Round down if we haven't passed a full day.\n    one_day_ago = now - timedelta(days=0, hours=8)\n    timestamp = one_day_ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n    assert get_time_difference_message(timestamp) == \"0 days ago\"\n\n    # Ensure we actually see multiple days.\n    five_days_ago = now - timedelta(days=5, hours=16)\n    timestamp = five_days_ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n    assert get_time_difference_message(timestamp) == \"5 days ago\"\n\n    # Ensure we raise on error.\n    with pytest.raises(ValueError):\n        get_time_difference_message(\"invalid timestamp\")\n"
  },
  {
    "path": "utils/chat_parsing.py",
    "content": "\"\"\"Utils that parse chat logs.\"\"\"\n\n\ndef clean_character_message(name: str, message: str) -> str:\n    \"\"\"\n    Sometimes the chatbot will respond multiple times in a single\n    message, each response being prefixed with '{bot_name}: '.\n    This function parses each sub-message and returns them as a single\n    continuous sentence.\n    \"\"\"\n    name_header = f\"{name}: \"\n\n    # The character isn't saying anything, return an empty list\n    if name_header not in message:\n        return \"\"\n\n    # The character may be saying something, parse and return all messages\n    split_message = message.split(name_header)\n    messages = [line.strip() for line in split_message]\n    messages = [line for line in messages if line]\n    clean_message = \" \".join(messages).strip()\n\n    return clean_message\n"
  },
  {
    "path": "utils/timestamp_parsing.py",
    "content": "\"\"\"Timestamp parsing utils.\"\"\"\n\nimport math\nfrom datetime import datetime\n\n\ndef get_time_difference_message(past_timestamp: str) -> str:\n    \"\"\"Converts a timestamp from the past to a \"X days ago\" format.\"\"\"\n    datetime_format = \"%Y-%m-%d %H:%M:%S\"\n    past = datetime.strptime(past_timestamp, datetime_format)\n    now = datetime.utcnow()\n    delta = now - past\n\n    days = math.floor(delta.days)\n    message = f\"{days} days ago\"\n    return message\n"
  }
]