Upload 18 files
Browse files- LICENSE +661 -0
- README.md +141 -12
- environment.yml +15 -0
- instruction_templates/Llama-3.yaml +17 -0
- instruction_templates/OpenChat-Correct.yaml +24 -0
- instruction_templates/SOLAR-10.7B.yaml +24 -0
- langchain_websearch.py +210 -0
- llm_web_search.py +147 -0
- qdrant_retriever.py +136 -0
- requirements.txt +8 -1
- script.js +24 -0
- script.py +567 -0
- semantic_chunker.py +233 -0
- system_prompts/bing_at_home +3 -0
- system_prompts/copilot_prompt +16 -0
- system_prompts/default_system_prompt.txt +5 -0
- system_prompts/second_person_command_last +3 -0
- system_prompts/websearch_gpt4_prompt +10 -0
LICENSE
ADDED
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works, specifically designed to ensure
|
12 |
+
cooperation with the community in the case of network server software.
|
13 |
+
|
14 |
+
The licenses for most software and other practical works are designed
|
15 |
+
to take away your freedom to share and change the works. By contrast,
|
16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
17 |
+
share and change all versions of a program--to make sure it remains free
|
18 |
+
software for all its users.
|
19 |
+
|
20 |
+
When we speak of free software, we are referring to freedom, not
|
21 |
+
price. Our General Public Licenses are designed to make sure that you
|
22 |
+
have the freedom to distribute copies of free software (and charge for
|
23 |
+
them if you wish), that you receive source code or can get it if you
|
24 |
+
want it, that you can change the software or use pieces of it in new
|
25 |
+
free programs, and that you know you can do these things.
|
26 |
+
|
27 |
+
Developers that use our General Public Licenses protect your rights
|
28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
29 |
+
you this License which gives you legal permission to copy, distribute
|
30 |
+
and/or modify the software.
|
31 |
+
|
32 |
+
A secondary benefit of defending all users' freedom is that
|
33 |
+
improvements made in alternate versions of the program, if they
|
34 |
+
receive widespread use, become available for other developers to
|
35 |
+
incorporate. Many developers of free software are heartened and
|
36 |
+
encouraged by the resulting cooperation. However, in the case of
|
37 |
+
software used on network servers, this result may fail to come about.
|
38 |
+
The GNU General Public License permits making a modified version and
|
39 |
+
letting the public access it on a server without ever releasing its
|
40 |
+
source code to the public.
|
41 |
+
|
42 |
+
The GNU Affero General Public License is designed specifically to
|
43 |
+
ensure that, in such cases, the modified source code becomes available
|
44 |
+
to the community. It requires the operator of a network server to
|
45 |
+
provide the source code of the modified version running there to the
|
46 |
+
users of that server. Therefore, public use of a modified version, on
|
47 |
+
a publicly accessible server, gives the public access to the source
|
48 |
+
code of the modified version.
|
49 |
+
|
50 |
+
An older license, called the Affero General Public License and
|
51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
53 |
+
released a new version of the Affero GPL which permits relicensing under
|
54 |
+
this license.
|
55 |
+
|
56 |
+
The precise terms and conditions for copying, distribution and
|
57 |
+
modification follow.
|
58 |
+
|
59 |
+
TERMS AND CONDITIONS
|
60 |
+
|
61 |
+
0. Definitions.
|
62 |
+
|
63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
64 |
+
|
65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
66 |
+
works, such as semiconductor masks.
|
67 |
+
|
68 |
+
"The Program" refers to any copyrightable work licensed under this
|
69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
70 |
+
"recipients" may be individuals or organizations.
|
71 |
+
|
72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
73 |
+
in a fashion requiring copyright permission, other than the making of an
|
74 |
+
exact copy. The resulting work is called a "modified version" of the
|
75 |
+
earlier work or a work "based on" the earlier work.
|
76 |
+
|
77 |
+
A "covered work" means either the unmodified Program or a work based
|
78 |
+
on the Program.
|
79 |
+
|
80 |
+
To "propagate" a work means to do anything with it that, without
|
81 |
+
permission, would make you directly or secondarily liable for
|
82 |
+
infringement under applicable copyright law, except executing it on a
|
83 |
+
computer or modifying a private copy. Propagation includes copying,
|
84 |
+
distribution (with or without modification), making available to the
|
85 |
+
public, and in some countries other activities as well.
|
86 |
+
|
87 |
+
To "convey" a work means any kind of propagation that enables other
|
88 |
+
parties to make or receive copies. Mere interaction with a user through
|
89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
90 |
+
|
91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
92 |
+
to the extent that it includes a convenient and prominently visible
|
93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
94 |
+
tells the user that there is no warranty for the work (except to the
|
95 |
+
extent that warranties are provided), that licensees may convey the
|
96 |
+
work under this License, and how to view a copy of this License. If
|
97 |
+
the interface presents a list of user commands or options, such as a
|
98 |
+
menu, a prominent item in the list meets this criterion.
|
99 |
+
|
100 |
+
1. Source Code.
|
101 |
+
|
102 |
+
The "source code" for a work means the preferred form of the work
|
103 |
+
for making modifications to it. "Object code" means any non-source
|
104 |
+
form of a work.
|
105 |
+
|
106 |
+
A "Standard Interface" means an interface that either is an official
|
107 |
+
standard defined by a recognized standards body, or, in the case of
|
108 |
+
interfaces specified for a particular programming language, one that
|
109 |
+
is widely used among developers working in that language.
|
110 |
+
|
111 |
+
The "System Libraries" of an executable work include anything, other
|
112 |
+
than the work as a whole, that (a) is included in the normal form of
|
113 |
+
packaging a Major Component, but which is not part of that Major
|
114 |
+
Component, and (b) serves only to enable use of the work with that
|
115 |
+
Major Component, or to implement a Standard Interface for which an
|
116 |
+
implementation is available to the public in source code form. A
|
117 |
+
"Major Component", in this context, means a major essential component
|
118 |
+
(kernel, window system, and so on) of the specific operating system
|
119 |
+
(if any) on which the executable work runs, or a compiler used to
|
120 |
+
produce the work, or an object code interpreter used to run it.
|
121 |
+
|
122 |
+
The "Corresponding Source" for a work in object code form means all
|
123 |
+
the source code needed to generate, install, and (for an executable
|
124 |
+
work) run the object code and to modify the work, including scripts to
|
125 |
+
control those activities. However, it does not include the work's
|
126 |
+
System Libraries, or general-purpose tools or generally available free
|
127 |
+
programs which are used unmodified in performing those activities but
|
128 |
+
which are not part of the work. For example, Corresponding Source
|
129 |
+
includes interface definition files associated with source files for
|
130 |
+
the work, and the source code for shared libraries and dynamically
|
131 |
+
linked subprograms that the work is specifically designed to require,
|
132 |
+
such as by intimate data communication or control flow between those
|
133 |
+
subprograms and other parts of the work.
|
134 |
+
|
135 |
+
The Corresponding Source need not include anything that users
|
136 |
+
can regenerate automatically from other parts of the Corresponding
|
137 |
+
Source.
|
138 |
+
|
139 |
+
The Corresponding Source for a work in source code form is that
|
140 |
+
same work.
|
141 |
+
|
142 |
+
2. Basic Permissions.
|
143 |
+
|
144 |
+
All rights granted under this License are granted for the term of
|
145 |
+
copyright on the Program, and are irrevocable provided the stated
|
146 |
+
conditions are met. This License explicitly affirms your unlimited
|
147 |
+
permission to run the unmodified Program. The output from running a
|
148 |
+
covered work is covered by this License only if the output, given its
|
149 |
+
content, constitutes a covered work. This License acknowledges your
|
150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
151 |
+
|
152 |
+
You may make, run and propagate covered works that you do not
|
153 |
+
convey, without conditions so long as your license otherwise remains
|
154 |
+
in force. You may convey covered works to others for the sole purpose
|
155 |
+
of having them make modifications exclusively for you, or provide you
|
156 |
+
with facilities for running those works, provided that you comply with
|
157 |
+
the terms of this License in conveying all material for which you do
|
158 |
+
not control copyright. Those thus making or running the covered works
|
159 |
+
for you must do so exclusively on your behalf, under your direction
|
160 |
+
and control, on terms that prohibit them from making any copies of
|
161 |
+
your copyrighted material outside their relationship with you.
|
162 |
+
|
163 |
+
Conveying under any other circumstances is permitted solely under
|
164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
165 |
+
makes it unnecessary.
|
166 |
+
|
167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
168 |
+
|
169 |
+
No covered work shall be deemed part of an effective technological
|
170 |
+
measure under any applicable law fulfilling obligations under article
|
171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
172 |
+
similar laws prohibiting or restricting circumvention of such
|
173 |
+
measures.
|
174 |
+
|
175 |
+
When you convey a covered work, you waive any legal power to forbid
|
176 |
+
circumvention of technological measures to the extent such circumvention
|
177 |
+
is effected by exercising rights under this License with respect to
|
178 |
+
the covered work, and you disclaim any intention to limit operation or
|
179 |
+
modification of the work as a means of enforcing, against the work's
|
180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
181 |
+
technological measures.
|
182 |
+
|
183 |
+
4. Conveying Verbatim Copies.
|
184 |
+
|
185 |
+
You may convey verbatim copies of the Program's source code as you
|
186 |
+
receive it, in any medium, provided that you conspicuously and
|
187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
188 |
+
keep intact all notices stating that this License and any
|
189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
190 |
+
keep intact all notices of the absence of any warranty; and give all
|
191 |
+
recipients a copy of this License along with the Program.
|
192 |
+
|
193 |
+
You may charge any price or no price for each copy that you convey,
|
194 |
+
and you may offer support or warranty protection for a fee.
|
195 |
+
|
196 |
+
5. Conveying Modified Source Versions.
|
197 |
+
|
198 |
+
You may convey a work based on the Program, or the modifications to
|
199 |
+
produce it from the Program, in the form of source code under the
|
200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
201 |
+
|
202 |
+
a) The work must carry prominent notices stating that you modified
|
203 |
+
it, and giving a relevant date.
|
204 |
+
|
205 |
+
b) The work must carry prominent notices stating that it is
|
206 |
+
released under this License and any conditions added under section
|
207 |
+
7. This requirement modifies the requirement in section 4 to
|
208 |
+
"keep intact all notices".
|
209 |
+
|
210 |
+
c) You must license the entire work, as a whole, under this
|
211 |
+
License to anyone who comes into possession of a copy. This
|
212 |
+
License will therefore apply, along with any applicable section 7
|
213 |
+
additional terms, to the whole of the work, and all its parts,
|
214 |
+
regardless of how they are packaged. This License gives no
|
215 |
+
permission to license the work in any other way, but it does not
|
216 |
+
invalidate such permission if you have separately received it.
|
217 |
+
|
218 |
+
d) If the work has interactive user interfaces, each must display
|
219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
221 |
+
work need not make them do so.
|
222 |
+
|
223 |
+
A compilation of a covered work with other separate and independent
|
224 |
+
works, which are not by their nature extensions of the covered work,
|
225 |
+
and which are not combined with it such as to form a larger program,
|
226 |
+
in or on a volume of a storage or distribution medium, is called an
|
227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
228 |
+
used to limit the access or legal rights of the compilation's users
|
229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
230 |
+
in an aggregate does not cause this License to apply to the other
|
231 |
+
parts of the aggregate.
|
232 |
+
|
233 |
+
6. Conveying Non-Source Forms.
|
234 |
+
|
235 |
+
You may convey a covered work in object code form under the terms
|
236 |
+
of sections 4 and 5, provided that you also convey the
|
237 |
+
machine-readable Corresponding Source under the terms of this License,
|
238 |
+
in one of these ways:
|
239 |
+
|
240 |
+
a) Convey the object code in, or embodied in, a physical product
|
241 |
+
(including a physical distribution medium), accompanied by the
|
242 |
+
Corresponding Source fixed on a durable physical medium
|
243 |
+
customarily used for software interchange.
|
244 |
+
|
245 |
+
b) Convey the object code in, or embodied in, a physical product
|
246 |
+
(including a physical distribution medium), accompanied by a
|
247 |
+
written offer, valid for at least three years and valid for as
|
248 |
+
long as you offer spare parts or customer support for that product
|
249 |
+
model, to give anyone who possesses the object code either (1) a
|
250 |
+
copy of the Corresponding Source for all the software in the
|
251 |
+
product that is covered by this License, on a durable physical
|
252 |
+
medium customarily used for software interchange, for a price no
|
253 |
+
more than your reasonable cost of physically performing this
|
254 |
+
conveying of source, or (2) access to copy the
|
255 |
+
Corresponding Source from a network server at no charge.
|
256 |
+
|
257 |
+
c) Convey individual copies of the object code with a copy of the
|
258 |
+
written offer to provide the Corresponding Source. This
|
259 |
+
alternative is allowed only occasionally and noncommercially, and
|
260 |
+
only if you received the object code with such an offer, in accord
|
261 |
+
with subsection 6b.
|
262 |
+
|
263 |
+
d) Convey the object code by offering access from a designated
|
264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
265 |
+
Corresponding Source in the same way through the same place at no
|
266 |
+
further charge. You need not require recipients to copy the
|
267 |
+
Corresponding Source along with the object code. If the place to
|
268 |
+
copy the object code is a network server, the Corresponding Source
|
269 |
+
may be on a different server (operated by you or a third party)
|
270 |
+
that supports equivalent copying facilities, provided you maintain
|
271 |
+
clear directions next to the object code saying where to find the
|
272 |
+
Corresponding Source. Regardless of what server hosts the
|
273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
274 |
+
available for as long as needed to satisfy these requirements.
|
275 |
+
|
276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
277 |
+
you inform other peers where the object code and Corresponding
|
278 |
+
Source of the work are being offered to the general public at no
|
279 |
+
charge under subsection 6d.
|
280 |
+
|
281 |
+
A separable portion of the object code, whose source code is excluded
|
282 |
+
from the Corresponding Source as a System Library, need not be
|
283 |
+
included in conveying the object code work.
|
284 |
+
|
285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
286 |
+
tangible personal property which is normally used for personal, family,
|
287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
290 |
+
product received by a particular user, "normally used" refers to a
|
291 |
+
typical or common use of that class of product, regardless of the status
|
292 |
+
of the particular user or of the way in which the particular user
|
293 |
+
actually uses, or expects or is expected to use, the product. A product
|
294 |
+
is a consumer product regardless of whether the product has substantial
|
295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
296 |
+
the only significant mode of use of the product.
|
297 |
+
|
298 |
+
"Installation Information" for a User Product means any methods,
|
299 |
+
procedures, authorization keys, or other information required to install
|
300 |
+
and execute modified versions of a covered work in that User Product from
|
301 |
+
a modified version of its Corresponding Source. The information must
|
302 |
+
suffice to ensure that the continued functioning of the modified object
|
303 |
+
code is in no case prevented or interfered with solely because
|
304 |
+
modification has been made.
|
305 |
+
|
306 |
+
If you convey an object code work under this section in, or with, or
|
307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
308 |
+
part of a transaction in which the right of possession and use of the
|
309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
310 |
+
fixed term (regardless of how the transaction is characterized), the
|
311 |
+
Corresponding Source conveyed under this section must be accompanied
|
312 |
+
by the Installation Information. But this requirement does not apply
|
313 |
+
if neither you nor any third party retains the ability to install
|
314 |
+
modified object code on the User Product (for example, the work has
|
315 |
+
been installed in ROM).
|
316 |
+
|
317 |
+
The requirement to provide Installation Information does not include a
|
318 |
+
requirement to continue to provide support service, warranty, or updates
|
319 |
+
for a work that has been modified or installed by the recipient, or for
|
320 |
+
the User Product in which it has been modified or installed. Access to a
|
321 |
+
network may be denied when the modification itself materially and
|
322 |
+
adversely affects the operation of the network or violates the rules and
|
323 |
+
protocols for communication across the network.
|
324 |
+
|
325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
326 |
+
in accord with this section must be in a format that is publicly
|
327 |
+
documented (and with an implementation available to the public in
|
328 |
+
source code form), and must require no special password or key for
|
329 |
+
unpacking, reading or copying.
|
330 |
+
|
331 |
+
7. Additional Terms.
|
332 |
+
|
333 |
+
"Additional permissions" are terms that supplement the terms of this
|
334 |
+
License by making exceptions from one or more of its conditions.
|
335 |
+
Additional permissions that are applicable to the entire Program shall
|
336 |
+
be treated as though they were included in this License, to the extent
|
337 |
+
that they are valid under applicable law. If additional permissions
|
338 |
+
apply only to part of the Program, that part may be used separately
|
339 |
+
under those permissions, but the entire Program remains governed by
|
340 |
+
this License without regard to the additional permissions.
|
341 |
+
|
342 |
+
When you convey a copy of a covered work, you may at your option
|
343 |
+
remove any additional permissions from that copy, or from any part of
|
344 |
+
it. (Additional permissions may be written to require their own
|
345 |
+
removal in certain cases when you modify the work.) You may place
|
346 |
+
additional permissions on material, added by you to a covered work,
|
347 |
+
for which you have or can give appropriate copyright permission.
|
348 |
+
|
349 |
+
Notwithstanding any other provision of this License, for material you
|
350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
351 |
+
that material) supplement the terms of this License with terms:
|
352 |
+
|
353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
354 |
+
terms of sections 15 and 16 of this License; or
|
355 |
+
|
356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
357 |
+
author attributions in that material or in the Appropriate Legal
|
358 |
+
Notices displayed by works containing it; or
|
359 |
+
|
360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
361 |
+
requiring that modified versions of such material be marked in
|
362 |
+
reasonable ways as different from the original version; or
|
363 |
+
|
364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
365 |
+
authors of the material; or
|
366 |
+
|
367 |
+
e) Declining to grant rights under trademark law for use of some
|
368 |
+
trade names, trademarks, or service marks; or
|
369 |
+
|
370 |
+
f) Requiring indemnification of licensors and authors of that
|
371 |
+
material by anyone who conveys the material (or modified versions of
|
372 |
+
it) with contractual assumptions of liability to the recipient, for
|
373 |
+
any liability that these contractual assumptions directly impose on
|
374 |
+
those licensors and authors.
|
375 |
+
|
376 |
+
All other non-permissive additional terms are considered "further
|
377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
378 |
+
received it, or any part of it, contains a notice stating that it is
|
379 |
+
governed by this License along with a term that is a further
|
380 |
+
restriction, you may remove that term. If a license document contains
|
381 |
+
a further restriction but permits relicensing or conveying under this
|
382 |
+
License, you may add to a covered work material governed by the terms
|
383 |
+
of that license document, provided that the further restriction does
|
384 |
+
not survive such relicensing or conveying.
|
385 |
+
|
386 |
+
If you add terms to a covered work in accord with this section, you
|
387 |
+
must place, in the relevant source files, a statement of the
|
388 |
+
additional terms that apply to those files, or a notice indicating
|
389 |
+
where to find the applicable terms.
|
390 |
+
|
391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
392 |
+
form of a separately written license, or stated as exceptions;
|
393 |
+
the above requirements apply either way.
|
394 |
+
|
395 |
+
8. Termination.
|
396 |
+
|
397 |
+
You may not propagate or modify a covered work except as expressly
|
398 |
+
provided under this License. Any attempt otherwise to propagate or
|
399 |
+
modify it is void, and will automatically terminate your rights under
|
400 |
+
this License (including any patent licenses granted under the third
|
401 |
+
paragraph of section 11).
|
402 |
+
|
403 |
+
However, if you cease all violation of this License, then your
|
404 |
+
license from a particular copyright holder is reinstated (a)
|
405 |
+
provisionally, unless and until the copyright holder explicitly and
|
406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
407 |
+
holder fails to notify you of the violation by some reasonable means
|
408 |
+
prior to 60 days after the cessation.
|
409 |
+
|
410 |
+
Moreover, your license from a particular copyright holder is
|
411 |
+
reinstated permanently if the copyright holder notifies you of the
|
412 |
+
violation by some reasonable means, this is the first time you have
|
413 |
+
received notice of violation of this License (for any work) from that
|
414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
415 |
+
your receipt of the notice.
|
416 |
+
|
417 |
+
Termination of your rights under this section does not terminate the
|
418 |
+
licenses of parties who have received copies or rights from you under
|
419 |
+
this License. If your rights have been terminated and not permanently
|
420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
421 |
+
material under section 10.
|
422 |
+
|
423 |
+
9. Acceptance Not Required for Having Copies.
|
424 |
+
|
425 |
+
You are not required to accept this License in order to receive or
|
426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
428 |
+
to receive a copy likewise does not require acceptance. However,
|
429 |
+
nothing other than this License grants you permission to propagate or
|
430 |
+
modify any covered work. These actions infringe copyright if you do
|
431 |
+
not accept this License. Therefore, by modifying or propagating a
|
432 |
+
covered work, you indicate your acceptance of this License to do so.
|
433 |
+
|
434 |
+
10. Automatic Licensing of Downstream Recipients.
|
435 |
+
|
436 |
+
Each time you convey a covered work, the recipient automatically
|
437 |
+
receives a license from the original licensors, to run, modify and
|
438 |
+
propagate that work, subject to this License. You are not responsible
|
439 |
+
for enforcing compliance by third parties with this License.
|
440 |
+
|
441 |
+
An "entity transaction" is a transaction transferring control of an
|
442 |
+
organization, or substantially all assets of one, or subdividing an
|
443 |
+
organization, or merging organizations. If propagation of a covered
|
444 |
+
work results from an entity transaction, each party to that
|
445 |
+
transaction who receives a copy of the work also receives whatever
|
446 |
+
licenses to the work the party's predecessor in interest had or could
|
447 |
+
give under the previous paragraph, plus a right to possession of the
|
448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
449 |
+
the predecessor has it or can get it with reasonable efforts.
|
450 |
+
|
451 |
+
You may not impose any further restrictions on the exercise of the
|
452 |
+
rights granted or affirmed under this License. For example, you may
|
453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
454 |
+
rights granted under this License, and you may not initiate litigation
|
455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
456 |
+
any patent claim is infringed by making, using, selling, offering for
|
457 |
+
sale, or importing the Program or any portion of it.
|
458 |
+
|
459 |
+
11. Patents.
|
460 |
+
|
461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
462 |
+
License of the Program or a work on which the Program is based. The
|
463 |
+
work thus licensed is called the contributor's "contributor version".
|
464 |
+
|
465 |
+
A contributor's "essential patent claims" are all patent claims
|
466 |
+
owned or controlled by the contributor, whether already acquired or
|
467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
468 |
+
by this License, of making, using, or selling its contributor version,
|
469 |
+
but do not include claims that would be infringed only as a
|
470 |
+
consequence of further modification of the contributor version. For
|
471 |
+
purposes of this definition, "control" includes the right to grant
|
472 |
+
patent sublicenses in a manner consistent with the requirements of
|
473 |
+
this License.
|
474 |
+
|
475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
476 |
+
patent license under the contributor's essential patent claims, to
|
477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
478 |
+
propagate the contents of its contributor version.
|
479 |
+
|
480 |
+
In the following three paragraphs, a "patent license" is any express
|
481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
482 |
+
(such as an express permission to practice a patent or covenant not to
|
483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
484 |
+
party means to make such an agreement or commitment not to enforce a
|
485 |
+
patent against the party.
|
486 |
+
|
487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
488 |
+
and the Corresponding Source of the work is not available for anyone
|
489 |
+
to copy, free of charge and under the terms of this License, through a
|
490 |
+
publicly available network server or other readily accessible means,
|
491 |
+
then you must either (1) cause the Corresponding Source to be so
|
492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
494 |
+
consistent with the requirements of this License, to extend the patent
|
495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
496 |
+
actual knowledge that, but for the patent license, your conveying the
|
497 |
+
covered work in a country, or your recipient's use of the covered work
|
498 |
+
in a country, would infringe one or more identifiable patents in that
|
499 |
+
country that you have reason to believe are valid.
|
500 |
+
|
501 |
+
If, pursuant to or in connection with a single transaction or
|
502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
503 |
+
covered work, and grant a patent license to some of the parties
|
504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
505 |
+
or convey a specific copy of the covered work, then the patent license
|
506 |
+
you grant is automatically extended to all recipients of the covered
|
507 |
+
work and works based on it.
|
508 |
+
|
509 |
+
A patent license is "discriminatory" if it does not include within
|
510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
512 |
+
specifically granted under this License. You may not convey a covered
|
513 |
+
work if you are a party to an arrangement with a third party that is
|
514 |
+
in the business of distributing software, under which you make payment
|
515 |
+
to the third party based on the extent of your activity of conveying
|
516 |
+
the work, and under which the third party grants, to any of the
|
517 |
+
parties who would receive the covered work from you, a discriminatory
|
518 |
+
patent license (a) in connection with copies of the covered work
|
519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
520 |
+
for and in connection with specific products or compilations that
|
521 |
+
contain the covered work, unless you entered into that arrangement,
|
522 |
+
or that patent license was granted, prior to 28 March 2007.
|
523 |
+
|
524 |
+
Nothing in this License shall be construed as excluding or limiting
|
525 |
+
any implied license or other defenses to infringement that may
|
526 |
+
otherwise be available to you under applicable patent law.
|
527 |
+
|
528 |
+
12. No Surrender of Others' Freedom.
|
529 |
+
|
530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
531 |
+
otherwise) that contradict the conditions of this License, they do not
|
532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
534 |
+
License and any other pertinent obligations, then as a consequence you may
|
535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
536 |
+
to collect a royalty for further conveying from those to whom you convey
|
537 |
+
the Program, the only way you could satisfy both those terms and this
|
538 |
+
License would be to refrain entirely from conveying the Program.
|
539 |
+
|
540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
541 |
+
|
542 |
+
Notwithstanding any other provision of this License, if you modify the
|
543 |
+
Program, your modified version must prominently offer all users
|
544 |
+
interacting with it remotely through a computer network (if your version
|
545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
546 |
+
Source of your version by providing access to the Corresponding Source
|
547 |
+
from a network server at no charge, through some standard or customary
|
548 |
+
means of facilitating copying of software. This Corresponding Source
|
549 |
+
shall include the Corresponding Source for any work covered by version 3
|
550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
551 |
+
following paragraph.
|
552 |
+
|
553 |
+
Notwithstanding any other provision of this License, you have
|
554 |
+
permission to link or combine any covered work with a work licensed
|
555 |
+
under version 3 of the GNU General Public License into a single
|
556 |
+
combined work, and to convey the resulting work. The terms of this
|
557 |
+
License will continue to apply to the part which is the covered work,
|
558 |
+
but the work with which it is combined will remain governed by version
|
559 |
+
3 of the GNU General Public License.
|
560 |
+
|
561 |
+
14. Revised Versions of this License.
|
562 |
+
|
563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
566 |
+
address new problems or concerns.
|
567 |
+
|
568 |
+
Each version is given a distinguishing version number. If the
|
569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
570 |
+
Public License "or any later version" applies to it, you have the
|
571 |
+
option of following the terms and conditions either of that numbered
|
572 |
+
version or of any later version published by the Free Software
|
573 |
+
Foundation. If the Program does not specify a version number of the
|
574 |
+
GNU Affero General Public License, you may choose any version ever published
|
575 |
+
by the Free Software Foundation.
|
576 |
+
|
577 |
+
If the Program specifies that a proxy can decide which future
|
578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
579 |
+
public statement of acceptance of a version permanently authorizes you
|
580 |
+
to choose that version for the Program.
|
581 |
+
|
582 |
+
Later license versions may give you additional or different
|
583 |
+
permissions. However, no additional obligations are imposed on any
|
584 |
+
author or copyright holder as a result of your choosing to follow a
|
585 |
+
later version.
|
586 |
+
|
587 |
+
15. Disclaimer of Warranty.
|
588 |
+
|
589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
597 |
+
|
598 |
+
16. Limitation of Liability.
|
599 |
+
|
600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
608 |
+
SUCH DAMAGES.
|
609 |
+
|
610 |
+
17. Interpretation of Sections 15 and 16.
|
611 |
+
|
612 |
+
If the disclaimer of warranty and limitation of liability provided
|
613 |
+
above cannot be given local legal effect according to their terms,
|
614 |
+
reviewing courts shall apply local law that most closely approximates
|
615 |
+
an absolute waiver of all civil liability in connection with the
|
616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
617 |
+
copy of the Program in return for a fee.
|
618 |
+
|
619 |
+
END OF TERMS AND CONDITIONS
|
620 |
+
|
621 |
+
How to Apply These Terms to Your New Programs
|
622 |
+
|
623 |
+
If you develop a new program, and you want it to be of the greatest
|
624 |
+
possible use to the public, the best way to achieve this is to make it
|
625 |
+
free software which everyone can redistribute and change under these terms.
|
626 |
+
|
627 |
+
To do so, attach the following notices to the program. It is safest
|
628 |
+
to attach them to the start of each source file to most effectively
|
629 |
+
state the exclusion of warranty; and each file should have at least
|
630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
631 |
+
|
632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
633 |
+
Copyright (C) <year> <name of author>
|
634 |
+
|
635 |
+
This program is free software: you can redistribute it and/or modify
|
636 |
+
it under the terms of the GNU Affero General Public License as published
|
637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
638 |
+
(at your option) any later version.
|
639 |
+
|
640 |
+
This program is distributed in the hope that it will be useful,
|
641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
643 |
+
GNU Affero General Public License for more details.
|
644 |
+
|
645 |
+
You should have received a copy of the GNU Affero General Public License
|
646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
647 |
+
|
648 |
+
Also add information on how to contact you by electronic and paper mail.
|
649 |
+
|
650 |
+
If your software can interact with users remotely through a computer
|
651 |
+
network, you should also make sure that it provides a way for users to
|
652 |
+
get its source. For example, if your program is a web application, its
|
653 |
+
interface could display a "Source" link that leads users to an archive
|
654 |
+
of the code. There are many ways you could offer source, and different
|
655 |
+
solutions will be better for different programs; see section 13 for the
|
656 |
+
specific requirements.
|
657 |
+
|
658 |
+
You should also get your employer (if you work as a programmer) or school,
|
659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
661 |
+
<https://www.gnu.org/licenses/>.
|
README.md
CHANGED
@@ -1,12 +1,141 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Give your local LLM the ability to search the web!
|
2 |
+
This project gives local LLMs the ability to search the web by outputting a specific
|
3 |
+
command. Once the command has been found in the model output using a regular expression,
|
4 |
+
[duckduckgo-search](https://pypi.org/project/duckduckgo-search/)
|
5 |
+
is used to search the web and return a number of result pages. Finally, an
|
6 |
+
ensemble of LangChain's [Contextual compression](https://python.langchain.com/docs/modules/data_connection/retrievers/contextual_compression/) and
|
7 |
+
[Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) (Or alternatively, [SPLADE](https://github.com/naver/splade))
|
8 |
+
is used to extract the relevant parts (if any) of each web page in the search results
|
9 |
+
and the results are appended to the model's output.
|
10 |
+
![llm_websearch](https://github.com/mamei16/LLM_Web_search/assets/25900898/f9d2d83c-e3cf-4f69-91c2-e9c3fe0b7d89)
|
11 |
+
|
12 |
+
|
13 |
+
* **[Table of Contents](#table-of-contents)**
|
14 |
+
* [Installation](#installation)
|
15 |
+
* [Usage](#usage)
|
16 |
+
+ [Using a custom regular expression](#using-a-custom-regular-expression)
|
17 |
+
+ [Reading web pages](#reading-web-pages)
|
18 |
+
* [Search backends](#search-backends)
|
19 |
+
+ [DuckDuckGo](#duckduckgo)
|
20 |
+
+ [SearXNG](#searxng)
|
21 |
+
+ [Search parameters](#search-parameters)
|
22 |
+
* [Keyword retrievers](#keyword-retrievers)
|
23 |
+
+ [Okapi BM25](#okapi-bm25)
|
24 |
+
+ [SPLADE](#splade)
|
25 |
+
* [Recommended models](#recommended-models)
|
26 |
+
|
27 |
+
## Installation
|
28 |
+
1. Go to the "Session" tab of the web UI and use "Install or update an extension"
|
29 |
+
to download the latest code for this extension.
|
30 |
+
2. To install the extension's depencies you have two options:
|
31 |
+
1. **The easy way:** Run the appropriate `update_wizard` script inside the text-generation-webui folder
|
32 |
+
and choose `Install/update extensions requirements`. This installs everything using `pip`,
|
33 |
+
which means using the unofficial `faiss-cpu` package. Therefore, it is not guaranteed to
|
34 |
+
work with your system (see [the official disclaimer](https://github.com/facebookresearch/faiss/wiki/Installing-Faiss#why-dont-you-support-installing-via-xxx-)).
|
35 |
+
2. **The safe way:** Manually update the conda environment in which you installed the dependencies of
|
36 |
+
[oobabooga's text-generation-webui](https://github.com/oobabooga/text-generation-webui).
|
37 |
+
Open the subfolder `text-generation-webui/extensions/LLM_Web_search` in a terminal or conda shell.
|
38 |
+
If you used the one-click install method, run the command
|
39 |
+
`conda env update -p <path_to_your_environment> --file environment.yml`,
|
40 |
+
where you need to replace `<path_to_your_environment>` with the path to the
|
41 |
+
`/installer_files/env` subfolder within the text-generation-webui folder.
|
42 |
+
Otherwise, if you made your own environment,
|
43 |
+
use `conda env update -n <name_of_your_environment> --file environment.yml`
|
44 |
+
(NB: Solving the environment can take a while)
|
45 |
+
3. Launch the Web UI with:
|
46 |
+
```python server.py --extension LLM_Web_search```
|
47 |
+
|
48 |
+
If the installation was successful and the extension was loaded, a new tab with the
|
49 |
+
title "LLM Web Search" should be visible in the web UI.
|
50 |
+
|
51 |
+
See https://github.com/oobabooga/text-generation-webui/wiki/07-%E2%80%90-Extensions for more
|
52 |
+
information about extensions.
|
53 |
+
|
54 |
+
## Usage
|
55 |
+
|
56 |
+
Search queries are extracted from the model's output using a regular expression. This is made easier by prompting the model
|
57 |
+
to use a fixed search command (see `system_prompts/` for example prompts).
|
58 |
+
Currently, only a single search query per model chat message is supported.
|
59 |
+
|
60 |
+
An example workflow of using this extension could be:
|
61 |
+
1. Load a model
|
62 |
+
2. Load a matching instruction template
|
63 |
+
3. Head over to the "LLM Web search" tab
|
64 |
+
4. Load a custom system message/prompt
|
65 |
+
5. Ensure that the query part of the command mentioned in the system message
|
66 |
+
can be matched using the current "Search command regex string"
|
67 |
+
(see "Using a custom regular expression" below)
|
68 |
+
6. Pick a hyperparameter generation preset that works well for you.
|
69 |
+
7. Choose "chat-instruct" or "instruct" mode and start chatting
|
70 |
+
|
71 |
+
### Using a custom regular expression
|
72 |
+
The default regular expression is:
|
73 |
+
```regexp
|
74 |
+
Search_web\("(.*)"\)
|
75 |
+
```
|
76 |
+
Where `Search_web` is the search command and everything between the quotation marks
|
77 |
+
inside the parentheses will be used as the search query. Every custom regular expression must use a
|
78 |
+
[capture group](https://www.regular-expressions.info/brackets.html) to extract the search
|
79 |
+
query. I recommend https://www.debuggex.com/ to try out custom regular expressions. If a regex
|
80 |
+
fulfills the requirement above, the search query should be matched by "Group 1" in Debuggex.
|
81 |
+
|
82 |
+
Here is an example of a more flexible, but more complex, regex that works for several
|
83 |
+
different models:
|
84 |
+
```regexp
|
85 |
+
[Ss]earch_web\((?:["'])(.*)(?:["'])\)
|
86 |
+
```
|
87 |
+
### Reading web pages
|
88 |
+
Experimental support exists for extracting the full text content from a webpage. The default regex to use this
|
89 |
+
functionality is:
|
90 |
+
```regexp
|
91 |
+
Open_url\("(.*)"\)
|
92 |
+
```
|
93 |
+
**Note**: The full content of a web page is likely to exceed the maximum context length of your average local LLM.
|
94 |
+
## Search backends
|
95 |
+
|
96 |
+
### DuckDuckGo
|
97 |
+
This is the default web search backend.
|
98 |
+
|
99 |
+
### SearXNG
|
100 |
+
|
101 |
+
Rudimentary support exists for SearXNG. To use a local or remote
|
102 |
+
SearXNG instance instead of DuckDuckGo, simply paste the URL into the
|
103 |
+
"SearXNG URL" text field of the "LLM Web Search" settings tab. The instance must support
|
104 |
+
returning results in JSON format.
|
105 |
+
|
106 |
+
#### Search parameters
|
107 |
+
To modify the categories, engines, languages etc. that should be used for a
|
108 |
+
specific query, it must follow the
|
109 |
+
[SearXNG search syntax](https://docs.searxng.org/user/search-syntax.html). Currently,
|
110 |
+
automatic redirect and Special Queries are not supported.
|
111 |
+
|
112 |
+
|
113 |
+
## Keyword retrievers
|
114 |
+
### Okapi BM25
|
115 |
+
This extension comes out of the box with
|
116 |
+
[Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) enabled, which is widely used and very popuplar
|
117 |
+
for keyword based document retrieval. It runs on the CPU and,
|
118 |
+
for the purpose of this extension, it is fast.
|
119 |
+
### SPLADE
|
120 |
+
If you don't run the extension in "CPU only" mode and have some VRAM to spare,
|
121 |
+
you can also select [SPLADE](https://github.com/naver/splade) in the "Advanced settings" section
|
122 |
+
as an alternative. It has been [shown](https://arxiv.org/pdf/2207.03834.pdf) to outperform BM25 in multiple benchmarks
|
123 |
+
and uses a technique called "query expansion" to add additional contextually relevant words
|
124 |
+
to the original query. However, it is slower than BM25. You can read more about it [here](https://www.pinecone.io/learn/splade/).
|
125 |
+
To use SPLADE, you have to install the additional dependency [qdrant-client](https://github.com/qdrant/qdrant-client).
|
126 |
+
Simply activate the conda environment of the main web UI and run
|
127 |
+
`pip install qdrant-client`.
|
128 |
+
To improve performance, documents are embedded in batches and in parallel. Increasing the
|
129 |
+
"SPLADE batch size" parameter setting improves performance up to a certain point,
|
130 |
+
but VRAM usage ramps up quickly with increasing batch size. A batch size of 8 appears
|
131 |
+
to be a good trade-off, but the default value is 2 to avoid running out of memory on smaller
|
132 |
+
GPUs.
|
133 |
+
|
134 |
+
## Recommended models
|
135 |
+
If you (like me) have ≤ 12 GB VRAM, I recommend using
|
136 |
+
[Llama-3-8B-instruct](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct).
|
137 |
+
You can find a matching instruction template in the extension's `instruction_templates`
|
138 |
+
folder. Simply copy it to the main web UI's `instruction-templates` folder.
|
139 |
+
**Note:** Several existing GGUF versions have a stop token issue, which can be solved by [editing the file's
|
140 |
+
metadata](https://www.reddit.com/r/LocalLLaMA/comments/1c7dkxh/tutorial_how_to_make_llama3instruct_ggufs_less/). A GGUF version where this issue has already been fixed can be found
|
141 |
+
[here](https://huggingface.co/AI-Engine/Meta-Llama-3-8B-Instruct-GGUF/blob/main/Meta-Llama-3-8B-Instruct.Q5_k_m_with_temp_stop_token_fix.gguf).
|
environment.yml
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
channels:
|
2 |
+
- defaults
|
3 |
+
- conda-forge
|
4 |
+
- pytorch
|
5 |
+
dependencies:
|
6 |
+
- pip
|
7 |
+
- faiss-cpu=1.8.0
|
8 |
+
- pip:
|
9 |
+
- duckduckgo_search==6.1.0
|
10 |
+
- beautifulsoup4==4.12.3
|
11 |
+
- langchain==0.2.1
|
12 |
+
- langchain-community==0.2.1
|
13 |
+
- unstructured==0.14.2
|
14 |
+
- rank_bm25==0.2.2
|
15 |
+
- sentence-transformers==2.7.0
|
instruction_templates/Llama-3.yaml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
instruction_template: |-
|
2 |
+
{%- set ns = namespace(found=false) -%}
|
3 |
+
{%- for message in messages -%}
|
4 |
+
{%- if message['role'] == 'system' -%}
|
5 |
+
{%- set ns.found = true -%}
|
6 |
+
{%- endif -%}
|
7 |
+
{%- endfor -%}
|
8 |
+
{%- for message in messages %}
|
9 |
+
{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' %}
|
10 |
+
{% if loop.index0 == 0 %}
|
11 |
+
{% set content = '<|begin_of_text|>' + content %}
|
12 |
+
{% endif %}
|
13 |
+
{{- content -}}
|
14 |
+
{%- endfor -%}
|
15 |
+
{%- if add_generation_prompt -%}
|
16 |
+
{{- '<|start_header_id|>' + 'assistant' + '<|end_header_id|>\n\n' -}}
|
17 |
+
{%- endif -%}
|
instruction_templates/OpenChat-Correct.yaml
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
instruction_template: |-
|
2 |
+
{%- set ns = namespace(found=false) -%}
|
3 |
+
{%- for message in messages -%}
|
4 |
+
{%- if message['role'] == 'system' -%}
|
5 |
+
{%- set ns.found = true -%}
|
6 |
+
{%- endif -%}
|
7 |
+
{%- endfor -%}
|
8 |
+
{%- if not ns.found -%}
|
9 |
+
{{- '' + '' + '' -}}
|
10 |
+
{%- endif %}
|
11 |
+
{%- for message in messages %}
|
12 |
+
{%- if message['role'] == 'system' -%}
|
13 |
+
{{- '' + message['content'] + '' -}}
|
14 |
+
{%- else -%}
|
15 |
+
{%- if message['role'] == 'user' -%}
|
16 |
+
{{-'GPT4 Correct User: ' + message['content'] + '<|end_of_turn|>'-}}
|
17 |
+
{%- else -%}
|
18 |
+
{{-'GPT4 Correct Assistant: ' + message['content'] + '<|end_of_turn|>' -}}
|
19 |
+
{%- endif -%}
|
20 |
+
{%- endif -%}
|
21 |
+
{%- endfor -%}
|
22 |
+
{%- if add_generation_prompt -%}
|
23 |
+
{{-'GPT4 Correct Assistant:'-}}
|
24 |
+
{%- endif -%}
|
instruction_templates/SOLAR-10.7B.yaml
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
instruction_template: |-
|
2 |
+
{%- set ns = namespace(found=false) -%}
|
3 |
+
{%- for message in messages -%}
|
4 |
+
{%- if message['role'] == 'system' -%}
|
5 |
+
{%- set ns.found = true -%}
|
6 |
+
{%- endif -%}
|
7 |
+
{%- endfor -%}
|
8 |
+
{%- if not ns.found -%}
|
9 |
+
{{- '' + '' + '' -}}
|
10 |
+
{%- endif %}
|
11 |
+
{%- for message in messages %}
|
12 |
+
{%- if message['role'] == 'system' -%}
|
13 |
+
{{- '' + message['content'] + '' -}}
|
14 |
+
{%- else -%}
|
15 |
+
{%- if message['role'] == 'user' -%}
|
16 |
+
{{-'### User: ' + message['content'] + '\n\n'-}}
|
17 |
+
{%- else -%}
|
18 |
+
{{-'### Assistant: ' + message['content'] + '\n\n' -}}
|
19 |
+
{%- endif -%}
|
20 |
+
{%- endif -%}
|
21 |
+
{%- endfor -%}
|
22 |
+
{%- if add_generation_prompt -%}
|
23 |
+
{{-'### Assistant:'-}}
|
24 |
+
{%- endif -%}
|
langchain_websearch.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import asyncio
|
3 |
+
import warnings
|
4 |
+
import logging
|
5 |
+
|
6 |
+
import aiohttp
|
7 |
+
import requests
|
8 |
+
from bs4 import BeautifulSoup
|
9 |
+
from langchain.retrievers.document_compressors import DocumentCompressorPipeline
|
10 |
+
from langchain.retrievers.ensemble import EnsembleRetriever
|
11 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
12 |
+
from langchain.retrievers.document_compressors.embeddings_filter import EmbeddingsFilter
|
13 |
+
from langchain.retrievers import ContextualCompressionRetriever
|
14 |
+
from langchain.schema import Document
|
15 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
16 |
+
from langchain_community.vectorstores import FAISS
|
17 |
+
from langchain_community.document_transformers import EmbeddingsRedundantFilter
|
18 |
+
from langchain_community.retrievers import BM25Retriever
|
19 |
+
from transformers import AutoTokenizer, AutoModelForMaskedLM
|
20 |
+
import optimum.bettertransformer.transformation
|
21 |
+
try:
|
22 |
+
from qdrant_client import QdrantClient, models
|
23 |
+
except ImportError:
|
24 |
+
qrant_client = None
|
25 |
+
|
26 |
+
from .qdrant_retriever import MyQdrantSparseVectorRetriever
|
27 |
+
from .semantic_chunker import BoundedSemanticChunker
|
28 |
+
|
29 |
+
|
30 |
+
class LangchainCompressor:
|
31 |
+
|
32 |
+
def __init__(self, device="cuda", num_results: int = 5, similarity_threshold: float = 0.5, chunk_size: int = 500,
|
33 |
+
ensemble_weighting: float = 0.5, splade_batch_size: int = 2, keyword_retriever: str = "bm25",
|
34 |
+
model_cache_dir: str = None, chunking_method: str = "character-based",
|
35 |
+
chunker_breakpoint_threshold_amount: int = 10):
|
36 |
+
self.device = device
|
37 |
+
self.embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2", model_kwargs={"device": device},
|
38 |
+
cache_folder=model_cache_dir)
|
39 |
+
if keyword_retriever == "splade":
|
40 |
+
if "QdrantClient" not in globals():
|
41 |
+
raise ImportError("Package qrant_client is missing. Please install it using 'pip install qdrant-client")
|
42 |
+
self.splade_doc_tokenizer = AutoTokenizer.from_pretrained("naver/efficient-splade-VI-BT-large-doc",
|
43 |
+
cache_dir=model_cache_dir)
|
44 |
+
self.splade_doc_model = AutoModelForMaskedLM.from_pretrained("naver/efficient-splade-VI-BT-large-doc",
|
45 |
+
cache_dir=model_cache_dir).to(self.device)
|
46 |
+
self.splade_query_tokenizer = AutoTokenizer.from_pretrained("naver/efficient-splade-VI-BT-large-query",
|
47 |
+
cache_dir=model_cache_dir)
|
48 |
+
self.splade_query_model = AutoModelForMaskedLM.from_pretrained("naver/efficient-splade-VI-BT-large-query",
|
49 |
+
cache_dir=model_cache_dir).to(self.device)
|
50 |
+
optimum_logger = optimum.bettertransformer.transformation.logger
|
51 |
+
original_log_level = optimum_logger.level
|
52 |
+
# Set the level to 'ERROR' to ignore "The BetterTransformer padding during training warning"
|
53 |
+
optimum_logger.setLevel(logging.ERROR)
|
54 |
+
self.splade_doc_model.to_bettertransformer()
|
55 |
+
self.splade_query_model.to_bettertransformer()
|
56 |
+
optimum_logger.setLevel(original_log_level)
|
57 |
+
self.splade_batch_size = splade_batch_size
|
58 |
+
|
59 |
+
self.spaces_regex = re.compile(r" {3,}")
|
60 |
+
self.num_results = num_results
|
61 |
+
self.similarity_threshold = similarity_threshold
|
62 |
+
self.chunking_method = chunking_method
|
63 |
+
self.chunk_size = chunk_size
|
64 |
+
self.chunker_breakpoint_threshold_amount = chunker_breakpoint_threshold_amount
|
65 |
+
self.ensemble_weighting = ensemble_weighting
|
66 |
+
self.keyword_retriever = keyword_retriever
|
67 |
+
|
68 |
+
def preprocess_text(self, text: str) -> str:
|
69 |
+
text = text.replace("\n", " \n")
|
70 |
+
text = self.spaces_regex.sub(" ", text)
|
71 |
+
text = text.strip()
|
72 |
+
return text
|
73 |
+
|
74 |
+
def retrieve_documents(self, query: str, url_list: list[str]) -> list[Document]:
|
75 |
+
yield "Downloading webpages..."
|
76 |
+
html_url_tupls = zip(asyncio.run(async_fetch_urls(url_list)), url_list)
|
77 |
+
html_url_tupls = [(content, url) for content, url in html_url_tupls if content is not None]
|
78 |
+
if not html_url_tupls:
|
79 |
+
return []
|
80 |
+
|
81 |
+
documents = [html_to_plaintext_doc(html, url) for html, url in html_url_tupls]
|
82 |
+
if self.chunking_method == "semantic":
|
83 |
+
text_splitter = BoundedSemanticChunker(self.embeddings, breakpoint_threshold_type="percentile",
|
84 |
+
breakpoint_threshold_amount=self.chunker_breakpoint_threshold_amount,
|
85 |
+
max_chunk_size=self.chunk_size)
|
86 |
+
else:
|
87 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=self.chunk_size, chunk_overlap=10,
|
88 |
+
separators=["\n\n", "\n", ".", ", ", " ", ""])
|
89 |
+
yield "Chunking page texts..."
|
90 |
+
split_docs = text_splitter.split_documents(documents)
|
91 |
+
yield "Retrieving relevant results..."
|
92 |
+
# filtered_docs = pipeline_compressor.compress_documents(documents, query)
|
93 |
+
faiss_retriever = FAISS.from_documents(split_docs, self.embeddings).as_retriever(
|
94 |
+
search_kwargs={"k": self.num_results}
|
95 |
+
)
|
96 |
+
|
97 |
+
# The sparse keyword retriever is good at finding relevant documents based on keywords,
|
98 |
+
# while the dense retriever is good at finding relevant documents based on semantic similarity.
|
99 |
+
if self.keyword_retriever == "bm25":
|
100 |
+
keyword_retriever = BM25Retriever.from_documents(split_docs, preprocess_func=self.preprocess_text)
|
101 |
+
keyword_retriever.k = self.num_results
|
102 |
+
elif self.keyword_retriever == "splade":
|
103 |
+
client = QdrantClient(location=":memory:")
|
104 |
+
collection_name = "sparse_collection"
|
105 |
+
vector_name = "sparse_vector"
|
106 |
+
|
107 |
+
client.create_collection(
|
108 |
+
collection_name,
|
109 |
+
vectors_config={},
|
110 |
+
sparse_vectors_config={
|
111 |
+
vector_name: models.SparseVectorParams(
|
112 |
+
index=models.SparseIndexParams(
|
113 |
+
on_disk=False,
|
114 |
+
)
|
115 |
+
)
|
116 |
+
},
|
117 |
+
)
|
118 |
+
|
119 |
+
keyword_retriever = MyQdrantSparseVectorRetriever(
|
120 |
+
splade_doc_tokenizer=self.splade_doc_tokenizer,
|
121 |
+
splade_doc_model=self.splade_doc_model,
|
122 |
+
splade_query_tokenizer=self.splade_query_tokenizer,
|
123 |
+
splade_query_model=self.splade_query_model,
|
124 |
+
device=self.device,
|
125 |
+
client=client,
|
126 |
+
collection_name=collection_name,
|
127 |
+
sparse_vector_name=vector_name,
|
128 |
+
sparse_encoder=None,
|
129 |
+
batch_size=self.splade_batch_size,
|
130 |
+
k=self.num_results
|
131 |
+
)
|
132 |
+
keyword_retriever.add_documents(split_docs)
|
133 |
+
else:
|
134 |
+
raise ValueError("self.keyword_retriever must be one of ('bm25', 'splade')")
|
135 |
+
|
136 |
+
redundant_filter = EmbeddingsRedundantFilter(embeddings=self.embeddings)
|
137 |
+
embeddings_filter = EmbeddingsFilter(embeddings=self.embeddings, k=None,
|
138 |
+
similarity_threshold=self.similarity_threshold)
|
139 |
+
pipeline_compressor = DocumentCompressorPipeline(
|
140 |
+
transformers=[redundant_filter, embeddings_filter]
|
141 |
+
)
|
142 |
+
|
143 |
+
compression_retriever = ContextualCompressionRetriever(base_compressor=pipeline_compressor,
|
144 |
+
base_retriever=faiss_retriever)
|
145 |
+
|
146 |
+
ensemble_retriever = EnsembleRetriever(
|
147 |
+
retrievers=[compression_retriever, keyword_retriever],
|
148 |
+
weights=[self.ensemble_weighting, 1 - self.ensemble_weighting]
|
149 |
+
)
|
150 |
+
compressed_docs = ensemble_retriever.invoke(query)
|
151 |
+
|
152 |
+
# Ensemble may return more than "num_results" results, so cut off excess ones
|
153 |
+
return compressed_docs[:self.num_results]
|
154 |
+
|
155 |
+
|
156 |
+
async def async_download_html(url, headers):
|
157 |
+
async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(10)) as session:
|
158 |
+
try:
|
159 |
+
resp = await session.get(url)
|
160 |
+
return await resp.text()
|
161 |
+
except UnicodeDecodeError:
|
162 |
+
print(
|
163 |
+
f"LLM_Web_search | {url} generated an exception: Expected content type text/html. Got {resp.headers['Content-Type']}.")
|
164 |
+
except TimeoutError as exc:
|
165 |
+
print('LLM_Web_search | %r did not load in time' % url)
|
166 |
+
except Exception as exc:
|
167 |
+
print('LLM_Web_search | %r generated an exception: %s' % (url, exc))
|
168 |
+
return None
|
169 |
+
|
170 |
+
|
171 |
+
async def async_fetch_urls(urls):
|
172 |
+
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
|
173 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
174 |
+
"Accept-Language": "en-US,en;q=0.5"}
|
175 |
+
webpages = await asyncio.gather(*[(async_download_html(url, headers)) for url in urls])
|
176 |
+
return webpages
|
177 |
+
|
178 |
+
|
179 |
+
def docs_to_pretty_str(docs) -> str:
|
180 |
+
ret_str = ""
|
181 |
+
for i, doc in enumerate(docs):
|
182 |
+
ret_str += f"Result {i+1}:\n"
|
183 |
+
ret_str += f"{doc.page_content}\n"
|
184 |
+
ret_str += f"Source URL: {doc.metadata['source']}\n\n"
|
185 |
+
return ret_str
|
186 |
+
|
187 |
+
|
188 |
+
def download_html(url: str) -> bytes:
|
189 |
+
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
|
190 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
191 |
+
"Accept-Language": "en-US,en;q=0.5"}
|
192 |
+
|
193 |
+
response = requests.get(url, headers=headers, verify=True, timeout=8)
|
194 |
+
response.raise_for_status()
|
195 |
+
|
196 |
+
content_type = response.headers.get("Content-Type", "")
|
197 |
+
if not content_type.startswith("text/html"):
|
198 |
+
raise ValueError(f"Expected content type text/html. Got {content_type}.")
|
199 |
+
return response.content
|
200 |
+
|
201 |
+
|
202 |
+
def html_to_plaintext_doc(html_text: str or bytes, url: str) -> Document:
|
203 |
+
with warnings.catch_warnings(action="ignore"):
|
204 |
+
soup = BeautifulSoup(html_text, features="lxml")
|
205 |
+
for script in soup(["script", "style"]):
|
206 |
+
script.extract()
|
207 |
+
|
208 |
+
strings = '\n'.join([s.strip() for s in soup.stripped_strings])
|
209 |
+
webpage_document = Document(page_content=strings, metadata={"source": url})
|
210 |
+
return webpage_document
|
llm_web_search.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import urllib
|
2 |
+
|
3 |
+
import requests
|
4 |
+
from requests.exceptions import JSONDecodeError
|
5 |
+
from duckduckgo_search import DDGS
|
6 |
+
from bs4 import BeautifulSoup
|
7 |
+
from langchain.schema import Document
|
8 |
+
|
9 |
+
from .langchain_websearch import docs_to_pretty_str, LangchainCompressor
|
10 |
+
|
11 |
+
|
12 |
+
class Generator:
|
13 |
+
"""Allows a generator method to return a final value after finishing
|
14 |
+
the generation. Credit: https://stackoverflow.com/a/34073559"""
|
15 |
+
def __init__(self, gen):
|
16 |
+
self.gen = gen
|
17 |
+
|
18 |
+
def __iter__(self):
|
19 |
+
self.value = yield from self.gen
|
20 |
+
return self.value
|
21 |
+
|
22 |
+
|
23 |
+
def dict_list_to_pretty_str(data: list[dict]) -> str:
|
24 |
+
ret_str = ""
|
25 |
+
if isinstance(data, dict):
|
26 |
+
data = [data]
|
27 |
+
if isinstance(data, list):
|
28 |
+
for i, d in enumerate(data):
|
29 |
+
ret_str += f"Result {i+1}\n"
|
30 |
+
ret_str += f"Title: {d['title']}\n"
|
31 |
+
ret_str += f"{d['body']}\n"
|
32 |
+
ret_str += f"Source URL: {d['href']}\n"
|
33 |
+
return ret_str
|
34 |
+
else:
|
35 |
+
raise ValueError("Input must be dict or list[dict]")
|
36 |
+
|
37 |
+
|
38 |
+
def search_duckduckgo(query: str, max_results: int, instant_answers: bool = True,
|
39 |
+
regular_search_queries: bool = True, get_website_content: bool = False) -> list[dict]:
|
40 |
+
query = query.strip("\"'")
|
41 |
+
with DDGS() as ddgs:
|
42 |
+
if instant_answers:
|
43 |
+
answer_list = ddgs.answers(query)
|
44 |
+
else:
|
45 |
+
answer_list = None
|
46 |
+
if answer_list:
|
47 |
+
answer_dict = answer_list[0]
|
48 |
+
answer_dict["title"] = query
|
49 |
+
answer_dict["body"] = answer_dict["text"]
|
50 |
+
answer_dict["href"] = answer_dict["url"]
|
51 |
+
answer_dict.pop('icon', None)
|
52 |
+
answer_dict.pop('topic', None)
|
53 |
+
answer_dict.pop('text', None)
|
54 |
+
answer_dict.pop('url', None)
|
55 |
+
return [answer_dict]
|
56 |
+
elif regular_search_queries:
|
57 |
+
results = []
|
58 |
+
for result in ddgs.text(query, region='wt-wt', safesearch='moderate',
|
59 |
+
timelimit=None, max_results=max_results):
|
60 |
+
if get_website_content:
|
61 |
+
result["body"] = get_webpage_content(result["href"])
|
62 |
+
results.append(result)
|
63 |
+
return results
|
64 |
+
else:
|
65 |
+
raise ValueError("One of ('instant_answers', 'regular_search_queries') must be True")
|
66 |
+
|
67 |
+
|
68 |
+
def langchain_search_duckduckgo(query: str, langchain_compressor: LangchainCompressor, max_results: int,
|
69 |
+
instant_answers: bool):
|
70 |
+
documents = []
|
71 |
+
query = query.strip("\"'")
|
72 |
+
yield f'Getting results from DuckDuckGo...'
|
73 |
+
with DDGS() as ddgs:
|
74 |
+
if instant_answers:
|
75 |
+
answer_list = ddgs.answers(query)
|
76 |
+
if answer_list:
|
77 |
+
if max_results > 1:
|
78 |
+
max_results -= 1 # We already have 1 result now
|
79 |
+
answer_dict = answer_list[0]
|
80 |
+
instant_answer_doc = Document(page_content=answer_dict["text"],
|
81 |
+
metadata={"source": answer_dict["url"]})
|
82 |
+
documents.append(instant_answer_doc)
|
83 |
+
|
84 |
+
results = []
|
85 |
+
result_urls = []
|
86 |
+
for result in ddgs.text(query, region='wt-wt', safesearch='moderate', timelimit=None,
|
87 |
+
max_results=langchain_compressor.num_results):
|
88 |
+
results.append(result)
|
89 |
+
result_urls.append(result["href"])
|
90 |
+
retrieval_gen = Generator(langchain_compressor.retrieve_documents(query, result_urls))
|
91 |
+
for status_message in retrieval_gen:
|
92 |
+
yield status_message
|
93 |
+
documents.extend(retrieval_gen.value)
|
94 |
+
if not documents: # Fall back to old simple search rather than returning nothing
|
95 |
+
print("LLM_Web_search | Could not find any page content "
|
96 |
+
"similar enough to be extracted, using basic search fallback...")
|
97 |
+
return dict_list_to_pretty_str(results[:max_results])
|
98 |
+
return docs_to_pretty_str(documents[:max_results])
|
99 |
+
|
100 |
+
|
101 |
+
def langchain_search_searxng(query: str, url: str, langchain_compressor: LangchainCompressor, max_results: int):
|
102 |
+
yield f'Getting results from Searxng...'
|
103 |
+
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
|
104 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
105 |
+
"Accept-Language": "en-US,en;q=0.5"}
|
106 |
+
result_urls = []
|
107 |
+
request_str = f"/search?q={urllib.parse.quote(query)}&format=json&pageno="
|
108 |
+
pageno = 1
|
109 |
+
while len(result_urls) < langchain_compressor.num_results:
|
110 |
+
response = requests.get(url + request_str + str(pageno), headers=headers)
|
111 |
+
if not result_urls: # no results to lose by raising an exception here
|
112 |
+
response.raise_for_status()
|
113 |
+
try:
|
114 |
+
response_dict = response.json()
|
115 |
+
except JSONDecodeError:
|
116 |
+
raise ValueError("JSONDecodeError: Please ensure that the SearXNG instance can return data in JSON format")
|
117 |
+
result_dicts = response_dict["results"]
|
118 |
+
if not result_dicts:
|
119 |
+
break
|
120 |
+
for result in result_dicts:
|
121 |
+
result_urls.append(result["url"])
|
122 |
+
pageno += 1
|
123 |
+
retrieval_gen = Generator(langchain_compressor.retrieve_documents(query, result_urls))
|
124 |
+
for status_message in retrieval_gen:
|
125 |
+
yield status_message
|
126 |
+
documents = retrieval_gen.value
|
127 |
+
return docs_to_pretty_str(documents[:max_results])
|
128 |
+
|
129 |
+
|
130 |
+
def get_webpage_content(url: str) -> str:
|
131 |
+
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
|
132 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
133 |
+
"Accept-Language": "en-US,en;q=0.5"}
|
134 |
+
if not url.startswith("https://"):
|
135 |
+
try:
|
136 |
+
response = requests.get(f"https://{url}", headers=headers)
|
137 |
+
except:
|
138 |
+
response = requests.get(url, headers=headers)
|
139 |
+
else:
|
140 |
+
response = requests.get(url, headers=headers)
|
141 |
+
|
142 |
+
soup = BeautifulSoup(response.content, features="lxml")
|
143 |
+
for script in soup(["script", "style"]):
|
144 |
+
script.extract()
|
145 |
+
|
146 |
+
strings = soup.stripped_strings
|
147 |
+
return '\n'.join([s.strip() for s in strings])
|
qdrant_retriever.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import (
|
2 |
+
Any,
|
3 |
+
Iterable,
|
4 |
+
List,
|
5 |
+
Optional,
|
6 |
+
Tuple,
|
7 |
+
cast,
|
8 |
+
Generator
|
9 |
+
)
|
10 |
+
|
11 |
+
import torch
|
12 |
+
from langchain_community.retrievers import QdrantSparseVectorRetriever
|
13 |
+
from langchain_community.vectorstores.qdrant import Qdrant
|
14 |
+
from langchain_core.pydantic_v1 import Field
|
15 |
+
from langchain_core.callbacks import CallbackManagerForRetrieverRun
|
16 |
+
from langchain.schema import Document
|
17 |
+
try:
|
18 |
+
from qdrant_client import QdrantClient, models
|
19 |
+
except ImportError:
|
20 |
+
pass
|
21 |
+
|
22 |
+
|
23 |
+
def batchify(_list: List, batch_size: int) -> Generator[List, None, None]:
|
24 |
+
for i in range(0, len(_list), batch_size):
|
25 |
+
yield _list[i:i + batch_size]
|
26 |
+
|
27 |
+
|
28 |
+
class MyQdrantSparseVectorRetriever(QdrantSparseVectorRetriever):
|
29 |
+
splade_doc_tokenizer: Any = Field(repr=False)
|
30 |
+
splade_doc_model: Any = Field(repr=False)
|
31 |
+
splade_query_tokenizer: Any = Field(repr=False)
|
32 |
+
splade_query_model: Any = Field(repr=False)
|
33 |
+
device: Any = Field(repr=False)
|
34 |
+
batch_size: int = Field(repr=False)
|
35 |
+
sparse_encoder: Any or None = Field(repr=False)
|
36 |
+
|
37 |
+
class Config:
|
38 |
+
"""Configuration for this pydantic object."""
|
39 |
+
arbitrary_types_allowed = True
|
40 |
+
|
41 |
+
def compute_document_vectors(self, texts: List[str], batch_size: int) -> Tuple[List[List[int]], List[List[float]]]:
|
42 |
+
indices = []
|
43 |
+
values = []
|
44 |
+
for text_batch in batchify(texts, batch_size):
|
45 |
+
with torch.no_grad():
|
46 |
+
tokens = self.splade_doc_tokenizer(text_batch, truncation=True, padding=True,
|
47 |
+
return_tensors="pt").to(self.device)
|
48 |
+
output = self.splade_doc_model(**tokens)
|
49 |
+
logits, attention_mask = output.logits, tokens.attention_mask
|
50 |
+
relu_log = torch.log(1 + torch.relu(logits))
|
51 |
+
weighted_log = relu_log * attention_mask.unsqueeze(-1)
|
52 |
+
tvecs, _ = torch.max(weighted_log, dim=1)
|
53 |
+
|
54 |
+
# extract all non-zero values and their indices from the sparse vectors
|
55 |
+
for batch in tvecs.cpu():
|
56 |
+
indices.append(batch.nonzero(as_tuple=True)[0].numpy())
|
57 |
+
values.append(batch[indices[-1]].numpy())
|
58 |
+
|
59 |
+
return indices, values
|
60 |
+
|
61 |
+
def compute_query_vector(self, text: str):
|
62 |
+
"""
|
63 |
+
Computes a vector from logits and attention mask using ReLU, log, and max operations.
|
64 |
+
"""
|
65 |
+
with torch.no_grad():
|
66 |
+
tokens = self.splade_query_tokenizer(text, return_tensors="pt").to(self.device)
|
67 |
+
output = self.splade_query_model(**tokens)
|
68 |
+
logits, attention_mask = output.logits, tokens.attention_mask
|
69 |
+
relu_log = torch.log(1 + torch.relu(logits))
|
70 |
+
weighted_log = relu_log * attention_mask.unsqueeze(-1)
|
71 |
+
max_val, _ = torch.max(weighted_log, dim=1)
|
72 |
+
query_vec = max_val.squeeze().cpu()
|
73 |
+
|
74 |
+
query_indices = query_vec.nonzero().numpy().flatten()
|
75 |
+
query_values = query_vec.detach().numpy()[query_indices]
|
76 |
+
|
77 |
+
return query_indices, query_values
|
78 |
+
|
79 |
+
def add_texts(
|
80 |
+
self,
|
81 |
+
texts: Iterable[str],
|
82 |
+
metadatas: Optional[List[dict]] = None,
|
83 |
+
**kwargs: Any,
|
84 |
+
):
|
85 |
+
client = cast(QdrantClient, self.client)
|
86 |
+
|
87 |
+
indices, values = self.compute_document_vectors(texts, self.batch_size)
|
88 |
+
|
89 |
+
points = [
|
90 |
+
models.PointStruct(
|
91 |
+
id=i + 1,
|
92 |
+
vector={
|
93 |
+
self.sparse_vector_name: models.SparseVector(
|
94 |
+
indices=indices[i],
|
95 |
+
values=values[i],
|
96 |
+
)
|
97 |
+
},
|
98 |
+
payload={
|
99 |
+
self.content_payload_key: texts[i],
|
100 |
+
self.metadata_payload_key: metadatas[i] if metadatas else None,
|
101 |
+
},
|
102 |
+
)
|
103 |
+
for i in range(len(texts))
|
104 |
+
]
|
105 |
+
client.upsert(self.collection_name, points=points, **kwargs)
|
106 |
+
if self.device == "cuda":
|
107 |
+
torch.cuda.empty_cache()
|
108 |
+
|
109 |
+
def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun) -> List[Document]:
|
110 |
+
client = cast(QdrantClient, self.client)
|
111 |
+
query_indices, query_values = self.compute_query_vector(query)
|
112 |
+
|
113 |
+
results = client.search(
|
114 |
+
self.collection_name,
|
115 |
+
query_filter=self.filter,
|
116 |
+
query_vector=models.NamedSparseVector(
|
117 |
+
name=self.sparse_vector_name,
|
118 |
+
vector=models.SparseVector(
|
119 |
+
indices=query_indices,
|
120 |
+
values=query_values,
|
121 |
+
),
|
122 |
+
),
|
123 |
+
limit=self.k,
|
124 |
+
with_vectors=False,
|
125 |
+
**self.search_options,
|
126 |
+
)
|
127 |
+
|
128 |
+
return [
|
129 |
+
Qdrant._document_from_scored_point(
|
130 |
+
point,
|
131 |
+
self.collection_name,
|
132 |
+
self.content_payload_key,
|
133 |
+
self.metadata_payload_key,
|
134 |
+
)
|
135 |
+
for point in results
|
136 |
+
]
|
requirements.txt
CHANGED
@@ -1 +1,8 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
faiss-cpu==1.8.0
|
2 |
+
duckduckgo_search==6.1.0
|
3 |
+
beautifulsoup4==4.12.3
|
4 |
+
langchain==0.2.1
|
5 |
+
langchain-community==0.2.1
|
6 |
+
unstructured==0.14.2
|
7 |
+
rank_bm25==0.2.2
|
8 |
+
sentence-transformers==2.7.0
|
script.js
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
var generate_button = document.getElementById("Generate");
|
2 |
+
generate_button.insertAdjacentHTML("afterend", '<div style="position:relative;"> <label style="color:#8b8b8b;white-space:nowrap;position:absolute;top:8px;right:0px;"><input type="checkbox" id="force-search" name="accept"> Force web search </label> </div>');
|
3 |
+
generate_button.style.setProperty("position", "relative");
|
4 |
+
generate_button.style.setProperty("top", "15px");
|
5 |
+
generate_button.style.setProperty("margin-left", "-10px");
|
6 |
+
|
7 |
+
var stop_button = document.getElementById("stop");
|
8 |
+
stop_button.style.setProperty("position", "relative");
|
9 |
+
stop_button.style.setProperty("top", "15px");
|
10 |
+
stop_button.style.setProperty("margin-left", "-10px");
|
11 |
+
|
12 |
+
var checkbox = document.getElementById("force-search");
|
13 |
+
var gradio_force_search_checkbox = document.getElementById("Force-search-checkbox").children[1].firstChild;
|
14 |
+
checkbox.addEventListener('change', function() {
|
15 |
+
if (this.checked) {
|
16 |
+
if (!gradio_force_search_checkbox.checked) {
|
17 |
+
gradio_force_search_checkbox.click();
|
18 |
+
}
|
19 |
+
} else {
|
20 |
+
if (gradio_force_search_checkbox.checked) {
|
21 |
+
gradio_force_search_checkbox.click();
|
22 |
+
}
|
23 |
+
}
|
24 |
+
});
|
script.py
ADDED
@@ -0,0 +1,567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import re
|
3 |
+
import json
|
4 |
+
import os
|
5 |
+
from datetime import datetime
|
6 |
+
|
7 |
+
import gradio as gr
|
8 |
+
import torch
|
9 |
+
|
10 |
+
import modules.shared as shared
|
11 |
+
from modules import chat, ui as ui_module
|
12 |
+
from modules.utils import gradio
|
13 |
+
from modules.text_generation import generate_reply_HF, generate_reply_custom
|
14 |
+
from .llm_web_search import get_webpage_content, langchain_search_duckduckgo, langchain_search_searxng, Generator
|
15 |
+
from .langchain_websearch import LangchainCompressor
|
16 |
+
|
17 |
+
|
18 |
+
params = {
|
19 |
+
"display_name": "LLM Web Search",
|
20 |
+
"is_tab": True,
|
21 |
+
"enable": True,
|
22 |
+
"search results per query": 5,
|
23 |
+
"langchain similarity score threshold": 0.5,
|
24 |
+
"instant answers": True,
|
25 |
+
"regular search results": True,
|
26 |
+
"search command regex": "",
|
27 |
+
"default search command regex": r"Search_web\(\"(.*)\"\)",
|
28 |
+
"open url command regex": "",
|
29 |
+
"default open url command regex": r"Open_url\(\"(.*)\"\)",
|
30 |
+
"display search results in chat": True,
|
31 |
+
"display extracted URL content in chat": True,
|
32 |
+
"searxng url": "",
|
33 |
+
"cpu only": True,
|
34 |
+
"chunk size": 500,
|
35 |
+
"duckduckgo results per query": 10,
|
36 |
+
"append current datetime": False,
|
37 |
+
"default system prompt filename": None,
|
38 |
+
"force search prefix": "Search_web",
|
39 |
+
"ensemble weighting": 0.5,
|
40 |
+
"keyword retriever": "bm25",
|
41 |
+
"splade batch size": 2,
|
42 |
+
"chunking method": "character-based",
|
43 |
+
"chunker breakpoint_threshold_amount": 30
|
44 |
+
}
|
45 |
+
custom_system_message_filename = None
|
46 |
+
extension_path = os.path.dirname(os.path.abspath(__file__))
|
47 |
+
langchain_compressor = None
|
48 |
+
update_history = None
|
49 |
+
force_search = False
|
50 |
+
|
51 |
+
|
52 |
+
def setup():
|
53 |
+
"""
|
54 |
+
Is executed when the extension gets imported.
|
55 |
+
:return:
|
56 |
+
"""
|
57 |
+
global params
|
58 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "true"
|
59 |
+
os.environ["QDRANT__TELEMETRY_DISABLED"] = "true"
|
60 |
+
|
61 |
+
try:
|
62 |
+
with open(os.path.join(extension_path, "settings.json"), "r") as f:
|
63 |
+
saved_params = json.load(f)
|
64 |
+
params.update(saved_params)
|
65 |
+
save_settings() # add keys of newly added feature to settings.json
|
66 |
+
except FileNotFoundError:
|
67 |
+
save_settings()
|
68 |
+
|
69 |
+
if not os.path.exists(os.path.join(extension_path, "system_prompts")):
|
70 |
+
os.makedirs(os.path.join(extension_path, "system_prompts"))
|
71 |
+
|
72 |
+
toggle_extension(params["enable"])
|
73 |
+
|
74 |
+
|
75 |
+
def save_settings():
|
76 |
+
global params
|
77 |
+
with open(os.path.join(extension_path, "settings.json"), "w") as f:
|
78 |
+
json.dump(params, f, indent=4)
|
79 |
+
current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
80 |
+
return gr.HTML(f'<span style="color:lawngreen"> Settings were saved at {current_datetime}</span>',
|
81 |
+
visible=True)
|
82 |
+
|
83 |
+
|
84 |
+
def toggle_extension(_enable: bool):
|
85 |
+
global langchain_compressor, custom_system_message_filename
|
86 |
+
if _enable:
|
87 |
+
langchain_compressor = LangchainCompressor(device="cpu" if params["cpu only"] else "cuda",
|
88 |
+
keyword_retriever=params["keyword retriever"],
|
89 |
+
model_cache_dir=os.path.join(extension_path, "hf_models"))
|
90 |
+
compressor_model = langchain_compressor.embeddings.client
|
91 |
+
compressor_model.to(compressor_model._target_device)
|
92 |
+
custom_system_message_filename = params.get("default system prompt filename")
|
93 |
+
else:
|
94 |
+
if not params["cpu only"] and 'langchain_compressor' in globals(): # free some VRAM
|
95 |
+
model_attrs = ["embeddings", "splade_doc_model", "splade_query_model"]
|
96 |
+
for model_attr in model_attrs:
|
97 |
+
if hasattr(langchain_compressor, model_attr):
|
98 |
+
model = getattr(langchain_compressor, model_attr)
|
99 |
+
if hasattr(model, "client"):
|
100 |
+
model.client.to("cpu")
|
101 |
+
del model.client
|
102 |
+
else:
|
103 |
+
if hasattr(model, "to"):
|
104 |
+
model.to("cpu")
|
105 |
+
del model
|
106 |
+
torch.cuda.empty_cache()
|
107 |
+
params.update({"enable": _enable})
|
108 |
+
return _enable
|
109 |
+
|
110 |
+
|
111 |
+
def get_available_system_prompts():
|
112 |
+
try:
|
113 |
+
return ["None"] + sorted(os.listdir(os.path.join(extension_path, "system_prompts")))
|
114 |
+
except FileNotFoundError:
|
115 |
+
return ["None"]
|
116 |
+
|
117 |
+
|
118 |
+
def load_system_prompt(filename: str or None):
|
119 |
+
global custom_system_message_filename
|
120 |
+
if not filename:
|
121 |
+
return
|
122 |
+
if filename == "None" or filename == "Select custom system message to load...":
|
123 |
+
custom_system_message_filename = None
|
124 |
+
return ""
|
125 |
+
with open(os.path.join(extension_path, "system_prompts", filename), "r") as f:
|
126 |
+
prompt_str = f.read()
|
127 |
+
|
128 |
+
if params["append current datetime"]:
|
129 |
+
prompt_str += f"\nDate and time of conversation: {datetime.now().strftime('%A %d %B %Y %H:%M')}"
|
130 |
+
|
131 |
+
shared.settings['custom_system_message'] = prompt_str
|
132 |
+
custom_system_message_filename = filename
|
133 |
+
return prompt_str
|
134 |
+
|
135 |
+
|
136 |
+
def save_system_prompt(filename, prompt):
|
137 |
+
if not filename:
|
138 |
+
return
|
139 |
+
|
140 |
+
with open(os.path.join(extension_path, "system_prompts", filename), "w") as f:
|
141 |
+
f.write(prompt)
|
142 |
+
|
143 |
+
return gr.HTML(f'<span style="color:lawngreen"> Saved successfully</span>',
|
144 |
+
visible=True)
|
145 |
+
|
146 |
+
|
147 |
+
def check_file_exists(filename):
|
148 |
+
if filename == "":
|
149 |
+
return gr.HTML("", visible=False)
|
150 |
+
if os.path.exists(os.path.join(extension_path, "system_prompts", filename)):
|
151 |
+
return gr.HTML(f'<span style="color:orange"> Warning: Filename already exists</span>', visible=True)
|
152 |
+
return gr.HTML("", visible=False)
|
153 |
+
|
154 |
+
|
155 |
+
def timeout_save_message():
|
156 |
+
time.sleep(2)
|
157 |
+
return gr.HTML("", visible=False)
|
158 |
+
|
159 |
+
|
160 |
+
def deactivate_system_prompt():
|
161 |
+
shared.settings['custom_system_message'] = None
|
162 |
+
return "None"
|
163 |
+
|
164 |
+
|
165 |
+
def toggle_forced_search(value):
|
166 |
+
global force_search
|
167 |
+
force_search = value
|
168 |
+
|
169 |
+
|
170 |
+
def ui():
|
171 |
+
"""
|
172 |
+
Creates custom gradio elements when the UI is launched.
|
173 |
+
:return:
|
174 |
+
"""
|
175 |
+
# Inject custom system message into the main textbox if a default one is set
|
176 |
+
shared.gradio['custom_system_message'].value = load_system_prompt(custom_system_message_filename)
|
177 |
+
|
178 |
+
def update_result_type_setting(choice: str):
|
179 |
+
if choice == "Instant answers":
|
180 |
+
params.update({"instant answers": True})
|
181 |
+
params.update({"regular search results": False})
|
182 |
+
elif choice == "Regular results":
|
183 |
+
params.update({"instant answers": False})
|
184 |
+
params.update({"regular search results": True})
|
185 |
+
elif choice == "Regular results and instant answers":
|
186 |
+
params.update({"instant answers": True})
|
187 |
+
params.update({"regular search results": True})
|
188 |
+
|
189 |
+
def update_regex_setting(input_str: str, setting_key: str, error_html_element: gr.component):
|
190 |
+
if input_str == "":
|
191 |
+
params.update({setting_key: params[f"default {setting_key}"]})
|
192 |
+
return {error_html_element: gr.HTML("", visible=False)}
|
193 |
+
try:
|
194 |
+
compiled = re.compile(input_str)
|
195 |
+
if compiled.groups > 1:
|
196 |
+
raise re.error(f"Only 1 capturing group allowed in regex, but there are {compiled.groups}.")
|
197 |
+
params.update({setting_key: input_str})
|
198 |
+
return {error_html_element: gr.HTML("", visible=False)}
|
199 |
+
except re.error as e:
|
200 |
+
return {error_html_element: gr.HTML(f'<span style="color:red"> Invalid regex. {str(e).capitalize()}</span>',
|
201 |
+
visible=True)}
|
202 |
+
|
203 |
+
def update_default_custom_system_message(check: bool):
|
204 |
+
if check:
|
205 |
+
params.update({"default system prompt filename": custom_system_message_filename})
|
206 |
+
else:
|
207 |
+
params.update({"default system prompt filename": None})
|
208 |
+
|
209 |
+
with gr.Row():
|
210 |
+
enable = gr.Checkbox(value=lambda: params['enable'], label='Enable LLM web search')
|
211 |
+
use_cpu_only = gr.Checkbox(value=lambda: params['cpu only'],
|
212 |
+
label='Run extension on CPU only '
|
213 |
+
'(Save settings and restart for the change to take effect)')
|
214 |
+
with gr.Column():
|
215 |
+
save_settings_btn = gr.Button("Save settings")
|
216 |
+
saved_success_elem = gr.HTML("", visible=False)
|
217 |
+
|
218 |
+
with gr.Row():
|
219 |
+
result_radio = gr.Radio(
|
220 |
+
["Regular results", "Regular results and instant answers"],
|
221 |
+
label="What kind of search results should be returned?",
|
222 |
+
value=lambda: "Regular results and instant answers" if
|
223 |
+
(params["regular search results"] and params["instant answers"]) else "Regular results"
|
224 |
+
)
|
225 |
+
with gr.Column():
|
226 |
+
search_command_regex = gr.Textbox(label="Search command regex string",
|
227 |
+
placeholder=params["default search command regex"],
|
228 |
+
value=lambda: params["search command regex"])
|
229 |
+
search_command_regex_error_label = gr.HTML("", visible=False)
|
230 |
+
|
231 |
+
with gr.Column():
|
232 |
+
open_url_command_regex = gr.Textbox(label="Open URL command regex string",
|
233 |
+
placeholder=params["default open url command regex"],
|
234 |
+
value=lambda: params["open url command regex"])
|
235 |
+
open_url_command_regex_error_label = gr.HTML("", visible=False)
|
236 |
+
|
237 |
+
with gr.Column():
|
238 |
+
show_results = gr.Checkbox(value=lambda: params['display search results in chat'],
|
239 |
+
label='Display search results in chat')
|
240 |
+
show_url_content = gr.Checkbox(value=lambda: params['display extracted URL content in chat'],
|
241 |
+
label='Display extracted URL content in chat')
|
242 |
+
gr.Markdown(value='---')
|
243 |
+
with gr.Row():
|
244 |
+
with gr.Column():
|
245 |
+
gr.Markdown(value='#### Load custom system message\n'
|
246 |
+
'Select a saved custom system message from within the system_prompts folder or "None" '
|
247 |
+
'to clear the selection')
|
248 |
+
system_prompt = gr.Dropdown(
|
249 |
+
choices=get_available_system_prompts(), label="Select custom system message",
|
250 |
+
value=lambda: 'Select custom system message to load...' if custom_system_message_filename is None else
|
251 |
+
custom_system_message_filename, elem_classes='slim-dropdown')
|
252 |
+
with gr.Row():
|
253 |
+
set_system_message_as_default = gr.Checkbox(
|
254 |
+
value=lambda: custom_system_message_filename == params["default system prompt filename"],
|
255 |
+
label='Set this custom system message as the default')
|
256 |
+
refresh_button = ui_module.create_refresh_button(system_prompt, lambda: None,
|
257 |
+
lambda: {'choices': get_available_system_prompts()},
|
258 |
+
'refresh-button', interactive=True)
|
259 |
+
refresh_button.elem_id = "custom-sysprompt-refresh"
|
260 |
+
delete_button = gr.Button('🗑️', elem_classes='refresh-button', interactive=True)
|
261 |
+
append_datetime = gr.Checkbox(value=lambda: params['append current datetime'],
|
262 |
+
label='Append current date and time when loading custom system message')
|
263 |
+
with gr.Column():
|
264 |
+
gr.Markdown(value='#### Create custom system message')
|
265 |
+
system_prompt_text = gr.Textbox(label="Custom system message", lines=3,
|
266 |
+
value=lambda: load_system_prompt(custom_system_message_filename))
|
267 |
+
sys_prompt_filename = gr.Text(label="Filename")
|
268 |
+
sys_prompt_save_button = gr.Button("Save Custom system message")
|
269 |
+
system_prompt_saved_success_elem = gr.HTML("", visible=False)
|
270 |
+
|
271 |
+
gr.Markdown(value='---')
|
272 |
+
with gr.Accordion("Advanced settings", open=False):
|
273 |
+
ensemble_weighting = gr.Slider(minimum=0, maximum=1, step=0.05, value=lambda: params["ensemble weighting"],
|
274 |
+
label="Ensemble Weighting", info="Smaller values = More keyword oriented, "
|
275 |
+
"Larger values = More focus on semantic similarity")
|
276 |
+
with gr.Row():
|
277 |
+
keyword_retriever = gr.Radio([("Okapi BM25", "bm25"),("SPLADE", "splade")], label="Sparse keyword retriever",
|
278 |
+
info="For change to take effect, toggle the extension off and on again",
|
279 |
+
value=lambda: params["keyword retriever"])
|
280 |
+
splade_batch_size = gr.Slider(minimum=2, maximum=256, step=2, value=lambda: params["splade batch size"],
|
281 |
+
label="SPLADE batch size",
|
282 |
+
info="Smaller values = Slower retrieval (but lower VRAM usage), "
|
283 |
+
"Larger values = Faster retrieval (but higher VRAM usage). "
|
284 |
+
"A good trade-off seems to be setting it = 8",
|
285 |
+
precision=0)
|
286 |
+
with gr.Row():
|
287 |
+
chunker = gr.Radio([("Character-based", "character-based"),
|
288 |
+
("Semantic", "semantic")], label="Chunking method",
|
289 |
+
value=lambda: params["chunking method"])
|
290 |
+
chunker_breakpoint_threshold_amount = gr.Slider(minimum=1, maximum=100, step=1,
|
291 |
+
value=lambda: params["chunker breakpoint_threshold_amount"],
|
292 |
+
label="Semantic chunking: sentence split threshold (%)",
|
293 |
+
info="Defines how different two consecutive sentences have"
|
294 |
+
" to be for them to be split into separate chunks",
|
295 |
+
precision=0)
|
296 |
+
gr.Markdown("**Note: Changing the following might result in DuckDuckGo rate limiting or the LM being overwhelmed**")
|
297 |
+
num_search_results = gr.Number(label="Max. search results to return per query", minimum=1, maximum=100,
|
298 |
+
value=lambda: params["search results per query"], precision=0)
|
299 |
+
num_process_search_results = gr.Number(label="Number of search results to process per query", minimum=1,
|
300 |
+
maximum=100, value=lambda: params["duckduckgo results per query"],
|
301 |
+
precision=0)
|
302 |
+
langchain_similarity_threshold = gr.Number(label="Langchain Similarity Score Threshold", minimum=0., maximum=1.,
|
303 |
+
value=lambda: params["langchain similarity score threshold"])
|
304 |
+
chunk_size = gr.Number(label="Max. chunk size", info="The maximal size of the individual chunks that each webpage will"
|
305 |
+
" be split into, in characters", minimum=2, maximum=10000,
|
306 |
+
value=lambda: params["chunk size"], precision=0)
|
307 |
+
|
308 |
+
with gr.Row():
|
309 |
+
searxng_url = gr.Textbox(label="SearXNG URL",
|
310 |
+
value=lambda: params["searxng url"])
|
311 |
+
|
312 |
+
# Event functions to update the parameters in the backend
|
313 |
+
enable.input(toggle_extension, enable, enable)
|
314 |
+
use_cpu_only.change(lambda x: params.update({"cpu only": x}), use_cpu_only, None)
|
315 |
+
save_settings_btn.click(save_settings, None, [saved_success_elem])
|
316 |
+
ensemble_weighting.change(lambda x: params.update({"ensemble weighting": x}), ensemble_weighting, None)
|
317 |
+
keyword_retriever.change(lambda x: params.update({"keyword retriever": x}), keyword_retriever, None)
|
318 |
+
splade_batch_size.change(lambda x: params.update({"splade batch size": x}), splade_batch_size, None)
|
319 |
+
chunker.change(lambda x: params.update({"chunking method": x}), chunker, None)
|
320 |
+
chunker_breakpoint_threshold_amount.change(lambda x: params.update({"chunker breakpoint_threshold_amount": x}),
|
321 |
+
chunker_breakpoint_threshold_amount, None)
|
322 |
+
num_search_results.change(lambda x: params.update({"search results per query": x}), num_search_results, None)
|
323 |
+
num_process_search_results.change(lambda x: params.update({"duckduckgo results per query": x}),
|
324 |
+
num_process_search_results, None)
|
325 |
+
langchain_similarity_threshold.change(lambda x: params.update({"langchain similarity score threshold": x}),
|
326 |
+
langchain_similarity_threshold, None)
|
327 |
+
chunk_size.change(lambda x: params.update({"chunk size": x}), chunk_size, None)
|
328 |
+
result_radio.change(update_result_type_setting, result_radio, None)
|
329 |
+
|
330 |
+
search_command_regex.change(lambda x: update_regex_setting(x, "search command regex",
|
331 |
+
search_command_regex_error_label),
|
332 |
+
search_command_regex, search_command_regex_error_label, show_progress="hidden")
|
333 |
+
|
334 |
+
open_url_command_regex.change(lambda x: update_regex_setting(x, "open url command regex",
|
335 |
+
open_url_command_regex_error_label),
|
336 |
+
open_url_command_regex, open_url_command_regex_error_label, show_progress="hidden")
|
337 |
+
|
338 |
+
show_results.change(lambda x: params.update({"display search results in chat": x}), show_results, None)
|
339 |
+
show_url_content.change(lambda x: params.update({"display extracted URL content in chat": x}), show_url_content,
|
340 |
+
None)
|
341 |
+
searxng_url.change(lambda x: params.update({"searxng url": x}), searxng_url, None)
|
342 |
+
|
343 |
+
delete_button.click(
|
344 |
+
lambda x: x, system_prompt, gradio('delete_filename')).then(
|
345 |
+
lambda: os.path.join(extension_path, "system_prompts", ""), None, gradio('delete_root')).then(
|
346 |
+
lambda: gr.update(visible=True), None, gradio('file_deleter'))
|
347 |
+
shared.gradio['delete_confirm'].click(
|
348 |
+
lambda: "None", None, system_prompt).then(
|
349 |
+
None, None, None, _js="() => { document.getElementById('custom-sysprompt-refresh').click() }")
|
350 |
+
system_prompt.change(load_system_prompt, system_prompt, shared.gradio['custom_system_message'])
|
351 |
+
system_prompt.change(load_system_prompt, system_prompt, system_prompt_text)
|
352 |
+
# restore checked state if chosen system prompt matches the default
|
353 |
+
system_prompt.change(lambda x: x == params["default system prompt filename"], system_prompt,
|
354 |
+
set_system_message_as_default)
|
355 |
+
sys_prompt_filename.change(check_file_exists, sys_prompt_filename, system_prompt_saved_success_elem)
|
356 |
+
sys_prompt_save_button.click(save_system_prompt, [sys_prompt_filename, system_prompt_text],
|
357 |
+
system_prompt_saved_success_elem,
|
358 |
+
show_progress="hidden").then(timeout_save_message,
|
359 |
+
None,
|
360 |
+
system_prompt_saved_success_elem,
|
361 |
+
_js="() => { document.getElementById('custom-sysprompt-refresh').click() }",
|
362 |
+
show_progress="hidden").then(lambda: "", None,
|
363 |
+
sys_prompt_filename,
|
364 |
+
show_progress="hidden")
|
365 |
+
append_datetime.change(lambda x: params.update({"append current datetime": x}), append_datetime, None)
|
366 |
+
# '.input' = only triggers when user changes the value of the component, not a function
|
367 |
+
set_system_message_as_default.input(update_default_custom_system_message, set_system_message_as_default, None)
|
368 |
+
|
369 |
+
# A dummy checkbox to enable the actual "Force web search" checkbox to trigger a gradio event
|
370 |
+
force_search_checkbox = gr.Checkbox(value=False, visible=False, elem_id="Force-search-checkbox")
|
371 |
+
force_search_checkbox.change(toggle_forced_search, force_search_checkbox, None)
|
372 |
+
|
373 |
+
|
374 |
+
def custom_generate_reply(question, original_question, seed, state, stopping_strings, is_chat):
|
375 |
+
"""
|
376 |
+
Overrides the main text generation function.
|
377 |
+
:return:
|
378 |
+
"""
|
379 |
+
global update_history, langchain_compressor
|
380 |
+
if shared.model.__class__.__name__ in ['LlamaCppModel', 'RWKVModel', 'ExllamaModel', 'Exllamav2Model',
|
381 |
+
'CtransformersModel']:
|
382 |
+
generate_func = generate_reply_custom
|
383 |
+
else:
|
384 |
+
generate_func = generate_reply_HF
|
385 |
+
|
386 |
+
if not params['enable']:
|
387 |
+
for reply in generate_func(question, original_question, seed, state, stopping_strings, is_chat=is_chat):
|
388 |
+
yield reply
|
389 |
+
return
|
390 |
+
|
391 |
+
web_search = False
|
392 |
+
read_webpage = False
|
393 |
+
max_search_results = int(params["search results per query"])
|
394 |
+
instant_answers = params["instant answers"]
|
395 |
+
# regular_search_results = params["regular search results"]
|
396 |
+
|
397 |
+
langchain_compressor.num_results = int(params["duckduckgo results per query"])
|
398 |
+
langchain_compressor.similarity_threshold = params["langchain similarity score threshold"]
|
399 |
+
langchain_compressor.chunk_size = params["chunk size"]
|
400 |
+
langchain_compressor.ensemble_weighting = params["ensemble weighting"]
|
401 |
+
langchain_compressor.splade_batch_size = params["splade batch size"]
|
402 |
+
langchain_compressor.chunking_method = params["chunking method"]
|
403 |
+
langchain_compressor.chunker_breakpoint_threshold_amount = params["chunker breakpoint_threshold_amount"]
|
404 |
+
|
405 |
+
search_command_regex = params["search command regex"]
|
406 |
+
open_url_command_regex = params["open url command regex"]
|
407 |
+
searxng_url = params["searxng url"]
|
408 |
+
display_search_results = params["display search results in chat"]
|
409 |
+
display_webpage_content = params["display extracted URL content in chat"]
|
410 |
+
|
411 |
+
if search_command_regex == "":
|
412 |
+
search_command_regex = params["default search command regex"]
|
413 |
+
if open_url_command_regex == "":
|
414 |
+
open_url_command_regex = params["default open url command regex"]
|
415 |
+
|
416 |
+
compiled_search_command_regex = re.compile(search_command_regex)
|
417 |
+
compiled_open_url_command_regex = re.compile(open_url_command_regex)
|
418 |
+
|
419 |
+
if force_search:
|
420 |
+
question += f" {params['force search prefix']}"
|
421 |
+
|
422 |
+
reply = None
|
423 |
+
for reply in generate_func(question, original_question, seed, state, stopping_strings, is_chat=is_chat):
|
424 |
+
|
425 |
+
if force_search:
|
426 |
+
reply = params["force search prefix"] + reply
|
427 |
+
|
428 |
+
search_re_match = compiled_search_command_regex.search(reply)
|
429 |
+
if search_re_match is not None:
|
430 |
+
yield reply
|
431 |
+
original_model_reply = reply
|
432 |
+
web_search = True
|
433 |
+
search_term = search_re_match.group(1)
|
434 |
+
print(f"LLM_Web_search | Searching for {search_term}...")
|
435 |
+
reply += "\n```plaintext"
|
436 |
+
reply += "\nSearch tool:\n"
|
437 |
+
if searxng_url == "":
|
438 |
+
search_generator = Generator(langchain_search_duckduckgo(search_term,
|
439 |
+
langchain_compressor,
|
440 |
+
max_search_results,
|
441 |
+
instant_answers))
|
442 |
+
else:
|
443 |
+
search_generator = Generator(langchain_search_searxng(search_term,
|
444 |
+
searxng_url,
|
445 |
+
langchain_compressor,
|
446 |
+
max_search_results))
|
447 |
+
try:
|
448 |
+
for status_message in search_generator:
|
449 |
+
yield original_model_reply + f"\n*{status_message}*"
|
450 |
+
search_results = search_generator.value
|
451 |
+
except Exception as exc:
|
452 |
+
exception_message = str(exc)
|
453 |
+
reply += f"The search tool encountered an error: {exception_message}"
|
454 |
+
print(f'LLM_Web_search | {search_term} generated an exception: {exception_message}')
|
455 |
+
else:
|
456 |
+
if search_results != "":
|
457 |
+
reply += search_results
|
458 |
+
else:
|
459 |
+
reply += f"\nThe search tool did not return any results."
|
460 |
+
reply += "```"
|
461 |
+
if display_search_results:
|
462 |
+
yield reply
|
463 |
+
break
|
464 |
+
|
465 |
+
open_url_re_match = compiled_open_url_command_regex.search(reply)
|
466 |
+
if open_url_re_match is not None:
|
467 |
+
yield reply
|
468 |
+
original_model_reply = reply
|
469 |
+
read_webpage = True
|
470 |
+
url = open_url_re_match.group(1)
|
471 |
+
print(f"LLM_Web_search | Reading {url}...")
|
472 |
+
reply += "\n```plaintext"
|
473 |
+
reply += "\nURL opener tool:\n"
|
474 |
+
try:
|
475 |
+
webpage_content = get_webpage_content(url)
|
476 |
+
except Exception as exc:
|
477 |
+
reply += f"Couldn't open {url}. Error message: {str(exc)}"
|
478 |
+
print(f'LLM_Web_search | {url} generated an exception: {str(exc)}')
|
479 |
+
else:
|
480 |
+
reply += f"\nText content of {url}:\n"
|
481 |
+
reply += webpage_content
|
482 |
+
reply += "```\n"
|
483 |
+
if display_webpage_content:
|
484 |
+
yield reply
|
485 |
+
break
|
486 |
+
yield reply
|
487 |
+
|
488 |
+
if web_search or read_webpage:
|
489 |
+
display_results = web_search and display_search_results or read_webpage and display_webpage_content
|
490 |
+
# Add results to context and continue model output
|
491 |
+
new_question = chat.generate_chat_prompt(f"{question}{reply}", state)
|
492 |
+
new_reply = ""
|
493 |
+
for new_reply in generate_func(new_question, new_question, seed, state,
|
494 |
+
stopping_strings, is_chat=is_chat):
|
495 |
+
if display_results:
|
496 |
+
yield f"{reply}\n{new_reply}"
|
497 |
+
else:
|
498 |
+
yield f"{original_model_reply}\n{new_reply}"
|
499 |
+
|
500 |
+
if not display_results:
|
501 |
+
update_history = [state["textbox"], f"{reply}\n{new_reply}"]
|
502 |
+
|
503 |
+
|
504 |
+
def output_modifier(string, state, is_chat=False):
|
505 |
+
"""
|
506 |
+
Modifies the output string before it is presented in the UI. In chat mode,
|
507 |
+
it is applied to the bot's reply. Otherwise, it is applied to the entire
|
508 |
+
output.
|
509 |
+
:param string:
|
510 |
+
:param state:
|
511 |
+
:param is_chat:
|
512 |
+
:return:
|
513 |
+
"""
|
514 |
+
return string
|
515 |
+
|
516 |
+
|
517 |
+
def custom_css():
|
518 |
+
"""
|
519 |
+
Returns custom CSS as a string. It is applied whenever the web UI is loaded.
|
520 |
+
:return:
|
521 |
+
"""
|
522 |
+
return ''
|
523 |
+
|
524 |
+
|
525 |
+
def custom_js():
|
526 |
+
"""
|
527 |
+
Returns custom javascript as a string. It is applied whenever the web UI is
|
528 |
+
loaded.
|
529 |
+
:return:
|
530 |
+
"""
|
531 |
+
with open(os.path.join(extension_path, "script.js"), "r") as f:
|
532 |
+
return f.read()
|
533 |
+
|
534 |
+
|
535 |
+
def chat_input_modifier(text, visible_text, state):
|
536 |
+
"""
|
537 |
+
Modifies both the visible and internal inputs in chat mode. Can be used to
|
538 |
+
hijack the chat input with custom content.
|
539 |
+
:param text:
|
540 |
+
:param visible_text:
|
541 |
+
:param state:
|
542 |
+
:return:
|
543 |
+
"""
|
544 |
+
return text, visible_text
|
545 |
+
|
546 |
+
|
547 |
+
def state_modifier(state):
|
548 |
+
"""
|
549 |
+
Modifies the dictionary containing the UI input parameters before it is
|
550 |
+
used by the text generation functions.
|
551 |
+
:param state:
|
552 |
+
:return:
|
553 |
+
"""
|
554 |
+
return state
|
555 |
+
|
556 |
+
|
557 |
+
def history_modifier(history):
|
558 |
+
"""
|
559 |
+
Modifies the chat history before the text generation in chat mode begins.
|
560 |
+
:param history:
|
561 |
+
:return:
|
562 |
+
"""
|
563 |
+
global update_history
|
564 |
+
if update_history:
|
565 |
+
history["internal"].append(update_history)
|
566 |
+
update_history = None
|
567 |
+
return history
|
semantic_chunker.py
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import re
|
3 |
+
from typing import Any, Dict, Iterable, List, Literal, Optional, Sequence, Tuple, cast
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
from langchain_community.utils.math import (
|
7 |
+
cosine_similarity,
|
8 |
+
)
|
9 |
+
from langchain_core.documents import BaseDocumentTransformer, Document
|
10 |
+
from langchain_core.embeddings import Embeddings
|
11 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
12 |
+
|
13 |
+
|
14 |
+
def calculate_cosine_distances(sentence_embeddings) -> np.array:
|
15 |
+
"""Calculate cosine distances between sentences.
|
16 |
+
|
17 |
+
Args:
|
18 |
+
sentence_embeddings: List of sentence embeddings to calculate distances for.
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
Distance between each pair of adjacent sentences
|
22 |
+
"""
|
23 |
+
return (1 - cosine_similarity(sentence_embeddings, sentence_embeddings)).flatten()[1::len(sentence_embeddings) + 1]
|
24 |
+
|
25 |
+
|
26 |
+
BreakpointThresholdType = Literal["percentile", "standard_deviation", "interquartile"]
|
27 |
+
BREAKPOINT_DEFAULTS: Dict[BreakpointThresholdType, float] = {
|
28 |
+
"percentile": 95,
|
29 |
+
"standard_deviation": 3,
|
30 |
+
"interquartile": 1.5,
|
31 |
+
}
|
32 |
+
|
33 |
+
|
34 |
+
class BoundedSemanticChunker(BaseDocumentTransformer):
|
35 |
+
"""First splits the text using semantic chunking according to the specified
|
36 |
+
'breakpoint_threshold_amount', but then uses a RecursiveCharacterTextSplitter
|
37 |
+
to split all chunks that are larger than 'max_chunk_size'.
|
38 |
+
|
39 |
+
Adapted from langchain_experimental.text_splitter.SemanticChunker"""
|
40 |
+
|
41 |
+
def __init__(
|
42 |
+
self,
|
43 |
+
embeddings: Embeddings,
|
44 |
+
buffer_size: int = 1,
|
45 |
+
add_start_index: bool = False,
|
46 |
+
breakpoint_threshold_type: BreakpointThresholdType = "percentile",
|
47 |
+
breakpoint_threshold_amount: Optional[float] = None,
|
48 |
+
number_of_chunks: Optional[int] = None,
|
49 |
+
max_chunk_size: int = 500,
|
50 |
+
):
|
51 |
+
self._add_start_index = add_start_index
|
52 |
+
self.embeddings = embeddings
|
53 |
+
self.buffer_size = buffer_size
|
54 |
+
self.breakpoint_threshold_type = breakpoint_threshold_type
|
55 |
+
self.number_of_chunks = number_of_chunks
|
56 |
+
if breakpoint_threshold_amount is None:
|
57 |
+
self.breakpoint_threshold_amount = BREAKPOINT_DEFAULTS[
|
58 |
+
breakpoint_threshold_type
|
59 |
+
]
|
60 |
+
else:
|
61 |
+
self.breakpoint_threshold_amount = breakpoint_threshold_amount
|
62 |
+
self.max_chunk_size = max_chunk_size
|
63 |
+
# Splitting the text on '.', '?', and '!'
|
64 |
+
self.sentence_split_regex = re.compile(r"(?<=[.?!])\s+")
|
65 |
+
|
66 |
+
assert self.breakpoint_threshold_type == "percentile", "only breakpoint_threshold_type 'percentile' is currently supported"
|
67 |
+
assert self.buffer_size == 1, "combining sentences is not supported yet"
|
68 |
+
|
69 |
+
def _calculate_sentence_distances(
|
70 |
+
self, sentences: List[dict]
|
71 |
+
) -> Tuple[List[float], List[dict]]:
|
72 |
+
"""Split text into multiple components."""
|
73 |
+
embeddings = self.embeddings.embed_documents(sentences)
|
74 |
+
return calculate_cosine_distances(embeddings)
|
75 |
+
|
76 |
+
def _calculate_breakpoint_threshold(self, distances: np.array, alt_breakpoint_threshold_amount=None) -> float:
|
77 |
+
if alt_breakpoint_threshold_amount is None:
|
78 |
+
breakpoint_threshold_amount = self.breakpoint_threshold_amount
|
79 |
+
else:
|
80 |
+
breakpoint_threshold_amount = alt_breakpoint_threshold_amount
|
81 |
+
if self.breakpoint_threshold_type == "percentile":
|
82 |
+
return cast(
|
83 |
+
float,
|
84 |
+
np.percentile(distances, breakpoint_threshold_amount),
|
85 |
+
)
|
86 |
+
elif self.breakpoint_threshold_type == "standard_deviation":
|
87 |
+
return cast(
|
88 |
+
float,
|
89 |
+
np.mean(distances)
|
90 |
+
+ breakpoint_threshold_amount * np.std(distances),
|
91 |
+
)
|
92 |
+
elif self.breakpoint_threshold_type == "interquartile":
|
93 |
+
q1, q3 = np.percentile(distances, [25, 75])
|
94 |
+
iqr = q3 - q1
|
95 |
+
|
96 |
+
return np.mean(distances) + breakpoint_threshold_amount * iqr
|
97 |
+
else:
|
98 |
+
raise ValueError(
|
99 |
+
f"Got unexpected `breakpoint_threshold_type`: "
|
100 |
+
f"{self.breakpoint_threshold_type}"
|
101 |
+
)
|
102 |
+
|
103 |
+
def _threshold_from_clusters(self, distances: List[float]) -> float:
|
104 |
+
"""
|
105 |
+
Calculate the threshold based on the number of chunks.
|
106 |
+
Inverse of percentile method.
|
107 |
+
"""
|
108 |
+
if self.number_of_chunks is None:
|
109 |
+
raise ValueError(
|
110 |
+
"This should never be called if `number_of_chunks` is None."
|
111 |
+
)
|
112 |
+
x1, y1 = len(distances), 0.0
|
113 |
+
x2, y2 = 1.0, 100.0
|
114 |
+
|
115 |
+
x = max(min(self.number_of_chunks, x1), x2)
|
116 |
+
|
117 |
+
# Linear interpolation formula
|
118 |
+
y = y1 + ((y2 - y1) / (x2 - x1)) * (x - x1)
|
119 |
+
y = min(max(y, 0), 100)
|
120 |
+
|
121 |
+
return cast(float, np.percentile(distances, y))
|
122 |
+
|
123 |
+
def split_text(
|
124 |
+
self,
|
125 |
+
text: str,
|
126 |
+
) -> List[str]:
|
127 |
+
sentences = self.sentence_split_regex.split(text)
|
128 |
+
|
129 |
+
# having len(sentences) == 1 would cause the following
|
130 |
+
# np.percentile to fail.
|
131 |
+
if len(sentences) == 1:
|
132 |
+
return sentences
|
133 |
+
|
134 |
+
bad_sentences = []
|
135 |
+
num_good_sentences = 0
|
136 |
+
|
137 |
+
distances = self._calculate_sentence_distances(sentences)
|
138 |
+
|
139 |
+
if self.number_of_chunks is not None:
|
140 |
+
breakpoint_distance_threshold = self._threshold_from_clusters(distances)
|
141 |
+
else:
|
142 |
+
breakpoint_distance_threshold = self._calculate_breakpoint_threshold(
|
143 |
+
distances
|
144 |
+
)
|
145 |
+
|
146 |
+
indices_above_thresh = [
|
147 |
+
i for i, x in enumerate(distances) if x > breakpoint_distance_threshold
|
148 |
+
]
|
149 |
+
|
150 |
+
chunks = []
|
151 |
+
start_index = 0
|
152 |
+
|
153 |
+
# Iterate through the breakpoints to slice the sentences
|
154 |
+
for index in indices_above_thresh:
|
155 |
+
# The end index is the current breakpoint
|
156 |
+
end_index = index
|
157 |
+
|
158 |
+
# Slice the sentence_dicts from the current start index to the end index
|
159 |
+
group = sentences[start_index : end_index + 1]
|
160 |
+
combined_text = " ".join(group)
|
161 |
+
if len(combined_text) <= self.max_chunk_size:
|
162 |
+
chunks.append(combined_text)
|
163 |
+
else:
|
164 |
+
sent_lengths = np.array([len(sd) for sd in group])
|
165 |
+
good_indices = np.flatnonzero(np.cumsum(sent_lengths) <= self.max_chunk_size)
|
166 |
+
smaller_group = [group[i] for i in good_indices]
|
167 |
+
if smaller_group:
|
168 |
+
combined_text = " ".join(smaller_group)
|
169 |
+
chunks.append(combined_text)
|
170 |
+
group = group[good_indices[-1]:]
|
171 |
+
bad_sentences.extend(group)
|
172 |
+
|
173 |
+
# Update the start index for the next group
|
174 |
+
start_index = index + 1
|
175 |
+
|
176 |
+
# The last group, if any sentences remain
|
177 |
+
if start_index < len(sentences):
|
178 |
+
group = sentences[start_index:]
|
179 |
+
combined_text = " ".join(group)
|
180 |
+
if len(combined_text) <= self.max_chunk_size:
|
181 |
+
chunks.append(combined_text)
|
182 |
+
else:
|
183 |
+
sent_lengths = np.array([len(sd) for sd in group])
|
184 |
+
good_indices = np.flatnonzero(np.cumsum(sent_lengths) <= self.max_chunk_size)
|
185 |
+
smaller_group = [group[i] for i in good_indices]
|
186 |
+
if smaller_group:
|
187 |
+
combined_text = " ".join(smaller_group)
|
188 |
+
chunks.append(combined_text)
|
189 |
+
group = group[good_indices[-1]:]
|
190 |
+
bad_sentences.extend(group)
|
191 |
+
|
192 |
+
# If pure semantic chunking wasn't able to split all text for any breakpoint_threshold_amount,
|
193 |
+
# split the remaining problematic text using a recursive character splitter instead
|
194 |
+
if len(bad_sentences) > 0:
|
195 |
+
recursive_splitter = RecursiveCharacterTextSplitter(chunk_size=self.max_chunk_size, chunk_overlap=10,
|
196 |
+
separators=["\n\n", "\n", ".", ", ", " ", ""])
|
197 |
+
remaining_text = "".join(bad_sentences)
|
198 |
+
chunks.extend(recursive_splitter.split_text(remaining_text))
|
199 |
+
return chunks
|
200 |
+
|
201 |
+
def create_documents(
|
202 |
+
self, texts: List[str], metadatas: Optional[List[dict]] = None
|
203 |
+
) -> List[Document]:
|
204 |
+
"""Create documents from a list of texts."""
|
205 |
+
_metadatas = metadatas or [{}] * len(texts)
|
206 |
+
documents = []
|
207 |
+
for i, text in enumerate(texts):
|
208 |
+
index = -1
|
209 |
+
for chunk in self.split_text(text):
|
210 |
+
metadata = copy.deepcopy(_metadatas[i])
|
211 |
+
if self._add_start_index:
|
212 |
+
index = text.find(chunk, index + 1)
|
213 |
+
metadata["start_index"] = index
|
214 |
+
new_doc = Document(page_content=chunk, metadata=metadata)
|
215 |
+
documents.append(new_doc)
|
216 |
+
return documents
|
217 |
+
|
218 |
+
def split_documents(self, documents: Iterable[Document]) -> List[Document]:
|
219 |
+
"""Split documents."""
|
220 |
+
texts, metadatas = [], []
|
221 |
+
for doc in documents:
|
222 |
+
texts.append(doc.page_content)
|
223 |
+
metadatas.append(doc.metadata)
|
224 |
+
return self.create_documents(texts, metadatas=metadatas)
|
225 |
+
|
226 |
+
def transform_documents(
|
227 |
+
self, documents: Sequence[Document], **kwargs: Any
|
228 |
+
) -> Sequence[Document]:
|
229 |
+
"""Transform sequence of documents by splitting them."""
|
230 |
+
return self.split_documents(list(documents))
|
231 |
+
|
232 |
+
|
233 |
+
|
system_prompts/bing_at_home
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
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.
|
2 |
+
|
3 |
+
Search tool command format: Search_web("<|query|>")
|
system_prompts/copilot_prompt
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
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:
|
2 |
+
|
3 |
+
1. **Context-Aware Web Search:**
|
4 |
+
- 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")`.
|
5 |
+
- Prioritize reliable sources and communicate findings clearly.
|
6 |
+
|
7 |
+
2. **Fact-Driven Humility:**
|
8 |
+
- Remain cautious about stating specific facts and up-to-date information based only on your pre-programmed knowledge base.
|
9 |
+
- If uncertainty arises, default to searching the web for accurate details.
|
10 |
+
|
11 |
+
3. **Polite and Detailed Responses:**
|
12 |
+
- Engage in friendly, empathetic conversations with users.
|
13 |
+
- Extract information from search results to guide your answers.
|
14 |
+
- Always end messages with an appropriate emoji to match the conveyed emotion.
|
15 |
+
|
16 |
+
Remember the search command format: `Search_web("query")`.
|
system_prompts/default_system_prompt.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
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:
|
2 |
+
|
3 |
+
Search_web("query")
|
4 |
+
|
5 |
+
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.
|
system_prompts/second_person_command_last
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
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:
|
2 |
+
|
3 |
+
Search_web("query")
|
system_prompts/websearch_gpt4_prompt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
You are an artificial intelligence assistant. You have access to a search tool. Use the search tool in the following circumstances:
|
2 |
+
|
3 |
+
- User is asking about current events or something that requires real-time information (weather, sports scores, etc.)
|
4 |
+
- User is asking about some term you are totally unfamiliar with (it might be new)
|
5 |
+
- User explicitly asks you to search or provide links to references
|
6 |
+
|
7 |
+
Use the following command to use the search tool:
|
8 |
+
Search_web("query")
|
9 |
+
|
10 |
+
The search tool will search the web and return the results. You extract the information from the results of the search tool to give helpful, detailed, and polite answers to the user's questions.
|