[
  {
    "path": ".github/ISSUE_TEMPLATE/bug.md",
    "content": "---\nname: Bug\nabout: Create a report to help improve the project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where the package manifests are located.\n# Please see the documentation for all configuration options:\n# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file\n\nversion: 2\nupdates:\n  - package-ecosystem: \"pip\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/stale_issues.yml",
    "content": "name: Close inactive issues\non:\n  schedule:\n    - cron: \"10 00 * * *\"\n\njobs:\n  close-issues:\n    runs-on: ubuntu-latest\n    permissions:\n      issues: write\n      pull-requests: write\n    steps:\n      - uses: actions/stale@v5\n        with:\n          stale-issue-message: \"\"\n          close-issue-message: \"This issue has been closed due to inactivity for 6 months. If you believe it is still relevant, please leave a comment below. You can tag a developer in your comment.\"\n          days-before-issue-stale: 180\n          days-before-issue-close: 0\n          stale-issue-label: \"stale\"\n          days-before-pr-stale: -1\n          days-before-pr-close: -1\n          repo-token: ${{ secrets.GITHUB_TOKEN }}"
  },
  {
    "path": ".github/workflows/unit_tests.yml",
    "content": "# This workflow will install Python dependencies, run tests and lint with a single version of Python\n# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python\n\nname: Unit Tests\n\non:\n  push:\n    branches: [ \"main\" ]\n  pull_request:\n    branches: [ \"main\" ]\n  schedule:\n    - cron: \"20 4 * * *\"\n\npermissions:\n  contents: read\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v4\n    - name: Set up Python 3.11\n      uses: actions/setup-python@v4\n      with:\n        python-version: \"3.11\"\n        cache: 'pip'\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install flake8 pytest optimum\n        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi\n    - name: Lint with flake8\n      run: |\n        # stop the build if there are Python syntax errors or undefined names\n        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics\n        # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide\n        flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics\n    - name: Test with pytest\n      run: |\n        pytest\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": "# Give your local LLM the ability to search the web!\n![unit tests](https://github.com/mamei16/LLM_Web_search/actions/workflows/unit_tests.yml/badge.svg?branch=main)\n\nThis project gives local LLMs the ability to search the web, either by using native tool calls or by outputting a specific\ncommand. Once a tool call has been issued or a command has been found in the model output using a regular expression, a web search is executed, returning a number of result pages. Finally, an\nensemble of a dense embedding model and \n[Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) (Or alternatively, [SPLADE](https://github.com/naver/splade))\nis used to extract the relevant parts (if any) of each web page in the search results\nand the results are appended to the model's output.\n![llm_websearch](https://github.com/mamei16/LLM_Web_search/assets/25900898/f9d2d83c-e3cf-4f69-91c2-e9c3fe0b7d89)\n\n\n* **[Table of Contents](#table-of-contents)**\n  * [Installation](#installation)\n  * [Usage](#usage)\n\t+ [Native Tool Calling Mode](#native-tool-calling-mode)\n\t+ [Legacy Mode](#legacy-mode)\n    \t+ [Using a custom regular expression](#using-a-custom-regular-expression)\n    \t+ [Reading web pages](#reading-web-pages)\n  * [Search backends](#search-backends)\n    + [DuckDuckGo](#duckduckgo)\n    + [SearXNG](#searxng)\n      + [Search parameters](#search-parameters)\n  * [Search types](#search-types)\n\t  + [Simple search](#simple-search)\n\t  + [Full search](#full-search)\n  * [Keyword retrievers](#keyword-retrievers)\n    + [Okapi BM25](#okapi-bm25)\n    + [SPLADE](#splade)\n  * [Chunking Methods](#chunking-methods)\n    + [Character-based Chunking](#character-based-chunking)\n    + [Semantic Chunking](#semantic-chunking)\n    + [Token Classification based Chunking](#token-classification-based-chunking)\n  * [Recommended models](#recommended-models)\n\n## Installation\n1. Go to the \"Session\" tab of the web UI and use \"Install or update an extension\" \nto download the latest code for this extension.\n2. Run the appropriate `update_wizard` script inside the text-generation-webui folder\n   and choose `Install/update extensions requirements`, then choose the name of this extension.\n3. Launch the Web UI by running the appropriate `start` script and enable the extension under the session tab.  \n Alternatively,\nyou can also start the server directly using the following command (assuming you have activated your conda/virtual environment):  \n```python server.py --extension LLM_Web_search```\n\nIf the installation was successful and the extension was loaded, a new tab with the \ntitle \"Web Search\" should be visible in the web UI.\n\nSee https://github.com/oobabooga/text-generation-webui/wiki/07-%E2%80%90-Extensions for more\ninformation about extensions.\n\n\n## Usage\n\n### Native Tool Calling Mode\nYou can make this extension available as a tool by simply checking the \"Add as tool when enabled\" checkbox in the \"Web Search\" tab. Refresh the list of tools in the \"Chat\" tab if needed.\n\nIn native tool calling mode, the current date and time is provided to the model with each set of search results.\n\n### Legacy Mode\n\nModels that have not been trained with native tool calling can still be taught how to perform web searches via zero-shot learning, i.e., by prompting the model\nto use a fixed search command (see `system_prompts/` for example prompts).\n\nSearch queries are then extracted from the model's output using a regular expression.\n\nAn example workflow of using this extension in legacy mode could be:\n1. Load a model\n2. Head over to the \"Web Search\" tab\n3. Load a custom system message/prompt\n4. Ensure that the query part of the command mentioned in the system message \ncan be matched using the current \"Search command regex string\" \n(see \"Using a custom regular expression\" below)\n5. Pick a generation parameter preset that works well for you. You can read more about generation parameters [here](https://github.com/oobabooga/text-generation-webui/wiki/03-%E2%80%90-Parameters-Tab#generation)\n6. Choose \"chat-instruct\" or \"instruct\" mode and start chatting\n\n#### Using a custom regular expression\nThe default regular expression is:  \n```regexp\nSearch_web\\(\"(.*)\"\\)\n```\nWhere `Search_web` is the search command and everything between the quotation marks\ninside the parentheses will be used as the search query. Every custom regular expression must use a\n[capture group](https://www.regular-expressions.info/brackets.html) to extract the search\nquery. I recommend https://www.debuggex.com/ to try out custom regular expressions. If a regex\nfulfills the requirement above, the search query should be matched by \"Group 1\" in Debuggex.\n\nHere is an example of a more flexible, but more complex, regex that works for several\ndifferent models:\n```regexp\n[Ss]earch_web\\((?:[\"'])(.*)(?:[\"'])\\)\n```\n#### Reading web pages\nBasic support exists for extracting the full text content from a webpage. The default regex to use this\nfunctionality is:\n```regexp\nDownload_webpage\\(\"(.*)\"\\)\n```\n**Note**: The full content of a web page is likely to exceed the maximum context length of your average local LLM.\n## Search backends\n\n### DuckDuckGo\nThis is the default web search backend. \n\n### SearXNG\n\nTo use a local or remote SearXNG instance instead of DuckDuckGo, simply paste the URL into the \n\"SearXNG URL\" text field of the \"LLM Web Search\" settings tab (be sure to include `http://` or `https://`). The instance must support\nreturning results in JSON format.\n\n#### Search parameters\nTo modify the categories, engines, languages etc. that should be used for a\nspecific query, it must follow the\n[SearXNG search syntax](https://docs.searxng.org/user/search-syntax.html). Currently, \nautomatic redirect and Special Queries are not supported.\n\n\n## Search types\n### Simple search\nQuickly finds answers using just the highlighted snippets from websites returned by the search engine. If you simply want results *fast*, choose this search type.  \nNote: Some advanced options in the UI will be hidden when simple search is enabled, as they have no effect in this case.  \nNote2: The snippets returned by SearXNG are often much more useful than those returned by DuckDuckGo, so consider using SearXNG as the search backend if you use simple search.\n### Full search\nScans entire websites in the results for a more comprehensive search. Ideally, this search type should be able to find \"needle in the haystack\" information hidden somewhere in the website text. Hence, choose this option if you want to trade a more resource intensive search process for generally more relevant search results.   \n**For the best possible search results, also enable token classification based chunking and use SPLADE as the keyword retriever.**\n## Keyword retrievers\n### Okapi BM25\nThis extension comes out of the box with \n[Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) enabled, which is widely used and very popular\nfor keyword based document retrieval. It runs on the CPU and,\nfor the purpose of this extension, it is fast.  \n### SPLADE\nIf you don't run the extension in \"CPU only\" mode and have some VRAM to spare,\nyou can also select [SPLADE](https://github.com/naver/splade) in the \"Advanced settings\" section\nas an alternative. It has been [shown](https://arxiv.org/pdf/2207.03834.pdf) to outperform BM25 in multiple benchmarks \nand uses a technique called \"query expansion\" to add additional contextually relevant words\nto the original query. However, it is slower than BM25. You can read more about it [here](https://www.pinecone.io/learn/splade/).  \n\nTo improve performance, documents are embedded in batches and in parallel. Increasing the\n\"SPLADE batch size\" parameter setting improves performance up to a certain point,\nbut VRAM usage ramps up quickly with increasing batch size. A batch size of 8 appears \nto be a good trade-off, but the default value is 2 to avoid running out of memory on smaller\nGPUs.\n\n## Chunking Methods\n\n### Character-based Chunking\n\nNaively partitions a website's text into fixed sized chunks without any regard for the text content. This is the default, since it is fast and requires no GPU.\n\n### Semantic Chunking\n\nTries to partition a website's text into chunks based on semantics. If two consecutive sentences have very different embeddings (based on the cosine distance between their embeddings), a new chunk will be started. How different two consecutive sentences have to be for them to end up in different chunks can be tuned using the ` sentence split threshold` parameter in the UI.  \nFor natural language, this method generally produces much better results than character-based chunking. However, it is noticeably slower, even when using the GPU.\n\n### Token Classification based Chunking\n\nThis chunking method employs a fine-tune of the DistilBERT transformer model, which has been trained to classify tokens (see [chonky](https://github.com/mirth/chonky)). If a token is classified as the positive class, a new paragraph (or a new chunk) is meant to be started after the token.\n \nWhile semantic chunking only compares pairs of consecutive sentences when deciding on where to start a new chunk, the token classification model can utilize a much longer context. However, the need to process this context means that this chunking method is slower than semantic chunking."
  },
  {
    "path": "chunkers/base_chunker.py",
    "content": "import warnings\nimport copy\nfrom typing import Any, List, Literal, Optional, Union, Callable, Iterable, Sequence\nfrom abc import abstractmethod\n\ntry:\n    from ..utils import Document\nexcept:\n    from utils import Document\n\n\nclass TextSplitter:\n    \"\"\"Interface for splitting text into chunks.\n    Source: https://github.com/langchain-ai/langchain/blob/master/libs/text-splitters/langchain_text_splitters/base.py#L30\n    \"\"\"\n\n    def __init__(\n        self,\n        chunk_size: int = 4000,\n        chunk_overlap: int = 200,\n        length_function: Callable[[str], int] = len,\n        keep_separator: Union[bool, Literal[\"start\", \"end\"]] = False,\n        add_start_index: bool = False,\n        strip_whitespace: bool = True,\n    ) -> None:\n        \"\"\"Create a new TextSplitter.\n\n        Args:\n            chunk_size: Maximum size of chunks to return\n            chunk_overlap: Overlap in characters between chunks\n            length_function: Function that measures the length of given chunks\n            keep_separator: Whether to keep the separator and where to place it\n                            in each corresponding chunk (True='start')\n            add_start_index: If `True`, includes chunk's start index in metadata\n            strip_whitespace: If `True`, strips whitespace from the start and end of\n                              every document\n        \"\"\"\n        if chunk_overlap > chunk_size:\n            raise ValueError(\n                f\"Got a larger chunk overlap ({chunk_overlap}) than chunk size \"\n                f\"({chunk_size}), should be smaller.\"\n            )\n        self._chunk_size = chunk_size\n        self._chunk_overlap = chunk_overlap\n        self._length_function = length_function\n        self._keep_separator = keep_separator\n        self._add_start_index = add_start_index\n        self._strip_whitespace = strip_whitespace\n\n    @abstractmethod\n    def split_text(self, text: str) -> List[str]:\n        \"\"\"Split text into multiple components.\"\"\"\n\n    def create_documents(\n        self, texts: List[str], metadatas: Optional[List[dict]] = None\n    ) -> List[Document]:\n        \"\"\"Create documents from a list of texts.\"\"\"\n        _metadatas = metadatas or [{}] * len(texts)\n        documents = []\n        for i, text in enumerate(texts):\n            index = 0\n            previous_chunk_len = 0\n            for chunk in self.split_text(text):\n                metadata = copy.deepcopy(_metadatas[i])\n                if self._add_start_index:\n                    offset = index + previous_chunk_len - self._chunk_overlap\n                    index = text.find(chunk, max(0, offset))\n                    metadata[\"start_index\"] = index\n                    previous_chunk_len = len(chunk)\n                new_doc = Document(page_content=chunk, metadata=metadata)\n                documents.append(new_doc)\n        return documents\n\n    def split_documents(self, documents: Iterable[Document]) -> List[Document]:\n        \"\"\"Split documents.\"\"\"\n        texts, metadatas = [], []\n        for doc in documents:\n            texts.append(doc.page_content)\n            metadatas.append(doc.metadata)\n        return self.create_documents(texts, metadatas=metadatas)\n\n    def _join_docs(self, docs: List[str], separator: str) -> Optional[str]:\n        text = separator.join(docs)\n        if self._strip_whitespace:\n            text = text.strip()\n        if text == \"\":\n            return None\n        else:\n            return text\n\n    def _merge_splits(self, splits: Iterable[str], separator: str) -> List[str]:\n        # We now want to combine these smaller pieces into medium size\n        # chunks to send to the LLM.\n        separator_len = self._length_function(separator)\n\n        docs = []\n        current_doc: List[str] = []\n        total = 0\n        for d in splits:\n            _len = self._length_function(d)\n            if (\n                total + _len + (separator_len if len(current_doc) > 0 else 0)\n                > self._chunk_size\n            ):\n                if total > self._chunk_size:\n                    warnings.warn(\n                        f\"Created a chunk of size {total}, \"\n                        f\"which is longer than the specified {self._chunk_size}\"\n                    )\n                if len(current_doc) > 0:\n                    doc = self._join_docs(current_doc, separator)\n                    if doc is not None:\n                        docs.append(doc)\n                    # Keep on popping if:\n                    # - we have a larger chunk than in the chunk overlap\n                    # - or if we still have any chunks and the length is long\n                    while total > self._chunk_overlap or (\n                        total + _len + (separator_len if len(current_doc) > 0 else 0)\n                        > self._chunk_size\n                        and total > 0\n                    ):\n                        total -= self._length_function(current_doc[0]) + (\n                            separator_len if len(current_doc) > 1 else 0\n                        )\n                        current_doc = current_doc[1:]\n            current_doc.append(d)\n            total += _len + (separator_len if len(current_doc) > 1 else 0)\n        doc = self._join_docs(current_doc, separator)\n        if doc is not None:\n            docs.append(doc)\n        return docs\n\n    def transform_documents(\n            self, documents: Sequence[Document], **kwargs: Any\n    ) -> Sequence[Document]:\n        \"\"\"Transform sequence of documents by splitting them.\"\"\"\n        return self.split_documents(list(documents))"
  },
  {
    "path": "chunkers/character_chunker.py",
    "content": "from typing import Any, List, Literal, Optional, Union, Callable\nimport re\n\ntry:\n    from ..chunkers.base_chunker import TextSplitter\nexcept:\n    from chunkers.base_chunker import TextSplitter\n\n\nclass RecursiveCharacterTextSplitter(TextSplitter):\n    \"\"\"Splitting text by recursively look at characters.\n\n    Recursively tries to split by different characters to find one\n    that works.\n\n    Adapted from Langchain:\n    https://github.com/langchain-ai/langchain/blob/0606aabfa39acb2ec575ea8bbfa4c8e662a6134f/libs/text-splitters/langchain_text_splitters/character.py#L58\n    \"\"\"\n    def __init__(self, chunk_size: int = 4000, chunk_overlap: int = 200, length_function: Callable[[str], int] = len,\n                 add_start_index: bool = False, strip_whitespace: bool = True, separators: Optional[List[str]] = None,\n                 keep_separator: Union[bool, Literal[\"start\", \"end\"]] = \"end\", is_separator_regex: bool = False,\n                 **kwargs: Any) -> None:\n        \"\"\"Create a new TextSplitter.\"\"\"\n        super().__init__(chunk_size, chunk_overlap, length_function, keep_separator, add_start_index, strip_whitespace)\n        if chunk_overlap > chunk_size:\n            raise ValueError(\n                f\"Got a larger chunk overlap ({chunk_overlap}) than chunk size \"\n                f\"({chunk_size}), should be smaller.\"\n            )\n\n        self._separators = separators or [\"\\n\\n\", \"\\n\", \" \", \"\"]\n        self._is_separator_regex = is_separator_regex\n\n    def _split_text(self, text: str, separators: List[str]) -> List[str]:\n        \"\"\"Split incoming text and return chunks.\"\"\"\n        final_chunks = []\n        # Get appropriate separator to use\n        separator = separators[-1]\n        new_separators = []\n        for i, _s in enumerate(separators):\n            _separator = _s if self._is_separator_regex else re.escape(_s)\n            if _s == \"\":\n                separator = _s\n                break\n            if re.search(_separator, text):\n                separator = _s\n                new_separators = separators[i + 1 :]\n                break\n\n        _separator = separator if self._is_separator_regex else re.escape(separator)\n        splits = _split_text_with_regex(text, _separator, self._keep_separator)\n\n        # Now go merging things, recursively splitting longer texts.\n        _good_splits = []\n        _separator = \"\" if self._keep_separator else separator\n        for s in splits:\n            if self._length_function(s) < self._chunk_size:\n                _good_splits.append(s)\n            else:\n                if _good_splits:\n                    merged_text = self._merge_splits(_good_splits, _separator)\n                    final_chunks.extend(merged_text)\n                    _good_splits = []\n                if not new_separators:\n                    final_chunks.append(s)\n                else:\n                    other_info = self._split_text(s, new_separators)\n                    final_chunks.extend(other_info)\n        if _good_splits:\n            merged_text = self._merge_splits(_good_splits, _separator)\n            final_chunks.extend(merged_text)\n        return final_chunks\n\n    def split_text(self, text: str) -> List[str]:\n        return self._split_text(text, self._separators)\n\n\ndef _split_text_with_regex(\n    text: str, separator: str, keep_separator: Union[bool, Literal[\"start\", \"end\"]]\n) -> List[str]:\n    # Now that we have the separator, split the text\n    if separator:\n        if keep_separator:\n            # The parentheses in the pattern keep the delimiters in the result.\n            _splits = re.split(f\"({separator})\", text)\n            splits = (\n                ([_splits[i] + _splits[i + 1] for i in range(0, len(_splits) - 1, 2)])\n                if keep_separator == \"end\"\n                else ([_splits[i] + _splits[i + 1] for i in range(1, len(_splits), 2)])\n            )\n            if len(_splits) % 2 == 0:\n                splits += _splits[-1:]\n            splits = (\n                (splits + [_splits[-1]])\n                if keep_separator == \"end\"\n                else ([_splits[0]] + splits)\n            )\n        else:\n            splits = re.split(separator, text)\n    else:\n        splits = list(text)\n    return [s for s in splits if s != \"\"]"
  },
  {
    "path": "chunkers/ner_chunker.py",
    "content": "from typing import List\nfrom attr import dataclass\n\nimport torch\nimport numpy as np\nfrom transformers import AutoTokenizer, AutoModelForTokenClassification\ntry:\n    from ..chunkers.base_chunker import TextSplitter\n    from ..chunkers.character_chunker import RecursiveCharacterTextSplitter\nexcept:\n    from chunkers.base_chunker import TextSplitter\n    from chunkers.character_chunker import RecursiveCharacterTextSplitter\n\n\ndef batchify(lst, batch_size):\n    last_item_shorter = False\n    if len(lst[-1]) < len(lst[0]):\n        last_item_shorter = True\n        max_index = len(lst)-1\n    else:\n        max_index = len(lst)\n\n    for i in range(0, max_index, batch_size):\n        yield lst[i : min(i + batch_size, max_index)]\n\n    if last_item_shorter:\n        yield lst[-1:]\n\n\n@dataclass\nclass Token:\n    index: int\n    start: int\n    end: int\n    length: int\n    decoded_str: str\n\n\nclass TokenClassificationChunker(TextSplitter):\n    def __init__(self, model_id=\"mirth/chonky_distilbert_base_uncased_1\", device=\"cpu\", model_cache_dir: str = None,\n                 max_chunk_size: int = 99999):\n        super().__init__()\n        self.device = device\n        self.is_modernbert = model_id.startswith(\"mirth/chonky_modernbert\")\n        self.is_mmBERT = model_id == \"mirth/chonky_mmbert_small_multilingual_1\"\n        self.max_chunk_size = max_chunk_size\n        self.character_splitter = RecursiveCharacterTextSplitter(chunk_size=max_chunk_size, chunk_overlap=10,\n                                                                 separators=[\"\\n\\n\", \"\\n\", \".\", \", \", \" \", \"\"])\n        id2label = {\n            0: \"O\",\n            1: \"separator\",\n        }\n        label2id = {\n            \"O\": 0,\n            \"separator\": 1,\n        }\n\n        if self.is_modernbert or self.is_mmBERT:\n            tokenizer_kwargs = {\"model_max_length\": 1024}\n        else:\n            tokenizer_kwargs = {}\n        self.tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=model_cache_dir, **tokenizer_kwargs)\n        self.model = AutoModelForTokenClassification.from_pretrained(\n            model_id,\n            num_labels=2,\n            id2label=id2label,\n            label2id=label2id,\n            cache_dir=model_cache_dir,\n            torch_dtype=torch.float32 if device == \"cpu\" else torch.float16\n        )\n        self.model.eval()\n        self.model.to(device)\n\n    def split_into_semantic_chunks(self, text, separator_indices: List[int]):\n        start_index = 0\n\n        for idx in separator_indices:\n            chunk = text[start_index:idx].strip()\n            if len(chunk) > self.max_chunk_size:\n                yield from self.character_splitter.split_text(chunk)\n            else:\n                yield chunk\n            start_index = idx\n\n        if start_index < len(text):\n            yield text[start_index:].strip()\n\n    def split_text(self, text: str) -> List[str]:\n        max_seq_len = self.tokenizer.model_max_length\n        window_step_size = max_seq_len // 2\n        ids_plus = self.tokenizer(text, truncation=True, add_special_tokens=True, return_offsets_mapping=True,\n                                  return_overflowing_tokens=True, stride=window_step_size)\n\n        tokens = [[Token(i*max_seq_len+j,\n                         offset_tup[0], offset_tup[1],\n                         offset_tup[1]-offset_tup[0],\n                         text[offset_tup[0]:offset_tup[1]]) for j, offset_tup in enumerate(offset_list)]\n                  for i, offset_list in enumerate(ids_plus[\"offset_mapping\"])]\n\n        input_ids = ids_plus[\"input_ids\"]\n        all_separator_tokens = []\n\n        batch_size = 4\n        for input_id_batch, token_batch in zip(batchify(input_ids, batch_size),\n                                               batchify(tokens, batch_size)):\n            with torch.no_grad():\n                output = self.model(torch.tensor(input_id_batch).to(self.device))\n\n            logits = output.logits.cpu().numpy()\n            maxes = np.max(logits, axis=-1, keepdims=True)\n            shifted_exp = np.exp(logits - maxes)\n            scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)\n            token_classes = scores.argmax(axis=-1)\n            # Find last index of each sequence of ones in token class sequence\n            separator_token_idx_tup = ((token_classes[:, :-1] - token_classes[:, 1:]) > 0).nonzero()\n\n            separator_tokens = [token_batch[i][j] for i, j in zip(*separator_token_idx_tup)]\n            all_separator_tokens.extend(separator_tokens)\n\n        flat_tokens = [token for window in tokens for token in window]\n        sorted_separator_tokens = sorted(all_separator_tokens, key=lambda x: x.start)\n        separator_indices = []\n        num_sep_tokens = len(sorted_separator_tokens)\n        for i in range(num_sep_tokens):\n            current_sep_token = sorted_separator_tokens[i]\n            if current_sep_token.end == 0:\n                continue\n            # next_token is the token succeeding current_sep_token in the original text\n            next_token = flat_tokens[current_sep_token.index+1]\n\n            # If current separator token is part of a bigger contiguous token, move to the end of the bigger token\n            while (current_sep_token.end == next_token.start and\n                   (not self.is_modernbert or (current_sep_token.decoded_str != '\\n'\n                                               and not next_token.decoded_str.startswith(' '))) and\n                   (not self.is_mmBERT or (not current_sep_token.decoded_str.startswith('\\n')\n                                               and not next_token.decoded_str.startswith(' ')))):\n                current_sep_token = next_token\n                next_token = flat_tokens[current_sep_token.index+1]\n\n            if i < num_sep_tokens - 1:\n                next_sep_token = sorted_separator_tokens[i + 1]\n                if ((current_sep_token.start + current_sep_token.length) > next_sep_token.start or\n                    ((next_sep_token.end - current_sep_token.end) <= 1)):\n                    continue\n\n            separator_indices.append(current_sep_token.end)\n\n        yield from self.split_into_semantic_chunks(text, separator_indices)\n"
  },
  {
    "path": "chunkers/semantic_chunker.py",
    "content": "import re\nfrom typing import Dict, List, Literal, Optional, Tuple, cast\n\nimport numpy as np\nfrom sentence_transformers import SentenceTransformer\n\ntry:\n    from ..chunkers.character_chunker import RecursiveCharacterTextSplitter\n    from ..chunkers.base_chunker import TextSplitter\n    from ..utils import Document\nexcept:\n    from chunkers.character_chunker import RecursiveCharacterTextSplitter\n    from chunkers.base_chunker import TextSplitter\n    from utils import Document\n\n\ndef calculate_cosine_distances(sentence_embeddings) -> np.array:\n    \"\"\"Calculate cosine distances between sentences.\n\n    Args:\n        sentence_embeddings: List of sentence embeddings to calculate distances for.\n\n    Returns:\n        Distance between each pair of adjacent sentences\n    \"\"\"\n    # Sliding window array over each pair of adjacent sentence embeddings\n    sliding_windows = np.lib.stride_tricks.sliding_window_view(sentence_embeddings, 2, axis=0)\n\n    dot_prod = np.prod(sliding_windows, axis=-1).sum(axis=1)\n\n    magnitude_prod = np.prod(np.linalg.norm(sliding_windows, axis=1), axis=1)\n\n    cos_sim = dot_prod / magnitude_prod\n    return 1 - cos_sim\n\n\nBreakpointThresholdType = Literal[\"percentile\", \"standard_deviation\", \"interquartile\"]\nBREAKPOINT_DEFAULTS: Dict[BreakpointThresholdType, float] = {\n    \"percentile\": 95,\n    \"standard_deviation\": 3,\n    \"interquartile\": 1.5,\n}\n\n\nclass BoundedSemanticChunker(TextSplitter):\n    \"\"\"First splits the text using semantic chunking according to the specified\n    'breakpoint_threshold_amount', but then uses a RecursiveCharacterTextSplitter\n    to split all chunks that are larger than 'max_chunk_size'.\n\n    Adapted from langchain_experimental.text_splitter.SemanticChunker\"\"\"\n\n    def __init__(self, embedding_model: SentenceTransformer, buffer_size: int = 1, add_start_index: bool = False,\n                 breakpoint_threshold_type: BreakpointThresholdType = \"percentile\",\n                 breakpoint_threshold_amount: Optional[float] = None, number_of_chunks: Optional[int] = None,\n                 max_chunk_size: int = 500, min_chunk_size: int = 4):\n        super().__init__(add_start_index=add_start_index)\n        self._add_start_index = add_start_index\n        self.embedding_model = embedding_model\n        self.buffer_size = buffer_size\n        self.breakpoint_threshold_type = breakpoint_threshold_type\n        self.number_of_chunks = number_of_chunks\n        if breakpoint_threshold_amount is None:\n            self.breakpoint_threshold_amount = BREAKPOINT_DEFAULTS[\n                breakpoint_threshold_type\n            ]\n        else:\n            self.breakpoint_threshold_amount = breakpoint_threshold_amount\n        self.max_chunk_size = max_chunk_size\n        self.min_chunk_size = min_chunk_size\n        # Splitting the text on '.', '?', and '!'\n        self.sentence_split_regex = re.compile(r\"(?<=[.?!])\\s+\")\n\n        assert self.breakpoint_threshold_type == \"percentile\", \"only breakpoint_threshold_type 'percentile' is currently supported\"\n        assert self.buffer_size == 1, \"combining sentences is not supported yet\"\n\n    def _calculate_sentence_distances(\n        self, sentences: List[dict]\n    ) -> Tuple[List[float], List[dict]]:\n        \"\"\"Split text into multiple components.\"\"\"\n        sentences = list(map(lambda x: x.replace(\"\\n\", \" \"), sentences))\n        embeddings = self.embedding_model.encode(sentences)\n        return calculate_cosine_distances(embeddings.tolist())\n\n    def _calculate_breakpoint_threshold(self, distances: np.array, alt_breakpoint_threshold_amount=None) -> float:\n        if alt_breakpoint_threshold_amount is None:\n            breakpoint_threshold_amount = self.breakpoint_threshold_amount\n        else:\n            breakpoint_threshold_amount = alt_breakpoint_threshold_amount\n        if self.breakpoint_threshold_type == \"percentile\":\n            return cast(\n                float,\n                np.percentile(distances, breakpoint_threshold_amount),\n            )\n        elif self.breakpoint_threshold_type == \"standard_deviation\":\n            return cast(\n                float,\n                np.mean(distances)\n                + breakpoint_threshold_amount * np.std(distances),\n            )\n        elif self.breakpoint_threshold_type == \"interquartile\":\n            q1, q3 = np.percentile(distances, [25, 75])\n            iqr = q3 - q1\n\n            return np.mean(distances) + breakpoint_threshold_amount * iqr\n        else:\n            raise ValueError(\n                f\"Got unexpected `breakpoint_threshold_type`: \"\n                f\"{self.breakpoint_threshold_type}\"\n            )\n\n    def _threshold_from_clusters(self, distances: List[float]) -> float:\n        \"\"\"\n        Calculate the threshold based on the number of chunks.\n        Inverse of percentile method.\n        \"\"\"\n        if self.number_of_chunks is None:\n            raise ValueError(\n                \"This should never be called if `number_of_chunks` is None.\"\n            )\n        x1, y1 = len(distances), 0.0\n        x2, y2 = 1.0, 100.0\n\n        x = max(min(self.number_of_chunks, x1), x2)\n\n        # Linear interpolation formula\n        y = y1 + ((y2 - y1) / (x2 - x1)) * (x - x1)\n        y = min(max(y, 0), 100)\n\n        return cast(float, np.percentile(distances, y))\n\n    def split_text(\n        self,\n        text: str,\n    ) -> List[str]:\n        sentences = self.sentence_split_regex.split(text)\n\n        # having len(sentences) == 1 would cause the following\n        # np.percentile to fail.\n        if len(sentences) == 1:\n            return sentences\n\n        bad_sentences = []\n\n        distances = self._calculate_sentence_distances(sentences)\n\n        if self.number_of_chunks is not None:\n            breakpoint_distance_threshold = self._threshold_from_clusters(distances)\n        else:\n            breakpoint_distance_threshold = self._calculate_breakpoint_threshold(\n                distances\n            )\n\n        indices_above_thresh = [\n            i for i, x in enumerate(distances) if x > breakpoint_distance_threshold\n        ]\n\n        chunks = []\n        start_index = 0\n\n        # Iterate through the breakpoints to slice the sentences\n        for index in indices_above_thresh:\n            # The end index is the current breakpoint\n            end_index = index\n\n            # Slice the sentence_dicts from the current start index to the end index\n            group = sentences[start_index : end_index + 1]\n            combined_text = \" \".join(group)\n            if self.min_chunk_size <= len(combined_text) <= self.max_chunk_size:\n                chunks.append(combined_text)\n            else:\n                sent_lengths = np.array([len(sd) for sd in group])\n                good_indices = np.flatnonzero(np.cumsum(sent_lengths) <= self.max_chunk_size)\n                smaller_group = [group[i] for i in good_indices]\n                if smaller_group:\n                    combined_text = \" \".join(smaller_group)\n                    if len(combined_text) >= self.min_chunk_size:\n                        chunks.append(combined_text)\n                        group = group[good_indices[-1]:]\n                bad_sentences.extend(group)\n\n            # Update the start index for the next group\n            start_index = index + 1\n\n        # The last group, if any sentences remain\n        if start_index < len(sentences):\n            group = sentences[start_index:]\n            combined_text = \" \".join(group)\n            if self.min_chunk_size <= len(combined_text) <= self.max_chunk_size:\n                chunks.append(combined_text)\n            else:\n                sent_lengths = np.array([len(sd) for sd in group])\n                good_indices = np.flatnonzero(np.cumsum(sent_lengths) <= self.max_chunk_size)\n                smaller_group = [group[i] for i in good_indices]\n                if smaller_group:\n                    combined_text = \" \".join(smaller_group)\n                    if len(combined_text) >= self.min_chunk_size:\n                        chunks.append(combined_text)\n                        group = group[good_indices[-1]:]\n                bad_sentences.extend(group)\n\n        # If pure semantic chunking wasn't able to split all text,\n        # split the remaining problematic text using a recursive character splitter instead\n        if len(bad_sentences) > 0:\n            recursive_splitter = RecursiveCharacterTextSplitter(chunk_size=self.max_chunk_size, chunk_overlap=10,\n                                                                separators=[\"\\n\\n\", \"\\n\", \".\", \", \", \" \", \"\"])\n            for bad_sentence in bad_sentences:\n                if len(bad_sentence) >= self.min_chunk_size:\n                    chunks.extend(recursive_splitter.split_text(bad_sentence))\n        return chunks\n\n"
  },
  {
    "path": "environment.yml",
    "content": "channels:\n  - defaults\n  - conda-forge\n  - pytorch\ndependencies:\n- pip\n- faiss-cpu=1.13.2\n- pip:\n  - beautifulsoup4==4.14.3\n  - unstructured==0.22.18\n  - rank_bm25==0.2.2\n  - sentence-transformers==5.3.0\n  - Brotli==1.2.0\n  - aiohttp>=3.12.14\n  - pydantic<=2.10.6\n  - regex\n"
  },
  {
    "path": "force_search_box_theme.js",
    "content": "function toggleForceSearchDarkMode() {\n  force_search_checkbox = document.getElementById(\"force-search\");\n  var currentCSS = document.getElementById(\"highlight-css\");\n  if (currentCSS.getAttribute(\"href\") === \"file/css/highlightjs/github-dark.min.css\") {\n    force_search_checkbox.style = \"filter: invert(0)\";\n    force_search_checkbox.parentElement.style.color = \"#9ca3af\";\n  } else {\n    force_search_checkbox.style = \"filter: invert(1)\";\n    force_search_checkbox.parentElement.style.color = \"#4b5563\";\n  }\n}"
  },
  {
    "path": "llm_web_search.py",
    "content": "import urllib\nfrom urllib.parse import quote_plus\nimport regex\nimport logging\nimport html\n\nimport requests\nfrom requests.exceptions import JSONDecodeError\nfrom bs4 import BeautifulSoup\n\ntry:\n    from .retrieval import DocumentRetriever\n    from .utils import Document, Generator\nexcept ImportError:\n    from retrieval import DocumentRetriever\n    from utils import Document, Generator\n\n\ndef perform_web_search(query, max_results=3, timeout=10):\n    \"\"\"Modified version of function from main webUI in modules/web_search.py\"\"\"\n    try:\n        # Use DuckDuckGo HTML search endpoint\n        search_url = f\"https://html.duckduckgo.com/html/?q={quote_plus(query)}\"\n        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}\n\n        response = requests.get(search_url, headers=headers, timeout=timeout)\n        response.raise_for_status()\n\n        if regex.search(\"anomaly-modal__mask\", response.text, regex.DOTALL):\n            raise ValueError(\"Web search failed due to CAPTCHA\")\n\n        # Extract results with regex\n        titles = regex.findall(r'<a[^>]*class=\"[^\"]*result__a[^\"]*\"[^>]*>(.*?)</a>', response.text, regex.DOTALL)\n        urls = regex.findall(r'<a[^>]*class=\"[^\"]*result__url[^\"]*\"[^>]*>(.*?)</a>', response.text, regex.DOTALL)\n        snippets = regex.findall(r'<a[^>]*class=\"[^\"]*result__snippet[^\"]*\"[^>]*>(.*?)</a>', response.text, regex.DOTALL)\n\n        result_dicts = []\n        for i in range(min(len(titles), len(urls), len(snippets), max_results)):\n            url = f\"https://{urls[i].strip()}\"\n            title = regex.sub(r'<[^>]+>', '', titles[i]).strip()\n            title = html.unescape(title)\n            snippet = html.unescape(snippets[i]).replace(\"<b>\", \"\").replace(\"</b>\", \"\")\n            result_dicts.append({\"url\": url, \"title\": title, \"content\": snippet})\n        return result_dicts\n\n    except Exception as e:\n        logger = logging.getLogger('text-generation-webui')\n        logger.error(f\"Error performing web search: {e}\")\n        return []\n\n\ndef retrieve_from_duckduckgo(query: str, document_retriever: DocumentRetriever, max_results: int,\n                             simple_search: bool = False):\n    documents = []\n    query = query.strip(\"\\\"'\")\n    yield f'Getting results from DuckDuckGo...'\n\n    result_documents = []\n    result_urls = []\n    for result in perform_web_search(query, max_results=max_results):\n        result_document = Document(page_content=f\"Title: {result['title']}\\n{result['content']}\",\n                                   metadata={\"source\": result[\"url\"]})\n        result_documents.append(result_document)\n        result_urls.append(result[\"url\"])\n\n    if simple_search:\n        retrieval_gen = Generator(document_retriever.retrieve_from_snippets(query, result_documents))\n    else:\n        retrieval_gen = Generator(document_retriever.retrieve_from_webpages(query, result_urls))\n\n    for status_message in retrieval_gen:\n        yield status_message\n    documents.extend(retrieval_gen.retval)\n\n    if not documents:    # Fall back to old simple search rather than returning nothing\n        print(\"LLM_Web_search | Could not find any page content \"\n              \"similar enough to be extracted, using basic search fallback...\")\n        return result_documents[:max_results]\n    return documents[:max_results]\n\n\ndef retrieve_from_searxng(query: str, url: str, document_retriever: DocumentRetriever, max_results: int,\n                          instant_answers: bool, simple_search: bool = False):\n    yield f'Getting results from Searxng...'\n    headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0\",\n               \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n               \"Accept-Language\": \"en-US,en;q=0.5\"}\n    result_documents = []\n    result_urls = []\n    request_str = f\"/search?q={urllib.parse.quote(query)}&format=json&pageno=\"\n    pageno = 1\n    while len(result_urls) < document_retriever.num_results:\n        response = requests.get(url + request_str + str(pageno), headers=headers)\n\n        if not result_urls:     # no results to lose by raising an exception here\n            response.raise_for_status()\n        try:\n            response_dict = response.json()\n        except JSONDecodeError:\n            raise ValueError(\"JSONDecodeError: Please ensure that the SearXNG instance can return data in JSON format\")\n\n        result_dicts = response_dict[\"results\"]\n        if not result_dicts:\n            if \"unresponsive_engines\" in response_dict and not result_urls:\n                raise ValueError(\"No results found. Some search engines were unresponsive: \" + str(\n                    response_dict[\"unresponsive_engines\"]))\n            break\n        for result in result_dicts:\n            if \"content\" in result:   # Since some websites don't provide any description\n                result_document = Document(page_content=f\"Title: {result['title']}\\n{result['content']}\",\n                                           metadata={\"source\": result[\"url\"]})\n                result_documents.append(result_document)\n            result_urls.append(result[\"url\"])\n\n        answers = response_dict[\"answers\"]\n        if instant_answers:\n            for answer in answers:\n                answer_document = Document(page_content=f\"Title: {query}\\n{answer}\",\n                                           metadata={\"source\": \"SearXNG instant answer\"})\n                result_documents.append(answer_document)\n        pageno += 1\n\n    if simple_search:\n        retrieval_gen = Generator(document_retriever.retrieve_from_snippets(query, result_documents))\n    else:\n        retrieval_gen = Generator(document_retriever.retrieve_from_webpages(query, result_urls))\n\n    for status_message in retrieval_gen:\n        yield status_message\n    documents = retrieval_gen.retval\n    return documents[:max_results]\n\n\ndef get_webpage_content(url: str) -> str:\n    headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0\",\n               \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n               \"Accept-Language\": \"en-US,en;q=0.5\"}\n    if not url.startswith(\"https://\"):\n        try:\n            response = requests.get(f\"https://{url}\", headers=headers)\n        except:\n            response = requests.get(url, headers=headers)\n    else:\n        response = requests.get(url, headers=headers)\n\n    soup = BeautifulSoup(response.content, features=\"lxml\")\n    for script in soup([\"script\", \"style\"]):\n        script.extract()\n\n    strings = soup.stripped_strings\n    return '\\n'.join([s.strip() for s in strings])\n"
  },
  {
    "path": "requirements.txt",
    "content": "faiss-cpu==1.13.2\nbeautifulsoup4==4.14.3\nunstructured==0.22.18\nrank_bm25==0.2.2\nsentence-transformers==5.3.0\nBrotli==1.2.0\naiohttp>=3.12.14\nregex\n"
  },
  {
    "path": "retrieval.py",
    "content": "import re\nimport asyncio\nimport warnings\nfrom typing import List, Dict, Iterable, Callable, Iterator\nfrom collections import defaultdict\nfrom itertools import chain\n\nimport aiohttp\nimport requests\nimport torch\nfrom bs4 import BeautifulSoup\nfrom transformers import AutoTokenizer, AutoModelForMaskedLM\nfrom transformers.utils.hub import cached_file\n\ntry:\n    from .retrievers.faiss_retriever import FaissRetriever\n    from .retrievers.bm25_retriever import BM25Retriever\n    from .retrievers.splade_retriever import SpladeRetriever\n    from .chunkers.semantic_chunker import BoundedSemanticChunker\n    from .chunkers.character_chunker import RecursiveCharacterTextSplitter\n    from .chunkers.ner_chunker import TokenClassificationChunker\n    from .utils import (Document, MySentenceTransformer, cosine_similarity,\n                        filter_similar_embeddings, bow_filter_similar_texts)\nexcept ImportError:\n    from retrievers.faiss_retriever import FaissRetriever\n    from retrievers.bm25_retriever import BM25Retriever\n    from retrievers.splade_retriever import SpladeRetriever\n    from chunkers.semantic_chunker import BoundedSemanticChunker\n    from chunkers.character_chunker import RecursiveCharacterTextSplitter\n    from chunkers.ner_chunker import TokenClassificationChunker\n    from utils import (Document, MySentenceTransformer, cosine_similarity,\n                       filter_similar_embeddings, bow_filter_similar_texts)\n\n\nclass DocumentRetriever:\n\n    def __init__(self, device=\"cuda\", num_results: int = 5, similarity_threshold: float = 0.5, chunk_size: int = 500,\n                 ensemble_weighting: float = 0.5, splade_batch_size: int = 2, keyword_retriever: str = \"bm25\",\n                 model_cache_dir: str = None, chunking_method: str = \"character-based\",\n                 chunker_breakpoint_threshold_amount: int = 10, client_timeout: int = 10,\n                 token_classification_model_id : str = \"mirth/chonky_distilbert_base_uncased_1\"):\n        self.model_cache_dir = model_cache_dir\n        self.device = device\n        self.embedding_model = MySentenceTransformer(\"all-MiniLM-L6-v2\", cache_folder=model_cache_dir,\n                                                     device=device,\n                                                     model_kwargs={\"torch_dtype\": torch.float32 if device == \"cpu\" else torch.float16})\n        if keyword_retriever == \"splade\":\n            splade_kwargs = {\"cache_dir\": model_cache_dir,\n                             \"torch_dtype\": torch.float32 if device == \"cpu\" else torch.float16,\n                             \"attn_implementation\":\"eager\",\n                             \"use_safetensors\": False}  # avoid weird redundant asynchronous safetensors download\n                                                        # after main download has already finished\n            self.splade_doc_tokenizer = AutoTokenizer.from_pretrained(\"naver/efficient-splade-VI-BT-large-doc\",\n                                                                      cache_dir=model_cache_dir)\n            self.splade_doc_model = AutoModelForMaskedLM.from_pretrained(\"naver/efficient-splade-VI-BT-large-doc\",\n                                                                         **splade_kwargs).to(self.device)\n            self.splade_query_tokenizer = AutoTokenizer.from_pretrained(\"naver/efficient-splade-VI-BT-large-query\",\n                                                                        cache_dir=model_cache_dir)\n            self.splade_query_model = AutoModelForMaskedLM.from_pretrained(\"naver/efficient-splade-VI-BT-large-query\",\n                                                                           **splade_kwargs).to(self.device)\n            self.splade_batch_size = splade_batch_size\n\n        self.token_classification_chunker = None\n        if chunking_method == \"token-classifier\":\n            self.token_classification_chunker = TokenClassificationChunker(model_id=token_classification_model_id,\n                                                                           device=self.device,\n                                                                           model_cache_dir=self.model_cache_dir,\n                                                                           max_chunk_size=chunk_size)\n\n        self.spaces_regex = re.compile(r\" {3,}\")\n        self.num_results = num_results\n        self.similarity_threshold = similarity_threshold\n        self.chunking_method = chunking_method\n        self.chunk_size = chunk_size\n        self.chunker_breakpoint_threshold_amount = chunker_breakpoint_threshold_amount\n        self.ensemble_weighting = ensemble_weighting\n        self.keyword_retriever = keyword_retriever\n        self.client_timeout = client_timeout\n        self.token_classification_model_id = token_classification_model_id\n\n    def preprocess_text(self, text: str) -> str:\n        text = text.replace(\"\\n\", \" \\n\")\n        text = self.spaces_regex.sub(\" \", text)\n        text = text.strip()\n        return text\n\n    def retrieve_from_snippets(self, query: str, documents: list[Document]) -> list[Document]:\n        yield \"Retrieving relevant results...\"\n        faiss_retriever = FaissRetriever(self.embedding_model, num_results=self.num_results,\n                                         similarity_threshold=self.similarity_threshold)\n        faiss_retriever.add_documents(documents)\n        return faiss_retriever.get_relevant_documents(query)\n\n    def retrieve_from_webpages(self, query: str, url_list: list[str]) -> list[Document]:\n        if self.chunking_method == \"semantic\":\n            text_splitter = BoundedSemanticChunker(self.embedding_model, breakpoint_threshold_type=\"percentile\",\n                                                   breakpoint_threshold_amount=self.chunker_breakpoint_threshold_amount,\n                                                   max_chunk_size=self.chunk_size)\n        elif self.chunking_method == \"token-classifier\":\n            model_is_downloaded = True\n            try:\n                cached_file(self.token_classification_model_id, \"config.json\", local_files_only=True,\n                            cache_dir=self.model_cache_dir)\n            except OSError:\n                model_is_downloaded = False\n                yield \"Downloading token classification model...\"\n            if not self.token_classification_chunker or not model_is_downloaded:\n                self.token_classification_chunker = TokenClassificationChunker(model_id=self.token_classification_model_id,\n                                                                               device=self.device,\n                                                                               model_cache_dir=self.model_cache_dir,\n                                                                               max_chunk_size=self.chunk_size)\n            text_splitter = self.token_classification_chunker\n        else:\n            text_splitter = RecursiveCharacterTextSplitter(chunk_size=self.chunk_size, chunk_overlap=10,\n                                                                separators=[\"\\n\\n\", \"\\n\", \".\", \", \", \" \", \"\"])\n\n        yield \"Downloading and chunking webpages...\"\n        split_docs = asyncio.run(async_fetch_chunk_websites(url_list, text_splitter, self.client_timeout))\n\n        yield \"Retrieving relevant results...\"\n        num_retrieval_results = max(self.num_results*2, 10)\n        text_to_dense_embedding = None\n        if self.ensemble_weighting > 0:\n            faiss_retriever = FaissRetriever(self.embedding_model, num_results=num_retrieval_results,\n                                          similarity_threshold=self.similarity_threshold)\n            faiss_retriever.add_documents(split_docs)\n            text_to_dense_embedding = faiss_retriever.text_to_embedding\n            dense_result_docs = faiss_retriever.get_relevant_documents(query)\n        else:\n            dense_result_docs = []\n\n        if self.ensemble_weighting < 1:\n            #  The sparse keyword retriever is good at finding relevant documents based on keywords,\n            #  while the dense retriever is good at finding relevant documents based on semantic similarity.\n            if self.keyword_retriever == \"bm25\":\n                keyword_retriever = BM25Retriever.from_documents(split_docs,\n                                                                 preprocess_func=self.preprocess_text)\n                keyword_retriever.k = num_retrieval_results\n            elif self.keyword_retriever == \"splade\":\n                keyword_retriever = SpladeRetriever(\n                    splade_doc_tokenizer=self.splade_doc_tokenizer,\n                    splade_doc_model=self.splade_doc_model,\n                    splade_query_tokenizer=self.splade_query_tokenizer,\n                    splade_query_model=self.splade_query_model,\n                    device=self.device,\n                    batch_size=self.splade_batch_size,\n                    k=num_retrieval_results\n                )\n                keyword_retriever.add_documents(split_docs)\n            else:\n                raise ValueError(\"self.keyword_retriever must be one of ('bm25', 'splade')\")\n            sparse_results_docs = keyword_retriever.get_relevant_documents(query)\n        else:\n            sparse_results_docs = []\n\n        ranked_docs = weighted_reciprocal_rank([dense_result_docs, sparse_results_docs],\n                                               weights=[self.ensemble_weighting,\n                                                        1 - self.ensemble_weighting])\n\n        source_url_to_rank = {url: i + 1 for i, url in enumerate(url_list)}\n        doc_rank_to_source_rank = {i:source_url_to_rank[doc.metadata['source']] for i, doc in enumerate(ranked_docs)}\n\n        if text_to_dense_embedding:\n            ranked_doc_embeddings = [text_to_dense_embedding[doc.page_content] for doc in ranked_docs]\n            included_idxs = filter_similar_embeddings(ranked_doc_embeddings, cosine_similarity,\n                                                      0.95, doc_rank_to_source_rank)\n        else:\n            included_idxs = bow_filter_similar_texts([doc.page_content for doc in ranked_docs],\n                                                     cosine_similarity, 0.95, doc_rank_to_source_rank)\n\n        return [ranked_docs[i] for i in included_idxs[:self.num_results]]\n\n\nasync def async_download_html(url: str, headers: Dict, timeout: int):\n    async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(timeout),\n                                     max_field_size=65536) as session:\n        try:\n            resp = await session.get(url)\n            return await resp.text(), url\n        except UnicodeDecodeError:\n            if not resp.headers['Content-Type'].startswith(\"text/html\"):\n                print(f\"LLM_Web_search | {url} generated an exception: Expected content type text/html. Got {resp.headers['Content-Type']}.\")\n        except TimeoutError:\n            print('LLM_Web_search | %r did not load in time' % url)\n        except Exception as exc:\n            print('LLM_Web_search | %r generated an exception: %s' % (url, exc))\n    return None\n\n\nasync def async_fetch_chunk_websites(urls: List[str],\n                                     text_splitter: BoundedSemanticChunker or RecursiveCharacterTextSplitter,\n                                     timeout: int = 10):\n    headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0\",\n               \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n               \"Accept-Language\": \"en-US,en;q=0.5\",\n               \"Accept-Encoding\": \"br;q=1.0, gzip;q=0.8, *;q=0.1\"}\n    result_futures = [async_download_html(url, headers, timeout) for url in urls]\n    chunks = []\n    for f in asyncio.as_completed(result_futures):\n        result = await f\n        if result:\n            resp_html, url = result\n            document = html_to_plaintext_doc(resp_html, url)\n            chunks.extend(text_splitter.split_documents([document]))\n    return chunks\n\n\ndef docs_to_pretty_str(docs) -> str:\n    ret_str = \"\"\n    for i, doc in enumerate(docs):\n        ret_str += f\"Result {i+1}:\\n\"\n        ret_str += f\"{doc.page_content}\\n\"\n        ret_str += f\"Source URL: {doc.metadata['source']}\\n\\n\"\n    return ret_str\n\n\ndef download_html(url: str) -> bytes:\n    headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0\",\n               \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n               \"Accept-Language\": \"en-US,en;q=0.5\"}\n\n    response = requests.get(url, headers=headers, verify=True, timeout=8)\n    response.raise_for_status()\n\n    content_type = response.headers.get(\"Content-Type\", \"\")\n    if not content_type.startswith(\"text/html\"):\n        raise ValueError(f\"Expected content type text/html. Got {content_type}.\")\n    return response.content\n\n\ndef html_to_plaintext_doc(html_text: str or bytes, url: str) -> Document:\n    with warnings.catch_warnings(action=\"ignore\"):\n        soup = BeautifulSoup(html_text, features=\"lxml\")\n    for script in soup([\"script\", \"style\"]):\n        script.extract()\n\n    strings = '\\n'.join([s.strip() for s in soup.stripped_strings])\n    webpage_document = Document(page_content=strings, metadata={\"source\": url})\n    return webpage_document\n\n\ndef weighted_reciprocal_rank(doc_lists: List[List[Document]], weights: List[float], c: int = 60) -> List[Document]:\n    \"\"\"\n    Perform weighted Reciprocal Rank Fusion on multiple rank lists.\n    You can find more details about RRF here:\n    https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf\n\n    Args:\n        doc_lists: A list of rank lists, where each rank list contains unique items.\n        weights: A list of weights corresponding to the rank lists. Defaults to equal\n            weighting for all lists.\n        c: A constant added to the rank, controlling the balance between the importance\n            of high-ranked items and the consideration given to lower-ranked items.\n            Default is 60.\n\n    Returns:\n        list: The final aggregated list of items sorted by their weighted RRF\n                scores in descending order.\n    \"\"\"\n    if len(doc_lists) != len(weights):\n        raise ValueError(\n            \"Number of rank lists must be equal to the number of weights.\"\n        )\n\n    # Associate each doc's content with its RRF score for later sorting by it\n    # Duplicated contents across retrievers are collapsed & scored cumulatively\n    rrf_score: Dict[str, float] = defaultdict(float)\n    for doc_list, weight in zip(doc_lists, weights):\n        for rank, doc in enumerate(doc_list, start=1):\n            rrf_score[doc.page_content] += weight / (rank + c)\n\n    # Docs are deduplicated by their contents then sorted by their scores\n    all_docs = chain.from_iterable(doc_lists)\n    sorted_docs = sorted(\n        unique_by_key(all_docs, lambda doc: doc.page_content),\n        reverse=True,\n        key=lambda doc: rrf_score[doc.page_content],\n    )\n    return sorted_docs\n\n\ndef unique_by_key(iterable: Iterable, key: Callable) -> Iterator:\n    \"\"\"Yield unique elements of an iterable based on a key function.\n\n    Args:\n        iterable: The iterable to filter.\n        key: A function that returns a hashable key for each element.\n\n    Yields:\n        Unique elements of the iterable based on the key function.\n    \"\"\"\n    seen = set()\n    for e in iterable:\n        if (k := key(e)) not in seen:\n            seen.add(k)\n            yield e\n"
  },
  {
    "path": "retrievers/bm25_retriever.py",
    "content": "from typing import List, Any, Callable, Iterable, Optional, Dict\n\nfrom rank_bm25 import BM25Okapi\n\ntry:\n    from ..utils import Document\nexcept:\n    from utils import Document\n\n\ndef default_preprocessing_func(text: str) -> List[str]:\n    return text.split()\n\n\nclass BM25Retriever:\n    \"\"\" Adapted from Langchain:\n    https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/retrievers/bm25.py\"\"\"\n    vectorizer: Any\n    \"\"\" BM25 vectorizer.\"\"\"\n    docs: List[Document]\n    \"\"\" List of documents.\"\"\"\n    k: int = 4\n    \"\"\" Number of documents to return.\"\"\"\n    preprocess_func: Callable[[str], List[str]] = default_preprocessing_func\n    \"\"\" Preprocessing function to use on the text before BM25 vectorization.\"\"\"\n\n    def __init__(self, vectorizer: Any, docs: List[Document], k: int = 4,\n                 preprocess_func: Callable[[str], List[str]] = default_preprocessing_func):\n        self.vectorizer = vectorizer\n        self.docs = docs\n        self.k = k\n        self.preprocess_func = preprocess_func\n\n    @classmethod\n    def from_texts(\n        cls,\n        texts: Iterable[str],\n        metadatas: Optional[Iterable[dict]] = None,\n        bm25_params: Optional[Dict[str, Any]] = None,\n        preprocess_func: Callable[[str], List[str]] = default_preprocessing_func,\n        **kwargs: Any,\n    ) -> \"BM25Retriever\":\n        \"\"\"\n        Create a BM25Retriever from a list of texts.\n        Args:\n            texts: A list of texts to vectorize.\n            metadatas: A list of metadata dicts to associate with each text.\n            bm25_params: Parameters to pass to the BM25 vectorizer.\n            preprocess_func: A function to preprocess each text before vectorization.\n            **kwargs: Any other arguments to pass to the retriever.\n\n        Returns:\n            A BM25Retriever instance.\n        \"\"\"\n        texts_processed = [preprocess_func(t) for t in texts]\n        bm25_params = bm25_params or {}\n        vectorizer = BM25Okapi(texts_processed, **bm25_params)\n        metadatas = metadatas or ({} for _ in texts)\n        docs = [Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas)]\n        return cls(\n            vectorizer=vectorizer, docs=docs, preprocess_func=preprocess_func, **kwargs\n        )\n\n    @classmethod\n    def from_documents(\n        cls,\n        documents: Iterable[Document],\n        *,\n        bm25_params: Optional[Dict[str, Any]] = None,\n        preprocess_func: Callable[[str], List[str]] = default_preprocessing_func,\n        **kwargs: Any,\n    ) -> \"BM25Retriever\":\n        \"\"\"\n        Create a BM25Retriever from a list of Documents.\n        Args:\n            documents: A list of Documents to vectorize.\n            bm25_params: Parameters to pass to the BM25 vectorizer.\n            preprocess_func: A function to preprocess each text before vectorization.\n            **kwargs: Any other arguments to pass to the retriever.\n\n        Returns:\n            A BM25Retriever instance.\n        \"\"\"\n        texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents))\n        return cls.from_texts(\n            texts=texts,\n            bm25_params=bm25_params,\n            metadatas=metadatas,\n            preprocess_func=preprocess_func,\n            **kwargs,\n        )\n\n    def get_relevant_documents(self, query: str) -> List[Document]:\n        processed_query = self.preprocess_func(query)\n        return_docs = self.vectorizer.get_top_n(processed_query, self.docs, n=self.k)\n        return return_docs\n"
  },
  {
    "path": "retrievers/faiss_retriever.py",
    "content": "from typing import List, Callable\n\nimport faiss\nimport numpy as np\n\ntry:\n    from ..utils import Document, cosine_similarity, MySentenceTransformer, SimilarLengthsBatchifyer\nexcept:\n    from utils import Document, cosine_similarity, MySentenceTransformer, SimilarLengthsBatchifyer\n\n\nclass FaissRetriever:\n\n    def __init__(self, embedding_model: MySentenceTransformer, num_results: int = 5, similarity_threshold: float = 0.5):\n        self.embedding_model = embedding_model\n        self.num_results = num_results\n        self.similarity_threshold = similarity_threshold\n        self.index = faiss.IndexFlatL2(embedding_model.get_sentence_embedding_dimension())\n        self.document_embeddings = []\n        self.documents = []\n        self.text_to_embedding = {}\n\n    def add_documents(self, documents: List[Document]):\n        if not documents:\n            return\n        self.documents = documents\n        self.document_embeddings = self.embedding_model.batch_encode([doc.page_content for doc in documents])\n        self.index.add(self.document_embeddings)\n        self.text_to_embedding = {document.page_content: embedding\n                                  for document, embedding in zip(documents, self.document_embeddings)}\n\n    def get_relevant_documents(self, query: str) -> List[Document]:\n        if not self.documents:\n            return []\n        query_embedding = self.embedding_model.encode(query)\n        D, I = self.index.search(query_embedding.reshape(1, -1), self.num_results)\n        result_indices = I[0]\n        relevant_doc_embeddings = self.document_embeddings[result_indices]\n        # dense_result_docs = [split_docs[i] for i in I[0]]\n\n        # Filter out documents that aren't similar enough\n        similarity = cosine_similarity([query_embedding], relevant_doc_embeddings)[0]\n        similar_enough = np.where(similarity > self.similarity_threshold)[0]\n\n        filtered_result_indices = result_indices[similar_enough]\n        return [self.documents[i] for i in filtered_result_indices]\n"
  },
  {
    "path": "retrievers/splade_retriever.py",
    "content": "from typing import (\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n    Dict\n)\n\nimport torch\nimport numpy as np\nfrom scipy.sparse import csr_array\n\ntry:\n    from ..utils import Document, SimilarLengthsBatchifyer\nexcept:\n    from utils import Document, SimilarLengthsBatchifyer\n\n\ndef neg_dot_dist(x, y):\n    dist = np.dot(x, y).data\n    if dist.size == 0:  # no overlapping non-zero entries between x and y\n        return np.inf\n    return -dist.sum()\n\n\nclass SpladeRetriever:\n    def __init__(self, splade_doc_tokenizer, splade_doc_model, splade_query_tokenizer, splade_query_model,\n                 device, batch_size, k):\n        self.splade_doc_tokenizer = splade_doc_tokenizer\n        self.splade_doc_model = splade_doc_model\n        self.splade_query_tokenizer = splade_query_tokenizer\n        self.splade_query_model = splade_query_model\n        self.device = device\n        self.batch_size = batch_size\n        self.k = k\n        self.vocab_size = splade_doc_model.config.vocab_size\n        self.texts: List[str] = []\n        self.metadatas: List[Dict] = []\n        self.sparse_doc_vecs: List[csr_array] = []\n\n    def compute_document_vectors(self, texts: List[str], batch_size: int) -> Tuple[List[List[int]], List[List[float]]]:\n        indices = []\n        values = []\n        tokenized_texts = self.splade_doc_tokenizer(texts, truncation=True, padding=False,\n                                                    return_tensors=\"np\")[\"input_ids\"]\n        batchifyer = SimilarLengthsBatchifyer(batch_size, tokenized_texts)\n        texts = np.array(texts)\n        batch_indices = []\n        for index_batch in batchifyer:\n            batch_indices.append(index_batch)\n            with torch.no_grad():\n                tokens = self.splade_doc_tokenizer(texts[index_batch].tolist(), truncation=True, padding=True,\n                                                   return_tensors=\"pt\").to(self.device)\n                output = self.splade_doc_model(**tokens)\n            logits, attention_mask = output.logits, tokens.attention_mask\n            relu_log = torch.log(1 + torch.relu(logits))\n            weighted_log = relu_log * attention_mask.unsqueeze(-1)\n            tvecs, _ = torch.max(weighted_log, dim=1)\n\n            # extract all non-zero values and their indices from the sparse vectors\n            for batch in tvecs.cpu().to(torch.float32):\n                indices.append(batch.nonzero(as_tuple=True)[0].numpy())\n                values.append(batch[indices[-1]].numpy())\n\n        # Restore order after SimilarLengthsBatchifyer disrupted it:\n        # Ensure that the order of 'indices' and 'values' matches the order of the 'texts' parameter\n        batch_indices = np.concatenate(batch_indices)\n        sorted_indices = np.argsort(batch_indices)\n        indices = [indices[i] for i in sorted_indices]\n        values = [values[i] for i in sorted_indices]\n        return indices, values\n\n    def compute_query_vector(self, text: str):\n        \"\"\"\n        Computes a vector from logits and attention mask using ReLU, log, and max operations.\n        \"\"\"\n        with torch.no_grad():\n            tokens = self.splade_query_tokenizer(text, return_tensors=\"pt\").to(self.device)\n            output = self.splade_query_model(**tokens)\n        logits, attention_mask = output.logits, tokens.attention_mask\n        relu_log = torch.log(1 + torch.relu(logits))\n        weighted_log = relu_log * attention_mask.unsqueeze(-1)\n        max_val, _ = torch.max(weighted_log, dim=1)\n        query_vec = max_val.squeeze().cpu().to(torch.float32)\n\n        query_indices = query_vec.nonzero().numpy().flatten()\n        query_values = query_vec.detach().numpy()[query_indices]\n\n        return query_indices, query_values\n\n    def add_documents(self, documents: List[Document])-> List[str]:\n        \"\"\"Run more documents through the embeddings and add to the vectorstore.\n\n        Args:\n            documents (List[Document]: Documents to add to the vectorstore.\n\n        Returns:\n            List[str]: List of IDs of the added texts.\n        \"\"\"\n        if not documents:\n            return []\n        texts = [doc.page_content for doc in documents]\n        metadatas = [doc.metadata for doc in documents]\n        return self.add_texts(texts, metadatas)\n\n    def add_texts(\n        self,\n        texts: Iterable[str],\n        metadatas: Optional[List[dict]] = None):\n\n        # Remove duplicate and empty texts\n        text_to_metadata = {texts[i]: metadatas[i] for i in range(len(texts)) if len(texts[i]) > 0}\n        texts = list(text_to_metadata.keys())\n        metadatas = list(text_to_metadata.values())\n        self.texts = texts\n        self.metadatas = metadatas\n\n        indices, values = self.compute_document_vectors(texts, self.batch_size)\n        self.sparse_doc_vecs = [csr_array((val, (ind,)),\n                                          shape=(self.vocab_size,)) for val, ind in zip(values, indices)]\n\n        if self.device == \"cuda\":\n            torch.cuda.empty_cache()\n\n    def get_relevant_documents(self, query: str) -> List[Document]:\n        if not self.texts:\n            return []\n        query_indices, query_values = self.compute_query_vector(query)\n\n        sparse_query_vec = csr_array((query_values, (query_indices,)),shape=(self.vocab_size,))\n        dists = [neg_dot_dist(sparse_query_vec, doc_vec) for doc_vec in self.sparse_doc_vecs]\n        sorted_indices = np.argsort(dists)\n\n        return [Document(self.texts[i], self.metadatas[i]) for i in sorted_indices[:self.k]]\n"
  },
  {
    "path": "script.js",
    "content": "var generate_button = document.getElementById(\"Generate\");\ngenerate_button.insertAdjacentHTML(\"afterend\", '<div style=\"position:relative;\"> <label style=\"color:#9ca3af;white-space:nowrap;position:absolute;right:0px;\"><input type=\"checkbox\" id=\"force-search\" name=\"accept\">  Force web search </label> </div>');\n\nvar stop_button = document.getElementById(\"stop\");\nvar chat_input = document.getElementById(\"chat-input\");\n\nfunction set_margins(generate_button, stop_button, chat_input, reset=false) {\n    if (reset) {\n        generate_button.style.setProperty(\"position\", \"\");\n        generate_button.style.setProperty(\"top\", \"\");\n        generate_button.style.setProperty(\"margin-left\", \"\");\n\n        stop_button.style.setProperty(\"position\", \"\");\n        stop_button.style.setProperty(\"top\", \"\");\n        stop_button.style.setProperty(\"margin-left\", \"\");\n\n        chat_input.style.marginBottom = \"\";\n    }\n    else {\n        generate_button.style.setProperty(\"position\", \"relative\");\n        generate_button.style.setProperty(\"top\", \"10px\");\n        generate_button.style.setProperty(\"margin-left\", \"-10px\");\n\n        stop_button.style.setProperty(\"position\", \"relative\");\n        stop_button.style.setProperty(\"top\", \"10px\");\n        stop_button.style.setProperty(\"margin-left\", \"-10px\");\n\n        chat_input.style.marginBottom = \"5px\";\n    }\n}\nset_margins(generate_button, stop_button, chat_input);\n\nvar force_search_checkbox = document.getElementById(\"force-search\");\nvar gradio_force_search_checkbox = document.getElementById(\"Force-search-checkbox\").children[1].firstChild;\nforce_search_checkbox.addEventListener('change', function() {\n  if (this.checked) {\n    if (!gradio_force_search_checkbox.checked) {\n        gradio_force_search_checkbox.click();\n    }\n  } else {\n    if (gradio_force_search_checkbox.checked) {\n        gradio_force_search_checkbox.click();\n    }\n  }\n});\n\nvar gradio_show_force_search_box = document.getElementById(\"show-force-search-box\").children[1].firstChild;\ngradio_show_force_search_box.addEventListener('change', function() {\n  if (this.checked) {\n    force_search_checkbox.parentElement.parentElement.style.display = '';\n    set_margins(generate_button, stop_button, chat_input);\n  } else {\n    force_search_checkbox.parentElement.parentElement.style.display = 'none';\n    set_margins(generate_button, stop_button, chat_input, true);\n  }\n});\n\nvar keep_results_checkbox = document.getElementById(\"keep-results-checkbox\");\nkeep_results_checkbox.insertAdjacentElement(\"afterend\", keep_results_checkbox.children[1]);\n\nconst event = new Event(\"change\");\ngradio_show_force_search_box.dispatchEvent(event);"
  },
  {
    "path": "script.py",
    "content": "import time\nimport json\nimport os\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom functools import partial\nimport logging\nfrom pathlib import Path\n\nimport gradio as gr\nimport torch\nimport regex\n\nimport modules\nimport modules.shared as shared\nfrom modules import chat, ui as ui_module\nfrom modules.utils import gradio\nfrom modules.text_generation import generate_reply_HF, generate_reply_custom\n\ntry:\n    from .llm_web_search import get_webpage_content, retrieve_from_duckduckgo, retrieve_from_searxng, Generator\n    from .retrieval import DocumentRetriever, docs_to_pretty_str\nexcept ImportError:\n    from llm_web_search import get_webpage_content, retrieve_from_duckduckgo, retrieve_from_searxng, Generator\n    from retrieval import DocumentRetriever, docs_to_pretty_str\n\n\ndef patched_is_path_allowed(abs_path_str):\n    \"\"\"Check if a path is under the extension's directory or under the configured user_data.\"\"\"\n    abs_path = Path(abs_path_str).resolve()\n    user_data_resolved = shared.user_data_dir.resolve()\n    extension_path_resolved = Path(__file__).parent.resolve()\n    return abs_path.is_relative_to(extension_path_resolved) or abs_path.is_relative_to(user_data_resolved)\n\n# Allow deleting files in this extension's subfolders even if not in 'user_data'\nmodules.utils._is_path_allowed = patched_is_path_allowed\n\n\nparams = {\n    \"display_name\": \"Web Search\",\n    \"is_tab\": True,\n    \"enable\": True,\n    \"search results per query\": 5,\n    \"langchain similarity score threshold\": 0.5,\n    \"instant answers\": True,\n    \"regular search results\": True,\n    \"search command regex\": \"\",\n    \"default search command regex\": r\"Search_web\\(\\\"(.*)\\\"\\)\",\n    \"open url command regex\": \"\",\n    \"default open url command regex\": r\"Download_webpage\\(\\\"(.*)\\\"\\)\",\n    \"display search results in chat\": True,\n    \"display extracted URL content in chat\": True,\n    \"keep results in context\": True,\n    \"searxng url\": \"\",\n    \"cpu only\": True,\n    \"chunk size\": 800,\n    \"duckduckgo results per query\": 10,\n    \"append current datetime\": False,\n    \"default system prompt filename\": None,\n    \"force search prefix\": \"Search_web\",\n    \"ensemble weighting\": 0.5,\n    \"keyword retriever\": \"bm25\",\n    \"splade batch size\": 2,\n    \"chunking method\": \"character-based\",\n    \"chunker breakpoint_threshold_amount\": 30,\n    \"simple search\": False,\n    \"client timeout\": 10,\n    \"show force search checkbox\": True,\n    \"token classification model id\": \"mirth/chonky_distilbert_base_uncased_1\",\n    \"think after searching\": True,\n    \"add as tool\": False\n}\nlogger = logging.getLogger('text-generation-webui')\ncustom_system_message_filename = None\nextension_path = os.path.dirname(os.path.abspath(__file__))\ndocument_retriever = None\nupdate_history_dict = defaultdict(str)\nchat_id = None\nforce_search = False\nGEN_LATENCY_THRESH = 0.01\n\n\ndef setup():\n    \"\"\"\n    Is executed when the extension gets imported.\n    :return:\n    \"\"\"\n    os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n\n    try:\n        with open(os.path.join(extension_path, \"settings.json\"), \"r\") as f:\n            saved_params = json.load(f)\n        params.update(saved_params)\n        save_settings()   # add keys of newly added feature to settings.json\n    except FileNotFoundError:\n        save_settings()\n\n    if not os.path.exists(os.path.join(extension_path, \"system_prompts\")):\n        os.makedirs(os.path.join(extension_path, \"system_prompts\"))\n\n    toggle_extension(params[\"enable\"])\n\n\ndef save_settings():\n    with open(os.path.join(extension_path, \"settings.json\"), \"w\") as f:\n        json.dump(params, f, indent=4)\n    current_datetime = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return gr.HTML(f'<span style=\"color:lawngreen\"> Settings were saved at {current_datetime}</span>',\n                   visible=True)\n\n\ndef toggle_extension(_enable: bool):\n    global document_retriever, custom_system_message_filename\n    if _enable:\n        document_retriever = DocumentRetriever(device=\"cpu\" if params[\"cpu only\"] else \"cuda\",\n                                               keyword_retriever=params[\"keyword retriever\"],\n                                               chunking_method=params[\"chunking method\"],\n                                               model_cache_dir=os.path.join(extension_path, \"hf_models\"))\n        embedding_model = document_retriever.embedding_model\n        embedding_model.to(embedding_model._target_device)\n        custom_system_message_filename = params.get(\"default system prompt filename\")\n    else:\n        if not params[\"cpu only\"]:  # free some VRAM\n            model_attrs = [\"embedding_model\", \"splade_doc_model\", \"splade_query_model\"]\n            for model_attr in model_attrs:\n                if hasattr(document_retriever, model_attr):\n                    model = getattr(document_retriever, model_attr)\n                    if hasattr(model, \"client\"):\n                        model.client.to(\"cpu\")\n                        del model.client\n                    else:\n                        if hasattr(model, \"to\"):\n                            model.to(\"cpu\")\n                        del model\n            torch.cuda.empty_cache()\n\n    params.update({\"enable\": _enable})\n\n    handle_add_as_tool(params.get(\"add as tool\"))\n\n    return _enable\n\n\ndef get_available_system_prompts():\n    try:\n        return [\"None\"] + sorted(os.listdir(os.path.join(extension_path, \"system_prompts\")))\n    except FileNotFoundError:\n        return [\"None\"]\n\n\ndef load_system_prompt(filename: str or None):\n    global custom_system_message_filename\n    if not filename:\n        return\n    if filename == \"None\" or filename == \"Select custom system message to load...\":\n        custom_system_message_filename = None\n        return \"\"\n    with open(os.path.join(extension_path, \"system_prompts\", filename), \"r\") as f:\n        prompt_str = f.read()\n\n    if params[\"append current datetime\"]:\n        prompt_str += f\"\\nDate and time of conversation: {datetime.now().strftime('%A %d %B %Y %H:%M')}\"\n\n    shared.settings['custom_system_message'] = prompt_str\n    custom_system_message_filename = filename\n    return prompt_str\n\n\ndef save_system_prompt(filename, prompt):\n    if not filename:\n        return\n\n    with open(os.path.join(extension_path, \"system_prompts\", filename), \"w\") as f:\n        f.write(prompt)\n\n    return gr.HTML(f'<span style=\"color:lawngreen\"> Saved successfully</span>',\n                   visible=True)\n\n\ndef check_file_exists(filename):\n    if filename == \"\":\n        return gr.HTML(\"\", visible=False)\n    if os.path.exists(os.path.join(extension_path, \"system_prompts\", filename)):\n        return gr.HTML(f'<span style=\"color:orange\"> Warning: Filename already exists</span>', visible=True)\n    return gr.HTML(\"\", visible=False)\n\n\ndef timeout_save_message():\n    time.sleep(2)\n    return gr.HTML(\"\", visible=False)\n\n\ndef deactivate_system_prompt():\n    shared.settings['custom_system_message'] = None\n    return \"None\"\n\n\ndef toggle_forced_search(value):\n    global force_search\n    force_search = value\n\n\ndef update_chat_id(_id):\n    global chat_id\n    chat_id = _id\n\n\ndef clear_update_history_dict():\n    update_history_dict[chat_id] = \"\"\n\n\ndef get_force_search_box_theme_js():\n    with open(os.path.join(extension_path, \"force_search_box_theme.js\"), \"r\") as f:\n        return f.read()\n\n\ndef create_tool_symlink():\n    tools_dir = shared.user_data_dir / 'tools'\n    tool_path = tools_dir / \"llm_web_search.py\"\n    if tools_dir.exists():\n        if not tool_path.exists():\n            os.symlink(os.path.join(extension_path, \"tool.py\"), tool_path)\n    else:\n        logger.error(\"Can't create llm_web_search tool symlink: 'tools' directory doesn't exist\")\n\n\ndef remove_tool_symlink():\n    tool_path = shared.user_data_dir / 'tools' / \"llm_web_search.py\"\n    if tool_path.exists():\n        tool_path.unlink()\n\n\ndef handle_add_as_tool(checked):\n    params.update({\"add as tool\": checked})\n    if checked and params.get(\"enable\"):\n        create_tool_symlink()\n    else:\n        remove_tool_symlink()\n\n\ndef ui():\n    \"\"\"\n    Creates custom gradio elements when the UI is launched.\n    :return:\n    \"\"\"\n    # Inject custom system message into the main textbox if a default one is set\n    shared.gradio['custom_system_message'].value = load_system_prompt(custom_system_message_filename)\n\n\n    def toggle_full_search_options(simple_search: bool):\n        if simple_search:\n            return [gr.update(visible=False)] * 7\n        else:\n            return [gr.update(visible=True)] * 7\n\n\n    def update_regex_setting(input_str: str, setting_key: str, error_html_element: gr.component):\n        if input_str == \"\":\n            params.update({setting_key: params[f\"default {setting_key}\"]})\n            return {error_html_element: gr.HTML(\"\", visible=False)}\n        try:\n            compiled = regex.compile(input_str)\n            if compiled.groups > 1:\n                raise regex.error(f\"Only 1 capturing group allowed in regex, but there are {compiled.groups}.\")\n            params.update({setting_key: input_str})\n            return {error_html_element: gr.HTML(\"\", visible=False)}\n        except regex.error as e:\n            return {error_html_element: gr.HTML(f'<span style=\"color:red\"> Invalid regex. {str(e).capitalize()}</span>',\n                                                visible=True)}\n\n    def update_default_custom_system_message(check: bool):\n        if check:\n            params.update({\"default system prompt filename\": custom_system_message_filename})\n        else:\n            params.update({\"default system prompt filename\": None})\n\n    with gr.Row():\n        enable = gr.Checkbox(value=lambda: params['enable'], label='Enable LLM web search')\n        add_as_tool = gr.Checkbox(value=lambda: params['add as tool'], label='Add as tool when enabled')\n        use_cpu_only = gr.Checkbox(value=lambda: params['cpu only'],\n                                   label='Run extension on CPU only',\n                                   info='(Save settings and restart for the change to take effect)')\n        with gr.Column():\n            save_settings_btn = gr.Button(\"Save settings\")\n            saved_success_elem = gr.HTML(\"\", visible=False)\n\n    with gr.Row():\n        with gr.Column():\n            search_type = gr.Radio([(\"Simple search\", True), (\"Full search\", False)], label=\"Search type\",\n                               value=lambda: params[\"simple search\"])\n        with gr.Column():\n            search_command_regex = gr.Textbox(label=\"Search command regex string\",\n                                              placeholder=params[\"default search command regex\"],\n                                              value=lambda: params[\"search command regex\"])\n            search_command_regex_error_label = gr.HTML(\"\", visible=False)\n\n        with gr.Column():\n            open_url_command_regex = gr.Textbox(label=\"Download webpage command regex string\",\n                                                placeholder=params[\"default open url command regex\"],\n                                                value=lambda: params[\"open url command regex\"])\n            open_url_command_regex_error_label = gr.HTML(\"\", visible=False)\n\n        with gr.Column():\n            show_results = gr.Checkbox(value=lambda: params['display search results in chat'],\n                                       label='Display search results in chat')\n            show_url_content = gr.Checkbox(value=lambda: params['display extracted URL content in chat'],\n                                           label='Display extracted URL content in chat')\n            keep_results_in_ctx = gr.Checkbox(value=lambda: params['keep results in context'],\n                                              label='Keep previous search results in context',\n                                              info=\"Only applies to searches outside of thinking blocks\",\n                                              interactive=not params['display search results in chat'],\n                                              elem_classes=\"settings-checkbox\", elem_id=\"keep-results-checkbox\")\n    gr.Markdown(value='---', elem_id=\"first-separator\")\n    with gr.Row():\n        with gr.Column():\n            gr.Markdown(value='#### Load custom system message\\n'\n                              'Select a saved custom system message from within the system_prompts folder or \"None\" '\n                              'to clear the selection')\n            system_prompt = gr.Dropdown(\n                choices=get_available_system_prompts(), label=\"Select custom system message\",\n                value=lambda: 'Select custom system message to load...' if custom_system_message_filename is None else\n                              custom_system_message_filename, elem_classes='slim-dropdown')\n            with gr.Row():\n                set_system_message_as_default = gr.Checkbox(\n                    value=lambda: custom_system_message_filename == params[\"default system prompt filename\"],\n                    label='Set this custom system message as the default')\n                refresh_button = ui_module.create_refresh_button(system_prompt, lambda: None,\n                                                                 lambda: {'choices': get_available_system_prompts()},\n                                                                 'refresh-button', interactive=True)\n                refresh_button.elem_id = \"custom-sysprompt-refresh\"\n                delete_button = gr.Button('🗑️', elem_classes='refresh-button', interactive=True)\n            append_datetime = gr.Checkbox(value=lambda: params['append current datetime'],\n                                          label='Append current date and time when loading custom system message')\n        with gr.Column():\n            gr.Markdown(value='#### Create custom system message')\n            system_prompt_text = gr.Textbox(label=\"Custom system message\", lines=3,\n                                            value=lambda: load_system_prompt(custom_system_message_filename))\n            sys_prompt_filename = gr.Text(label=\"Filename\")\n            sys_prompt_save_button = gr.Button(\"Save Custom system message\")\n            system_prompt_saved_success_elem = gr.HTML(\"\", visible=False)\n\n    gr.Markdown(value='---')\n    with gr.Accordion(\"Advanced settings\", open=False):\n        ensemble_weighting = gr.Slider(minimum=0, maximum=1, step=0.05, value=lambda: params[\"ensemble weighting\"],\n                                       label=\"Ensemble Weighting\", info=\"Smaller values = More keyword oriented, \"\n                                                                        \"Larger values = More focus on semantic similarity\",\n                                       visible=not params[\"simple search\"])\n        with gr.Row():\n            keyword_retriever = gr.Radio([(\"Okapi BM25\", \"bm25\"),(\"SPLADE\", \"splade\")], label=\"Sparse keyword retriever\",\n                                         info=\"For change to take effect, toggle the extension off and on again\",\n                                         value=lambda: params[\"keyword retriever\"],\n                                         visible=not params[\"simple search\"])\n            splade_batch_size = gr.Slider(minimum=2, maximum=256, step=2, value=lambda: params[\"splade batch size\"],\n                                          label=\"SPLADE batch size\",\n                                          info=\"Smaller values = Slower retrieval (but lower VRAM usage), \"\n                                               \"Larger values = Faster retrieval (but higher VRAM usage). \"\n                                               \"A good trade-off seems to be setting it = 8\",\n                                          visible=not params[\"simple search\"])\n        with gr.Row():\n            chunker = gr.Radio([(\"Character-based\", \"character-based\"),\n                                (\"Semantic\", \"semantic\"), (\"Token Classifier\", \"token-classifier\")],\n                               label=\"Chunking method\",\n                               value=lambda: params[\"chunking method\"],\n                               visible=not params[\"simple search\"])\n            chunker_breakpoint_threshold_amount = gr.Slider(minimum=1, maximum=100, step=1,\n                                                            value=lambda: params[\"chunker breakpoint_threshold_amount\"],\n                                                            label=\"Semantic chunking: sentence split threshold (%)\",\n                                                            info=\"Defines how different two consecutive sentences have\"\n                                                                 \" to be for them to be split into separate chunks\",\n                                                            visible=not params[\"simple search\"])\n        token_classification_chunker_model = gr.Dropdown(label=\"Token Classifier Model\",\n                                                         choices=[\"mirth/chonky_distilbert_base_uncased_1\",\n                                                                  \"mamei16/chonky_distilbert_base_uncased_1.1\",\n                                                                  \"mamei16/chonky_distilbert-base-multilingual-cased\",\n                                                                  \"mirth/chonky_modernbert_base_1\",\n                                                                  \"mirth/chonky_modernbert_large_1\"],\n                                                         value=lambda: params[\"token classification model id\"])\n\n        client_timeout = gr.Number(label=\"Client timeout (in seconds)\", info=\"When reached, pending or unfinished webpage \"\n                                         \"downloads will be cancelled to start the retrieval process immediately\",\n                                   minimum=1, maximum=100,\n                                   value=lambda: params[\"client timeout\"])\n        with gr.Row():\n            num_search_results = gr.Number(label=\"Max. search results to return per query\", minimum=1, maximum=100,\n                                           value=lambda: params[\"search results per query\"])\n            num_process_search_results = gr.Number(label=\"Number of search results to process per query\", minimum=1,\n                                                   maximum=100, value=lambda: params[\"duckduckgo results per query\"])\n        similarity_score_threshold = gr.Number(label=\"Similarity Score Threshold\", minimum=0., maximum=1.,\n                                               value=lambda: params[\"langchain similarity score threshold\"],\n                                               info=\"Discard chunks that are not similar \"\n                                                    \"enough to the search query and hence fall below the threshold.\")\n        chunk_size = gr.Number(label=\"Max. chunk size\", info=\"The maximal size of the individual chunks that each webpage will\"\n                                     \" be split into, in characters\", minimum=2, maximum=10000,\n                               value=lambda: params[\"chunk size\"],\n                               visible=not params[\"simple search\"])\n        think_after_search = gr.Checkbox(label=\"Enable thinking after searching\",\n                                         info='Used by pre-2507 Qwen3.',\n                                         value=lambda: params[\"think after searching\"])\n        show_force_search = gr.Checkbox(value=lambda: params['show force search checkbox'],\n                                        label='Show force search checkbox', elem_id=\"show-force-search-box\")\n\n    with gr.Row():\n        searxng_url = gr.Textbox(label=\"SearXNG URL\",\n                                 value=lambda: params[\"searxng url\"])\n\n    # Event functions to update the parameters in the backend\n    enable.input(toggle_extension, enable, enable)\n    add_as_tool.change(handle_add_as_tool, add_as_tool, None)\n    use_cpu_only.change(lambda x: params.update({\"cpu only\": x}), use_cpu_only, None)\n    save_settings_btn.click(save_settings, None, [saved_success_elem])\n    ensemble_weighting.change(lambda x: params.update({\"ensemble weighting\": x}), ensemble_weighting, None)\n    keyword_retriever.change(lambda x: params.update({\"keyword retriever\": x}), keyword_retriever, None)\n    splade_batch_size.change(lambda x: params.update({\"splade batch size\": x}), splade_batch_size, None)\n    chunker.change(lambda x: params.update({\"chunking method\": x}), chunker, None)\n    chunker_breakpoint_threshold_amount.change(lambda x: params.update({\"chunker breakpoint_threshold_amount\": x}),\n                                               chunker_breakpoint_threshold_amount, None)\n    token_classification_chunker_model.change(lambda x: params.update({\"token classification model id\": x}),\n                                                                      token_classification_chunker_model, None)\n    client_timeout.change(lambda x: params.update({\"client timeout\": x}), client_timeout, None)\n    num_search_results.change(lambda x: params.update({\"search results per query\": x}), num_search_results, None)\n    num_process_search_results.change(lambda x: params.update({\"duckduckgo results per query\": x}),\n                                      num_process_search_results, None)\n    similarity_score_threshold.change(lambda x: params.update({\"langchain similarity score threshold\": x}),\n                                      similarity_score_threshold, None)\n    chunk_size.change(lambda x: params.update({\"chunk size\": x}), chunk_size, None)\n    search_type.change(lambda x: params.update({\"simple search\": x}),\n                       search_type,\n                       None).then(toggle_full_search_options, search_type, [ensemble_weighting, keyword_retriever,\n                                                                            splade_batch_size, chunker, chunk_size,\n                                                                            chunker_breakpoint_threshold_amount,\n                                                                            client_timeout])\n\n    search_command_regex.change(lambda x: update_regex_setting(x, \"search command regex\",\n                                                               search_command_regex_error_label),\n                                search_command_regex, search_command_regex_error_label, show_progress=\"hidden\")\n\n    open_url_command_regex.change(lambda x: update_regex_setting(x, \"open url command regex\",\n                                                                 open_url_command_regex_error_label),\n                                  open_url_command_regex, open_url_command_regex_error_label, show_progress=\"hidden\")\n\n    show_results.change(lambda x: params.update({\"display search results in chat\": x}), show_results,\n                        None).then(lambda x: gr.update(interactive=not x), show_results, keep_results_in_ctx,\n                                          show_progress=\"hidden\")\n    show_url_content.change(lambda x: params.update({\"display extracted URL content in chat\": x}), show_url_content,\n                            None)\n    keep_results_in_ctx.change(lambda x: params.update({\"keep results in context\": x}), keep_results_in_ctx,None)\n    show_force_search.change(lambda x: params.update({\"show force search checkbox\": x}), show_force_search, None)\n    searxng_url.change(lambda x: params.update({\"searxng url\": x}), searxng_url, None)\n\n    delete_button.click(\n        lambda x: x, system_prompt, gradio('delete_filename')).then(\n        lambda: os.path.join(extension_path, \"system_prompts\", \"\"), None, gradio('delete_root')).then(\n        lambda: gr.update(visible=True), None, gradio('file_deleter'))\n    shared.gradio['delete_confirm'].click(\n        lambda: \"None\", None, system_prompt).then(\n        None, None, None, _js=\"() => { document.getElementById('custom-sysprompt-refresh').click() }\")\n    system_prompt.change(load_system_prompt, system_prompt, shared.gradio['custom_system_message'])\n    system_prompt.change(load_system_prompt, system_prompt, system_prompt_text)\n    # restore checked state if chosen system prompt matches the default\n    system_prompt.change(lambda x: x == params[\"default system prompt filename\"], system_prompt,\n                         set_system_message_as_default)\n    sys_prompt_filename.change(check_file_exists, sys_prompt_filename, system_prompt_saved_success_elem)\n    sys_prompt_save_button.click(save_system_prompt, [sys_prompt_filename, system_prompt_text],\n                                 system_prompt_saved_success_elem,\n                                 show_progress=\"hidden\").then(timeout_save_message,\n                                                              None,\n                                                              system_prompt_saved_success_elem,\n                                                              _js=\"() => { document.getElementById('custom-sysprompt-refresh').click() }\",\n                                                              show_progress=\"hidden\").then(lambda: \"\", None,\n                                                                                        sys_prompt_filename,\n                                                                                        show_progress=\"hidden\")\n    append_datetime.change(lambda x: params.update({\"append current datetime\": x}), append_datetime, None)\n    # '.input' = only triggers when user changes the value of the component, not a function\n    set_system_message_as_default.input(update_default_custom_system_message, set_system_message_as_default, None)\n\n    # A dummy checkbox to enable the actual \"Force web search\" checkbox to trigger a gradio event\n    force_search_checkbox = gr.Checkbox(value=False, visible=False, elem_id=\"Force-search-checkbox\")\n    force_search_checkbox.change(toggle_forced_search, force_search_checkbox, None)\n\n    # Add event listener to \"Past chats\" radio menu to get the current unique chat ID\n    shared.gradio['unique_id'].change(update_chat_id, shared.gradio['unique_id'], None)\n\n    # Don't update internal history with search results if last reply was removed\n    shared.gradio['Remove last'].click(clear_update_history_dict, None, None)\n\n    # Change font color and invert checkmark color of force search checkbox when dark mode is toggled\n    shared.gradio['theme_state'].change(None, None, None, js=f\"() => {{ {get_force_search_box_theme_js()}; toggleForceSearchDarkMode() }}\")\n\n    think_after_search.change(lambda x: params.update({\"think after searching\": x}), think_after_search, None)\n\n\ndef get_generation_prompt(state, impersonate=False, enable_thinking=True):\n\n    def _get_generation_prompt(renderer, impersonate=False, strip_trailing_spaces=True):\n        '''\n        Given a Jinja template, reverse-engineers the prefix and the suffix for\n        an assistant message (if impersonate=False) or an user message\n        (if impersonate=True)\n        '''\n\n        if impersonate:\n            messages = [\n                {\"role\": \"user\", \"content\": \"<<|user-message-1|>>\"},\n                {\"role\": \"user\", \"content\": \"<<|user-message-2|>>\"},\n            ]\n        else:\n            messages = [\n                {\"role\": \"assistant\", \"content\": \"<<|user-message-1|>>\"},\n                {\"role\": \"assistant\", \"content\": \"<<|user-message-2|>>\"},\n            ]\n\n        prompt = renderer(messages=messages)\n\n        suffix_plus_prefix = prompt.split(\"<<|user-message-1|>>\")[1].split(\"<<|user-message-2|>>\")[0]\n        suffix = prompt.split(\"<<|user-message-2|>>\")[1]\n        prefix = suffix_plus_prefix[len(suffix):]\n\n        if strip_trailing_spaces:\n            prefix = prefix.rstrip(' ')\n\n        return prefix, suffix\n\n    chat_template_str = state['chat_template_str']\n    if state['mode'] != 'instruct':\n        chat_template_str = chat.replace_character_names(chat_template_str, state['name1'], state['name2'])\n\n    instruction_template = chat.jinja_env.from_string(state['instruction_template_str'])\n    chat_template = chat.jinja_env.from_string(chat_template_str)\n\n    instruct_renderer = partial(\n        instruction_template.render,\n        builtin_tools=None,\n        tools=None,\n        tools_in_user_message=False,\n        add_generation_prompt=False\n    )\n\n    chat_renderer = partial(\n        chat_template.render,\n        add_generation_prompt=False,\n        name1=state['name1'],\n        name2=state['name2'],\n        user_bio=chat.replace_character_names(state['user_bio'], state['name1'], state['name2']),\n    )\n    if state[\"mode\"] == \"instruct\":\n        start_turn_str, end_turn_str = _get_generation_prompt(instruct_renderer, impersonate, False)\n    else:\n        start_turn_str, end_turn_str = _get_generation_prompt(chat_renderer, impersonate, False)\n\n    if not enable_thinking:\n        start_turn_str += chat.get_thinking_suppression_string(instruction_template)\n\n    return start_turn_str, end_turn_str\n\n\ndef custom_generate_reply(question, original_question, state, stopping_strings, is_chat, recursive_call=False):\n    \"\"\"\n    Overrides the main text generation function.\n    :return:\n    \"\"\"\n    if shared.model.__class__.__name__ in ['LlamaServer', 'LlamaCppModel', 'RWKVModel', 'ExllamaModel', 'Exllamav2Model',\n                                           'CtransformersModel']:\n        generate_func = generate_reply_custom\n    else:\n        generate_func = generate_reply_HF\n\n    if not params['enable']:\n        for reply in generate_func(question, original_question, state, stopping_strings, is_chat=is_chat):\n            yield reply\n        return\n\n    web_search = False\n    read_webpage = False\n    max_search_results = int(params[\"search results per query\"])\n    instant_answers = params[\"instant answers\"]\n    simple_search = params[\"simple search\"]\n\n    document_retriever.num_results = int(params[\"duckduckgo results per query\"])\n    document_retriever.similarity_threshold = params[\"langchain similarity score threshold\"]\n    document_retriever.chunk_size = params[\"chunk size\"]\n    document_retriever.ensemble_weighting = params[\"ensemble weighting\"]\n    document_retriever.splade_batch_size = params[\"splade batch size\"]\n    document_retriever.chunking_method = params[\"chunking method\"]\n    document_retriever.chunker_breakpoint_threshold_amount = params[\"chunker breakpoint_threshold_amount\"]\n    document_retriever.client_timeout = params[\"client timeout\"]\n    document_retriever.token_classification_model_id = params[\"token classification model id\"]\n\n    search_command_regex = params[\"search command regex\"]\n    open_url_command_regex = params[\"open url command regex\"]\n    searxng_url = params[\"searxng url\"]\n    display_search_results = params[\"display search results in chat\"]\n    display_webpage_content = params[\"display extracted URL content in chat\"]\n    keep_results_in_context = params[\"keep results in context\"]\n\n    if search_command_regex == \"\":\n        search_command_regex = params[\"default search command regex\"]\n    if open_url_command_regex == \"\":\n        open_url_command_regex = params[\"default open url command regex\"]\n\n    compiled_search_command_regex = regex.compile(search_command_regex)\n    compiled_open_url_command_regex = regex.compile(open_url_command_regex)\n    search_command = search_command_regex.rstrip(\"*\\\\[':.(?]\\\")\")\n    open_url_command = open_url_command_regex.rstrip(\"*\\\\[':.(?]\\\")\")\n\n    if force_search and not recursive_call:\n        question += f\" {params['force search prefix']}\"\n\n    search_start_idx = 0\n    model_reply_gen = generate_func(question, original_question, state, stopping_strings, is_chat=is_chat)\n    reply = None\n    for reply in model_reply_gen:\n\n        if force_search and not recursive_call:\n            reply = params[\"force search prefix\"] + reply\n\n        reply_substr = reply[search_start_idx:]\n\n        search_re_match = compiled_search_command_regex.search(reply_substr)\n        if search_re_match is not None:\n            yield reply\n            search_term = search_re_match.group(1)\n\n            if search_term == \"query\":\n                search_start_idx = search_start_idx + search_re_match.span()[1]\n                logger.info(f'LLM_Web_search | Ignoring search for query \"query\"')\n                continue\n\n            model_reply_gen.close()\n            original_model_reply = reply\n            web_search = True\n            logger.info(f\"LLM_Web_search | Searching for {search_term}...\")\n\n            reply += \"\\n```plaintext\"\n            reply += \"\\nSearch tool:\\n\"\n\n            if searxng_url == \"\":\n                search_generator = Generator(retrieve_from_duckduckgo(search_term,\n                                                                      document_retriever,\n                                                                      max_search_results,\n                                                                      simple_search))\n            else:\n                search_generator = Generator(retrieve_from_searxng(search_term,\n                                                                   searxng_url,\n                                                                   document_retriever,\n                                                                   max_search_results,\n                                                                   instant_answers,\n                                                                   simple_search))\n            try:\n                for status_message in search_generator:\n                    time.sleep(GEN_LATENCY_THRESH)\n                    # Insert zero-width space before '*' to avoid empty line after newline\n                    yield original_model_reply + f\"\\n​*{status_message}*\"\n                time.sleep(GEN_LATENCY_THRESH)\n                yield original_model_reply + \"\\n​*Is typing...*\"\n                search_results = docs_to_pretty_str(search_generator.retval)\n            except Exception as exc:\n                exception_message = str(exc)\n                reply += f\"The search tool encountered an error: {exception_message}\"\n                logger.warning(f'LLM_Web_search | {search_term} generated an exception: {exception_message}')\n            else:\n                if search_results != \"\":\n                    reply += search_results\n                else:\n                    reply += f\"\\nThe search tool did not return any results.\"\n\n            reply += \"```\\n\"\n            if display_search_results:\n                time.sleep(GEN_LATENCY_THRESH)\n                yield reply\n\n            break\n\n        open_url_re_match = compiled_open_url_command_regex.search(reply)\n        if open_url_re_match is not None:\n            yield reply\n\n            url = open_url_re_match.group(1)\n\n            if url == \"url\":\n                search_start_idx = search_start_idx + open_url_re_match.span()[1]\n                logger.info(f'LLM_Web_search | Ignoring tool call to open url \"url\"')\n                continue\n\n            model_reply_gen.close()\n            original_model_reply = reply\n            read_webpage = True\n\n            logger.info(f\"LLM_Web_search | Reading {url}...\")\n            reply += \"\\n```plaintext\"\n            reply += \"\\nURL opener tool:\\n\"\n            try:\n                webpage_content = get_webpage_content(url)\n            except Exception as exc:\n                reply += f\"Couldn't open {url}. Error message: {str(exc)}\"\n                logger.warning(f'LLM_Web_search | {url} generated an exception: {str(exc)}')\n            else:\n                reply += f\"\\nText content of {url}:\\n\"\n                reply += webpage_content\n\n            reply += \"```\\n\"\n            if display_webpage_content:\n                yield reply + \"*Is typing...*\"\n            else:\n                yield original_model_reply + \"\\n*Is typing...*\"\n\n            break\n\n        yield reply\n\n    if web_search or read_webpage:\n        display_results = web_search and display_search_results or read_webpage and display_webpage_content\n        # Add results to context and continue model output\n        start_turn_str, end_turn_str = get_generation_prompt(state, enable_thinking=params[\"think after searching\"])\n        new_question = question + reply + end_turn_str + start_turn_str\n        new_reply = \"\"\n        for new_reply in custom_generate_reply(new_question, new_question, state,\n                                               stopping_strings, is_chat=is_chat, recursive_call=True):\n            if display_results:\n                yield f\"{reply}{new_reply}\"\n            else:\n                yield f\"{original_model_reply}\\n{new_reply}\"\n\n        if not display_results and keep_results_in_context:\n            update_history_dict[state[\"unique_id\"]] = f\"{reply}\\n{update_history_dict[state['unique_id']]}\"\n    else:\n        if recursive_call and not display_search_results:\n            update_history_dict[state[\"unique_id\"]] = f\"{reply}\\n{update_history_dict[state['unique_id']]}\"\n\n\ndef output_modifier(string, state, is_chat=False):\n    \"\"\"\n    Modifies the output string before it is presented in the UI. In chat mode,\n    it is applied to the bot's reply. Otherwise, it is applied to the entire\n    output.\n    :param string:\n    :param state:\n    :param is_chat:\n    :return:\n    \"\"\"\n    return string\n\n\ndef custom_css():\n    \"\"\"\n    Returns a CSS string that gets appended to the CSS for the webui.\n    \"\"\"\n    with open(os.path.join(extension_path, \"style.css\"), \"r\") as f:\n        return f.read()\n\n\ndef custom_js():\n    \"\"\"\n    Returns custom javascript as a string. It is applied whenever the web UI is\n    loaded.\n    :return:\n    \"\"\"\n    with open(os.path.join(extension_path, \"script.js\"), \"r\") as f:\n        script_js = f.read()\n    force_search_box_theme_js = get_force_search_box_theme_js()\n    return script_js + force_search_box_theme_js + \";toggleForceSearchDarkMode();\"\n\n\ndef chat_input_modifier(text, visible_text, state):\n    \"\"\"\n    Modifies both the visible and internal inputs in chat mode. Can be used to\n    hijack the chat input with custom content.\n    :param text:\n    :param visible_text:\n    :param state:\n    :return:\n    \"\"\"\n    return text, visible_text\n\n\ndef state_modifier(state):\n    \"\"\"\n    Modifies the dictionary containing the UI input parameters before it is\n    used by the text generation functions.\n    :param state:\n    :return:\n    \"\"\"\n    return state\n\n\ndef history_modifier(history):\n    \"\"\"\n    Modifies the chat history before the text generation in chat mode begins.\n    :param history:\n    :return:\n    \"\"\"\n    if update_history_dict[chat_id]:\n        # Replace the last reply in the internal history (which does not contain any search results) with the\n        # concatenation of all recursive searches and their model completions, which *do* contain the full results.\n        if len(history[\"internal\"]) > 0:\n            history[\"internal\"][-1][-1] = update_history_dict[chat_id]\n        update_history_dict[chat_id] = \"\"\n    return history\n"
  },
  {
    "path": "style.css",
    "content": ".settings-checkbox > label > input[disabled] {\n    opacity: .6;\n    filter: grayscale(100%);\n}\n\n.settings-checkbox > label.disabled > span {\n    color: #525252;\n    opacity: .6;\n}\n\n#first-separator {\n    margin-top: -10px;\n}"
  },
  {
    "path": "system_prompts/bing_at_home",
    "content": "A chat between a curious user and artificial intelligence assistant. The assistant ends every message with an emoji matching the emotion of the the message. The assistant is never confident about facts. The assistant always searches the web for facts. The assistant uses the available tools to retrieve relevant information and give helpful, detailed, and polite answers to the user's questions.\n\nSearch tool command format: Search_web(\"<|query|>\")\n"
  },
  {
    "path": "system_prompts/copilot_prompt",
    "content": "You are a state-of-the-art artificial intelligence assistant equipped with a comprehensive web search tool. Your mission is to provide accurate, up-to-date information and helpful answers to user queries. Here are the key guidelines:\n\n1. **Context-Aware Web Search:**\n   - When a user message contains relevant information or context suggesting the need for a web search, you will autonomously output the search command: Search_web(\"query\")\n   - Prioritize reliable sources and communicate findings clearly.\n\n2. **Fact-Driven Humility:**\n   - Remain cautious about stating specific facts and up-to-date information based only on your pre-programmed knowledge base.\n   - If uncertainty arises, default to searching the web for accurate details.\n\n3. **Polite and Detailed Responses:**\n   - Engage in friendly, empathetic conversations with users.\n   - Extract information from search results to guide your answers.\n   - Always end messages with an appropriate emoji to match the conveyed emotion.\n\nRemember the search command format: Search_web(\"query\")\n"
  },
  {
    "path": "system_prompts/deep_search",
    "content": "You are a highly capable AI assistant with advanced web search and webpage download capabilities. Your mission is to provide exceptionally accurate and up-to-date information, ensuring user satisfaction.\n\n1. **Web Search:** When information is needed, output Search_web(\"query\"). Prioritize reliable sources. If initial results are irrelevant, refine the query (Search_web(\"refined query\")). Only refine a maximum of three times.\n\n2. **Webpage Download:** If a search result snippet is promising, but is cut off or otherwise suggests that the full page might contain the answer, output Download_webpage(\"URL\"). Extract relevant information from the downloaded page.\n\n3. **Responses:** Provide detailed answers, citing sources (URL or brief description). Use an appropriate emoji.  Your insightful and thorough responses are greatly appreciated.\n\nRemember: Search_web(\"query\"), Download_webpage(\"URL\"). Use tools judiciously.\n"
  },
  {
    "path": "system_prompts/default_system_prompt.txt",
    "content": "A chat between a curious user and artificial intelligence assistant. The assistant is never confident about facts and up-to-date information. The assistant can search the web for facts and up to date information using the following search command format:\n\nSearch_web(\"query\")\n\nThe search tool will search the web for these keywords and return the results. Finally, the assistant extracts the information from the results of the search tool to guide its response."
  },
  {
    "path": "system_prompts/reasoning_enforce_search",
    "content": "You are a reasoning agent with access to a search function: `search_web(\"query\")`. Your task is to solve problems by combining your knowledge with external information. Follow these rules:\n\n1. **If the answer requires external data**, you **must** use `search_web(\"query\")` immediately.\n2. **Do not rely on pre-existing knowledge** if a search is required. If you say \"I should verify,\" you must follow with `search_web(\"query\")`.\n3. **You cannot proceed to the final answer without using the search results**. Skipping the search is invalid.\n4. **Examples**:\n   - \"What is the capital of Nigeria?\" →\n     ```\n     search_web(\"capital of Nigeria\")\n     The search result states that the capital is Abuja.\n     The capital of Nigeria is Abuja.\n     ```\n   - \"What is the latest update on the Mars rover mission?\" →\n     ```\n     search_web(\"latest Mars rover mission updates\")\n     The search result mentions that NASA's Perseverance rover recently collected a sample.\n     The latest update is that the Perseverance rover successfully collected a rock sample for return to Earth.\n     ```\n\n**Failure to use `search_web()` when required will result in an invalid response.**\n\n"
  },
  {
    "path": "system_prompts/second_person_command_last",
    "content": "You are a state of the art artificial intelligence assistant. However, you are never confident about specific facts and up-to-date information. You must search the web to obtain this information. The search tool will return the results. Finally, you extract the information from the results of the search tool to guide your response. To trigger a web search, you must use the following search command format:\n\nSearch_web(\"query\")\n"
  },
  {
    "path": "test_basics.py",
    "content": "import unittest\n\nfrom llm_web_search import retrieve_from_duckduckgo, Generator\nfrom retrieval import DocumentRetriever\n\n\nclass MyTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.document_retriever = DocumentRetriever(device=\"cpu\", num_results=10, similarity_threshold=0.5, chunk_size=500,\n                                                    ensemble_weighting=0.5, keyword_retriever=\"bm25\",\n                                                    chunking_method=\"character-based\")\n\n    def test_basic_search(self):\n        gen = Generator(retrieve_from_duckduckgo(\"How much does a LLama weigh?\",\n                                                 self.document_retriever, max_results=5))\n        status_messages = list(gen)\n        self.assertEqual(status_messages[0], \"Getting results from DuckDuckGo...\")\n        self.assertEqual(status_messages[1], \"Downloading and chunking webpages...\")\n        self.assertEqual(status_messages[2], \"Retrieving relevant results...\")\n\n        search_result_dict = gen.retval\n        self.assertEqual(len(search_result_dict), 5)\n\n        for document in search_result_dict:\n            self.assertIsNotNone(document.page_content)\n            self.assertNotEqual(document.page_content, \"\")\n            self.assertIsNotNone(document.metadata['source'])\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tool.py",
    "content": "import logging\nfrom datetime import datetime\n\nfrom modules.extensions import state\n\n\nlogger = logging.getLogger('text-generation-webui')\n\nif not \"LLM_Web_search\" in state:\n    raise ValueError(\"Can't use llm_web_search tool. LLM_Web_search extension not loaded.\")\n\n\nextension_module = state[\"LLM_Web_search\"][-1]\n\nparams                   = extension_module.params\nretrieve_from_duckduckgo = extension_module.retrieve_from_duckduckgo\nretrieve_from_searxng    = extension_module.retrieve_from_searxng\nGenerator                = extension_module.Generator\ndocument_retriever       = extension_module.document_retriever\n\n\ntool = {\n    \"type\": \"function\",\n    \"function\": {\n        \"name\": \"web_search\",\n        \"description\": \"Execute a web search\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"query\": {\"type\": \"string\", \"description\": \"The question or keywords to search for.\"},\n            },\n            \"required\": [\"query\"]\n        }\n    }\n}\n\n\ndef docs_to_dicts(docs):\n    dicts = []\n    for i, doc in enumerate(docs):\n        doc_dict = {\"Content\": doc.page_content,\n                    \"Source URL\": doc.metadata['source']}\n        dicts.append(doc_dict)\n    return dicts\n\n\ndef execute(arguments):\n    if not \"LLM_Web_search\" in state:\n        error_msg = \"Can't use llm_web_search tool. LLM_Web_search extension not loaded.\"\n        logger.error(error_msg)\n        return {\"Error\": error_msg}\n    elif not params[\"enable\"]:\n        error_msg = \"Can't use llm_web_search tool. LLM_Web_search extension is disabled.\"\n        logger.error(error_msg)\n        return {\"Error\": error_msg}\n\n    query = arguments.get('query', '')\n\n    max_search_results = int(params[\"search results per query\"])\n    instant_answers    = params[\"instant answers\"]\n    simple_search      = params[\"simple search\"]\n    searxng_url        = params[\"searxng url\"]\n\n    document_retriever.num_results                         = int(params[\"duckduckgo results per query\"])\n    document_retriever.similarity_threshold                = params[\"langchain similarity score threshold\"]\n    document_retriever.chunk_size                          = params[\"chunk size\"]\n    document_retriever.ensemble_weighting                  = params[\"ensemble weighting\"]\n    document_retriever.splade_batch_size                   = params[\"splade batch size\"]\n    document_retriever.chunking_method                     = params[\"chunking method\"]\n    document_retriever.chunker_breakpoint_threshold_amount = params[\"chunker breakpoint_threshold_amount\"]\n    document_retriever.client_timeout                      = params[\"client timeout\"]\n    document_retriever.token_classification_model_id       = params[\"token classification model id\"]\n\n    if searxng_url == \"\":\n        search_generator = Generator(retrieve_from_duckduckgo(query,\n                                                              document_retriever,\n                                                              max_search_results,\n                                                              simple_search))\n    else:\n        search_generator = Generator(retrieve_from_searxng(query,\n                                                           searxng_url,\n                                                           document_retriever,\n                                                           max_search_results,\n                                                           instant_answers,\n                                                           simple_search))\n    try:\n        for _ in search_generator:\n            pass\n        search_results_dict = {\"Results\": docs_to_dicts(search_generator.retval),\n                               \"Current datetime\": datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")}\n    except Exception as exc:\n        exception_message = str(exc)\n        search_results_dict = {\"Error\": exception_message}\n        logger.warning(f'LLM_Web_search | {query} generated an exception: {exception_message}')\n\n    return search_results_dict\n"
  },
  {
    "path": "utils.py",
    "content": "from typing import Dict, Literal, List, Callable\nimport warnings\nimport math\nimport copy\nfrom dataclasses import dataclass\nimport re\nfrom collections import Counter\n\nfrom torch import Tensor\nimport torch\nimport numpy as np\nfrom sentence_transformers import SentenceTransformer, quantize_embeddings\nfrom sentence_transformers.util import batch_to_device, truncate_embeddings\n\n\n@dataclass\nclass Document:\n    page_content: str\n    metadata: Dict\n\n\nclass Generator:\n    \"\"\"Allows a generator method to return a final value after finishing\n    the generation. Credit: https://stackoverflow.com/a/34073559\"\"\"\n    def __init__(self, gen):\n        self.gen = gen\n\n    def __iter__(self):\n        self.retval = yield from self.gen\n        return self.retval\n\n\ndef cosine_similarity(X, Y) -> np.ndarray:\n    \"\"\"Row-wise cosine similarity between two equal-width matrices.\"\"\"\n    if len(X) == 0 or len(Y) == 0:\n        return np.array([])\n\n    X = np.array(X)\n    Y = np.array(Y)\n    if X.shape[1] != Y.shape[1]:\n        raise ValueError(\n            f\"Number of columns in X and Y must be the same. X has shape {X.shape} \"\n            f\"and Y has shape {Y.shape}.\"\n        )\n    X_norm = np.linalg.norm(X, axis=1)\n    Y_norm = np.linalg.norm(Y, axis=1)\n    # Ignore divide by zero errors run time warnings as those are handled below.\n    with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n        similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)\n    similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0\n    return similarity\n\n\nclass SimilarLengthsBatchifyer:\n    \"\"\"\n    Generator class to split samples into batches. Groups sample sequences\n    of equal/similar length together to minimize the need for padding within a batch.\n    \"\"\"\n    def __init__(self, batch_size, inputs, max_padding_len=10):\n        # Remember number of samples\n        self.num_samples = len(inputs)\n\n        self.unique_lengths = set()\n        self.length_to_sample_indices = {}\n\n        for i in range(0, len(inputs)):\n            len_input = len(inputs[i])\n\n            self.unique_lengths.add(len_input)\n\n            # For each length, keep track of the indices of the samples that have this length\n            # E.g.: self.length_to_sample_indices = { 3: [3,5,11], 4: [1,2], ...}\n            if len_input in self.length_to_sample_indices:\n                self.length_to_sample_indices[len_input].append(i)\n            else:\n                self.length_to_sample_indices[len_input] = [i]\n\n        # Use a dynamic batch size to speed up inference at a constant VRAM usage\n        self.unique_lengths = sorted(list(self.unique_lengths))\n        max_chars_per_batch = self.unique_lengths[-1] * batch_size\n        self.length_to_batch_size = {length: int(max_chars_per_batch / (length * batch_size)) * batch_size for length in self.unique_lengths}\n\n        # Merge samples of similar lengths in those cases where the amount of samples\n        # of a particular length is < dynamic batch size\n        accum_len_diff = 0\n        for i in range(1, len(self.unique_lengths)):\n            if accum_len_diff >= max_padding_len:\n                accum_len_diff = 0\n                continue\n            curr_len = self.unique_lengths[i]\n            prev_len = self.unique_lengths[i-1]\n            len_diff = curr_len - prev_len\n            if (len_diff <= max_padding_len and\n                    (len(self.length_to_sample_indices[curr_len]) < self.length_to_batch_size[curr_len]\n                     or len(self.length_to_sample_indices[prev_len]) < self.length_to_batch_size[prev_len])):\n                self.length_to_sample_indices[curr_len].extend(self.length_to_sample_indices[prev_len])\n                self.length_to_sample_indices[prev_len] = []\n                accum_len_diff += len_diff\n            else:\n                accum_len_diff = 0\n\n    def __len__(self):\n        return self.num_samples\n\n    def __iter__(self):\n        # Iterate over all possible sentence lengths\n        for length in self.unique_lengths:\n\n            # Get indices of all samples for the current length\n            # for example, all indices of samples with a length of 7\n            sequence_indices = self.length_to_sample_indices[length]\n            if len(sequence_indices) == 0:\n                continue\n\n            dyn_batch_size = self.length_to_batch_size[length]\n\n            # Compute the number of batches\n            num_batches = np.ceil(len(sequence_indices) / dyn_batch_size)\n\n            # Loop over all possible batches\n            for batch_indices in np.array_split(sequence_indices, num_batches):\n                yield batch_indices\n    \n    \nclass MySentenceTransformer(SentenceTransformer):\n    def batch_encode(\n            self,\n            sentences: str | list[str],\n            prompt_name: str | None = None,\n            prompt: str | None = None,\n            batch_size: int = 32,\n            output_value: Literal[\"sentence_embedding\", \"token_embeddings\"] | None = \"sentence_embedding\",\n            precision: Literal[\"float32\", \"int8\", \"uint8\", \"binary\", \"ubinary\"] = \"float32\",\n            convert_to_numpy: bool = True,\n            convert_to_tensor: bool = False,\n            device: str = None,\n            normalize_embeddings: bool = False,\n            **kwargs,\n    ) -> list[Tensor] | np.ndarray | Tensor:\n        if self.device.type == \"hpu\" and not self.is_hpu_graph_enabled:\n            import habana_frameworks.torch as ht\n\n            ht.hpu.wrap_in_hpu_graph(self, disable_tensor_cache=True)\n            self.is_hpu_graph_enabled = True\n\n        self.eval()\n        if convert_to_tensor:\n            convert_to_numpy = False\n\n        if output_value != \"sentence_embedding\":\n            convert_to_tensor = False\n            convert_to_numpy = False\n\n        input_was_string = False\n        if isinstance(sentences, str) or not hasattr(\n                sentences, \"__len__\"\n        ):  # Cast an individual sentence to a list with length 1\n            sentences = [sentences]\n            input_was_string = True\n\n        if prompt is None:\n            if prompt_name is not None:\n                try:\n                    prompt = self.prompts[prompt_name]\n                except KeyError:\n                    raise ValueError(\n                        f\"Prompt name '{prompt_name}' not found in the configured prompts dictionary with keys {list(self.prompts.keys())!r}.\"\n                    )\n            elif self.default_prompt_name is not None:\n                prompt = self.prompts.get(self.default_prompt_name, None)\n        else:\n            if prompt_name is not None:\n                warnings.warn(\n                    \"Encode with either a `prompt`, a `prompt_name`, or neither, but not both. \"\n                    \"Ignoring the `prompt_name` in favor of `prompt`.\"\n                )\n\n        extra_features = {}\n        if prompt is not None:\n            sentences = [prompt + sentence for sentence in sentences]\n\n            # Some models (e.g. INSTRUCTOR, GRIT) require removing the prompt before pooling\n            # Tracking the prompt length allow us to remove the prompt during pooling\n            tokenized_prompt = self.tokenize([prompt])\n            if \"input_ids\" in tokenized_prompt:\n                extra_features[\"prompt_length\"] = tokenized_prompt[\"input_ids\"].shape[-1] - 1\n\n        if device is None:\n            device = self.device\n        else:\n            device = torch.device(device)\n\n        self.to(device)\n\n        all_embeddings = []\n        tokenized_sentences = self.tokenizer(sentences, verbose=False)[\"input_ids\"]\n        batchifyer = SimilarLengthsBatchifyer(batch_size, tokenized_sentences)\n        sentences = np.array(sentences)\n        batch_indices = []\n        for index_batch in batchifyer:\n            batch_indices.append(index_batch)\n            sentences_batch = sentences[index_batch]\n            features = self.tokenize(sentences_batch)\n            if self.device.type == \"hpu\":\n                if \"input_ids\" in features:\n                    curr_tokenize_len = features[\"input_ids\"].shape\n                    additional_pad_len = 2 ** math.ceil(math.log2(curr_tokenize_len[1])) - curr_tokenize_len[1]\n                    features[\"input_ids\"] = torch.cat(\n                        (\n                            features[\"input_ids\"],\n                            torch.ones((curr_tokenize_len[0], additional_pad_len), dtype=torch.int8),\n                        ),\n                        -1,\n                    )\n                    features[\"attention_mask\"] = torch.cat(\n                        (\n                            features[\"attention_mask\"],\n                            torch.zeros((curr_tokenize_len[0], additional_pad_len), dtype=torch.int8),\n                        ),\n                        -1,\n                    )\n                    if \"token_type_ids\" in features:\n                        features[\"token_type_ids\"] = torch.cat(\n                            (\n                                features[\"token_type_ids\"],\n                                torch.zeros((curr_tokenize_len[0], additional_pad_len), dtype=torch.int8),\n                            ),\n                            -1,\n                        )\n\n            features = batch_to_device(features, device)\n            features.update(extra_features)\n\n            with torch.no_grad():\n                out_features = self.forward(features, **kwargs)\n                if self.device.type == \"hpu\":\n                    out_features = copy.deepcopy(out_features)\n\n                out_features[\"sentence_embedding\"] = truncate_embeddings(\n                    out_features[\"sentence_embedding\"], self.truncate_dim\n                )\n\n                if output_value == \"token_embeddings\":\n                    embeddings = []\n                    for token_emb, attention in zip(out_features[output_value], out_features[\"attention_mask\"]):\n                        last_mask_id = len(attention) - 1\n                        while last_mask_id > 0 and attention[last_mask_id].item() == 0:\n                            last_mask_id -= 1\n\n                        embeddings.append(token_emb[0: last_mask_id + 1])\n                elif output_value is None:  # Return all outputs\n                    embeddings = []\n                    for sent_idx in range(len(out_features[\"sentence_embedding\"])):\n                        row = {name: out_features[name][sent_idx] for name in out_features}\n                        embeddings.append(row)\n                else:  # Sentence embeddings\n                    embeddings = out_features[output_value]\n                    embeddings = embeddings.detach()\n                    if normalize_embeddings:\n                        embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)\n\n                    # fixes for #522 and #487 to avoid oom problems on gpu with large datasets\n                    if convert_to_numpy:\n                        embeddings = embeddings.to(\"cpu\", non_blocking=True)\n                        sync_device(device)\n\n                all_embeddings.extend(embeddings)\n\n        # Restore order after SimilarLengthsBatchifyer disrupted it:\n        # Ensure that the order of 'indices' and 'values' matches the order of the 'texts' parameter\n        batch_indices = np.concatenate(batch_indices)\n        sorted_indices = np.argsort(batch_indices)\n        all_embeddings = [all_embeddings[i] for i in sorted_indices]\n\n        if precision and precision != \"float32\":\n            all_embeddings = quantize_embeddings(all_embeddings, precision=precision)\n\n        if convert_to_tensor:\n            if len(all_embeddings):\n                if isinstance(all_embeddings, np.ndarray):\n                    all_embeddings = torch.from_numpy(all_embeddings)\n            else:\n                all_embeddings = torch.Tensor()\n        elif convert_to_numpy:\n            if not isinstance(all_embeddings, np.ndarray):\n                if all_embeddings and all_embeddings[0].dtype == torch.bfloat16:\n                    all_embeddings = np.asarray([emb.float().numpy() for emb in all_embeddings])\n                else:\n                    all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])\n        elif isinstance(all_embeddings, np.ndarray):\n            all_embeddings = [torch.from_numpy(embedding) for embedding in all_embeddings]\n\n        if input_was_string:\n            all_embeddings = all_embeddings[0]\n\n        return all_embeddings\n\n\ndef sync_device(device: torch.device):\n    if device.type == \"cpu\":\n        return\n    elif device.type == \"cuda\":\n        torch.cuda.synchronize()\n    elif device.type == \"mps\":\n        torch.mps.synchronize()\n    elif device.type == \"xpu\":\n        torch.xpu.synchronize(device)\n    else:\n        warnings.warn(\"Device type does not match 'cuda', 'xpu' or 'mps'. Not synchronizing\")\n\n\ndef filter_similar_embeddings(\n    embedded_documents: List[List[float]], similarity_fn: Callable, threshold: float,\n    doc_rank_to_source_rank: dict\n) -> List[int]:\n    \"\"\"Filter redundant documents based on the similarity of their embeddings.\"\"\"\n    similarity = np.tril(similarity_fn(embedded_documents, embedded_documents), k=-1)\n    redundant = np.where(similarity > threshold)\n    redundant_stacked = np.column_stack(redundant)\n    redundant_sorted = np.argsort(similarity[redundant])[::-1]\n    included_idxs = set(range(len(embedded_documents)))\n    for first_idx, second_idx in redundant_stacked[redundant_sorted]:\n        if first_idx in included_idxs and second_idx in included_idxs:\n            first_source_rank = doc_rank_to_source_rank[first_idx]\n            second_source_rank = doc_rank_to_source_rank[second_idx]\n            if first_source_rank == second_source_rank:\n                # Tiebreaker: drop the second document of any highly similar pair.\n                included_idxs.remove(second_idx)\n            else:\n                # Drop the document whose source came later in the search engine results\n                index_to_drop = first_idx if first_source_rank < second_source_rank else second_idx\n                included_idxs.remove(index_to_drop)\n    return list(sorted(included_idxs))\n\n\ndef bow_filter_similar_texts(texts: List[str], similarity_fn: Callable, threshold: float,\n                             doc_rank_to_source_rank: dict) -> List[int]:\n    \"\"\"Filter redundant documents based on the similarity of their bag-of-words.\"\"\"\n    if not texts:\n        return []\n    punct_pat = re.compile(\"[\\n.,?!:;]\")\n    bow_dicts = [Counter(punct_pat.sub(\" \", text).lower().split()) for text in texts]\n    vocab_dict = {}\n    for bow_dict in bow_dicts:\n        vocab_dict |= dict.fromkeys(bow_dict, 0)\n\n    # construct bag-of-words lists using the values of the union of the vocab dict and each BOW dict\n    bow_lists = []\n    for bow_dict in bow_dicts:\n        bow_lists.append(list((vocab_dict | bow_dict).values()))\n\n    bow_matrix = np.vstack(bow_lists)\n    similarity = np.tril(similarity_fn(bow_matrix, bow_matrix), k=-1)\n    redundant = np.where(similarity > threshold)\n    redundant_stacked = np.column_stack(redundant)\n    redundant_sorted = np.argsort(similarity[redundant])[::-1]\n    included_idxs = set(range(len(texts)))\n    for first_idx, second_idx in redundant_stacked[redundant_sorted]:\n        if first_idx in included_idxs and second_idx in included_idxs:\n            first_source_rank = doc_rank_to_source_rank[first_idx]\n            second_source_rank = doc_rank_to_source_rank[second_idx]\n            if first_source_rank == second_source_rank:\n                # Tiebreaker: drop the second document of any highly similar pair.\n                included_idxs.remove(second_idx)\n            else:\n                # Drop the document whose source came later in the search engine results\n                index_to_drop = first_idx if first_source_rank < second_source_rank else second_idx\n                included_idxs.remove(index_to_drop)\n    return list(sorted(included_idxs))\n"
  }
]