Repository: mamei16/LLM_Web_search
Branch: main
Commit: 60fe801b11b9
Files: 31
Total size: 170.0 KB
Directory structure:
gitextract_us8kqexm/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug.md
│ │ └── feature_request.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── stale_issues.yml
│ └── unit_tests.yml
├── LICENSE
├── README.md
├── chunkers/
│ ├── base_chunker.py
│ ├── character_chunker.py
│ ├── ner_chunker.py
│ └── semantic_chunker.py
├── environment.yml
├── force_search_box_theme.js
├── llm_web_search.py
├── requirements.txt
├── retrieval.py
├── retrievers/
│ ├── bm25_retriever.py
│ ├── faiss_retriever.py
│ └── splade_retriever.py
├── script.js
├── script.py
├── style.css
├── system_prompts/
│ ├── bing_at_home
│ ├── copilot_prompt
│ ├── deep_search
│ ├── default_system_prompt.txt
│ ├── reasoning_enforce_search
│ └── second_person_command_last
├── test_basics.py
├── tool.py
└── utils.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug.md
================================================
---
name: Bug
about: Create a report to help improve the project
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "pip" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
================================================
FILE: .github/workflows/stale_issues.yml
================================================
name: Close inactive issues
on:
schedule:
- cron: "10 00 * * *"
jobs:
close-issues:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
stale-issue-message: ""
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."
days-before-issue-stale: 180
days-before-issue-close: 0
stale-issue-label: "stale"
days-before-pr-stale: -1
days-before-pr-close: -1
repo-token: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .github/workflows/unit_tests.yml
================================================
# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
name: Unit Tests
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: "20 4 * * *"
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.11
uses: actions/setup-python@v4
with:
python-version: "3.11"
cache: 'pip'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest optimum
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: README.md
================================================
# Give your local LLM the ability to search the web!

This project gives local LLMs the ability to search the web, either by using native tool calls or by outputting a specific
command. 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
ensemble of a dense embedding model and
[Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) (Or alternatively, [SPLADE](https://github.com/naver/splade))
is used to extract the relevant parts (if any) of each web page in the search results
and the results are appended to the model's output.

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