├── .gitignore
├── LICENSE
├── README.md
├── agents
└── agents.ipynb
├── api
├── app.py
└── client.py
├── chain
├── attention.pdf
└── retriever.ipynb
├── chatbot
├── app.py
└── localama.py
├── groq
├── app.py
├── groq.ipynb
└── llama3.py
├── huggingface
├── huggingface.ipynb
└── us_census
│ ├── acsbr-015.pdf
│ ├── acsbr-016.pdf
│ ├── acsbr-017.pdf
│ └── p70-178.pdf
├── objectbox
├── .env
├── app.py
└── us_census
│ ├── acsbr-015.pdf
│ ├── acsbr-016.pdf
│ ├── acsbr-017.pdf
│ └── p70-178.pdf
├── openai
└── GPT4o_Lanchain_RAG.ipynb
├── rag
├── attention.pdf
├── simplerag.ipynb
└── speech.txt
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Updated-Langchain
--------------------------------------------------------------------------------
/agents/agents.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 3,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "name": "stdout",
10 | "output_type": "stream",
11 | "text": [
12 | "Collecting arxiv\n",
13 | " Using cached arxiv-2.1.0-py3-none-any.whl.metadata (6.1 kB)\n",
14 | "Collecting feedparser==6.0.10 (from arxiv)\n",
15 | " Using cached feedparser-6.0.10-py3-none-any.whl.metadata (2.3 kB)\n",
16 | "Requirement already satisfied: requests==2.31.0 in e:\\langchain\\venv\\lib\\site-packages (from arxiv) (2.31.0)\n",
17 | "Collecting sgmllib3k (from feedparser==6.0.10->arxiv)\n",
18 | " Using cached sgmllib3k-1.0.0-py3-none-any.whl\n",
19 | "Requirement already satisfied: charset-normalizer<4,>=2 in e:\\langchain\\venv\\lib\\site-packages (from requests==2.31.0->arxiv) (3.3.2)\n",
20 | "Requirement already satisfied: idna<4,>=2.5 in e:\\langchain\\venv\\lib\\site-packages (from requests==2.31.0->arxiv) (3.6)\n",
21 | "Requirement already satisfied: urllib3<3,>=1.21.1 in e:\\langchain\\venv\\lib\\site-packages (from requests==2.31.0->arxiv) (2.2.1)\n",
22 | "Requirement already satisfied: certifi>=2017.4.17 in e:\\langchain\\venv\\lib\\site-packages (from requests==2.31.0->arxiv) (2024.2.2)\n",
23 | "Using cached arxiv-2.1.0-py3-none-any.whl (11 kB)\n",
24 | "Using cached feedparser-6.0.10-py3-none-any.whl (81 kB)\n",
25 | "Installing collected packages: sgmllib3k, feedparser, arxiv\n",
26 | "Successfully installed arxiv-2.1.0 feedparser-6.0.10 sgmllib3k-1.0.0\n"
27 | ]
28 | }
29 | ],
30 | "source": [
31 | "!pip install arxiv"
32 | ]
33 | },
34 | {
35 | "cell_type": "code",
36 | "execution_count": 6,
37 | "metadata": {},
38 | "outputs": [],
39 | "source": [
40 | "from langchain_community.tools import WikipediaQueryRun\n",
41 | "from langchain_community.utilities import WikipediaAPIWrapper"
42 | ]
43 | },
44 | {
45 | "cell_type": "code",
46 | "execution_count": 16,
47 | "metadata": {},
48 | "outputs": [],
49 | "source": [
50 | "api_wrapper=WikipediaAPIWrapper(top_k_results=1,doc_content_chars_max=200)\n",
51 | "wiki=WikipediaQueryRun(api_wrapper=api_wrapper)"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": 17,
57 | "metadata": {},
58 | "outputs": [
59 | {
60 | "data": {
61 | "text/plain": [
62 | "'wikipedia'"
63 | ]
64 | },
65 | "execution_count": 17,
66 | "metadata": {},
67 | "output_type": "execute_result"
68 | }
69 | ],
70 | "source": [
71 | "wiki.name"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": 12,
77 | "metadata": {},
78 | "outputs": [
79 | {
80 | "data": {
81 | "text/plain": [
82 | "VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=)"
83 | ]
84 | },
85 | "execution_count": 12,
86 | "metadata": {},
87 | "output_type": "execute_result"
88 | }
89 | ],
90 | "source": [
91 | "from langchain_community.document_loaders import WebBaseLoader\n",
92 | "from langchain_community.vectorstores import FAISS\n",
93 | "from langchain_openai import OpenAIEmbeddings\n",
94 | "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
95 | "\n",
96 | "loader=WebBaseLoader(\"https://docs.smith.langchain.com/\")\n",
97 | "docs=loader.load()\n",
98 | "documents=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200).split_documents(docs)\n",
99 | "vectordb=FAISS.from_documents(documents,OpenAIEmbeddings())\n",
100 | "retriever=vectordb.as_retriever()\n",
101 | "retriever\n"
102 | ]
103 | },
104 | {
105 | "cell_type": "code",
106 | "execution_count": 13,
107 | "metadata": {},
108 | "outputs": [],
109 | "source": [
110 | "from langchain.tools.retriever import create_retriever_tool\n",
111 | "retriever_tool=create_retriever_tool(retriever,\"langsmith_search\",\n",
112 | " \"Search for information about LangSmith. For any questions about LangSmith, you must use this tool!\")"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": 14,
118 | "metadata": {},
119 | "outputs": [
120 | {
121 | "data": {
122 | "text/plain": [
123 | "'langsmith_search'"
124 | ]
125 | },
126 | "execution_count": 14,
127 | "metadata": {},
128 | "output_type": "execute_result"
129 | }
130 | ],
131 | "source": [
132 | "retriever_tool.name"
133 | ]
134 | },
135 | {
136 | "cell_type": "code",
137 | "execution_count": 15,
138 | "metadata": {},
139 | "outputs": [
140 | {
141 | "data": {
142 | "text/plain": [
143 | "'arxiv'"
144 | ]
145 | },
146 | "execution_count": 15,
147 | "metadata": {},
148 | "output_type": "execute_result"
149 | }
150 | ],
151 | "source": [
152 | "## Arxiv Tool\n",
153 | "from langchain_community.utilities import ArxivAPIWrapper\n",
154 | "from langchain_community.tools import ArxivQueryRun\n",
155 | "\n",
156 | "arxiv_wrapper=ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=200)\n",
157 | "arxiv=ArxivQueryRun(api_wrapper=arxiv_wrapper)\n",
158 | "arxiv.name"
159 | ]
160 | },
161 | {
162 | "cell_type": "code",
163 | "execution_count": 18,
164 | "metadata": {},
165 | "outputs": [],
166 | "source": [
167 | "tools=[wiki,arxiv,retriever_tool]"
168 | ]
169 | },
170 | {
171 | "cell_type": "code",
172 | "execution_count": 19,
173 | "metadata": {},
174 | "outputs": [
175 | {
176 | "data": {
177 | "text/plain": [
178 | "[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=, top_k_results=1, lang='en', load_all_available_meta=False, doc_content_chars_max=200)),\n",
179 | " ArxivQueryRun(api_wrapper=ArxivAPIWrapper(arxiv_search=, arxiv_exceptions=(, , ), top_k_results=1, ARXIV_MAX_QUERY_LENGTH=300, load_max_docs=100, load_all_available_meta=False, doc_content_chars_max=200, arxiv_result=)),\n",
180 | " Tool(name='langsmith_search', description='Search for information about LangSmith. For any questions about LangSmith, you must use this tool!', args_schema=, func=functools.partial(, retriever=VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=), document_prompt=PromptTemplate(input_variables=['page_content'], template='{page_content}'), document_separator='\\n\\n'), coroutine=functools.partial(, retriever=VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=), document_prompt=PromptTemplate(input_variables=['page_content'], template='{page_content}'), document_separator='\\n\\n'))]"
181 | ]
182 | },
183 | "execution_count": 19,
184 | "metadata": {},
185 | "output_type": "execute_result"
186 | }
187 | ],
188 | "source": [
189 | "tools"
190 | ]
191 | },
192 | {
193 | "cell_type": "code",
194 | "execution_count": 20,
195 | "metadata": {},
196 | "outputs": [],
197 | "source": [
198 | "from dotenv import load_dotenv\n",
199 | "\n",
200 | "load_dotenv()\n",
201 | "import os\n",
202 | "os.environ['OPENAI_API_KEY']=os.getenv(\"OPENAI_API_KEY\")\n",
203 | "from langchain_openai import ChatOpenAI\n",
204 | "\n",
205 | "llm = ChatOpenAI(model=\"gpt-3.5-turbo-0125\", temperature=0)"
206 | ]
207 | },
208 | {
209 | "cell_type": "code",
210 | "execution_count": 22,
211 | "metadata": {},
212 | "outputs": [
213 | {
214 | "data": {
215 | "text/plain": [
216 | "[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are a helpful assistant')),\n",
217 | " MessagesPlaceholder(variable_name='chat_history', optional=True),\n",
218 | " HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')),\n",
219 | " MessagesPlaceholder(variable_name='agent_scratchpad')]"
220 | ]
221 | },
222 | "execution_count": 22,
223 | "metadata": {},
224 | "output_type": "execute_result"
225 | }
226 | ],
227 | "source": [
228 | "from langchain import hub\n",
229 | "# Get the prompt to use - you can modify this!\n",
230 | "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
231 | "prompt.messages"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": 23,
237 | "metadata": {},
238 | "outputs": [],
239 | "source": [
240 | "### Agents\n",
241 | "from langchain.agents import create_openai_tools_agent\n",
242 | "agent=create_openai_tools_agent(llm,tools,prompt)"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "execution_count": 26,
248 | "metadata": {},
249 | "outputs": [
250 | {
251 | "data": {
252 | "text/plain": [
253 | "AgentExecutor(verbose=True, agent=RunnableMultiActionAgent(runnable=RunnableAssign(mapper={\n",
254 | " agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
255 | "})\n",
256 | "| ChatPromptTemplate(input_variables=['agent_scratchpad', 'input'], input_types={'chat_history': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]], 'agent_scratchpad': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]]}, metadata={'lc_hub_owner': 'hwchase17', 'lc_hub_repo': 'openai-functions-agent', 'lc_hub_commit_hash': 'a1655024b06afbd95d17449f21316291e0726f13dcfaf990cc0d18087ad689a5'}, messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are a helpful assistant')), MessagesPlaceholder(variable_name='chat_history', optional=True), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')), MessagesPlaceholder(variable_name='agent_scratchpad')])\n",
257 | "| RunnableBinding(bound=ChatOpenAI(client=, async_client=, model_name='gpt-3.5-turbo-0125', temperature=0.0, openai_api_key=SecretStr('**********'), openai_proxy=''), kwargs={'tools': [{'type': 'function', 'function': {'name': 'wikipedia', 'description': 'A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.', 'parameters': {'properties': {'__arg1': {'title': '__arg1', 'type': 'string'}}, 'required': ['__arg1'], 'type': 'object'}}}, {'type': 'function', 'function': {'name': 'arxiv', 'description': 'A wrapper around Arxiv.org Useful for when you need to answer questions about Physics, Mathematics, Computer Science, Quantitative Biology, Quantitative Finance, Statistics, Electrical Engineering, and Economics from scientific articles on arxiv.org. Input should be a search query.', 'parameters': {'type': 'object', 'properties': {'query': {'description': 'search query to look up', 'type': 'string'}}, 'required': ['query']}}}, {'type': 'function', 'function': {'name': 'langsmith_search', 'description': 'Search for information about LangSmith. For any questions about LangSmith, you must use this tool!', 'parameters': {'type': 'object', 'properties': {'query': {'description': 'query to look up in retriever', 'type': 'string'}}, 'required': ['query']}}}]})\n",
258 | "| OpenAIToolsAgentOutputParser(), input_keys_arg=[], return_keys_arg=[], stream_runnable=True), tools=[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=, top_k_results=1, lang='en', load_all_available_meta=False, doc_content_chars_max=200)), ArxivQueryRun(api_wrapper=ArxivAPIWrapper(arxiv_search=, arxiv_exceptions=(, , ), top_k_results=1, ARXIV_MAX_QUERY_LENGTH=300, load_max_docs=100, load_all_available_meta=False, doc_content_chars_max=200, arxiv_result=)), Tool(name='langsmith_search', description='Search for information about LangSmith. For any questions about LangSmith, you must use this tool!', args_schema=, func=functools.partial(, retriever=VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=), document_prompt=PromptTemplate(input_variables=['page_content'], template='{page_content}'), document_separator='\\n\\n'), coroutine=functools.partial(, retriever=VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=), document_prompt=PromptTemplate(input_variables=['page_content'], template='{page_content}'), document_separator='\\n\\n'))])"
259 | ]
260 | },
261 | "execution_count": 26,
262 | "metadata": {},
263 | "output_type": "execute_result"
264 | }
265 | ],
266 | "source": [
267 | "## Agent Executer\n",
268 | "from langchain.agents import AgentExecutor\n",
269 | "agent_executor=AgentExecutor(agent=agent,tools=tools,verbose=True)\n",
270 | "agent_executor"
271 | ]
272 | },
273 | {
274 | "cell_type": "code",
275 | "execution_count": 27,
276 | "metadata": {},
277 | "outputs": [
278 | {
279 | "name": "stdout",
280 | "output_type": "stream",
281 | "text": [
282 | "\n",
283 | "\n",
284 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
285 | "\u001b[32;1m\u001b[1;3m\n",
286 | "Invoking: `langsmith_search` with `{'query': 'Langsmith'}`\n",
287 | "\n",
288 | "\n",
289 | "\u001b[0m\u001b[38;5;200m\u001b[1;3mGetting started with LangSmith | 🦜️🛠️ LangSmith\n",
290 | "\n",
291 | "Skip to main contentLangSmith API DocsSearchGo to AppQuick StartUser GuideTracingEvaluationProduction Monitoring & AutomationsPrompt HubProxyPricingSelf-HostingCookbookQuick StartOn this pageGetting started with LangSmithIntroductionLangSmith is a platform for building production-grade LLM applications. It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence. Use of LangChain is not necessary - LangSmith works on its own!Install LangSmithWe offer Python and Typescript SDKs for all your LangSmith needs.PythonTypeScriptpip install -U langsmithyarn add langchain langsmithCreate an API keyTo create an API key head to the setting pages. Then click Create API Key.Setup your environmentShellexport LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=# The below examples use the OpenAI API, though it's not necessary in generalexport OPENAI_API_KEY=Log your first traceWe provide multiple ways to log traces\n",
292 | "\n",
293 | "Learn about the workflows LangSmith supports at each stage of the LLM application lifecycle.Pricing: Learn about the pricing model for LangSmith.Self-Hosting: Learn about self-hosting options for LangSmith.Proxy: Learn about the proxy capabilities of LangSmith.Tracing: Learn about the tracing capabilities of LangSmith.Evaluation: Learn about the evaluation capabilities of LangSmith.Prompt Hub Learn about the Prompt Hub, a prompt management tool built into LangSmith.Additional ResourcesLangSmith Cookbook: A collection of tutorials and end-to-end walkthroughs using LangSmith.LangChain Python: Docs for the Python LangChain library.LangChain Python API Reference: documentation to review the core APIs of LangChain.LangChain JS: Docs for the TypeScript LangChain libraryDiscord: Join us on our Discord to discuss all things LangChain!FAQHow do I migrate projects between organizations?Currently we do not support project migration betwen organizations. While you can manually imitate this by\n",
294 | "\n",
295 | "team deals with sensitive data that cannot be logged. How can I ensure that only my team can access it?If you are interested in a private deployment of LangSmith or if you need to self-host, please reach out to us at sales@langchain.dev. Self-hosting LangSmith requires an annual enterprise license that also comes with support and formalized access to the LangChain team.Was this page helpful?NextUser GuideIntroductionInstall LangSmithCreate an API keySetup your environmentLog your first traceCreate your first evaluationNext StepsAdditional ResourcesFAQHow do I migrate projects between organizations?Why aren't my runs aren't showing up in my project?My team deals with sensitive data that cannot be logged. How can I ensure that only my team can access it?CommunityDiscordTwitterGitHubDocs CodeLangSmith SDKPythonJS/TSMoreHomepageBlogLangChain Python DocsLangChain JS/TS DocsCopyright © 2024 LangChain, Inc.\u001b[0m\u001b[32;1m\u001b[1;3mLangSmith is a platform for building production-grade LLM (Large Language Model) applications. It allows you to closely monitor and evaluate your application, ensuring you can ship quickly and with confidence. LangSmith offers Python and Typescript SDKs for all your development needs. You can create an API key, set up your environment, and log your first trace using LangSmith.\n",
296 | "\n",
297 | "LangSmith supports various workflows at each stage of the LLM application lifecycle, and you can learn more about its pricing model, self-hosting options, proxy capabilities, tracing capabilities, evaluation capabilities, and the Prompt Hub tool. Additionally, LangSmith provides a Cookbook with tutorials and walkthroughs, along with documentation for the Python and TypeScript LangChain libraries.\n",
298 | "\n",
299 | "If you have sensitive data that cannot be logged or if you need a private deployment of LangSmith, you can reach out to the LangChain team at sales@langchain.dev for self-hosting options that require an annual enterprise license.\n",
300 | "\n",
301 | "For more information, you can visit the LangSmith website or join their Discord community to discuss all things LangChain.\u001b[0m\n",
302 | "\n",
303 | "\u001b[1m> Finished chain.\u001b[0m\n"
304 | ]
305 | },
306 | {
307 | "data": {
308 | "text/plain": [
309 | "{'input': 'Tell me about Langsmith',\n",
310 | " 'output': 'LangSmith is a platform for building production-grade LLM (Large Language Model) applications. It allows you to closely monitor and evaluate your application, ensuring you can ship quickly and with confidence. LangSmith offers Python and Typescript SDKs for all your development needs. You can create an API key, set up your environment, and log your first trace using LangSmith.\\n\\nLangSmith supports various workflows at each stage of the LLM application lifecycle, and you can learn more about its pricing model, self-hosting options, proxy capabilities, tracing capabilities, evaluation capabilities, and the Prompt Hub tool. Additionally, LangSmith provides a Cookbook with tutorials and walkthroughs, along with documentation for the Python and TypeScript LangChain libraries.\\n\\nIf you have sensitive data that cannot be logged or if you need a private deployment of LangSmith, you can reach out to the LangChain team at sales@langchain.dev for self-hosting options that require an annual enterprise license.\\n\\nFor more information, you can visit the LangSmith website or join their Discord community to discuss all things LangChain.'}"
311 | ]
312 | },
313 | "execution_count": 27,
314 | "metadata": {},
315 | "output_type": "execute_result"
316 | }
317 | ],
318 | "source": [
319 | "agent_executor.invoke({\"input\":\"Tell me about Langsmith\"})"
320 | ]
321 | },
322 | {
323 | "cell_type": "code",
324 | "execution_count": 29,
325 | "metadata": {},
326 | "outputs": [
327 | {
328 | "name": "stdout",
329 | "output_type": "stream",
330 | "text": [
331 | "\n",
332 | "\n",
333 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
334 | "\u001b[32;1m\u001b[1;3m\n",
335 | "Invoking: `arxiv` with `{'query': '1605.08386'}`\n",
336 | "\n",
337 | "\n",
338 | "\u001b[0m\u001b[33;1m\u001b[1;3mPublished: 2016-05-26\n",
339 | "Title: Heat-bath random walks with Markov bases\n",
340 | "Authors: Caprice Stanley, Tobias Windisch\n",
341 | "Summary: Graphs on lattice points are studied whose edges come from a finite set of\n",
342 | "allo\u001b[0m\u001b[32;1m\u001b[1;3mThe paper with the identifier 1605.08386 is titled \"Heat-bath random walks with Markov bases\" by Caprice Stanley and Tobias Windisch. It discusses the study of graphs on lattice points where the edges are derived from a finite set of allocations.\u001b[0m\n",
343 | "\n",
344 | "\u001b[1m> Finished chain.\u001b[0m\n"
345 | ]
346 | },
347 | {
348 | "data": {
349 | "text/plain": [
350 | "{'input': \"What's the paper 1605.08386 about?\",\n",
351 | " 'output': 'The paper with the identifier 1605.08386 is titled \"Heat-bath random walks with Markov bases\" by Caprice Stanley and Tobias Windisch. It discusses the study of graphs on lattice points where the edges are derived from a finite set of allocations.'}"
352 | ]
353 | },
354 | "execution_count": 29,
355 | "metadata": {},
356 | "output_type": "execute_result"
357 | }
358 | ],
359 | "source": [
360 | "agent_executor.invoke({\"input\":\"What's the paper 1605.08386 about?\"})"
361 | ]
362 | },
363 | {
364 | "cell_type": "code",
365 | "execution_count": null,
366 | "metadata": {},
367 | "outputs": [],
368 | "source": []
369 | }
370 | ],
371 | "metadata": {
372 | "kernelspec": {
373 | "display_name": "Python 3",
374 | "language": "python",
375 | "name": "python3"
376 | },
377 | "language_info": {
378 | "codemirror_mode": {
379 | "name": "ipython",
380 | "version": 3
381 | },
382 | "file_extension": ".py",
383 | "mimetype": "text/x-python",
384 | "name": "python",
385 | "nbconvert_exporter": "python",
386 | "pygments_lexer": "ipython3",
387 | "version": "3.10.0"
388 | }
389 | },
390 | "nbformat": 4,
391 | "nbformat_minor": 2
392 | }
393 |
--------------------------------------------------------------------------------
/api/app.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 | from langchain.prompts import ChatPromptTemplate
3 | from langchain.chat_models import ChatOpenAI
4 | from langserve import add_routes
5 | import uvicorn
6 | import os
7 | from langchain_community.llms import Ollama
8 | from dotenv import load_dotenv
9 |
10 | load_dotenv()
11 |
12 | os.environ['OPENAI_API_KEY']=os.getenv("OPENAI_API_KEY")
13 |
14 | app=FastAPI(
15 | title="Langchain Server",
16 | version="1.0",
17 | decsription="A simple API Server"
18 |
19 | )
20 |
21 | add_routes(
22 | app,
23 | ChatOpenAI(),
24 | path="/openai"
25 | )
26 | model=ChatOpenAI()
27 | ##ollama llama2
28 | llm=Ollama(model="llama2")
29 |
30 | prompt1=ChatPromptTemplate.from_template("Write me an essay about {topic} with 100 words")
31 | prompt2=ChatPromptTemplate.from_template("Write me an poem about {topic} for a 5 years child with 100 words")
32 |
33 | add_routes(
34 | app,
35 | prompt1|model,
36 | path="/essay"
37 |
38 |
39 | )
40 |
41 | add_routes(
42 | app,
43 | prompt2|llm,
44 | path="/poem"
45 |
46 |
47 | )
48 |
49 |
50 | if __name__=="__main__":
51 | uvicorn.run(app,host="localhost",port=8000)
52 |
53 |
--------------------------------------------------------------------------------
/api/client.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import streamlit as st
3 |
4 | def get_openai_response(input_text):
5 | response=requests.post("http://localhost:8000/essay/invoke",
6 | json={'input':{'topic':input_text}})
7 |
8 | return response.json()['output']['content']
9 |
10 | def get_ollama_response(input_text):
11 | response=requests.post(
12 | "http://localhost:8000/poem/invoke",
13 | json={'input':{'topic':input_text}})
14 |
15 | return response.json()['output']
16 |
17 | ## streamlit framework
18 |
19 | st.title('Langchain Demo With LLAMA2 API')
20 | input_text=st.text_input("Write an essay on")
21 | input_text1=st.text_input("Write a poem on")
22 |
23 | if input_text:
24 | st.write(get_openai_response(input_text))
25 |
26 | if input_text1:
27 | st.write(get_ollama_response(input_text1))
28 |
--------------------------------------------------------------------------------
/chain/attention.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/chain/attention.pdf
--------------------------------------------------------------------------------
/chatbot/app.py:
--------------------------------------------------------------------------------
1 | from langchain_openai import ChatOpenAI
2 | from langchain_core.prompts import ChatPromptTemplate
3 | from langchain_core.output_parsers import StrOutputParser
4 |
5 | import streamlit as st
6 | import os
7 | from dotenv import load_dotenv
8 |
9 | os.environ["OPENAI_API_KEY"]=os.getenv("OPENAI_API_KEY")
10 | ## Langmith tracking
11 | os.environ["LANGCHAIN_TRACING_V2"]="true"
12 | os.environ["LANGCHAIN_API_KEY"]=os.getenv("LANGCHAIN_API_KEY")
13 |
14 | ## Prompt Template
15 |
16 | prompt=ChatPromptTemplate.from_messages(
17 | [
18 | ("system","You are a helpful assistant. Please response to the user queries"),
19 | ("user","Question:{question}")
20 | ]
21 | )
22 |
23 | ## streamlit framework
24 |
25 | st.title('Langchain Demo With OPENAI API')
26 | input_text=st.text_input("Search the topic u want")
27 |
28 | # openAI LLm
29 | llm=ChatOpenAI(model="gpt-3.5-turbo")
30 | output_parser=StrOutputParser()
31 | chain=prompt|llm|output_parser
32 |
33 | if input_text:
34 | st.write(chain.invoke({'question':input_text}))
--------------------------------------------------------------------------------
/chatbot/localama.py:
--------------------------------------------------------------------------------
1 | from langchain_openai import ChatOpenAI
2 | from langchain_core.prompts import ChatPromptTemplate
3 | from langchain_core.output_parsers import StrOutputParser
4 | from langchain_community.llms import Ollama
5 | import streamlit as st
6 | import os
7 | from dotenv import load_dotenv
8 |
9 | load_dotenv()
10 |
11 | os.environ["LANGCHAIN_TRACING_V2"]="true"
12 | os.environ["LANGCHAIN_API_KEY"]=os.getenv("LANGCHAIN_API_KEY")
13 |
14 | ## Prompt Template
15 |
16 | prompt=ChatPromptTemplate.from_messages(
17 | [
18 | ("system","You are a helpful assistant. Please response to the user queries"),
19 | ("user","Question:{question}")
20 | ]
21 | )
22 | ## streamlit framework
23 |
24 | st.title('Langchain Demo With LLAMA2 API')
25 | input_text=st.text_input("Search the topic u want")
26 |
27 | # ollama LLAma2 LLm
28 | llm=Ollama(model="llama2")
29 | output_parser=StrOutputParser()
30 | chain=prompt|llm|output_parser
31 |
32 | if input_text:
33 | st.write(chain.invoke({"question":input_text}))
--------------------------------------------------------------------------------
/groq/app.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import os
3 | from langchain_groq import ChatGroq
4 | from langchain_community.document_loaders import WebBaseLoader
5 | from langchain.embeddings import OllamaEmbeddings
6 | from langchain.text_splitter import RecursiveCharacterTextSplitter
7 | from langchain.chains.combine_documents import create_stuff_documents_chain
8 | from langchain_core.prompts import ChatPromptTemplate
9 | from langchain.chains import create_retrieval_chain
10 | from langchain_community.vectorstores import FAISS
11 | import time
12 |
13 | from dotenv import load_dotenv
14 | load_dotenv()
15 |
16 | ## load the Groq API key
17 | groq_api_key=os.environ['GROQ_API_KEY']
18 |
19 | if "vector" not in st.session_state:
20 | st.session_state.embeddings=OllamaEmbeddings()
21 | st.session_state.loader=WebBaseLoader("https://docs.smith.langchain.com/")
22 | st.session_state.docs=st.session_state.loader.load()
23 |
24 | st.session_state.text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200)
25 | st.session_state.final_documents=st.session_state.text_splitter.split_documents(st.session_state.docs[:50])
26 | st.session_state.vectors=FAISS.from_documents(st.session_state.final_documents,st.session_state.embeddings)
27 |
28 | st.title("ChatGroq Demo")
29 | llm=ChatGroq(groq_api_key=groq_api_key,
30 | model_name="mixtral-8x7b-32768")
31 |
32 | prompt=ChatPromptTemplate.from_template(
33 | """
34 | Answer the questions based on the provided context only.
35 | Please provide the most accurate response based on the question
36 |
37 | {context}
38 |
39 | Questions:{input}
40 |
41 | """
42 | )
43 | document_chain = create_stuff_documents_chain(llm, prompt)
44 | retriever = st.session_state.vectors.as_retriever()
45 | retrieval_chain = create_retrieval_chain(retriever, document_chain)
46 |
47 | prompt=st.text_input("Input you prompt here")
48 |
49 | if prompt:
50 | start=time.process_time()
51 | response=retrieval_chain.invoke({"input":prompt})
52 | print("Response time :",time.process_time()-start)
53 | st.write(response['answer'])
54 |
55 | # With a streamlit expander
56 | with st.expander("Document Similarity Search"):
57 | # Find the relevant chunks
58 | for i, doc in enumerate(response["context"]):
59 | st.write(doc.page_content)
60 | st.write("--------------------------------")
61 |
62 |
--------------------------------------------------------------------------------
/groq/groq.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 32,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "data": {
10 | "text/plain": [
11 | "True"
12 | ]
13 | },
14 | "execution_count": 32,
15 | "metadata": {},
16 | "output_type": "execute_result"
17 | }
18 | ],
19 | "source": [
20 | "import os\n",
21 | "from langchain_groq import ChatGroq\n",
22 | "from langchain_community.document_loaders import WebBaseLoader\n",
23 | "from langchain_community.embeddings import OllamaEmbeddings\n",
24 | "from langchain_community.embeddings import OpenAIEmbeddings\n",
25 | "from langchain.vectorstores.cassandra import Cassandra\n",
26 | "import cassio\n",
27 | "from dotenv import load_dotenv\n",
28 | "load_dotenv()"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": 33,
34 | "metadata": {},
35 | "outputs": [],
36 | "source": [
37 | "groq_api_key=os.environ['GROQ_API_KEY']\n",
38 | "\n",
39 | "## connection of the ASTRA DB\n",
40 | "ASTRA_DB_APPLICATION_TOKEN=\"AstraCS:mifTZmAApXkXyN:8ae5390b5181dbf4ed575bbc3ccddbb9845300cb7071b9f98bf3ba72cbca837c\" # enter the \"AstraCS:...\" string found in in your Token JSON file\"\n",
41 | "ASTRA_DB_ID=\"31d5fd09-8c1f-c-aee0bda20405\"\n",
42 | "cassio.init(token=ASTRA_DB_APPLICATION_TOKEN,database_id=ASTRA_DB_ID)"
43 | ]
44 | },
45 | {
46 | "cell_type": "code",
47 | "execution_count": 34,
48 | "metadata": {},
49 | "outputs": [],
50 | "source": [
51 | "from langchain_community.document_loaders import WebBaseLoader\n",
52 | "import bs4\n",
53 | "loader=WebBaseLoader(web_paths=(\"https://lilianweng.github.io/posts/2023-06-23-agent/\",),\n",
54 | " bs_kwargs=dict(parse_only=bs4.SoupStrainer(\n",
55 | " class_=(\"post-title\",\"post-content\",\"post-header\")\n",
56 | "\n",
57 | " )))\n",
58 | "\n",
59 | "text_documents=loader.load()"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": 35,
65 | "metadata": {},
66 | "outputs": [
67 | {
68 | "data": {
69 | "text/plain": [
70 | "[Document(page_content='\\n\\n LLM Powered Autonomous Agents\\n \\nDate: June 23, 2023 | Estimated Reading Time: 31 min | Author: Lilian Weng\\n\\n\\nBuilding agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview#\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\nFig. 1. Overview of a LLM-powered autonomous agent system.\\nComponent One: Planning#\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.\\nTask Decomposition#\\nChain of thought (CoT; Wei et al. 2022) has become a standard prompting technique for enhancing model performance on complex tasks. The model is instructed to “think step by step” to utilize more test-time computation to decompose hard tasks into smaller and simpler steps. CoT transforms big tasks into multiple manageable tasks and shed lights into an interpretation of the model’s thinking process.\\nTree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first decomposes the problem into multiple thought steps and generates multiple thoughts per step, creating a tree structure. The search process can be BFS (breadth-first search) or DFS (depth-first search) with each state evaluated by a classifier (via a prompt) or majority vote.\\nTask decomposition can be done (1) by LLM with simple prompting like \"Steps for XYZ.\\\\n1.\", \"What are the subgoals for achieving XYZ?\", (2) by using task-specific instructions; e.g. \"Write a story outline.\" for writing a novel, or (3) with human inputs.\\nAnother quite distinct approach, LLM+P (Liu et al. 2023), involves relying on an external classical planner to do long-horizon planning. This approach utilizes the Planning Domain Definition Language (PDDL) as an intermediate interface to describe the planning problem. In this process, LLM (1) translates the problem into “Problem PDDL”, then (2) requests a classical planner to generate a PDDL plan based on an existing “Domain PDDL”, and finally (3) translates the PDDL plan back into natural language. Essentially, the planning step is outsourced to an external tool, assuming the availability of domain-specific PDDL and a suitable planner which is common in certain robotic setups but not in many other domains.\\nSelf-Reflection#\\nSelf-reflection is a vital aspect that allows autonomous agents to improve iteratively by refining past action decisions and correcting previous mistakes. It plays a crucial role in real-world tasks where trial and error are inevitable.\\nReAct (Yao et al. 2023) integrates reasoning and acting within LLM by extending the action space to be a combination of task-specific discrete actions and the language space. The former enables LLM to interact with the environment (e.g. use Wikipedia search API), while the latter prompting LLM to generate reasoning traces in natural language.\\nThe ReAct prompt template incorporates explicit steps for LLM to think, roughly formatted as:\\nThought: ...\\nAction: ...\\nObservation: ...\\n... (Repeated many times)\\n\\nFig. 2. Examples of reasoning trajectories for knowledge-intensive tasks (e.g. HotpotQA, FEVER) and decision-making tasks (e.g. AlfWorld Env, WebShop). (Image source: Yao et al. 2023).\\nIn both experiments on knowledge-intensive tasks and decision-making tasks, ReAct works better than the Act-only baseline where Thought: … step is removed.\\nReflexion (Shinn & Labash 2023) is a framework to equips agents with dynamic memory and self-reflection capabilities to improve reasoning skills. Reflexion has a standard RL setup, in which the reward model provides a simple binary reward and the action space follows the setup in ReAct where the task-specific action space is augmented with language to enable complex reasoning steps. After each action $a_t$, the agent computes a heuristic $h_t$ and optionally may decide to reset the environment to start a new trial depending on the self-reflection results.\\n\\nFig. 3. Illustration of the Reflexion framework. (Image source: Shinn & Labash, 2023)\\nThe heuristic function determines when the trajectory is inefficient or contains hallucination and should be stopped. Inefficient planning refers to trajectories that take too long without success. Hallucination is defined as encountering a sequence of consecutive identical actions that lead to the same observation in the environment.\\nSelf-reflection is created by showing two-shot examples to LLM and each example is a pair of (failed trajectory, ideal reflection for guiding future changes in the plan). Then reflections are added into the agent’s working memory, up to three, to be used as context for querying LLM.\\n\\nFig. 4. Experiments on AlfWorld Env and HotpotQA. Hallucination is a more common failure than inefficient planning in AlfWorld. (Image source: Shinn & Labash, 2023)\\nChain of Hindsight (CoH; Liu et al. 2023) encourages the model to improve on its own outputs by explicitly presenting it with a sequence of past outputs, each annotated with feedback. Human feedback data is a collection of $D_h = \\\\{(x, y_i , r_i , z_i)\\\\}_{i=1}^n$, where $x$ is the prompt, each $y_i$ is a model completion, $r_i$ is the human rating of $y_i$, and $z_i$ is the corresponding human-provided hindsight feedback. Assume the feedback tuples are ranked by reward, $r_n \\\\geq r_{n-1} \\\\geq \\\\dots \\\\geq r_1$ The process is supervised fine-tuning where the data is a sequence in the form of $\\\\tau_h = (x, z_i, y_i, z_j, y_j, \\\\dots, z_n, y_n)$, where $\\\\leq i \\\\leq j \\\\leq n$. The model is finetuned to only predict $y_n$ where conditioned on the sequence prefix, such that the model can self-reflect to produce better output based on the feedback sequence. The model can optionally receive multiple rounds of instructions with human annotators at test time.\\nTo avoid overfitting, CoH adds a regularization term to maximize the log-likelihood of the pre-training dataset. To avoid shortcutting and copying (because there are many common words in feedback sequences), they randomly mask 0% - 5% of past tokens during training.\\nThe training dataset in their experiments is a combination of WebGPT comparisons, summarization from human feedback and human preference dataset.\\n\\nFig. 5. After fine-tuning with CoH, the model can follow instructions to produce outputs with incremental improvement in a sequence. (Image source: Liu et al. 2023)\\nThe idea of CoH is to present a history of sequentially improved outputs in context and train the model to take on the trend to produce better outputs. Algorithm Distillation (AD; Laskin et al. 2023) applies the same idea to cross-episode trajectories in reinforcement learning tasks, where an algorithm is encapsulated in a long history-conditioned policy. Considering that an agent interacts with the environment many times and in each episode the agent gets a little better, AD concatenates this learning history and feeds that into the model. Hence we should expect the next predicted action to lead to better performance than previous trials. The goal is to learn the process of RL instead of training a task-specific policy itself.\\n\\nFig. 6. Illustration of how Algorithm Distillation (AD) works. (Image source: Laskin et al. 2023).\\nThe paper hypothesizes that any algorithm that generates a set of learning histories can be distilled into a neural network by performing behavioral cloning over actions. The history data is generated by a set of source policies, each trained for a specific task. At the training stage, during each RL run, a random task is sampled and a subsequence of multi-episode history is used for training, such that the learned policy is task-agnostic.\\nIn reality, the model has limited context window length, so episodes should be short enough to construct multi-episode history. Multi-episodic contexts of 2-4 episodes are necessary to learn a near-optimal in-context RL algorithm. The emergence of in-context RL requires long enough context.\\nIn comparison with three baselines, including ED (expert distillation, behavior cloning with expert trajectories instead of learning history), source policy (used for generating trajectories for distillation by UCB), RL^2 (Duan et al. 2017; used as upper bound since it needs online RL), AD demonstrates in-context RL with performance getting close to RL^2 despite only using offline RL and learns much faster than other baselines. When conditioned on partial training history of the source policy, AD also improves much faster than ED baseline.\\n\\nFig. 7. Comparison of AD, ED, source policy and RL^2 on environments that require memory and exploration. Only binary reward is assigned. The source policies are trained with A3C for \"dark\" environments and DQN for watermaze.(Image source: Laskin et al. 2023)\\nComponent Two: Memory#\\n(Big thank you to ChatGPT for helping me draft this section. I’ve learned a lot about the human brain and data structure for fast MIPS in my conversations with ChatGPT.)\\nTypes of Memory#\\nMemory can be defined as the processes used to acquire, store, retain, and later retrieve information. There are several types of memory in human brains.\\n\\n\\nSensory Memory: This is the earliest stage of memory, providing the ability to retain impressions of sensory information (visual, auditory, etc) after the original stimuli have ended. Sensory memory typically only lasts for up to a few seconds. Subcategories include iconic memory (visual), echoic memory (auditory), and haptic memory (touch).\\n\\n\\nShort-Term Memory (STM) or Working Memory: It stores information that we are currently aware of and needed to carry out complex cognitive tasks such as learning and reasoning. Short-term memory is believed to have the capacity of about 7 items (Miller 1956) and lasts for 20-30 seconds.\\n\\n\\nLong-Term Memory (LTM): Long-term memory can store information for a remarkably long time, ranging from a few days to decades, with an essentially unlimited storage capacity. There are two subtypes of LTM:\\n\\nExplicit / declarative memory: This is memory of facts and events, and refers to those memories that can be consciously recalled, including episodic memory (events and experiences) and semantic memory (facts and concepts).\\nImplicit / procedural memory: This type of memory is unconscious and involves skills and routines that are performed automatically, like riding a bike or typing on a keyboard.\\n\\n\\n\\n\\nFig. 8. Categorization of human memory.\\nWe can roughly consider the following mappings:\\n\\nSensory memory as learning embedding representations for raw inputs, including text, image or other modalities;\\nShort-term memory as in-context learning. It is short and finite, as it is restricted by the finite context window length of Transformer.\\nLong-term memory as the external vector store that the agent can attend to at query time, accessible via fast retrieval.\\n\\nMaximum Inner Product Search (MIPS)#\\nThe external memory can alleviate the restriction of finite attention span. A standard practice is to save the embedding representation of information into a vector store database that can support fast maximum inner-product search (MIPS). To optimize the retrieval speed, the common choice is the approximate nearest neighbors (ANN)\\u200b algorithm to return approximately top k nearest neighbors to trade off a little accuracy lost for a huge speedup.\\nA couple common choices of ANN algorithms for fast MIPS:\\n\\nLSH (Locality-Sensitive Hashing): It introduces a hashing function such that similar input items are mapped to the same buckets with high probability, where the number of buckets is much smaller than the number of inputs.\\nANNOY (Approximate Nearest Neighbors Oh Yeah): The core data structure are random projection trees, a set of binary trees where each non-leaf node represents a hyperplane splitting the input space into half and each leaf stores one data point. Trees are built independently and at random, so to some extent, it mimics a hashing function. ANNOY search happens in all the trees to iteratively search through the half that is closest to the query and then aggregates the results. The idea is quite related to KD tree but a lot more scalable.\\nHNSW (Hierarchical Navigable Small World): It is inspired by the idea of small world networks where most nodes can be reached by any other nodes within a small number of steps; e.g. “six degrees of separation” feature of social networks. HNSW builds hierarchical layers of these small-world graphs, where the bottom layers contain the actual data points. The layers in the middle create shortcuts to speed up search. When performing a search, HNSW starts from a random node in the top layer and navigates towards the target. When it can’t get any closer, it moves down to the next layer, until it reaches the bottom layer. Each move in the upper layers can potentially cover a large distance in the data space, and each move in the lower layers refines the search quality.\\nFAISS (Facebook AI Similarity Search): It operates on the assumption that in high dimensional space, distances between nodes follow a Gaussian distribution and thus there should exist clustering of data points. FAISS applies vector quantization by partitioning the vector space into clusters and then refining the quantization within clusters. Search first looks for cluster candidates with coarse quantization and then further looks into each cluster with finer quantization.\\nScaNN (Scalable Nearest Neighbors): The main innovation in ScaNN is anisotropic vector quantization. It quantizes a data point $x_i$ to $\\\\tilde{x}_i$ such that the inner product $\\\\langle q, x_i \\\\rangle$ is as similar to the original distance of $\\\\angle q, \\\\tilde{x}_i$ as possible, instead of picking the closet quantization centroid points.\\n\\n\\nFig. 9. Comparison of MIPS algorithms, measured in recall@10. (Image source: Google Blog, 2020)\\nCheck more MIPS algorithms and performance comparison in ann-benchmarks.com.\\nComponent Three: Tool Use#\\nTool use is a remarkable and distinguishing characteristic of human beings. We create, modify and utilize external objects to do things that go beyond our physical and cognitive limits. Equipping LLMs with external tools can significantly extend the model capabilities.\\n\\nFig. 10. A picture of a sea otter using rock to crack open a seashell, while floating in the water. While some other animals can use tools, the complexity is not comparable with humans. (Image source: Animals using tools)\\nMRKL (Karpas et al. 2022), short for “Modular Reasoning, Knowledge and Language”, is a neuro-symbolic architecture for autonomous agents. A MRKL system is proposed to contain a collection of “expert” modules and the general-purpose LLM works as a router to route inquiries to the best suitable expert module. These modules can be neural (e.g. deep learning models) or symbolic (e.g. math calculator, currency converter, weather API).\\nThey did an experiment on fine-tuning LLM to call a calculator, using arithmetic as a test case. Their experiments showed that it was harder to solve verbal math problems than explicitly stated math problems because LLMs (7B Jurassic1-large model) failed to extract the right arguments for the basic arithmetic reliably. The results highlight when the external symbolic tools can work reliably, knowing when to and how to use the tools are crucial, determined by the LLM capability.\\nBoth TALM (Tool Augmented Language Models; Parisi et al. 2022) and Toolformer (Schick et al. 2023) fine-tune a LM to learn to use external tool APIs. The dataset is expanded based on whether a newly added API call annotation can improve the quality of model outputs. See more details in the “External APIs” section of Prompt Engineering.\\nChatGPT Plugins and OpenAI API function calling are good examples of LLMs augmented with tool use capability working in practice. The collection of tool APIs can be provided by other developers (as in Plugins) or self-defined (as in function calls).\\nHuggingGPT (Shen et al. 2023) is a framework to use ChatGPT as the task planner to select models available in HuggingFace platform according to the model descriptions and summarize the response based on the execution results.\\n\\nFig. 11. Illustration of how HuggingGPT works. (Image source: Shen et al. 2023)\\nThe system comprises of 4 stages:\\n(1) Task planning: LLM works as the brain and parses the user requests into multiple tasks. There are four attributes associated with each task: task type, ID, dependencies, and arguments. They use few-shot examples to guide LLM to do task parsing and planning.\\nInstruction:\\n\\nThe AI assistant can parse user input to several tasks: [{\"task\": task, \"id\", task_id, \"dep\": dependency_task_ids, \"args\": {\"text\": text, \"image\": URL, \"audio\": URL, \"video\": URL}}]. The \"dep\" field denotes the id of the previous task which generates a new resource that the current task relies on. A special tag \"-task_id\" refers to the generated text image, audio and video in the dependency task with id as task_id. The task MUST be selected from the following options: {{ Available Task List }}. There is a logical relationship between tasks, please note their order. If the user input can\\'t be parsed, you need to reply empty JSON. Here are several cases for your reference: {{ Demonstrations }}. The chat history is recorded as {{ Chat History }}. From this chat history, you can find the path of the user-mentioned resources for your task planning.\\n\\n(2) Model selection: LLM distributes the tasks to expert models, where the request is framed as a multiple-choice question. LLM is presented with a list of models to choose from. Due to the limited context length, task type based filtration is needed.\\nInstruction:\\n\\nGiven the user request and the call command, the AI assistant helps the user to select a suitable model from a list of models to process the user request. The AI assistant merely outputs the model id of the most appropriate model. The output must be in a strict JSON format: \"id\": \"id\", \"reason\": \"your detail reason for the choice\". We have a list of models for you to choose from {{ Candidate Models }}. Please select one model from the list.\\n\\n(3) Task execution: Expert models execute on the specific tasks and log results.\\nInstruction:\\n\\nWith the input and the inference results, the AI assistant needs to describe the process and results. The previous stages can be formed as - User Input: {{ User Input }}, Task Planning: {{ Tasks }}, Model Selection: {{ Model Assignment }}, Task Execution: {{ Predictions }}. You must first answer the user\\'s request in a straightforward manner. Then describe the task process and show your analysis and model inference results to the user in the first person. If inference results contain a file path, must tell the user the complete file path.\\n\\n(4) Response generation: LLM receives the execution results and provides summarized results to users.\\nTo put HuggingGPT into real world usage, a couple challenges need to solve: (1) Efficiency improvement is needed as both LLM inference rounds and interactions with other models slow down the process; (2) It relies on a long context window to communicate over complicated task content; (3) Stability improvement of LLM outputs and external model services.\\nAPI-Bank (Li et al. 2023) is a benchmark for evaluating the performance of tool-augmented LLMs. It contains 53 commonly used API tools, a complete tool-augmented LLM workflow, and 264 annotated dialogues that involve 568 API calls. The selection of APIs is quite diverse, including search engines, calculator, calendar queries, smart home control, schedule management, health data management, account authentication workflow and more. Because there are a large number of APIs, LLM first has access to API search engine to find the right API to call and then uses the corresponding documentation to make a call.\\n\\nFig. 12. Pseudo code of how LLM makes an API call in API-Bank. (Image source: Li et al. 2023)\\nIn the API-Bank workflow, LLMs need to make a couple of decisions and at each step we can evaluate how accurate that decision is. Decisions include:\\n\\nWhether an API call is needed.\\nIdentify the right API to call: if not good enough, LLMs need to iteratively modify the API inputs (e.g. deciding search keywords for Search Engine API).\\nResponse based on the API results: the model can choose to refine and call again if results are not satisfied.\\n\\nThis benchmark evaluates the agent’s tool use capabilities at three levels:\\n\\nLevel-1 evaluates the ability to call the API. Given an API’s description, the model needs to determine whether to call a given API, call it correctly, and respond properly to API returns.\\nLevel-2 examines the ability to retrieve the API. The model needs to search for possible APIs that may solve the user’s requirement and learn how to use them by reading documentation.\\nLevel-3 assesses the ability to plan API beyond retrieve and call. Given unclear user requests (e.g. schedule group meetings, book flight/hotel/restaurant for a trip), the model may have to conduct multiple API calls to solve it.\\n\\nCase Studies#\\nScientific Discovery Agent#\\nChemCrow (Bran et al. 2023) is a domain-specific example in which LLM is augmented with 13 expert-designed tools to accomplish tasks across organic synthesis, drug discovery, and materials design. The workflow, implemented in LangChain, reflects what was previously described in the ReAct and MRKLs and combines CoT reasoning with tools relevant to the tasks:\\n\\nThe LLM is provided with a list of tool names, descriptions of their utility, and details about the expected input/output.\\nIt is then instructed to answer a user-given prompt using the tools provided when necessary. The instruction suggests the model to follow the ReAct format - Thought, Action, Action Input, Observation.\\n\\nOne interesting observation is that while the LLM-based evaluation concluded that GPT-4 and ChemCrow perform nearly equivalently, human evaluations with experts oriented towards the completion and chemical correctness of the solutions showed that ChemCrow outperforms GPT-4 by a large margin. This indicates a potential problem with using LLM to evaluate its own performance on domains that requires deep expertise. The lack of expertise may cause LLMs not knowing its flaws and thus cannot well judge the correctness of task results.\\nBoiko et al. (2023) also looked into LLM-empowered agents for scientific discovery, to handle autonomous design, planning, and performance of complex scientific experiments. This agent can use tools to browse the Internet, read documentation, execute code, call robotics experimentation APIs and leverage other LLMs.\\nFor example, when requested to \"develop a novel anticancer drug\", the model came up with the following reasoning steps:\\n\\ninquired about current trends in anticancer drug discovery;\\nselected a target;\\nrequested a scaffold targeting these compounds;\\nOnce the compound was identified, the model attempted its synthesis.\\n\\nThey also discussed the risks, especially with illicit drugs and bioweapons. They developed a test set containing a list of known chemical weapon agents and asked the agent to synthesize them. 4 out of 11 requests (36%) were accepted to obtain a synthesis solution and the agent attempted to consult documentation to execute the procedure. 7 out of 11 were rejected and among these 7 rejected cases, 5 happened after a Web search while 2 were rejected based on prompt only.\\nGenerative Agents Simulation#\\nGenerative Agents (Park, et al. 2023) is super fun experiment where 25 virtual characters, each controlled by a LLM-powered agent, are living and interacting in a sandbox environment, inspired by The Sims. Generative agents create believable simulacra of human behavior for interactive applications.\\nThe design of generative agents combines LLM with memory, planning and reflection mechanisms to enable agents to behave conditioned on past experience, as well as to interact with other agents.\\n\\nMemory stream: is a long-term memory module (external database) that records a comprehensive list of agents’ experience in natural language.\\n\\nEach element is an observation, an event directly provided by the agent.\\n- Inter-agent communication can trigger new natural language statements.\\n\\n\\nRetrieval model: surfaces the context to inform the agent’s behavior, according to relevance, recency and importance.\\n\\nRecency: recent events have higher scores\\nImportance: distinguish mundane from core memories. Ask LM directly.\\nRelevance: based on how related it is to the current situation / query.\\n\\n\\nReflection mechanism: synthesizes memories into higher level inferences over time and guides the agent’s future behavior. They are higher-level summaries of past events (<- note that this is a bit different from self-reflection above)\\n\\nPrompt LM with 100 most recent observations and to generate 3 most salient high-level questions given a set of observations/statements. Then ask LM to answer those questions.\\n\\n\\nPlanning & Reacting: translate the reflections and the environment information into actions\\n\\nPlanning is essentially in order to optimize believability at the moment vs in time.\\nPrompt template: {Intro of an agent X}. Here is X\\'s plan today in broad strokes: 1)\\nRelationships between agents and observations of one agent by another are all taken into consideration for planning and reacting.\\nEnvironment information is present in a tree structure.\\n\\n\\n\\n\\nFig. 13. The generative agent architecture. (Image source: Park et al. 2023)\\nThis fun simulation results in emergent social behavior, such as information diffusion, relationship memory (e.g. two agents continuing the conversation topic) and coordination of social events (e.g. host a party and invite many others).\\nProof-of-Concept Examples#\\nAutoGPT has drawn a lot of attention into the possibility of setting up autonomous agents with LLM as the main controller. It has quite a lot of reliability issues given the natural language interface, but nevertheless a cool proof-of-concept demo. A lot of code in AutoGPT is about format parsing.\\nHere is the system message used by AutoGPT, where {{...}} are user inputs:\\nYou are {{ai-name}}, {{user-provided AI bot description}}.\\nYour decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications.\\n\\nGOALS:\\n\\n1. {{user-provided goal 1}}\\n2. {{user-provided goal 2}}\\n3. ...\\n4. ...\\n5. ...\\n\\nConstraints:\\n1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.\\n2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.\\n3. No user assistance\\n4. Exclusively use the commands listed in double quotes e.g. \"command name\"\\n5. Use subprocesses for commands that will not terminate within a few minutes\\n\\nCommands:\\n1. Google Search: \"google\", args: \"input\": \"\"\\n2. Browse Website: \"browse_website\", args: \"url\": \"\", \"question\": \"\"\\n3. Start GPT Agent: \"start_agent\", args: \"name\": \"\", \"task\": \"\", \"prompt\": \"\"\\n4. Message GPT Agent: \"message_agent\", args: \"key\": \"\", \"message\": \"\"\\n5. List GPT Agents: \"list_agents\", args:\\n6. Delete GPT Agent: \"delete_agent\", args: \"key\": \"\"\\n7. Clone Repository: \"clone_repository\", args: \"repository_url\": \"\", \"clone_path\": \"\"\\n8. Write to file: \"write_to_file\", args: \"file\": \"\", \"text\": \"\"\\n9. Read file: \"read_file\", args: \"file\": \"\"\\n10. Append to file: \"append_to_file\", args: \"file\": \"\", \"text\": \"\"\\n11. Delete file: \"delete_file\", args: \"file\": \"\"\\n12. Search Files: \"search_files\", args: \"directory\": \"\"\\n13. Analyze Code: \"analyze_code\", args: \"code\": \"\"\\n14. Get Improved Code: \"improve_code\", args: \"suggestions\": \"\", \"code\": \"\"\\n15. Write Tests: \"write_tests\", args: \"code\": \"\", \"focus\": \"\"\\n16. Execute Python File: \"execute_python_file\", args: \"file\": \"\"\\n17. Generate Image: \"generate_image\", args: \"prompt\": \"\"\\n18. Send Tweet: \"send_tweet\", args: \"text\": \"\"\\n19. Do Nothing: \"do_nothing\", args:\\n20. Task Complete (Shutdown): \"task_complete\", args: \"reason\": \"\"\\n\\nResources:\\n1. Internet access for searches and information gathering.\\n2. Long Term memory management.\\n3. GPT-3.5 powered Agents for delegation of simple tasks.\\n4. File output.\\n\\nPerformance Evaluation:\\n1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.\\n2. Constructively self-criticize your big-picture behavior constantly.\\n3. Reflect on past decisions and strategies to refine your approach.\\n4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.\\n\\nYou should only respond in JSON format as described below\\nResponse Format:\\n{\\n \"thoughts\": {\\n \"text\": \"thought\",\\n \"reasoning\": \"reasoning\",\\n \"plan\": \"- short bulleted\\\\n- list that conveys\\\\n- long-term plan\",\\n \"criticism\": \"constructive self-criticism\",\\n \"speak\": \"thoughts summary to say to user\"\\n },\\n \"command\": {\\n \"name\": \"command name\",\\n \"args\": {\\n \"arg name\": \"value\"\\n }\\n }\\n}\\nEnsure the response can be parsed by Python json.loads\\nGPT-Engineer is another project to create a whole repository of code given a task specified in natural language. The GPT-Engineer is instructed to think over a list of smaller components to build and ask for user input to clarify questions as needed.\\nHere are a sample conversation for task clarification sent to OpenAI ChatCompletion endpoint used by GPT-Engineer. The user inputs are wrapped in {{user input text}}.\\n[\\n {\\n \"role\": \"system\",\\n \"content\": \"You will read instructions and not carry them out, only seek to clarify them.\\\\nSpecifically you will first summarise a list of super short bullets of areas that need clarification.\\\\nThen you will pick one clarifying question, and wait for an answer from the user.\\\\n\"\\n },\\n {\\n \"role\": \"user\",\\n \"content\": \"We are writing {{a Super Mario game in python. MVC components split in separate files. Keyboard control.}}\\\\n\"\\n },\\n {\\n \"role\": \"assistant\",\\n \"content\": \"Summary of areas that need clarification:\\\\n1. Specifics of the Super Mario game (e.g. level design, characters, gameplay mechanics)\\\\n2. Details about the MVC components (e.g. which components are in each file)\\\\n3. Keyboard control implementation (e.g. which keys to use, how to handle input)\\\\n\\\\nClarifying question:\\\\nCan you provide more details about the Super Mario game, such as level design, characters, and gameplay mechanics?\"\\n },\\n {\\n \"role\": \"user\",\\n \"content\": \"{{There are 10 levels in total. The main character is a plumber named Mario, who can walk and jump. It is a classical platform game just like Super Mario. The main character moves from left to right, trying to get to the destination, where there are many obstacles and attacks from enemies in the process.}}\\\\n\\\\nIs anything else unclear? If yes, only answer in the form:\\\\n{remaining unclear areas} remaining questions.\\\\n{Next question}\\\\nIf everything is sufficiently clear, only answer \\\\\"Nothing more to clarify.\\\\\".\"\\n },\\n {\\n \"role\": \"assistant\",\\n \"content\": \"Remaining unclear areas: 2 remaining questions.\\\\nCan you provide more information about how the MVC components are split into separate files?\"\\n },\\n {\\n \"role\": \"user\",\\n \"content\": \"{{Make your own assumptions and state them explicitly before starting}}\"\\n }\\n]\\nThen after these clarification, the agent moved into the code writing mode with a different system message.\\nSystem message:\\n\\nYou will get instructions for code to write.\\nYou will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.\\nMake sure that every detail of the architecture is, in the end, implemented as code.\\nThink step by step and reason yourself to the right decisions to make sure we get it right.\\nYou will first lay out the names of the core classes, functions, methods that will be necessary, as well as a quick comment on their purpose.\\nThen you will output the content of each file including ALL code.\\nEach file must strictly follow a markdown code block format, where the following tokens must be replaced such that\\nFILENAME is the lowercase file name including the file extension,\\nLANG is the markup code block language for the code’s language, and CODE is the code:\\nFILENAME\\nCODE\\nYou will start with the “entrypoint” file, then go to the ones that are imported by that file, and so on.\\nPlease note that the code should be fully functional. No placeholders.\\nFollow a language and framework appropriate best practice file naming convention.\\nMake sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.\\nEnsure to implement all code, if you are unsure, write a plausible implementation.\\nInclude module dependency or package manager dependency definition file.\\nBefore you finish, double check that all parts of the architecture is present in the files.\\nUseful to know:\\nYou almost always put different classes in different files.\\nFor Python, you always create an appropriate requirements.txt file.\\nFor NodeJS, you always create an appropriate package.json file.\\nYou always add a comment briefly describing the purpose of the function definition.\\nYou try to add comments explaining very complex bits of logic.\\nYou always follow the best practices for the requested languages in terms of describing the code written as a defined\\npackage/project.\\nPython toolbelt preferences:\\n\\npytest\\ndataclasses\\n\\n\\nConversatin samples:\\n[\\n {\\n \"role\": \"system\",\\n \"content\": \"You will get instructions for code to write.\\\\nYou will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.\\\\nMake sure that every detail of the architecture is, in the end, implemented as code.\\\\n\\\\nThink step by step and reason yourself to the right decisions to make sure we get it right.\\\\nYou will first lay out the names of the core classes, functions, methods that will be necessary, as well as a quick comment on their purpose.\\\\n\\\\nThen you will output the content of each file including ALL code.\\\\nEach file must strictly follow a markdown code block format, where the following tokens must be replaced such that\\\\nFILENAME is the lowercase file name including the file extension,\\\\nLANG is the markup code block language for the code\\'s language, and CODE is the code:\\\\n\\\\nFILENAME\\\\n```LANG\\\\nCODE\\\\n```\\\\n\\\\nYou will start with the \\\\\"entrypoint\\\\\" file, then go to the ones that are imported by that file, and so on.\\\\nPlease note that the code should be fully functional. No placeholders.\\\\n\\\\nFollow a language and framework appropriate best practice file naming convention.\\\\nMake sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.\\\\nEnsure to implement all code, if you are unsure, write a plausible implementation.\\\\nInclude module dependency or package manager dependency definition file.\\\\nBefore you finish, double check that all parts of the architecture is present in the files.\\\\n\\\\nUseful to know:\\\\nYou almost always put different classes in different files.\\\\nFor Python, you always create an appropriate requirements.txt file.\\\\nFor NodeJS, you always create an appropriate package.json file.\\\\nYou always add a comment briefly describing the purpose of the function definition.\\\\nYou try to add comments explaining very complex bits of logic.\\\\nYou always follow the best practices for the requested languages in terms of describing the code written as a defined\\\\npackage/project.\\\\n\\\\n\\\\nPython toolbelt preferences:\\\\n- pytest\\\\n- dataclasses\\\\n\"\\n },\\n # … same conversation as earlier, ended with \"Make your own assumptions and state them explicitly before starting\".\\n {\\n \"role\": \"assistant\",\\n \"content\": \"Assumptions:\\\\n1. Model: The model will contain the game\\'s data, such as level information, character states, and enemy positions.\\\\n2. View: The view will handle the game\\'s visuals, including rendering the game objects, backgrounds, and updating the display.\\\\n3. Controller: The controller will manage user input, such as keyboard controls, and update the model accordingly.\\\\n\\\\nWith these assumptions in mind, is there any specific aspect of the keyboard control implementation you would like me to clarify?\"\\n },\\n {\\n \"role\": \"user\",\\n \"content\": \"Please now remember the steps:\\\\n\\\\nThink step by step and reason yourself to the right decisions to make sure we get it right.\\\\nFirst lay out the names of the core classes, functions, methods that will be necessary, As well as a quick comment on their purpose.\\\\n\\\\nThen you will output the content of each file including ALL code.\\\\nEach file must strictly follow a markdown code block format, where the following tokens must be replaced such that\\\\nFILENAME is the lowercase file name including the file extension,\\\\nLANG is the markup code block language for the code\\'s language, and CODE is the code:\\\\n\\\\nFILENAME\\\\n```LANG\\\\nCODE\\\\n```\\\\n\\\\nPlease note that the code should be fully functional. No placeholders.\\\\n\\\\nYou will start with the \\\\\"entrypoint\\\\\" file, then go to the ones that are imported by that file, and so on.\\\\nFollow a language and framework appropriate best practice file naming convention.\\\\nMake sure that files contain all imports, types etc. The code should be fully functional. Make sure that code in different files are compatible with each other.\\\\nBefore you finish, double check that all parts of the architecture is present in the files.\\\\n\"\\n }\\n]\\nChallenges#\\nAfter going through key ideas and demos of building LLM-centered agents, I start to see a couple common limitations:\\n\\n\\nFinite context length: The restricted context capacity limits the inclusion of historical information, detailed instructions, API call context, and responses. The design of the system has to work with this limited communication bandwidth, while mechanisms like self-reflection to learn from past mistakes would benefit a lot from long or infinite context windows. Although vector stores and retrieval can provide access to a larger knowledge pool, their representation power is not as powerful as full attention.\\n\\n\\nChallenges in long-term planning and task decomposition: Planning over a lengthy history and effectively exploring the solution space remain challenging. LLMs struggle to adjust plans when faced with unexpected errors, making them less robust compared to humans who learn from trial and error.\\n\\n\\nReliability of natural language interface: Current agent system relies on natural language as an interface between LLMs and external components such as memory and tools. However, the reliability of model outputs is questionable, as LLMs may make formatting errors and occasionally exhibit rebellious behavior (e.g. refuse to follow an instruction). Consequently, much of the agent demo code focuses on parsing model output.\\n\\n\\nCitation#\\nCited as:\\n\\nWeng, Lilian. (Jun 2023). “LLM-powered Autonomous Agents”. Lil’Log. https://lilianweng.github.io/posts/2023-06-23-agent/.\\n\\nOr\\n@article{weng2023agent,\\n title = \"LLM-powered Autonomous Agents\",\\n author = \"Weng, Lilian\",\\n journal = \"lilianweng.github.io\",\\n year = \"2023\",\\n month = \"Jun\",\\n url = \"https://lilianweng.github.io/posts/2023-06-23-agent/\"\\n}\\nReferences#\\n[1] Wei et al. “Chain of thought prompting elicits reasoning in large language models.” NeurIPS 2022\\n[2] Yao et al. “Tree of Thoughts: Dliberate Problem Solving with Large Language Models.” arXiv preprint arXiv:2305.10601 (2023).\\n[3] Liu et al. “Chain of Hindsight Aligns Language Models with Feedback\\n“ arXiv preprint arXiv:2302.02676 (2023).\\n[4] Liu et al. “LLM+P: Empowering Large Language Models with Optimal Planning Proficiency” arXiv preprint arXiv:2304.11477 (2023).\\n[5] Yao et al. “ReAct: Synergizing reasoning and acting in language models.” ICLR 2023.\\n[6] Google Blog. “Announcing ScaNN: Efficient Vector Similarity Search” July 28, 2020.\\n[7] https://chat.openai.com/share/46ff149e-a4c7-4dd7-a800-fc4a642ea389\\n[8] Shinn & Labash. “Reflexion: an autonomous agent with dynamic memory and self-reflection” arXiv preprint arXiv:2303.11366 (2023).\\n[9] Laskin et al. “In-context Reinforcement Learning with Algorithm Distillation” ICLR 2023.\\n[10] Karpas et al. “MRKL Systems A modular, neuro-symbolic architecture that combines large language models, external knowledge sources and discrete reasoning.” arXiv preprint arXiv:2205.00445 (2022).\\n[11] Weaviate Blog. Why is Vector Search so fast? Sep 13, 2022.\\n[12] Li et al. “API-Bank: A Benchmark for Tool-Augmented LLMs” arXiv preprint arXiv:2304.08244 (2023).\\n[13] Shen et al. “HuggingGPT: Solving AI Tasks with ChatGPT and its Friends in HuggingFace” arXiv preprint arXiv:2303.17580 (2023).\\n[14] Bran et al. “ChemCrow: Augmenting large-language models with chemistry tools.” arXiv preprint arXiv:2304.05376 (2023).\\n[15] Boiko et al. “Emergent autonomous scientific research capabilities of large language models.” arXiv preprint arXiv:2304.05332 (2023).\\n[16] Joon Sung Park, et al. “Generative Agents: Interactive Simulacra of Human Behavior.” arXiv preprint arXiv:2304.03442 (2023).\\n[17] AutoGPT. https://github.com/Significant-Gravitas/Auto-GPT\\n[18] GPT-Engineer. https://github.com/AntonOsika/gpt-engineer\\n', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'})]"
71 | ]
72 | },
73 | "execution_count": 35,
74 | "metadata": {},
75 | "output_type": "execute_result"
76 | }
77 | ],
78 | "source": [
79 | "text_documents"
80 | ]
81 | },
82 | {
83 | "cell_type": "code",
84 | "execution_count": 36,
85 | "metadata": {},
86 | "outputs": [
87 | {
88 | "data": {
89 | "text/plain": [
90 | "[Document(page_content='LLM Powered Autonomous Agents\\n \\nDate: June 23, 2023 | Estimated Reading Time: 31 min | Author: Lilian Weng\\n\\n\\nBuilding agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview#\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
91 | " Document(page_content='Memory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
92 | " Document(page_content='Fig. 1. Overview of a LLM-powered autonomous agent system.\\nComponent One: Planning#\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.\\nTask Decomposition#\\nChain of thought (CoT; Wei et al. 2022) has become a standard prompting technique for enhancing model performance on complex tasks. The model is instructed to “think step by step” to utilize more test-time computation to decompose hard tasks into smaller and simpler steps. CoT transforms big tasks into multiple manageable tasks and shed lights into an interpretation of the model’s thinking process.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
93 | " Document(page_content='Tree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first decomposes the problem into multiple thought steps and generates multiple thoughts per step, creating a tree structure. The search process can be BFS (breadth-first search) or DFS (depth-first search) with each state evaluated by a classifier (via a prompt) or majority vote.\\nTask decomposition can be done (1) by LLM with simple prompting like \"Steps for XYZ.\\\\n1.\", \"What are the subgoals for achieving XYZ?\", (2) by using task-specific instructions; e.g. \"Write a story outline.\" for writing a novel, or (3) with human inputs.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
94 | " Document(page_content='Another quite distinct approach, LLM+P (Liu et al. 2023), involves relying on an external classical planner to do long-horizon planning. This approach utilizes the Planning Domain Definition Language (PDDL) as an intermediate interface to describe the planning problem. In this process, LLM (1) translates the problem into “Problem PDDL”, then (2) requests a classical planner to generate a PDDL plan based on an existing “Domain PDDL”, and finally (3) translates the PDDL plan back into natural language. Essentially, the planning step is outsourced to an external tool, assuming the availability of domain-specific PDDL and a suitable planner which is common in certain robotic setups but not in many other domains.\\nSelf-Reflection#\\nSelf-reflection is a vital aspect that allows autonomous agents to improve iteratively by refining past action decisions and correcting previous mistakes. It plays a crucial role in real-world tasks where trial and error are inevitable.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'})]"
95 | ]
96 | },
97 | "execution_count": 36,
98 | "metadata": {},
99 | "output_type": "execute_result"
100 | }
101 | ],
102 | "source": [
103 | "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
104 | "text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200)\n",
105 | "docs=text_splitter.split_documents(text_documents)\n",
106 | "docs[:5]"
107 | ]
108 | },
109 | {
110 | "cell_type": "code",
111 | "execution_count": 37,
112 | "metadata": {},
113 | "outputs": [],
114 | "source": [
115 | "## Convert Data Into Vectors and store in AstraDB\n",
116 | "os.environ[\"OPENAI_API_KEY\"]=os.getenv(\"OPENAI_API_KEY\")\n",
117 | "embeddings=OpenAIEmbeddings()\n",
118 | "astra_vector_store=Cassandra(\n",
119 | " embedding=embeddings,\n",
120 | " table_name=\"qa_mini_demo\",\n",
121 | " session=None,\n",
122 | " keyspace=None\n",
123 | "\n",
124 | ")"
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": 38,
130 | "metadata": {},
131 | "outputs": [
132 | {
133 | "name": "stdout",
134 | "output_type": "stream",
135 | "text": [
136 | "Inserted 66 headlines.\n"
137 | ]
138 | }
139 | ],
140 | "source": [
141 | "from langchain.indexes.vectorstore import VectorStoreIndexWrapper\n",
142 | "astra_vector_store.add_documents(docs)\n",
143 | "print(\"Inserted %i headlines.\" % len(docs))\n",
144 | "\n",
145 | "astra_vector_index = VectorStoreIndexWrapper(vectorstore=astra_vector_store)"
146 | ]
147 | },
148 | {
149 | "cell_type": "code",
150 | "execution_count": 39,
151 | "metadata": {},
152 | "outputs": [],
153 | "source": [
154 | "llm=ChatGroq(groq_api_key=groq_api_key,\n",
155 | " model_name=\"mixtral-8x7b-32768\")\n",
156 | "\n",
157 | "from langchain_core.prompts import ChatPromptTemplate\n",
158 | "prompt = ChatPromptTemplate.from_template(\"\"\"\n",
159 | "Answer the following question based only on the provided context. \n",
160 | "Think step by step before providing a detailed answer. \n",
161 | "I will tip you $1000 if the user finds the answer helpful. \n",
162 | "\n",
163 | "{context}\n",
164 | "\n",
165 | "\n",
166 | "Question: {input}\"\"\")"
167 | ]
168 | },
169 | {
170 | "cell_type": "code",
171 | "execution_count": 40,
172 | "metadata": {},
173 | "outputs": [
174 | {
175 | "data": {
176 | "text/plain": [
177 | "'Chain of Thought (CoT) is a prompting technique introduced by Wei et al. in 2022 that has become a standard method for enhancing model performance on complex tasks. The main idea behind CoT is to instruct the model to \"think step by step,\" thereby utilizing more computational resources during test time. This approach decomposes complex tasks into smaller, more manageable steps, providing insights into the model\\'s thinking process. By breaking down tasks and generating step-by-step solutions, CoT has proven to be an effective technique for addressing complex problems within the limitations of the model\\'s capabilities.'"
178 | ]
179 | },
180 | "execution_count": 40,
181 | "metadata": {},
182 | "output_type": "execute_result"
183 | }
184 | ],
185 | "source": [
186 | "astra_vector_index.query(\"Chain of thought (CoT; Wei et al. 2022) has become a standard prompting technique\",llm=llm)"
187 | ]
188 | },
189 | {
190 | "cell_type": "code",
191 | "execution_count": 41,
192 | "metadata": {},
193 | "outputs": [],
194 | "source": [
195 | "from langchain.chains import create_retrieval_chain\n",
196 | "from langchain.chains.combine_documents import create_stuff_documents_chain\n",
197 | "\n",
198 | "retriever=astra_vector_store.as_retriever()\n",
199 | "document_chain=create_stuff_documents_chain(llm,prompt)\n",
200 | "retrieval_chain=create_retrieval_chain(retriever,document_chain)"
201 | ]
202 | },
203 | {
204 | "cell_type": "code",
205 | "execution_count": 43,
206 | "metadata": {},
207 | "outputs": [
208 | {
209 | "data": {
210 | "text/plain": [
211 | "{'input': 'Chain of thought (CoT; Wei et al. 2022) has become a standard prompting technique',\n",
212 | " 'context': [Document(page_content='Tree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first decomposes the problem into multiple thought steps and generates multiple thoughts per step, creating a tree structure. The search process can be BFS (breadth-first search) or DFS (depth-first search) with each state evaluated by a classifier (via a prompt) or majority vote.\\nTask decomposition can be done (1) by LLM with simple prompting like \"Steps for XYZ.\\\\n1.\", \"What are the subgoals for achieving XYZ?\", (2) by using task-specific instructions; e.g. \"Write a story outline.\" for writing a novel, or (3) with human inputs.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
213 | " Document(page_content='Fig. 1. Overview of a LLM-powered autonomous agent system.\\nComponent One: Planning#\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.\\nTask Decomposition#\\nChain of thought (CoT; Wei et al. 2022) has become a standard prompting technique for enhancing model performance on complex tasks. The model is instructed to “think step by step” to utilize more test-time computation to decompose hard tasks into smaller and simpler steps. CoT transforms big tasks into multiple manageable tasks and shed lights into an interpretation of the model’s thinking process.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
214 | " Document(page_content='Chain of Hindsight (CoH; Liu et al. 2023) encourages the model to improve on its own outputs by explicitly presenting it with a sequence of past outputs, each annotated with feedback. Human feedback data is a collection of $D_h = \\\\{(x, y_i , r_i , z_i)\\\\}_{i=1}^n$, where $x$ is the prompt, each $y_i$ is a model completion, $r_i$ is the human rating of $y_i$, and $z_i$ is the corresponding human-provided hindsight feedback. Assume the feedback tuples are ranked by reward, $r_n \\\\geq r_{n-1} \\\\geq \\\\dots \\\\geq r_1$ The process is supervised fine-tuning where the data is a sequence in the form of $\\\\tau_h = (x, z_i, y_i, z_j, y_j, \\\\dots, z_n, y_n)$, where $\\\\leq i \\\\leq j \\\\leq n$. The model is finetuned to only predict $y_n$ where conditioned on the sequence prefix, such that the model can self-reflect to produce better output based on the feedback sequence. The model can optionally receive multiple rounds of instructions with human annotators at test time.', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'}),\n",
215 | " Document(page_content='ReAct (Yao et al. 2023) integrates reasoning and acting within LLM by extending the action space to be a combination of task-specific discrete actions and the language space. The former enables LLM to interact with the environment (e.g. use Wikipedia search API), while the latter prompting LLM to generate reasoning traces in natural language.\\nThe ReAct prompt template incorporates explicit steps for LLM to think, roughly formatted as:\\nThought: ...\\nAction: ...\\nObservation: ...\\n... (Repeated many times)', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/'})],\n",
216 | " 'answer': 'The Chain of Thought (CoT) is a standard prompting technique introduced by Wei et al. in 2022, which enhances model performance on complex tasks. The main idea behind CoT is to instruct the model to \"think step by step,\" thereby utilizing more test-time computation to decompose hard tasks into smaller and more manageable tasks. This approach sheds light on the model\\'s thinking process and transforms complex tasks into a series of simpler, more approachable sub-tasks.\\n\\nIn the context of AI and language models, the CoT technique helps to break down complex problems into a chain of smaller, interconnected thoughts, allowing the model to tackle each step more effectively. This method can be applied to various tasks, such as mathematical problem-solving, text generation, or understanding complex instructions. By following the chain of thought, the model can better navigate complex problem-solving scenarios, making it a valuable tool for improving language model performance and understanding.'}"
217 | ]
218 | },
219 | "execution_count": 43,
220 | "metadata": {},
221 | "output_type": "execute_result"
222 | }
223 | ],
224 | "source": [
225 | "response=retrieval_chain.invoke({\"input\":\"Chain of thought (CoT; Wei et al. 2022) has become a standard prompting technique\"})\n",
226 | "response"
227 | ]
228 | },
229 | {
230 | "cell_type": "code",
231 | "execution_count": 44,
232 | "metadata": {},
233 | "outputs": [
234 | {
235 | "data": {
236 | "text/plain": [
237 | "'The Chain of Thought (CoT) is a standard prompting technique introduced by Wei et al. in 2022, which enhances model performance on complex tasks. The main idea behind CoT is to instruct the model to \"think step by step,\" thereby utilizing more test-time computation to decompose hard tasks into smaller and more manageable tasks. This approach sheds light on the model\\'s thinking process and transforms complex tasks into a series of simpler, more approachable sub-tasks.\\n\\nIn the context of AI and language models, the CoT technique helps to break down complex problems into a chain of smaller, interconnected thoughts, allowing the model to tackle each step more effectively. This method can be applied to various tasks, such as mathematical problem-solving, text generation, or understanding complex instructions. By following the chain of thought, the model can better navigate complex problem-solving scenarios, making it a valuable tool for improving language model performance and understanding.'"
238 | ]
239 | },
240 | "execution_count": 44,
241 | "metadata": {},
242 | "output_type": "execute_result"
243 | }
244 | ],
245 | "source": [
246 | "response[\"answer\"]"
247 | ]
248 | },
249 | {
250 | "cell_type": "code",
251 | "execution_count": null,
252 | "metadata": {},
253 | "outputs": [],
254 | "source": []
255 | }
256 | ],
257 | "metadata": {
258 | "kernelspec": {
259 | "display_name": "Python 3",
260 | "language": "python",
261 | "name": "python3"
262 | },
263 | "language_info": {
264 | "codemirror_mode": {
265 | "name": "ipython",
266 | "version": 3
267 | },
268 | "file_extension": ".py",
269 | "mimetype": "text/x-python",
270 | "name": "python",
271 | "nbconvert_exporter": "python",
272 | "pygments_lexer": "ipython3",
273 | "version": "3.10.0"
274 | }
275 | },
276 | "nbformat": 4,
277 | "nbformat_minor": 2
278 | }
279 |
--------------------------------------------------------------------------------
/groq/llama3.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import os
3 | from langchain_groq import ChatGroq
4 | from langchain_openai import OpenAIEmbeddings
5 | from langchain.text_splitter import RecursiveCharacterTextSplitter
6 | from langchain.chains.combine_documents import create_stuff_documents_chain
7 | from langchain_core.prompts import ChatPromptTemplate
8 | from langchain.chains import create_retrieval_chain
9 | from langchain_community.vectorstores import FAISS
10 | from langchain_community.document_loaders import PyPDFDirectoryLoader
11 |
12 | from dotenv import load_dotenv
13 |
14 | load_dotenv()
15 |
16 | ## load the GROQ And OpenAI API KEY
17 | os.environ['OPENAI_API_KEY']=os.getenv("OPENAI_API_KEY")
18 | groq_api_key=os.getenv('GROQ_API_KEY')
19 |
20 | st.title("Chatgroq With Llama3 Demo")
21 |
22 | llm=ChatGroq(groq_api_key=groq_api_key,
23 | model_name="Llama3-8b-8192")
24 |
25 | prompt=ChatPromptTemplate.from_template(
26 | """
27 | Answer the questions based on the provided context only.
28 | Please provide the most accurate response based on the question
29 |
30 | {context}
31 |
32 | Questions:{input}
33 |
34 | """
35 | )
36 |
37 | def vector_embedding():
38 |
39 | if "vectors" not in st.session_state:
40 |
41 | st.session_state.embeddings=OpenAIEmbeddings()
42 | st.session_state.loader=PyPDFDirectoryLoader("./us_census") ## Data Ingestion
43 | st.session_state.docs=st.session_state.loader.load() ## Document Loading
44 | st.session_state.text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200) ## Chunk Creation
45 | st.session_state.final_documents=st.session_state.text_splitter.split_documents(st.session_state.docs[:20]) #splitting
46 | st.session_state.vectors=FAISS.from_documents(st.session_state.final_documents,st.session_state.embeddings) #vector OpenAI embeddings
47 |
48 |
49 |
50 |
51 |
52 | prompt1=st.text_input("Enter Your Question From Doduments")
53 |
54 |
55 | if st.button("Documents Embedding"):
56 | vector_embedding()
57 | st.write("Vector Store DB Is Ready")
58 |
59 | import time
60 |
61 |
62 |
63 | if prompt1:
64 | document_chain=create_stuff_documents_chain(llm,prompt)
65 | retriever=st.session_state.vectors.as_retriever()
66 | retrieval_chain=create_retrieval_chain(retriever,document_chain)
67 | start=time.process_time()
68 | response=retrieval_chain.invoke({'input':prompt1})
69 | print("Response time :",time.process_time()-start)
70 | st.write(response['answer'])
71 |
72 | # With a streamlit expander
73 | with st.expander("Document Similarity Search"):
74 | # Find the relevant chunks
75 | for i, doc in enumerate(response["context"]):
76 | st.write(doc.page_content)
77 | st.write("--------------------------------")
78 |
79 |
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/huggingface/huggingface.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 2,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "from langchain_community.document_loaders import PyPDFLoader\n",
10 | "from langchain_community.document_loaders import PyPDFDirectoryLoader\n",
11 | "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
12 | "from langchain_community.vectorstores import FAISS\n",
13 | "\n",
14 | "from langchain_community.embeddings import HuggingFaceBgeEmbeddings\n",
15 | "from langchain.prompts import PromptTemplate\n",
16 | "\n",
17 | "from langchain.chains import RetrievalQA\n",
18 | "\n"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": 4,
24 | "metadata": {},
25 | "outputs": [
26 | {
27 | "data": {
28 | "text/plain": [
29 | "Document(page_content='Health Insurance Coverage Status and Type \\nby Geography: 2021 and 2022\\nAmerican Community Survey Briefs\\nACSBR-015Issued September 2023Douglas Conway and Breauna Branch\\nINTRODUCTION\\nDemographic shifts as well as economic and govern-\\nment policy changes can affect people’s access to health coverage. For example, between 2021 and 2022, the labor market continued to improve, which may have affected private coverage in the United States \\nduring that time.\\n1 Public policy changes included \\nthe renewal of the Public Health Emergency, which \\nallowed Medicaid enrollees to remain covered under the Continuous Enrollment Provision.\\n2 The American \\nRescue Plan (ARP) enhanced Marketplace premium subsidies for those with incomes above 400 percent of the poverty level as well as for unemployed people.\\n3', metadata={'source': 'us_census\\\\acsbr-015.pdf', 'page': 0})"
30 | ]
31 | },
32 | "execution_count": 4,
33 | "metadata": {},
34 | "output_type": "execute_result"
35 | }
36 | ],
37 | "source": [
38 | "## Read the ppdfs from the folder\n",
39 | "loader=PyPDFDirectoryLoader(\"./us_census\")\n",
40 | "\n",
41 | "documents=loader.load()\n",
42 | "\n",
43 | "text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200)\n",
44 | "\n",
45 | "final_documents=text_splitter.split_documents(documents)\n",
46 | "final_documents[0]"
47 | ]
48 | },
49 | {
50 | "cell_type": "code",
51 | "execution_count": 5,
52 | "metadata": {},
53 | "outputs": [
54 | {
55 | "data": {
56 | "text/plain": [
57 | "316"
58 | ]
59 | },
60 | "execution_count": 5,
61 | "metadata": {},
62 | "output_type": "execute_result"
63 | }
64 | ],
65 | "source": [
66 | "len(final_documents)"
67 | ]
68 | },
69 | {
70 | "cell_type": "code",
71 | "execution_count": 8,
72 | "metadata": {},
73 | "outputs": [
74 | {
75 | "name": "stderr",
76 | "output_type": "stream",
77 | "text": [
78 | "e:\\Langchain\\venv\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
79 | " from .autonotebook import tqdm as notebook_tqdm\n"
80 | ]
81 | }
82 | ],
83 | "source": [
84 | "## Embedding Using Huggingface\n",
85 | "huggingface_embeddings=HuggingFaceBgeEmbeddings(\n",
86 | " model_name=\"BAAI/bge-small-en-v1.5\", #sentence-transformers/all-MiniLM-l6-v2\n",
87 | " model_kwargs={'device':'cpu'},\n",
88 | " encode_kwargs={'normalize_embeddings':True}\n",
89 | "\n",
90 | ")"
91 | ]
92 | },
93 | {
94 | "cell_type": "code",
95 | "execution_count": 10,
96 | "metadata": {},
97 | "outputs": [
98 | {
99 | "name": "stdout",
100 | "output_type": "stream",
101 | "text": [
102 | "[-8.46568644e-02 -1.19099217e-02 -3.37892585e-02 2.94559337e-02\n",
103 | " 5.19159958e-02 5.73839322e-02 -4.10017520e-02 2.74268016e-02\n",
104 | " -1.05128214e-01 -1.58056132e-02 7.94858634e-02 5.64318486e-02\n",
105 | " -1.31765157e-02 -3.41543928e-02 5.81604475e-03 4.72547710e-02\n",
106 | " -1.30746774e-02 3.12988879e-03 -3.44225690e-02 3.08406260e-02\n",
107 | " -4.09086421e-02 3.52737904e-02 -2.43761651e-02 -4.35831733e-02\n",
108 | " 2.41503324e-02 1.31986588e-02 -4.84452769e-03 1.92347374e-02\n",
109 | " -5.43912649e-02 -1.42735064e-01 5.15528210e-03 2.93115843e-02\n",
110 | " -5.60810715e-02 -8.53536371e-03 3.14141326e-02 2.76736189e-02\n",
111 | " -2.06188373e-02 8.24231505e-02 4.15425114e-02 5.79654835e-02\n",
112 | " -3.71587239e-02 6.26157876e-03 -2.41390076e-02 -5.61792636e-03\n",
113 | " -2.51715183e-02 5.04967198e-03 -2.52801236e-02 -2.91945064e-03\n",
114 | " -8.24046135e-03 -5.69604561e-02 2.30822619e-02 -5.54219959e-03\n",
115 | " 5.11555411e-02 6.09937944e-02 6.49766475e-02 -5.38514033e-02\n",
116 | " 2.19109710e-02 -2.54194364e-02 -4.49223518e-02 4.22459245e-02\n",
117 | " 4.75252084e-02 7.23217207e-04 -2.61084497e-01 9.30173397e-02\n",
118 | " 1.13597196e-02 4.90668938e-02 -1.06287086e-02 -8.08727555e-03\n",
119 | " -1.53562622e-02 -5.33785969e-02 -6.89967200e-02 4.75178175e-02\n",
120 | " -5.68596013e-02 9.38643236e-03 4.24065925e-02 2.54346598e-02\n",
121 | " 9.67096724e-03 7.90799968e-03 2.25160886e-02 1.91007671e-03\n",
122 | " 3.06091923e-02 2.43992303e-02 -1.34115480e-02 -4.77401279e-02\n",
123 | " 4.89939749e-02 -9.49416459e-02 5.62894158e-02 -4.76260781e-02\n",
124 | " 2.81447303e-02 -2.54329499e-02 -3.84951308e-02 1.00940112e-02\n",
125 | " 1.90582985e-04 3.36625241e-02 1.00181838e-02 2.83524077e-02\n",
126 | " -2.68963701e-03 -6.96359901e-03 -3.54914516e-02 3.42758894e-01\n",
127 | " -1.94496289e-02 1.43988123e-02 -5.68810571e-03 1.71480775e-02\n",
128 | " -2.88607483e-03 -5.81653193e-02 6.35178352e-04 5.17297909e-03\n",
129 | " 2.06331387e-02 1.65708251e-02 2.15096809e-02 -2.38796007e-02\n",
130 | " 2.89275143e-02 4.67319153e-02 -3.56104821e-02 -1.05078742e-02\n",
131 | " 3.70704755e-02 1.57502498e-02 9.43095461e-02 -2.50715371e-02\n",
132 | " -9.55965184e-03 1.78565886e-02 -9.41779092e-03 -4.57858741e-02\n",
133 | " 1.82930417e-02 5.81431836e-02 4.94311154e-02 1.46350682e-01\n",
134 | " 2.16057692e-02 -3.92896198e-02 1.03241250e-01 -3.48299928e-02\n",
135 | " -6.61871349e-03 7.07991235e-03 9.26990295e-04 4.49867966e-03\n",
136 | " -2.89777480e-02 4.02419232e-02 -5.23192994e-03 4.59961966e-02\n",
137 | " 4.23976406e-03 -4.83790739e-03 -3.23238224e-03 -1.41072914e-01\n",
138 | " -3.76811475e-02 1.83623895e-01 -2.96609867e-02 4.90660444e-02\n",
139 | " 3.90551575e-02 -1.57757346e-02 -3.86351012e-02 4.65630889e-02\n",
140 | " -2.43486036e-02 3.57695147e-02 -3.54947336e-02 2.36265883e-02\n",
141 | " -3.41984764e-04 3.11703496e-02 -2.39356644e-02 -5.94757982e-02\n",
142 | " 6.06259257e-02 -3.81902158e-02 -7.04255328e-02 1.42479865e-02\n",
143 | " 3.34432051e-02 -3.85255218e-02 -1.71951596e-02 -7.12288395e-02\n",
144 | " 2.64976211e-02 1.09495688e-02 1.32650323e-02 3.89527939e-02\n",
145 | " 1.60355382e-02 -3.17630395e-02 1.02013692e-01 2.92911958e-02\n",
146 | " -2.29205769e-02 -8.38053040e-03 -1.72173064e-02 -6.78820610e-02\n",
147 | " 5.39418403e-03 -2.32346989e-02 -6.07407168e-02 -3.86575758e-02\n",
148 | " -1.54306367e-02 -3.84982936e-02 -5.02867699e-02 5.04235253e-02\n",
149 | " 4.94898260e-02 -1.41083300e-02 -2.98144598e-03 9.76440133e-05\n",
150 | " -6.59190416e-02 3.01006734e-02 -5.46592870e-04 -1.64787639e-02\n",
151 | " -5.21614477e-02 -3.30222957e-03 4.75748219e-02 -3.40808518e-02\n",
152 | " -2.98659913e-02 2.75014956e-02 5.90203749e-03 -2.64040008e-03\n",
153 | " -1.61242671e-02 2.05222610e-02 1.21105220e-02 -5.49782291e-02\n",
154 | " 5.10389581e-02 -7.92088546e-03 7.25206453e-03 3.51751335e-02\n",
155 | " 3.66276912e-02 5.67682087e-04 2.60788649e-02 2.50971057e-02\n",
156 | " 1.14481300e-02 -2.54925024e-02 1.96417440e-02 2.84220409e-02\n",
157 | " 2.82554235e-02 6.57489598e-02 9.26554129e-02 -2.68629670e-01\n",
158 | " -8.90553114e-04 3.16917268e-03 5.08358562e-03 -6.42101169e-02\n",
159 | " -4.56614904e-02 -4.62259948e-02 3.60924639e-02 8.29056371e-03\n",
160 | " 8.92349407e-02 5.68022132e-02 6.91062305e-03 -1.08684311e-02\n",
161 | " 9.36060175e-02 1.03680165e-02 -8.60929266e-02 1.77331921e-02\n",
162 | " -2.00802702e-02 -1.85124874e-02 5.62404632e-04 -9.38337017e-03\n",
163 | " 7.76061229e-03 -5.37273772e-02 -2.30028406e-02 7.48890713e-02\n",
164 | " -1.29693234e-02 6.53716922e-02 -4.24983352e-02 -7.10293651e-02\n",
165 | " -1.56803615e-02 -6.23028576e-02 5.36034741e-02 -6.53212238e-03\n",
166 | " -1.15985490e-01 6.70967922e-02 1.93367060e-02 -6.67827874e-02\n",
167 | " -2.01754435e-03 -6.27636909e-02 -2.95005478e-02 -2.71986630e-02\n",
168 | " 4.49796803e-02 -6.61587194e-02 2.13751234e-02 -2.94077471e-02\n",
169 | " -5.71503267e-02 4.05282490e-02 7.11039603e-02 -6.80165365e-02\n",
170 | " 2.11908873e-02 1.30515285e-02 -2.91152820e-02 -2.25581583e-02\n",
171 | " -1.60188414e-02 3.20554040e-02 -5.89460693e-02 -2.97131632e-02\n",
172 | " 3.42681594e-02 -1.58376191e-02 -9.31771472e-03 3.59834097e-02\n",
173 | " 3.65337380e-03 4.73319739e-02 -1.06235184e-02 -8.69734772e-03\n",
174 | " -4.38009948e-02 5.94554143e-03 -2.41493657e-02 -7.79940188e-02\n",
175 | " 1.46542490e-02 1.05613861e-02 5.45365028e-02 -3.17896828e-02\n",
176 | " -1.26762642e-02 7.92561378e-03 -1.38133150e-02 5.01396768e-02\n",
177 | " -7.28576025e-03 -5.23702893e-03 -5.32640517e-02 4.78208959e-02\n",
178 | " -5.38353659e-02 1.11437477e-02 3.96674089e-02 -1.93496253e-02\n",
179 | " 9.94823873e-03 -3.53479455e-03 3.58561263e-03 -9.61500779e-03\n",
180 | " 2.15323791e-02 -1.82350334e-02 -2.15188656e-02 -1.38835954e-02\n",
181 | " -1.76698975e-02 3.38015234e-04 -3.84854589e-04 -2.25800529e-01\n",
182 | " 4.51243371e-02 1.53376386e-02 -1.76966917e-02 -1.42525993e-02\n",
183 | " -7.00285891e-03 -3.13724913e-02 2.13672244e-03 -9.28345323e-03\n",
184 | " -1.66986901e-02 4.66264114e-02 7.71809518e-02 1.26696959e-01\n",
185 | " -1.83595419e-02 -1.39637077e-02 -1.23306655e-03 5.93339056e-02\n",
186 | " -1.37463736e-03 1.98233537e-02 -2.92635858e-02 4.96656746e-02\n",
187 | " -6.07207343e-02 1.53544754e-01 -4.67309207e-02 1.97028890e-02\n",
188 | " -7.67833516e-02 -7.73231685e-03 3.71618718e-02 -3.00591048e-02\n",
189 | " 8.30263086e-03 2.06259061e-02 1.97466253e-03 3.39764208e-02\n",
190 | " -1.70869529e-02 4.84796055e-02 1.20781595e-02 1.24999117e-02\n",
191 | " 5.61724417e-02 9.88546945e-03 2.13879198e-02 -4.25293520e-02\n",
192 | " -1.94036588e-02 2.47837696e-02 1.37260715e-02 6.41119629e-02\n",
193 | " -2.84481011e-02 -4.64116633e-02 -5.36255538e-02 -6.95093986e-05\n",
194 | " 6.45710081e-02 -4.32005967e-04 -1.32471016e-02 5.85135119e-03\n",
195 | " 1.48595814e-02 -5.41847497e-02 -2.02038661e-02 -5.98262921e-02\n",
196 | " 3.67029347e-02 1.43319997e-03 -8.64463206e-03 2.90671345e-02\n",
197 | " 4.38365377e-02 -7.64942840e-02 1.55717917e-02 6.65831119e-02]\n",
198 | "(384,)\n"
199 | ]
200 | }
201 | ],
202 | "source": [
203 | "import numpy as np\n",
204 | "print(np.array(huggingface_embeddings.embed_query(final_documents[0].page_content)))\n",
205 | "print(np.array(huggingface_embeddings.embed_query(final_documents[0].page_content)).shape)"
206 | ]
207 | },
208 | {
209 | "cell_type": "code",
210 | "execution_count": 11,
211 | "metadata": {},
212 | "outputs": [],
213 | "source": [
214 | "## VectorStore Creation\n",
215 | "vectorstore=FAISS.from_documents(final_documents[:120],huggingface_embeddings)"
216 | ]
217 | },
218 | {
219 | "cell_type": "code",
220 | "execution_count": 14,
221 | "metadata": {},
222 | "outputs": [
223 | {
224 | "name": "stdout",
225 | "output_type": "stream",
226 | "text": [
227 | "2 U.S. Census Bureau\n",
228 | "WHAT IS HEALTH INSURANCE COVERAGE?\n",
229 | "This brief presents state-level estimates of health insurance coverage \n",
230 | "using data from the American Community Survey (ACS). The \n",
231 | "U.S. Census Bureau conducts the ACS throughout the year; the \n",
232 | "survey asks respondents to report their coverage at the time of \n",
233 | "interview. The resulting measure of health insurance coverage, \n",
234 | "therefore, reflects an annual average of current comprehensive \n",
235 | "health insurance coverage status.* This uninsured rate measures a \n",
236 | "different concept than the measure based on the Current Population \n",
237 | "Survey Annual Social and Economic Supplement (CPS ASEC). \n",
238 | "For reporting purposes, the ACS broadly classifies health insurance \n",
239 | "coverage as private insurance or public insurance. The ACS defines \n",
240 | "private health insurance as a plan provided through an employer \n",
241 | "or a union, coverage purchased directly by an individual from an \n",
242 | "insurance company or through an exchange (such as healthcare.\n"
243 | ]
244 | }
245 | ],
246 | "source": [
247 | "## Query using Similarity Search\n",
248 | "query=\"WHAT IS HEALTH INSURANCE COVERAGE?\"\n",
249 | "relevant_docments=vectorstore.similarity_search(query)\n",
250 | "\n",
251 | "print(relevant_docments[0].page_content)"
252 | ]
253 | },
254 | {
255 | "cell_type": "code",
256 | "execution_count": 15,
257 | "metadata": {},
258 | "outputs": [
259 | {
260 | "name": "stdout",
261 | "output_type": "stream",
262 | "text": [
263 | "tags=['FAISS', 'HuggingFaceBgeEmbeddings'] vectorstore= search_kwargs={'k': 3}\n"
264 | ]
265 | }
266 | ],
267 | "source": [
268 | "retriever=vectorstore.as_retriever(search_type=\"similarity\",search_kwargs={\"k\":3})\n",
269 | "print(retriever)"
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "execution_count": 16,
275 | "metadata": {},
276 | "outputs": [],
277 | "source": [
278 | "import os\n",
279 | "os.environ['HUGGINGFACEHUB_API_TOKEN']=\"\""
280 | ]
281 | },
282 | {
283 | "cell_type": "markdown",
284 | "metadata": {},
285 | "source": [
286 | "The Hugging Face Hub is an platform with over 350k models, 75k datasets, and 150k demo apps (Spaces), all open source and publicly available, in an online platform where people can easily collaborate and build ML together."
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": 17,
292 | "metadata": {},
293 | "outputs": [
294 | {
295 | "name": "stderr",
296 | "output_type": "stream",
297 | "text": [
298 | "e:\\Langchain\\venv\\lib\\site-packages\\langchain_core\\_api\\deprecation.py:117: LangChainDeprecationWarning: The class `langchain_community.llms.huggingface_hub.HuggingFaceHub` was deprecated in langchain-community 0.0.21 and will be removed in 0.2.0. Use HuggingFaceEndpoint instead.\n",
299 | " warn_deprecated(\n"
300 | ]
301 | },
302 | {
303 | "data": {
304 | "text/plain": [
305 | "'What is the health insurance coverage?\\n\\nThe health insurance coverage is a contract between the insurer and the insured. The insurer agrees to pay the insured for the medical expenses incurred by the insured. The insured agrees to pay the premium to the insurer.\\n\\nWhat is the health insurance coverage?\\n\\nThe health insurance coverage is a contract between the insurer and the insured. The insurer agrees to pay the insured for the medical expenses incurred by the insured.'"
306 | ]
307 | },
308 | "execution_count": 17,
309 | "metadata": {},
310 | "output_type": "execute_result"
311 | }
312 | ],
313 | "source": [
314 | "from langchain_community.llms import HuggingFaceHub\n",
315 | "\n",
316 | "hf=HuggingFaceHub(\n",
317 | " repo_id=\"mistralai/Mistral-7B-v0.1\",\n",
318 | " model_kwargs={\"temperature\":0.1,\"max_length\":500}\n",
319 | "\n",
320 | ")\n",
321 | "query=\"What is the health insurance coverage?\"\n",
322 | "hf.invoke(query)"
323 | ]
324 | },
325 | {
326 | "cell_type": "code",
327 | "execution_count": null,
328 | "metadata": {},
329 | "outputs": [],
330 | "source": [
331 | "#Hugging Face models can be run locally through the HuggingFacePipeline class.\n",
332 | "from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline\n",
333 | "\n",
334 | "hf = HuggingFacePipeline.from_model_id(\n",
335 | " model_id=\"mistralai/Mistral-7B-v0.1\",\n",
336 | " task=\"text-generation\",\n",
337 | " pipeline_kwargs={\"temperature\": 0, \"max_new_tokens\": 300}\n",
338 | ")\n",
339 | "\n",
340 | "llm = hf \n",
341 | "llm.invoke(query)"
342 | ]
343 | },
344 | {
345 | "cell_type": "code",
346 | "execution_count": 22,
347 | "metadata": {},
348 | "outputs": [],
349 | "source": [
350 | "prompt_template=\"\"\"\n",
351 | "Use the following piece of context to answer the question asked.\n",
352 | "Please try to provide the answer only based on the context\n",
353 | "\n",
354 | "{context}\n",
355 | "Question:{question}\n",
356 | "\n",
357 | "Helpful Answers:\n",
358 | " \"\"\""
359 | ]
360 | },
361 | {
362 | "cell_type": "code",
363 | "execution_count": 24,
364 | "metadata": {},
365 | "outputs": [],
366 | "source": [
367 | "prompt=PromptTemplate(template=prompt_template,input_variables=[\"context\",\"question\"])"
368 | ]
369 | },
370 | {
371 | "cell_type": "code",
372 | "execution_count": 25,
373 | "metadata": {},
374 | "outputs": [],
375 | "source": [
376 | "retrievalQA=RetrievalQA.from_chain_type(\n",
377 | " llm=hf,\n",
378 | " chain_type=\"stuff\",\n",
379 | " retriever=retriever,\n",
380 | " return_source_documents=True,\n",
381 | " chain_type_kwargs={\"prompt\":prompt}\n",
382 | ")"
383 | ]
384 | },
385 | {
386 | "cell_type": "code",
387 | "execution_count": 28,
388 | "metadata": {},
389 | "outputs": [],
390 | "source": [
391 | "query=\"\"\"DIFFERENCES IN THE\n",
392 | "UNINSURED RATE BY STATE\n",
393 | "IN 2022\"\"\""
394 | ]
395 | },
396 | {
397 | "cell_type": "code",
398 | "execution_count": 29,
399 | "metadata": {},
400 | "outputs": [
401 | {
402 | "name": "stdout",
403 | "output_type": "stream",
404 | "text": [
405 | "\n",
406 | "Use the following piece of context to answer the question asked.\n",
407 | "Please try to provide the answer only based on the context\n",
408 | "\n",
409 | "comparison of ACS and CPS ASEC measures \n",
410 | "of health insurance coverage, refer to < www.\n",
411 | "census.gov/topics/health/health-insurance/\n",
412 | "guidance.html >.\n",
413 | "9 Respondents may have more than one \n",
414 | "health insurance coverage type at the time \n",
415 | "of interview. As a result, adding the total \n",
416 | "number of people with private coverage and \n",
417 | "the total number with public coverage will \n",
418 | "sum to more than the total number with any \n",
419 | "coverage.• From 2021 to 2022, nine states \n",
420 | "reported increases in private \n",
421 | "coverage, while seven reported \n",
422 | "decreases (Appendix Table B-2). \n",
423 | "DIFFERENCES IN THE \n",
424 | "UNINSURED RATE BY STATE \n",
425 | "IN 2022\n",
426 | "In 2022, uninsured rates at the \n",
427 | "time of interview ranged across \n",
428 | "states from a low of 2.4 percent \n",
429 | "in Massachusetts to a high of 16.6 \n",
430 | "percent in Texas, compared to the \n",
431 | "national rate of 8.0 percent.10 Ten \n",
432 | "of the 15 states with uninsured \n",
433 | "10 The uninsured rates in the District \n",
434 | "of Columbia and Massachusetts were not \n",
435 | "statistically different.rates above the national aver -\n",
436 | "\n",
437 | "percent (Appendix Table B-5). \n",
438 | "Medicaid coverage accounted \n",
439 | "for a portion of that difference. \n",
440 | "Medicaid coverage was 22.7 per -\n",
441 | "cent in the group of states that \n",
442 | "expanded Medicaid eligibility and \n",
443 | "18.0 percent in the group of nonex -\n",
444 | "pansion states.\n",
445 | "CHANGES IN THE UNINSURED \n",
446 | "RATE BY STATE FROM 2021 \n",
447 | "TO 2022\n",
448 | "From 2021 to 2022, uninsured rates \n",
449 | "decreased across 27 states, while \n",
450 | "only Maine had an increase. The \n",
451 | "uninsured rate in Maine increased \n",
452 | "from 5.7 percent to 6.6 percent, \n",
453 | "although it remained below the \n",
454 | "national average. Maine’s uninsured \n",
455 | "rate was still below 8.0 percent, \n",
456 | "21 Douglas Conway and Breauna Branch, \n",
457 | "“Health Insurance Coverage Status and Type \n",
458 | "by Geography: 2019 and 2021,” 2022, < www.\n",
459 | "census.gov/content/dam/Census/library/\n",
460 | "publications/2022/acs/acsbr-013.pdf >.\n",
461 | "\n",
462 | "library/publications/2022/acs/acsbr-013.pdf >.\n",
463 | "39 In 2022, the private coverage rates were \n",
464 | "not statistically different in North Dakota and \n",
465 | "Utah.Figure /five.tab/period.tab\n",
466 | "Percentage of Uninsured People for the /two.tab/five.tab Most Populous Metropolitan \n",
467 | "Areas/colon.tab /two.tab/zero.tab/two.tab/one.tab and /two.tab/zero.tab/two.tab/two.tab\n",
468 | "(Civilian, noninstitutionalized population) /uni00A0\n",
469 | "* Denotes a statistically significant change between 2021 and 2022 at the 90 percent confidence level.\n",
470 | "Note: For information on confidentiality protection, sampling error, nonsampling error, and definitions in the American Community\n",
471 | "Survey, refer to .\n",
472 | "Source: U.S. Census Bureau, 2021 and 2022 American Community Survey, 1-year estimates. Boston-Cambridge-Newton/comma.tab MA-NH\n",
473 | "San Francisco-Oakland-Berkeley/comma.tab CA\n",
474 | "*Detroit-Warren-Dearborn/comma.tab MI\n",
475 | "Question:DIFFERENCES IN THE\n",
476 | "UNINSURED RATE BY STATE\n",
477 | "IN 2022\n",
478 | "\n",
479 | "Helpful Answers:\n",
480 | " 1.\n",
481 | " 2.\n",
482 | " 3.\n",
483 | " 4.\n",
484 | " 5.\n",
485 | " 6.\n",
486 | " 7.\n",
487 | " 8.\n",
488 | " 9.\n",
489 | " 10.\n",
490 | " 11.\n",
491 | " 12.\n",
492 | " 13.\n",
493 | " 14.\n",
494 | " 15.\n",
495 | " 16.\n",
496 | " 17.\n",
497 | " 18.\n",
498 | " 19.\n",
499 | " 20.\n",
500 | " 21.\n",
501 | " 22.\n",
502 | "\n"
503 | ]
504 | }
505 | ],
506 | "source": [
507 | "# Call the QA chain with our query.\n",
508 | "result = retrievalQA.invoke({\"query\": query})\n",
509 | "print(result['result'])"
510 | ]
511 | },
512 | {
513 | "cell_type": "code",
514 | "execution_count": null,
515 | "metadata": {},
516 | "outputs": [],
517 | "source": []
518 | },
519 | {
520 | "cell_type": "code",
521 | "execution_count": null,
522 | "metadata": {},
523 | "outputs": [],
524 | "source": []
525 | }
526 | ],
527 | "metadata": {
528 | "kernelspec": {
529 | "display_name": "Python 3",
530 | "language": "python",
531 | "name": "python3"
532 | },
533 | "language_info": {
534 | "codemirror_mode": {
535 | "name": "ipython",
536 | "version": 3
537 | },
538 | "file_extension": ".py",
539 | "mimetype": "text/x-python",
540 | "name": "python",
541 | "nbconvert_exporter": "python",
542 | "pygments_lexer": "ipython3",
543 | "version": "3.10.0"
544 | }
545 | },
546 | "nbformat": 4,
547 | "nbformat_minor": 2
548 | }
549 |
--------------------------------------------------------------------------------
/huggingface/us_census/acsbr-015.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/huggingface/us_census/acsbr-015.pdf
--------------------------------------------------------------------------------
/huggingface/us_census/acsbr-016.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/huggingface/us_census/acsbr-016.pdf
--------------------------------------------------------------------------------
/huggingface/us_census/acsbr-017.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/huggingface/us_census/acsbr-017.pdf
--------------------------------------------------------------------------------
/huggingface/us_census/p70-178.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/huggingface/us_census/p70-178.pdf
--------------------------------------------------------------------------------
/objectbox/.env:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/objectbox/app.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 | import os
3 | from langchain_groq import ChatGroq
4 | from langchain_openai import OpenAIEmbeddings
5 | from langchain.text_splitter import RecursiveCharacterTextSplitter
6 | from langchain.chains.combine_documents import create_stuff_documents_chain
7 | from langchain_core.prompts import ChatPromptTemplate
8 | from langchain.chains import create_retrieval_chain
9 | from langchain_objectbox.vectorstores import ObjectBox
10 | from langchain_community.document_loaders import PyPDFDirectoryLoader
11 |
12 | from dotenv import load_dotenv
13 | load_dotenv()
14 |
15 | ## load the Groq And OpenAI Api Key
16 | os.environ['OPEN_API_KEY']=os.getenv("OPENAI_API_KEY")
17 | groq_api_key=os.getenv('GROQ_API_KEY')
18 |
19 | st.title("Objectbox VectorstoreDB With Llama3 Demo")
20 |
21 | llm=ChatGroq(groq_api_key=groq_api_key,
22 | model_name="Llama3-8b-8192")
23 |
24 | prompt=ChatPromptTemplate.from_template(
25 | """
26 | Answer the questions based on the provided context only.
27 | Please provide the most accurate response based on the question
28 |
29 | {context}
30 |
31 | Questions:{input}
32 |
33 | """
34 |
35 | )
36 |
37 |
38 | ## Vector Enbedding and Objectbox Vectorstore db
39 |
40 | def vector_embedding():
41 |
42 | if "vectors" not in st.session_state:
43 | st.session_state.embeddings=OpenAIEmbeddings()
44 | st.session_state.loader=PyPDFDirectoryLoader("./us_census") ## Data Ingestion
45 | st.session_state.docs=st.session_state.loader.load() ## Documents Loading
46 | st.session_state.text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200)
47 | st.session_state.final_documents=st.session_state.text_splitter.split_documents(st.session_state.docs[:20])
48 | st.session_state.vectors=ObjectBox.from_documents(st.session_state.final_documents,st.session_state.embeddings,embedding_dimensions=768)
49 |
50 |
51 | input_prompt=st.text_input("Enter Your Question From Documents")
52 |
53 | if st.button("Documents Embedding"):
54 | vector_embedding()
55 | st.write("ObjectBox Database is ready")
56 |
57 | import time
58 |
59 | if input_prompt:
60 | document_chain=create_stuff_documents_chain(llm,prompt)
61 | retriever=st.session_state.vectors.as_retriever()
62 | retrieval_chain=create_retrieval_chain(retriever,document_chain)
63 | start=time.process_time()
64 |
65 | response=retrieval_chain.invoke({'input':input_prompt})
66 |
67 | print("Response time :",time.process_time()-start)
68 | st.write(response['answer'])
69 |
70 | # With a streamlit expander
71 | with st.expander("Document Similarity Search"):
72 | # Find the relevant chunks
73 | for i, doc in enumerate(response["context"]):
74 | st.write(doc.page_content)
75 | st.write("--------------------------------")
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/objectbox/us_census/acsbr-015.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/objectbox/us_census/acsbr-015.pdf
--------------------------------------------------------------------------------
/objectbox/us_census/acsbr-016.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/objectbox/us_census/acsbr-016.pdf
--------------------------------------------------------------------------------
/objectbox/us_census/acsbr-017.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/objectbox/us_census/acsbr-017.pdf
--------------------------------------------------------------------------------
/objectbox/us_census/p70-178.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/objectbox/us_census/p70-178.pdf
--------------------------------------------------------------------------------
/openai/GPT4o_Lanchain_RAG.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 16,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "## RAG Application With GPT-4o"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 1,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "from dotenv import load_dotenv\n",
19 | "\n",
20 | "load_dotenv()\n",
21 | "import os\n",
22 | "os.environ['OPENAI_API_KEY']=os.getenv(\"OPENAI_API_KEY\")"
23 | ]
24 | },
25 | {
26 | "cell_type": "markdown",
27 | "metadata": {},
28 | "source": [
29 | "# 1. Get a Data Loader\n"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": 2,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "from langchain_community.document_loaders import WebBaseLoader\n"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": 3,
44 | "metadata": {},
45 | "outputs": [
46 | {
47 | "data": {
48 | "text/plain": [
49 | "[Document(page_content=\"\\n\\n\\n\\n\\nLangSmith User Guide | 🦜️🛠️ LangSmith\\n\\n\\n\\n\\n\\n\\n\\nSkip to main contentLangSmith API DocsSearchGo to AppQuick StartUser GuideTracingEvaluationProduction Monitoring & AutomationsPrompt HubProxyPricingSelf-HostingCookbookThis is outdated documentation for 🦜️🛠️ LangSmith, which is no longer actively maintained.For up-to-date documentation, see the latest version.User GuideOn this pageLangSmith User GuideLangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.Prototyping\\u200bPrototyping LLM applications often involves quick experimentation between prompts, model types, retrieval strategy and other parameters.\\nThe ability to rapidly understand how the model is performing — and debug where it is failing — is incredibly important for this phase.Debugging\\u200bWhen developing new LLM applications, we suggest having LangSmith tracing enabled by default.\\nOftentimes, it isn’t necessary to look at every single trace. However, when things go wrong (an unexpected end result, infinite agent loop, slower than expected execution, higher than expected token usage), it’s extremely helpful to debug by looking through the application traces. LangSmith gives clear visibility and debugging information at each step of an LLM sequence, making it much easier to identify and root-cause issues.\\nWe provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set\\u200bWhile many developers still ship an initial version of their application based on “vibe checks”, we’ve seen an increasing number of engineering teams start to adopt a more test driven approach. LangSmith allows developers to create datasets, which are collections of inputs and reference outputs, and use these to run tests on their LLM applications.\\nThese test cases can be uploaded in bulk, created on the fly, or exported from application traces. LangSmith also makes it easy to run custom evaluations (both LLM and heuristic based) to score test results.Comparison View\\u200bWhen prototyping different versions of your applications and making changes, it’s important to see whether or not you’ve regressed with respect to your initial test cases.\\nOftentimes, changes in the prompt, retrieval strategy, or model choice can have huge implications in responses produced by your application.\\nIn order to get a sense for which variant is performing better, it’s useful to be able to view results for different configurations on the same datapoints side-by-side. We’ve invested heavily in a user-friendly comparison view for test runs to track and diagnose regressions in test scores across multiple revisions of your application.Playground\\u200bLangSmith provides a playground environment for rapid iteration and experimentation.\\nThis allows you to quickly test out different prompts and models. You can open the playground from any prompt or model run in your trace.\\nEvery playground run is logged in the system and can be used to create test cases or compare with other runs.Beta Testing\\u200bBeta testing allows developers to collect more data on how their LLM applications are performing in real-world scenarios. In this phase, it’s important to develop an understanding for the types of inputs the app is performing well or poorly on and how exactly it’s breaking down in those cases. Both feedback collection and run annotation are critical for this workflow. This will help in curation of test cases that can help track regressions/improvements and development of automatic evaluations.Capturing Feedback\\u200bWhen launching your application to an initial set of users, it’s important to gather human feedback on the responses it’s producing. This helps draw attention to the most interesting runs and highlight edge cases that are causing problematic responses. LangSmith allows you to attach feedback scores to logged traces (oftentimes, this is hooked up to a feedback button in your app), then filter on traces that have a specific feedback tag and score. A common workflow is to filter on traces that receive a poor user feedback score, then drill down into problematic points using the detailed trace view.Annotating Traces\\u200bLangSmith also supports sending runs to annotation queues, which allow annotators to closely inspect interesting traces and annotate them with respect to different criteria. Annotators can be PMs, engineers, or even subject matter experts. This allows users to catch regressions across important evaluation criteria.Adding Runs to a Dataset\\u200bAs your application progresses through the beta testing phase, it's essential to continue collecting data to refine and improve its performance. LangSmith enables you to add runs as examples to datasets (from both the project page and within an annotation queue), expanding your test coverage on real-world scenarios. This is a key benefit in having your logging system and your evaluation/testing system in the same platform.Production\\u200bClosely inspecting key data points, growing benchmarking datasets, annotating traces, and drilling down into important data in trace view are workflows you’ll also want to do once your app hits production.However, especially at the production stage, it’s crucial to get a high-level overview of application performance with respect to latency, cost, and feedback scores. This ensures that it's delivering desirable results at scale.Online evaluations and automations allow you to process and score production traces in near real-time.Additionally, threads provide a seamless way to group traces from a single conversation, making it easier to track the performance of your application across multiple turns.Monitoring and A/B Testing\\u200bLangSmith provides monitoring charts that allow you to track key metrics over time. You can expand to view metrics for a given period and drill down into a specific data point to get a trace table for that time period — this is especially handy for debugging production issues.LangSmith also allows for tag and metadata grouping, which allows users to mark different versions of their applications with different identifiers and view how they are performing side-by-side within each chart. This is helpful for A/B testing changes in prompt, model, or retrieval strategy.Automations\\u200bAutomations are a powerful feature in LangSmith that allow you to perform actions on traces in near real-time. This can be used to automatically score traces, send them to annotation queues, or send them to datasets.To define an automation, simply provide a filter condition, a sampling rate, and an action to perform. Automations are particularly helpful for processing traces at production scale.Threads\\u200bMany LLM applications are multi-turn, meaning that they involve a series of interactions between the user and the application. LangSmith provides a threads view that groups traces from a single conversation together, making it easier to track the performance of and annotate your application across multiple turns.Was this page helpful?PreviousQuick StartNextOverviewPrototypingBeta TestingProductionCommunityDiscordTwitterGitHubDocs CodeLangSmith SDKPythonJS/TSMoreHomepageBlogLangChain Python DocsLangChain JS/TS DocsCopyright © 2024 LangChain, Inc.\\n\\n\\n\\n\", metadata={'source': 'https://docs.smith.langchain.com/user_guide', 'title': 'LangSmith User Guide | 🦜️🛠️ LangSmith', 'description': 'LangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.', 'language': 'en'})]"
50 | ]
51 | },
52 | "execution_count": 3,
53 | "metadata": {},
54 | "output_type": "execute_result"
55 | }
56 | ],
57 | "source": [
58 | "loader = WebBaseLoader(\"https://docs.smith.langchain.com/user_guide\")\n",
59 | "data = loader.load()\n",
60 | "data"
61 | ]
62 | },
63 | {
64 | "cell_type": "markdown",
65 | "metadata": {},
66 | "source": [
67 | "# 2. Convert data to Vector Database\n"
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": 4,
73 | "metadata": {},
74 | "outputs": [],
75 | "source": [
76 | "\n",
77 | "from langchain_objectbox.vectorstores import ObjectBox ##vector Database\n",
78 | "from langchain_openai import OpenAIEmbeddings\n"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": 7,
84 | "metadata": {},
85 | "outputs": [],
86 | "source": []
87 | },
88 | {
89 | "cell_type": "code",
90 | "execution_count": 5,
91 | "metadata": {},
92 | "outputs": [],
93 | "source": [
94 | "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
95 | "\n",
96 | "text_splitter = RecursiveCharacterTextSplitter()\n",
97 | "documents = text_splitter.split_documents(data)"
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": 6,
103 | "metadata": {},
104 | "outputs": [
105 | {
106 | "data": {
107 | "text/plain": [
108 | "[Document(page_content='LangSmith User Guide | 🦜️🛠️ LangSmith', metadata={'source': 'https://docs.smith.langchain.com/user_guide', 'title': 'LangSmith User Guide | 🦜️🛠️ LangSmith', 'description': 'LangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.', 'language': 'en'}),\n",
109 | " Document(page_content='Skip to main contentLangSmith API DocsSearchGo to AppQuick StartUser GuideTracingEvaluationProduction Monitoring & AutomationsPrompt HubProxyPricingSelf-HostingCookbookThis is outdated documentation for 🦜️🛠️ LangSmith, which is no longer actively maintained.For up-to-date documentation, see the latest version.User GuideOn this pageLangSmith User GuideLangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.Prototyping\\u200bPrototyping LLM applications often involves quick experimentation between prompts, model types, retrieval strategy and other parameters.\\nThe ability to rapidly understand how the model is performing — and debug where it is failing — is incredibly important for this phase.Debugging\\u200bWhen developing new LLM applications, we suggest having LangSmith tracing enabled by default.\\nOftentimes, it isn’t necessary to look at every single trace. However, when things go wrong (an unexpected end result, infinite agent loop, slower than expected execution, higher than expected token usage), it’s extremely helpful to debug by looking through the application traces. LangSmith gives clear visibility and debugging information at each step of an LLM sequence, making it much easier to identify and root-cause issues.\\nWe provide native rendering of chat messages, functions, and retrieve documents.Initial Test Set\\u200bWhile many developers still ship an initial version of their application based on “vibe checks”, we’ve seen an increasing number of engineering teams start to adopt a more test driven approach. LangSmith allows developers to create datasets, which are collections of inputs and reference outputs, and use these to run tests on their LLM applications.\\nThese test cases can be uploaded in bulk, created on the fly, or exported from application traces. LangSmith also makes it easy to run custom evaluations (both LLM and heuristic based) to score test results.Comparison View\\u200bWhen prototyping different versions of your applications and making changes, it’s important to see whether or not you’ve regressed with respect to your initial test cases.\\nOftentimes, changes in the prompt, retrieval strategy, or model choice can have huge implications in responses produced by your application.\\nIn order to get a sense for which variant is performing better, it’s useful to be able to view results for different configurations on the same datapoints side-by-side. We’ve invested heavily in a user-friendly comparison view for test runs to track and diagnose regressions in test scores across multiple revisions of your application.Playground\\u200bLangSmith provides a playground environment for rapid iteration and experimentation.\\nThis allows you to quickly test out different prompts and models. You can open the playground from any prompt or model run in your trace.', metadata={'source': 'https://docs.smith.langchain.com/user_guide', 'title': 'LangSmith User Guide | 🦜️🛠️ LangSmith', 'description': 'LangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.', 'language': 'en'}),\n",
110 | " Document(page_content=\"Every playground run is logged in the system and can be used to create test cases or compare with other runs.Beta Testing\\u200bBeta testing allows developers to collect more data on how their LLM applications are performing in real-world scenarios. In this phase, it’s important to develop an understanding for the types of inputs the app is performing well or poorly on and how exactly it’s breaking down in those cases. Both feedback collection and run annotation are critical for this workflow. This will help in curation of test cases that can help track regressions/improvements and development of automatic evaluations.Capturing Feedback\\u200bWhen launching your application to an initial set of users, it’s important to gather human feedback on the responses it’s producing. This helps draw attention to the most interesting runs and highlight edge cases that are causing problematic responses. LangSmith allows you to attach feedback scores to logged traces (oftentimes, this is hooked up to a feedback button in your app), then filter on traces that have a specific feedback tag and score. A common workflow is to filter on traces that receive a poor user feedback score, then drill down into problematic points using the detailed trace view.Annotating Traces\\u200bLangSmith also supports sending runs to annotation queues, which allow annotators to closely inspect interesting traces and annotate them with respect to different criteria. Annotators can be PMs, engineers, or even subject matter experts. This allows users to catch regressions across important evaluation criteria.Adding Runs to a Dataset\\u200bAs your application progresses through the beta testing phase, it's essential to continue collecting data to refine and improve its performance. LangSmith enables you to add runs as examples to datasets (from both the project page and within an annotation queue), expanding your test coverage on real-world scenarios. This is a key benefit in having your logging system and your evaluation/testing system in the same platform.Production\\u200bClosely inspecting key data points, growing benchmarking datasets, annotating traces, and drilling down into important data in trace view are workflows you’ll also want to do once your app hits production.However, especially at the production stage, it’s crucial to get a high-level overview of application performance with respect to latency, cost, and feedback scores. This ensures that it's delivering desirable results at scale.Online evaluations and automations allow you to process and score production traces in near real-time.Additionally, threads provide a seamless way to group traces from a single conversation, making it easier to track the performance of your application across multiple turns.Monitoring and A/B Testing\\u200bLangSmith provides monitoring charts that allow you to track key metrics over time. You can expand to view metrics for a given period and drill down into a specific data point to get a trace table for that time period — this is especially handy for debugging production issues.LangSmith also allows for tag and metadata grouping, which allows users to mark different versions of their applications with different identifiers and view how they are performing side-by-side within each chart. This is helpful for A/B testing changes in prompt, model, or retrieval strategy.Automations\\u200bAutomations are a powerful feature in LangSmith that allow you to perform actions on traces in near real-time. This can be used to automatically score traces, send them to annotation queues, or send them to datasets.To define an automation, simply provide a filter condition, a sampling rate, and an action to perform. Automations are particularly helpful for processing traces at production scale.Threads\\u200bMany LLM applications are multi-turn, meaning that they involve a series of interactions between the user and the application. LangSmith provides a threads view that groups traces from a single conversation together, making it easier to\", metadata={'source': 'https://docs.smith.langchain.com/user_guide', 'title': 'LangSmith User Guide | 🦜️🛠️ LangSmith', 'description': 'LangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.', 'language': 'en'}),\n",
111 | " Document(page_content='meaning that they involve a series of interactions between the user and the application. LangSmith provides a threads view that groups traces from a single conversation together, making it easier to track the performance of and annotate your application across multiple turns.Was this page helpful?PreviousQuick StartNextOverviewPrototypingBeta TestingProductionCommunityDiscordTwitterGitHubDocs CodeLangSmith SDKPythonJS/TSMoreHomepageBlogLangChain Python DocsLangChain JS/TS DocsCopyright © 2024 LangChain, Inc.', metadata={'source': 'https://docs.smith.langchain.com/user_guide', 'title': 'LangSmith User Guide | 🦜️🛠️ LangSmith', 'description': 'LangSmith is a platform for LLM application development, monitoring, and testing. In this guide, we’ll highlight the breadth of workflows LangSmith supports and how they fit into each stage of the application development lifecycle. We hope this will inform users how to best utilize this powerful platform or give them something to consider if they’re just starting their journey.', 'language': 'en'})]"
112 | ]
113 | },
114 | "execution_count": 6,
115 | "metadata": {},
116 | "output_type": "execute_result"
117 | }
118 | ],
119 | "source": [
120 | "documents"
121 | ]
122 | },
123 | {
124 | "cell_type": "markdown",
125 | "metadata": {},
126 | "source": []
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": 7,
131 | "metadata": {},
132 | "outputs": [
133 | {
134 | "data": {
135 | "text/plain": [
136 | ""
137 | ]
138 | },
139 | "execution_count": 7,
140 | "metadata": {},
141 | "output_type": "execute_result"
142 | }
143 | ],
144 | "source": [
145 | "from langchain_openai import OpenAIEmbeddings\n",
146 | "vector = ObjectBox.from_documents(documents, OpenAIEmbeddings(), embedding_dimensions=768)\n",
147 | "vector"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "# 3. Make a RAG pipeline\n"
155 | ]
156 | },
157 | {
158 | "cell_type": "code",
159 | "execution_count": 8,
160 | "metadata": {},
161 | "outputs": [],
162 | "source": [
163 | "from langchain_openai import ChatOpenAI\n",
164 | "from langchain_core.output_parsers import StrOutputParser\n",
165 | "from langchain_core.prompts import ChatPromptTemplate\n",
166 | "from langchain.chains import RetrievalQA\n",
167 | "from langchain import hub"
168 | ]
169 | },
170 | {
171 | "cell_type": "code",
172 | "execution_count": 9,
173 | "metadata": {},
174 | "outputs": [
175 | {
176 | "data": {
177 | "text/plain": [
178 | "ChatPromptTemplate(input_variables=['context', 'question'], metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'}, messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\\nQuestion: {question} \\nContext: {context} \\nAnswer:\"))])"
179 | ]
180 | },
181 | "execution_count": 9,
182 | "metadata": {},
183 | "output_type": "execute_result"
184 | }
185 | ],
186 | "source": [
187 | "llm = ChatOpenAI(model=\"gpt-4o\") ## Calling Gpt-4o\n",
188 | "prompt = hub.pull(\"rlm/rag-prompt\")\n",
189 | "prompt\n",
190 | "\n"
191 | ]
192 | },
193 | {
194 | "cell_type": "code",
195 | "execution_count": 12,
196 | "metadata": {},
197 | "outputs": [
198 | {
199 | "data": {
200 | "text/plain": [
201 | "ChatPromptTemplate(input_variables=['context', 'question'], metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'}, messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\\nQuestion: {question} \\nContext: {context} \\nAnswer:\"))])"
202 | ]
203 | },
204 | "execution_count": 12,
205 | "metadata": {},
206 | "output_type": "execute_result"
207 | }
208 | ],
209 | "source": [
210 | "prompt"
211 | ]
212 | },
213 | {
214 | "cell_type": "code",
215 | "execution_count": 10,
216 | "metadata": {},
217 | "outputs": [],
218 | "source": [
219 | "qa_chain = RetrievalQA.from_chain_type(\n",
220 | " llm,\n",
221 | " retriever=vector.as_retriever(),\n",
222 | " chain_type_kwargs={\"prompt\": prompt}\n",
223 | " )"
224 | ]
225 | },
226 | {
227 | "cell_type": "code",
228 | "execution_count": 11,
229 | "metadata": {},
230 | "outputs": [
231 | {
232 | "name": "stderr",
233 | "output_type": "stream",
234 | "text": [
235 | "e:\\Langchain\\venv\\lib\\site-packages\\langchain_core\\_api\\deprecation.py:119: LangChainDeprecationWarning: The method `Chain.__call__` was deprecated in langchain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
236 | " warn_deprecated(\n"
237 | ]
238 | },
239 | {
240 | "data": {
241 | "text/plain": [
242 | "{'query': 'Explain what is langsmith',\n",
243 | " 'result': 'LangSmith is a platform designed for the development, monitoring, and testing of LLM (Large Language Model) applications. It supports various stages of the application lifecycle, including prototyping, debugging, beta testing, and production. The platform offers tools for tracing, evaluation, feedback collection, A/B testing, and automations to ensure optimal performance and quality of LLM applications.'}"
244 | ]
245 | },
246 | "execution_count": 11,
247 | "metadata": {},
248 | "output_type": "execute_result"
249 | }
250 | ],
251 | "source": [
252 | "question = \"Explain what is langsmith\"\n",
253 | "result = qa_chain({\"query\": question })\n",
254 | "result"
255 | ]
256 | },
257 | {
258 | "cell_type": "code",
259 | "execution_count": 12,
260 | "metadata": {},
261 | "outputs": [
262 | {
263 | "data": {
264 | "text/plain": [
265 | "'LangSmith is a platform designed for the development, monitoring, and testing of LLM (Large Language Model) applications. It supports various stages of the application lifecycle, including prototyping, debugging, beta testing, and production. The platform offers tools for tracing, evaluation, feedback collection, A/B testing, and automations to ensure optimal performance and quality of LLM applications.'"
266 | ]
267 | },
268 | "execution_count": 12,
269 | "metadata": {},
270 | "output_type": "execute_result"
271 | }
272 | ],
273 | "source": [
274 | "result[\"result\"]"
275 | ]
276 | },
277 | {
278 | "cell_type": "code",
279 | "execution_count": 13,
280 | "metadata": {},
281 | "outputs": [
282 | {
283 | "name": "stdout",
284 | "output_type": "stream",
285 | "text": [
286 | "('LangSmith is a platform designed for the development, monitoring, and '\n",
287 | " 'testing of LLM (Large Language Model) applications. It supports various '\n",
288 | " 'stages of the application lifecycle, including prototyping, debugging, beta '\n",
289 | " 'testing, and production. The platform offers tools for tracing, evaluation, '\n",
290 | " 'feedback collection, A/B testing, and automations to ensure optimal '\n",
291 | " 'performance and quality of LLM applications.')\n"
292 | ]
293 | }
294 | ],
295 | "source": [
296 | "import pprint\n",
297 | "pp = pprint.PrettyPrinter(indent=5)\n",
298 | "pp.pprint(result[\"result\"])"
299 | ]
300 | },
301 | {
302 | "cell_type": "code",
303 | "execution_count": 14,
304 | "metadata": {},
305 | "outputs": [
306 | {
307 | "data": {
308 | "text/plain": [
309 | "{'query': 'Explain Monitoring and A/B Testing in langsmith',\n",
310 | " 'result': 'LangSmith provides monitoring charts to track key metrics over time, allowing users to drill down into specific data points for debugging production issues. It also supports A/B testing by enabling tag and metadata grouping, which allows users to compare the performance of different versions of their applications side-by-side within each chart. This helps in evaluating changes in prompt, model, or retrieval strategy effectively.'}"
311 | ]
312 | },
313 | "execution_count": 14,
314 | "metadata": {},
315 | "output_type": "execute_result"
316 | }
317 | ],
318 | "source": [
319 | "question = \"Explain Monitoring and A/B Testing in langsmith\"\n",
320 | "result = qa_chain({\"query\": question })\n",
321 | "result"
322 | ]
323 | },
324 | {
325 | "cell_type": "code",
326 | "execution_count": null,
327 | "metadata": {},
328 | "outputs": [],
329 | "source": []
330 | }
331 | ],
332 | "metadata": {
333 | "kernelspec": {
334 | "display_name": "base",
335 | "language": "python",
336 | "name": "python3"
337 | },
338 | "language_info": {
339 | "codemirror_mode": {
340 | "name": "ipython",
341 | "version": 3
342 | },
343 | "file_extension": ".py",
344 | "mimetype": "text/x-python",
345 | "name": "python",
346 | "nbconvert_exporter": "python",
347 | "pygments_lexer": "ipython3",
348 | "version": "3.10.0"
349 | }
350 | },
351 | "nbformat": 4,
352 | "nbformat_minor": 2
353 | }
354 |
--------------------------------------------------------------------------------
/rag/attention.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krishnaik06/Updated-Langchain/8f54bb019cf788a55d9ee0b833d5967c7e963a3d/rag/attention.pdf
--------------------------------------------------------------------------------
/rag/speech.txt:
--------------------------------------------------------------------------------
1 | The world must be made safe for democracy. Its peace must be planted upon the tested foundations of political liberty. We have no selfish ends to serve. We desire no conquest, no dominion. We seek no indemnities for ourselves, no material compensation for the sacrifices we shall freely make. We are but one of the champions of the rights of mankind. We shall be satisfied when those rights have been made as secure as the faith and the freedom of nations can make them.
2 |
3 | Just because we fight without rancor and without selfish object, seeking nothing for ourselves but what we shall wish to share with all free peoples, we shall, I feel confident, conduct our operations as belligerents without passion and ourselves observe with proud punctilio the principles of right and of fair play we profess to be fighting for.
4 |
5 | …
6 |
7 | It will be all the easier for us to conduct ourselves as belligerents in a high spirit of right and fairness because we act without animus, not in enmity toward a people or with the desire to bring any injury or disadvantage upon them, but only in armed opposition to an irresponsible government which has thrown aside all considerations of humanity and of right and is running amuck. We are, let me say again, the sincere friends of the German people, and shall desire nothing so much as the early reestablishment of intimate relations of mutual advantage between us—however hard it may be for them, for the time being, to believe that this is spoken from our hearts.
8 |
9 | We have borne with their present government through all these bitter months because of that friendship—exercising a patience and forbearance which would otherwise have been impossible. We shall, happily, still have an opportunity to prove that friendship in our daily attitude and actions toward the millions of men and women of German birth and native sympathy who live among us and share our life, and we shall be proud to prove it toward all who are in fact loyal to their neighbors and to the government in the hour of test. They are, most of them, as true and loyal Americans as if they had never known any other fealty or allegiance. They will be prompt to stand with us in rebuking and restraining the few who may be of a different mind and purpose. If there should be disloyalty, it will be dealt with with a firm hand of stern repression; but, if it lifts its head at all, it will lift it only here and there and without countenance except from a lawless and malignant few.
10 |
11 | It is a distressing and oppressive duty, gentlemen of the Congress, which I have performed in thus addressing you. There are, it may be, many months of fiery trial and sacrifice ahead of us. It is a fearful thing to lead this great peaceful people into war, into the most terrible and disastrous of all wars, civilization itself seeming to be in the balance. But the right is more precious than peace, and we shall fight for the things which we have always carried nearest our hearts—for democracy, for the right of those who submit to authority to have a voice in their own governments, for the rights and liberties of small nations, for a universal dominion of right by such a concert of free peoples as shall bring peace and safety to all nations and make the world itself at last free.
12 |
13 | To such a task we can dedicate our lives and our fortunes, everything that we are and everything that we have, with the pride of those who know that the day has come when America is privileged to spend her blood and her might for the principles that gave her birth and happiness and the peace which she has treasured. God helping her, she can do no other.
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | langchain_openai
2 | langchain_core
3 | python-dotenv
4 | streamlit
5 | langchain_community
6 | langserve
7 | fastapi
8 | uvicorn
9 | sse_starlette
10 | bs4
11 | pypdf
12 | chromadb
13 | faiss-cpu
14 | groq
15 | cassio
16 | beautifulsoup4
17 | langchain-groq
18 | wikipedia
19 | arxiv
20 | langchainhub
21 | sentence_transformers
22 | PyPDF2
23 | langchain-objectbox
--------------------------------------------------------------------------------