first
Browse files- .devcontainer/devcontainer.json +46 -0
- .gitignore +167 -0
- .pre-commit-config.yaml +17 -0
- LICENSE +202 -0
- README.md +1 -1
- README_.md +40 -0
- poetry.lock +0 -0
- pyproject.toml +25 -0
- streamlit_agent/Chinook.db +0 -0
- streamlit_agent/__init__.py +0 -0
- streamlit_agent/basic_streaming.py +38 -0
- streamlit_agent/callbacks/__init__.py +0 -0
- streamlit_agent/callbacks/capturing_callback_handler.py +159 -0
- streamlit_agent/clear_results.py +32 -0
- streamlit_agent/minimal_agent.py +17 -0
- streamlit_agent/mrkl_demo.py +102 -0
- streamlit_agent/runs/alanis.pickle +3 -0
- streamlit_agent/runs/leo.pickle +3 -0
- streamlit_agent/search_and_chat.py +36 -0
.devcontainer/devcontainer.json
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
|
2 |
+
// https://github.com/microsoft/vscode-dev-containers/tree/v0.209.6/containers/python-3
|
3 |
+
{
|
4 |
+
"image": "mcr.microsoft.com/devcontainers/python:0-3.11-bullseye",
|
5 |
+
"customizations": {
|
6 |
+
"codespaces": {
|
7 |
+
"openFiles": [
|
8 |
+
"README.md",
|
9 |
+
"streamlit_agent/mrkl_demo.py"
|
10 |
+
]
|
11 |
+
},
|
12 |
+
"vscode": {
|
13 |
+
"settings": {},
|
14 |
+
"extensions": [
|
15 |
+
"ms-python.python",
|
16 |
+
"ms-python.vscode-pylance"
|
17 |
+
]
|
18 |
+
}
|
19 |
+
},
|
20 |
+
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
21 |
+
"forwardPorts": [
|
22 |
+
8501
|
23 |
+
],
|
24 |
+
// Use 'postCreateCommand' to run commands after the container is created.
|
25 |
+
// Install app dependencies.
|
26 |
+
"postCreateCommand": "pip3 install --user .",
|
27 |
+
// Use 'postAttachCommand' to run commands after a tool has attached to the container.
|
28 |
+
// Start the app.
|
29 |
+
"postAttachCommand": {
|
30 |
+
"server": "streamlit run streamlit_agent/mrkl_demo.py --server.enableCORS false --server.enableXsrfProtection false"
|
31 |
+
},
|
32 |
+
"portsAttributes": {
|
33 |
+
"8501": {
|
34 |
+
"label": "Application",
|
35 |
+
"onAutoForward": "openPreview"
|
36 |
+
}
|
37 |
+
},
|
38 |
+
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
|
39 |
+
"remoteUser": "vscode",
|
40 |
+
"features": {
|
41 |
+
// Optional features for development - increase container boot time!
|
42 |
+
// "ghcr.io/devcontainers-contrib/features/coverage-py:2": {},
|
43 |
+
// "git": "latest",
|
44 |
+
// "github-cli": "latest"
|
45 |
+
}
|
46 |
+
}
|
.gitignore
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.vs/
|
2 |
+
.vscode/
|
3 |
+
.idea/
|
4 |
+
# Byte-compiled / optimized / DLL files
|
5 |
+
__pycache__/
|
6 |
+
*.py[cod]
|
7 |
+
*$py.class
|
8 |
+
|
9 |
+
# C extensions
|
10 |
+
*.so
|
11 |
+
|
12 |
+
# Distribution / packaging
|
13 |
+
.Python
|
14 |
+
build/
|
15 |
+
develop-eggs/
|
16 |
+
dist/
|
17 |
+
downloads/
|
18 |
+
eggs/
|
19 |
+
.eggs/
|
20 |
+
lib/
|
21 |
+
lib64/
|
22 |
+
parts/
|
23 |
+
sdist/
|
24 |
+
var/
|
25 |
+
wheels/
|
26 |
+
pip-wheel-metadata/
|
27 |
+
share/python-wheels/
|
28 |
+
*.egg-info/
|
29 |
+
.installed.cfg
|
30 |
+
*.egg
|
31 |
+
MANIFEST
|
32 |
+
|
33 |
+
# PyInstaller
|
34 |
+
# Usually these files are written by a python script from a template
|
35 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
36 |
+
*.manifest
|
37 |
+
*.spec
|
38 |
+
|
39 |
+
# Installer logs
|
40 |
+
pip-log.txt
|
41 |
+
pip-delete-this-directory.txt
|
42 |
+
|
43 |
+
# Unit test / coverage reports
|
44 |
+
htmlcov/
|
45 |
+
.tox/
|
46 |
+
.nox/
|
47 |
+
.coverage
|
48 |
+
.coverage.*
|
49 |
+
.cache
|
50 |
+
nosetests.xml
|
51 |
+
coverage.xml
|
52 |
+
*.cover
|
53 |
+
*.py,cover
|
54 |
+
.hypothesis/
|
55 |
+
.pytest_cache/
|
56 |
+
|
57 |
+
# Translations
|
58 |
+
*.mo
|
59 |
+
*.pot
|
60 |
+
|
61 |
+
# Django stuff:
|
62 |
+
*.log
|
63 |
+
local_settings.py
|
64 |
+
db.sqlite3
|
65 |
+
db.sqlite3-journal
|
66 |
+
|
67 |
+
# Flask stuff:
|
68 |
+
instance/
|
69 |
+
.webassets-cache
|
70 |
+
|
71 |
+
# Scrapy stuff:
|
72 |
+
.scrapy
|
73 |
+
|
74 |
+
# Sphinx documentation
|
75 |
+
docs/_build/
|
76 |
+
docs/docs/_build/
|
77 |
+
|
78 |
+
# PyBuilder
|
79 |
+
target/
|
80 |
+
|
81 |
+
# Jupyter Notebook
|
82 |
+
.ipynb_checkpoints
|
83 |
+
notebooks/
|
84 |
+
|
85 |
+
# IPython
|
86 |
+
profile_default/
|
87 |
+
ipython_config.py
|
88 |
+
|
89 |
+
# pyenv
|
90 |
+
.python-version
|
91 |
+
|
92 |
+
# pipenv
|
93 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
94 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
95 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
96 |
+
# install all needed dependencies.
|
97 |
+
#Pipfile.lock
|
98 |
+
|
99 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
100 |
+
__pypackages__/
|
101 |
+
|
102 |
+
# Celery stuff
|
103 |
+
celerybeat-schedule
|
104 |
+
celerybeat.pid
|
105 |
+
|
106 |
+
# SageMath parsed files
|
107 |
+
*.sage.py
|
108 |
+
|
109 |
+
# Environments
|
110 |
+
.env
|
111 |
+
.envrc
|
112 |
+
.venv
|
113 |
+
.venvs
|
114 |
+
env/
|
115 |
+
venv/
|
116 |
+
ENV/
|
117 |
+
env.bak/
|
118 |
+
venv.bak/
|
119 |
+
|
120 |
+
# Spyder project settings
|
121 |
+
.spyderproject
|
122 |
+
.spyproject
|
123 |
+
|
124 |
+
# Rope project settings
|
125 |
+
.ropeproject
|
126 |
+
|
127 |
+
# mkdocs documentation
|
128 |
+
/site
|
129 |
+
|
130 |
+
# mypy
|
131 |
+
.mypy_cache/
|
132 |
+
.dmypy.json
|
133 |
+
dmypy.json
|
134 |
+
|
135 |
+
# Pyre type checker
|
136 |
+
.pyre/
|
137 |
+
|
138 |
+
# macOS display setting files
|
139 |
+
.DS_Store
|
140 |
+
|
141 |
+
# Wandb directory
|
142 |
+
wandb/
|
143 |
+
|
144 |
+
# asdf tool versions
|
145 |
+
.tool-versions
|
146 |
+
/.ruff_cache/
|
147 |
+
|
148 |
+
*.pkl
|
149 |
+
*.bin
|
150 |
+
|
151 |
+
# integration test artifacts
|
152 |
+
data_map*
|
153 |
+
\[('_type', 'fake'), ('stop', None)]
|
154 |
+
|
155 |
+
# Replit files
|
156 |
+
*replit*
|
157 |
+
|
158 |
+
node_modules
|
159 |
+
docs/.yarn/
|
160 |
+
docs/node_modules/
|
161 |
+
docs/.docusaurus/
|
162 |
+
docs/.cache-loader/
|
163 |
+
docs/_dist
|
164 |
+
docs/api_reference/_build
|
165 |
+
docs/docs_skeleton/build
|
166 |
+
docs/docs_skeleton/node_modules
|
167 |
+
docs/docs_skeleton/yarn.lock
|
.pre-commit-config.yaml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
repos:
|
2 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
3 |
+
rev: v4.4.0
|
4 |
+
hooks:
|
5 |
+
- id: check-yaml
|
6 |
+
- id: end-of-file-fixer
|
7 |
+
- id: trailing-whitespace
|
8 |
+
- repo: https://github.com/psf/black
|
9 |
+
rev: 23.3.0
|
10 |
+
hooks:
|
11 |
+
- id: black
|
12 |
+
# It is recommended to specify the latest version of Python
|
13 |
+
# supported by your project here, or alternatively use
|
14 |
+
# pre-commit's default_language_version, see
|
15 |
+
# https://pre-commit.com/#top_level-default_language_version
|
16 |
+
language_version: python3.11
|
17 |
+
args: ["--line-length", "100"]
|
LICENSE
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
202 |
+
|
README.md
CHANGED
@@ -5,7 +5,7 @@ colorFrom: gray
|
|
5 |
colorTo: pink
|
6 |
sdk: streamlit
|
7 |
sdk_version: 1.21.0
|
8 |
-
app_file:
|
9 |
pinned: false
|
10 |
---
|
11 |
|
|
|
5 |
colorTo: pink
|
6 |
sdk: streamlit
|
7 |
sdk_version: 1.21.0
|
8 |
+
app_file: streamlit_agent\mrkl_demo.py
|
9 |
pinned: false
|
10 |
---
|
11 |
|
README_.md
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# π¦οΈπ LangChain π€ Streamlit agent examples
|
2 |
+
|
3 |
+
[](https://codespaces.new/langchain-ai/streamlit-agent?quickstart=1)
|
4 |
+
|
5 |
+
This repository contains reference implementations of various LangChain agents as Streamlit apps including:
|
6 |
+
|
7 |
+
- `basic_streaming.py`: How to do streaming with a simple app using `langchain.chat_models.ChatOpenAI`
|
8 |
+
- `mrkl_demo.py`: An agent that replicates the [MRKL demo](https://python.langchain.com/docs/modules/agents/how_to/mrkl)
|
9 |
+
- `minimal_agent.py`: A minimal agent with search (requires setting `OPENAI_API_KEY` env to run)
|
10 |
+
- `search_and_chat.py`: A search-enabled chatbot that remembers chat history
|
11 |
+
|
12 |
+
Apps feature LangChain π€ Streamlit integrations such as the
|
13 |
+
[Callback integration](https://python.langchain.com/docs/modules/callbacks/integrations/streamlit).
|
14 |
+
|
15 |
+
## Setup
|
16 |
+
|
17 |
+
This project uses [Poetry](https://python-poetry.org/) for dependency management.
|
18 |
+
|
19 |
+
```shell
|
20 |
+
# Create Python environment
|
21 |
+
$ poetry install
|
22 |
+
|
23 |
+
# Install git pre-commit hooks
|
24 |
+
$ poetry shell
|
25 |
+
$ pre-commit install
|
26 |
+
```
|
27 |
+
|
28 |
+
## Running
|
29 |
+
|
30 |
+
```shell
|
31 |
+
# Run mrkl_demo.py or another app the same way
|
32 |
+
$ streamlit run streamlit_agent/mrkl_demo.py
|
33 |
+
```
|
34 |
+
|
35 |
+
## Contributing
|
36 |
+
|
37 |
+
We plan to add more agent examples over time - PRs welcome
|
38 |
+
|
39 |
+
- [ ] Chat QA over docs
|
40 |
+
- [ ] SQL agent
|
poetry.lock
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pyproject.toml
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[tool.poetry]
|
2 |
+
name = "streamlit-agent"
|
3 |
+
version = "0.1.0"
|
4 |
+
description = ""
|
5 |
+
authors = ["Tim Conkling <[email protected]>", "Joshua Carroll <[email protected]>"]
|
6 |
+
license = "Apache 2.0"
|
7 |
+
readme = "README.md"
|
8 |
+
packages = [{include = "streamlit_agent"}]
|
9 |
+
|
10 |
+
[tool.poetry.dependencies]
|
11 |
+
python = "^3.11"
|
12 |
+
langchain = ">=0.0.216"
|
13 |
+
streamlit = ">=1.24.0"
|
14 |
+
openai = "^0.27.8"
|
15 |
+
duckduckgo-search = "^3.8.3"
|
16 |
+
|
17 |
+
|
18 |
+
[tool.poetry.group.dev.dependencies]
|
19 |
+
black = "^23.3.0"
|
20 |
+
mypy = "^1.4.1"
|
21 |
+
pre-commit = "^3.3.3"
|
22 |
+
|
23 |
+
[build-system]
|
24 |
+
requires = ["poetry-core"]
|
25 |
+
build-backend = "poetry.core.masonry.api"
|
streamlit_agent/Chinook.db
ADDED
Binary file (913 kB). View file
|
|
streamlit_agent/__init__.py
ADDED
File without changes
|
streamlit_agent/basic_streaming.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.callbacks.base import BaseCallbackHandler
|
2 |
+
from langchain.chat_models import ChatOpenAI
|
3 |
+
from langchain.schema import ChatMessage
|
4 |
+
import streamlit as st
|
5 |
+
|
6 |
+
|
7 |
+
class StreamHandler(BaseCallbackHandler):
|
8 |
+
def __init__(self, container, initial_text=""):
|
9 |
+
self.container = container
|
10 |
+
self.text = initial_text
|
11 |
+
|
12 |
+
def on_llm_new_token(self, token: str, **kwargs) -> None:
|
13 |
+
self.text += token
|
14 |
+
self.container.markdown(self.text)
|
15 |
+
|
16 |
+
|
17 |
+
with st.sidebar:
|
18 |
+
openai_api_key = st.text_input("OpenAI API Key", type="password")
|
19 |
+
|
20 |
+
if "messages" not in st.session_state:
|
21 |
+
st.session_state["messages"] = [ChatMessage(role="assistant", content="How can I help you?")]
|
22 |
+
|
23 |
+
for msg in st.session_state.messages:
|
24 |
+
st.chat_message(msg.role).write(msg.content)
|
25 |
+
|
26 |
+
if prompt := st.chat_input():
|
27 |
+
st.session_state.messages.append(ChatMessage(role="user", content=prompt))
|
28 |
+
st.chat_message("user").write(prompt)
|
29 |
+
|
30 |
+
if not openai_api_key:
|
31 |
+
st.info("Please add your OpenAI API key to continue.")
|
32 |
+
st.stop()
|
33 |
+
|
34 |
+
with st.chat_message("assistant"):
|
35 |
+
stream_handler = StreamHandler(st.empty())
|
36 |
+
llm = ChatOpenAI(openai_api_key=openai_api_key, streaming=True, callbacks=[stream_handler])
|
37 |
+
response = llm(st.session_state.messages)
|
38 |
+
st.session_state.messages.append(ChatMessage(role="assistant", content=response.content))
|
streamlit_agent/callbacks/__init__.py
ADDED
File without changes
|
streamlit_agent/callbacks/capturing_callback_handler.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Callback Handler captures all callbacks in a session for future offline playback."""
|
2 |
+
|
3 |
+
from __future__ import annotations
|
4 |
+
|
5 |
+
import pickle
|
6 |
+
import time
|
7 |
+
from typing import Any, TypedDict
|
8 |
+
|
9 |
+
from langchain.callbacks.base import BaseCallbackHandler
|
10 |
+
|
11 |
+
|
12 |
+
# This is intentionally not an enum so that we avoid serializing a
|
13 |
+
# custom class with pickle.
|
14 |
+
class CallbackType:
|
15 |
+
ON_LLM_START = "on_llm_start"
|
16 |
+
ON_LLM_NEW_TOKEN = "on_llm_new_token"
|
17 |
+
ON_LLM_END = "on_llm_end"
|
18 |
+
ON_LLM_ERROR = "on_llm_error"
|
19 |
+
ON_TOOL_START = "on_tool_start"
|
20 |
+
ON_TOOL_END = "on_tool_end"
|
21 |
+
ON_TOOL_ERROR = "on_tool_error"
|
22 |
+
ON_TEXT = "on_text"
|
23 |
+
ON_CHAIN_START = "on_chain_start"
|
24 |
+
ON_CHAIN_END = "on_chain_end"
|
25 |
+
ON_CHAIN_ERROR = "on_chain_error"
|
26 |
+
ON_AGENT_ACTION = "on_agent_action"
|
27 |
+
ON_AGENT_FINISH = "on_agent_finish"
|
28 |
+
|
29 |
+
|
30 |
+
# We use TypedDict, rather than NamedTuple, so that we avoid serializing a
|
31 |
+
# custom class with pickle. All of this class's members should be basic Python types.
|
32 |
+
class CallbackRecord(TypedDict):
|
33 |
+
callback_type: str
|
34 |
+
args: tuple[Any, ...]
|
35 |
+
kwargs: dict[str, Any]
|
36 |
+
time_delta: float # Number of seconds between this record and the previous one
|
37 |
+
|
38 |
+
|
39 |
+
def load_records_from_file(path: str) -> list[CallbackRecord]:
|
40 |
+
"""Load the list of CallbackRecords from a pickle file at the given path."""
|
41 |
+
with open(path, "rb") as file:
|
42 |
+
records = pickle.load(file)
|
43 |
+
|
44 |
+
if not isinstance(records, list):
|
45 |
+
raise RuntimeError(f"Bad CallbackRecord data in {path}")
|
46 |
+
return records
|
47 |
+
|
48 |
+
|
49 |
+
def playback_callbacks(
|
50 |
+
handlers: list[BaseCallbackHandler],
|
51 |
+
records_or_filename: list[CallbackRecord] | str,
|
52 |
+
max_pause_time: float,
|
53 |
+
) -> str:
|
54 |
+
if isinstance(records_or_filename, list):
|
55 |
+
records = records_or_filename
|
56 |
+
else:
|
57 |
+
records = load_records_from_file(records_or_filename)
|
58 |
+
|
59 |
+
for record in records:
|
60 |
+
pause_time = min(record["time_delta"], max_pause_time)
|
61 |
+
if pause_time > 0:
|
62 |
+
time.sleep(pause_time)
|
63 |
+
|
64 |
+
for handler in handlers:
|
65 |
+
if record["callback_type"] == CallbackType.ON_LLM_START:
|
66 |
+
handler.on_llm_start(*record["args"], **record["kwargs"])
|
67 |
+
elif record["callback_type"] == CallbackType.ON_LLM_NEW_TOKEN:
|
68 |
+
handler.on_llm_new_token(*record["args"], **record["kwargs"])
|
69 |
+
elif record["callback_type"] == CallbackType.ON_LLM_END:
|
70 |
+
handler.on_llm_end(*record["args"], **record["kwargs"])
|
71 |
+
elif record["callback_type"] == CallbackType.ON_LLM_ERROR:
|
72 |
+
handler.on_llm_error(*record["args"], **record["kwargs"])
|
73 |
+
elif record["callback_type"] == CallbackType.ON_TOOL_START:
|
74 |
+
handler.on_tool_start(*record["args"], **record["kwargs"])
|
75 |
+
elif record["callback_type"] == CallbackType.ON_TOOL_END:
|
76 |
+
handler.on_tool_end(*record["args"], **record["kwargs"])
|
77 |
+
elif record["callback_type"] == CallbackType.ON_TOOL_ERROR:
|
78 |
+
handler.on_tool_error(*record["args"], **record["kwargs"])
|
79 |
+
elif record["callback_type"] == CallbackType.ON_TEXT:
|
80 |
+
handler.on_text(*record["args"], **record["kwargs"])
|
81 |
+
elif record["callback_type"] == CallbackType.ON_CHAIN_START:
|
82 |
+
handler.on_chain_start(*record["args"], **record["kwargs"])
|
83 |
+
elif record["callback_type"] == CallbackType.ON_CHAIN_END:
|
84 |
+
handler.on_chain_end(*record["args"], **record["kwargs"])
|
85 |
+
elif record["callback_type"] == CallbackType.ON_CHAIN_ERROR:
|
86 |
+
handler.on_chain_error(*record["args"], **record["kwargs"])
|
87 |
+
elif record["callback_type"] == CallbackType.ON_AGENT_ACTION:
|
88 |
+
handler.on_agent_action(*record["args"], **record["kwargs"])
|
89 |
+
elif record["callback_type"] == CallbackType.ON_AGENT_FINISH:
|
90 |
+
handler.on_agent_finish(*record["args"], **record["kwargs"])
|
91 |
+
|
92 |
+
# Return the agent's result
|
93 |
+
for record in records:
|
94 |
+
if record["callback_type"] == CallbackType.ON_AGENT_FINISH:
|
95 |
+
return record["args"][0][0]["output"]
|
96 |
+
|
97 |
+
return "[Missing Agent Result]"
|
98 |
+
|
99 |
+
|
100 |
+
class CapturingCallbackHandler(BaseCallbackHandler):
|
101 |
+
def __init__(self) -> None:
|
102 |
+
self._records: list[CallbackRecord] = []
|
103 |
+
self._last_time: float | None = None
|
104 |
+
|
105 |
+
def dump_records_to_file(self, path: str) -> None:
|
106 |
+
"""Write the list of CallbackRecords to a pickle file at the given path."""
|
107 |
+
with open(path, "wb") as file:
|
108 |
+
pickle.dump(self._records, file)
|
109 |
+
|
110 |
+
def _append_record(
|
111 |
+
self, type: str, args: tuple[Any, ...], kwargs: dict[str, Any]
|
112 |
+
) -> None:
|
113 |
+
time_now = time.time()
|
114 |
+
time_delta = time_now - self._last_time if self._last_time is not None else 0
|
115 |
+
self._last_time = time_now
|
116 |
+
self._records.append(
|
117 |
+
CallbackRecord(
|
118 |
+
callback_type=type, args=args, kwargs=kwargs, time_delta=time_delta
|
119 |
+
)
|
120 |
+
)
|
121 |
+
|
122 |
+
def on_llm_start(self, *args: Any, **kwargs: Any) -> None:
|
123 |
+
self._append_record(CallbackType.ON_LLM_START, args, kwargs)
|
124 |
+
|
125 |
+
def on_llm_new_token(self, *args: Any, **kwargs: Any) -> None:
|
126 |
+
self._append_record(CallbackType.ON_LLM_NEW_TOKEN, args, kwargs)
|
127 |
+
|
128 |
+
def on_llm_end(self, *args: Any, **kwargs: Any) -> None:
|
129 |
+
self._append_record(CallbackType.ON_LLM_END, args, kwargs)
|
130 |
+
|
131 |
+
def on_llm_error(self, *args: Any, **kwargs: Any) -> None:
|
132 |
+
self._append_record(CallbackType.ON_LLM_ERROR, args, kwargs)
|
133 |
+
|
134 |
+
def on_tool_start(self, *args: Any, **kwargs: Any) -> None:
|
135 |
+
self._append_record(CallbackType.ON_TOOL_START, args, kwargs)
|
136 |
+
|
137 |
+
def on_tool_end(self, *args: Any, **kwargs: Any) -> None:
|
138 |
+
self._append_record(CallbackType.ON_TOOL_END, args, kwargs)
|
139 |
+
|
140 |
+
def on_tool_error(self, *args: Any, **kwargs: Any) -> None:
|
141 |
+
self._append_record(CallbackType.ON_TOOL_ERROR, args, kwargs)
|
142 |
+
|
143 |
+
def on_text(self, *args: Any, **kwargs: Any) -> None:
|
144 |
+
self._append_record(CallbackType.ON_TEXT, args, kwargs)
|
145 |
+
|
146 |
+
def on_chain_start(self, *args: Any, **kwargs: Any) -> None:
|
147 |
+
self._append_record(CallbackType.ON_CHAIN_START, args, kwargs)
|
148 |
+
|
149 |
+
def on_chain_end(self, *args: Any, **kwargs: Any) -> None:
|
150 |
+
self._append_record(CallbackType.ON_CHAIN_END, args, kwargs)
|
151 |
+
|
152 |
+
def on_chain_error(self, *args: Any, **kwargs: Any) -> None:
|
153 |
+
self._append_record(CallbackType.ON_CHAIN_ERROR, args, kwargs)
|
154 |
+
|
155 |
+
def on_agent_action(self, *args: Any, **kwargs: Any) -> Any:
|
156 |
+
self._append_record(CallbackType.ON_AGENT_ACTION, args, kwargs)
|
157 |
+
|
158 |
+
def on_agent_finish(self, *args: Any, **kwargs: Any) -> None:
|
159 |
+
self._append_record(CallbackType.ON_AGENT_FINISH, args, kwargs)
|
streamlit_agent/clear_results.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
|
4 |
+
# A hack to "clear" the previous result when submitting a new prompt. This avoids
|
5 |
+
# the "previous run's text is grayed-out but visible during rerun" Streamlit behavior.
|
6 |
+
class DirtyState:
|
7 |
+
NOT_DIRTY = "NOT_DIRTY"
|
8 |
+
DIRTY = "DIRTY"
|
9 |
+
UNHANDLED_SUBMIT = "UNHANDLED_SUBMIT"
|
10 |
+
|
11 |
+
|
12 |
+
def get_dirty_state() -> str:
|
13 |
+
return st.session_state.get("dirty_state", DirtyState.NOT_DIRTY)
|
14 |
+
|
15 |
+
|
16 |
+
def set_dirty_state(state: str) -> None:
|
17 |
+
st.session_state["dirty_state"] = state
|
18 |
+
|
19 |
+
|
20 |
+
def with_clear_container(submit_clicked: bool) -> bool:
|
21 |
+
if get_dirty_state() == DirtyState.DIRTY:
|
22 |
+
if submit_clicked:
|
23 |
+
set_dirty_state(DirtyState.UNHANDLED_SUBMIT)
|
24 |
+
st.experimental_rerun()
|
25 |
+
else:
|
26 |
+
set_dirty_state(DirtyState.NOT_DIRTY)
|
27 |
+
|
28 |
+
if submit_clicked or get_dirty_state() == DirtyState.UNHANDLED_SUBMIT:
|
29 |
+
set_dirty_state(DirtyState.DIRTY)
|
30 |
+
return True
|
31 |
+
|
32 |
+
return False
|
streamlit_agent/minimal_agent.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.llms import OpenAI
|
2 |
+
from langchain.agents import AgentType, initialize_agent, load_tools
|
3 |
+
from langchain.callbacks import StreamlitCallbackHandler
|
4 |
+
import streamlit as st
|
5 |
+
|
6 |
+
llm = OpenAI(temperature=0, streaming=True)
|
7 |
+
tools = load_tools(["ddg-search"])
|
8 |
+
agent = initialize_agent(
|
9 |
+
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
|
10 |
+
)
|
11 |
+
|
12 |
+
if prompt := st.chat_input():
|
13 |
+
st.chat_message("user").write(prompt)
|
14 |
+
with st.chat_message("assistant"):
|
15 |
+
st_callback = StreamlitCallbackHandler(st.container())
|
16 |
+
response = agent.run(prompt, callbacks=[st_callback])
|
17 |
+
st.write(response)
|
streamlit_agent/mrkl_demo.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
|
3 |
+
import streamlit as st
|
4 |
+
|
5 |
+
from langchain import SQLDatabase
|
6 |
+
from langchain.agents import AgentType
|
7 |
+
from langchain.agents import initialize_agent, Tool
|
8 |
+
from langchain.callbacks import StreamlitCallbackHandler
|
9 |
+
from langchain.chains import LLMMathChain, SQLDatabaseChain
|
10 |
+
from langchain.llms import OpenAI
|
11 |
+
from langchain.utilities import DuckDuckGoSearchAPIWrapper
|
12 |
+
|
13 |
+
from streamlit_agent.callbacks.capturing_callback_handler import playback_callbacks
|
14 |
+
from streamlit_agent.clear_results import with_clear_container
|
15 |
+
|
16 |
+
DB_PATH = (Path(__file__).parent / "Chinook.db").absolute()
|
17 |
+
|
18 |
+
SAVED_SESSIONS = {
|
19 |
+
"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?": "leo.pickle",
|
20 |
+
"What is the full name of the artist who recently released an album called "
|
21 |
+
"'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs "
|
22 |
+
"are in the FooBar database?": "alanis.pickle",
|
23 |
+
}
|
24 |
+
|
25 |
+
st.set_page_config(
|
26 |
+
page_title="MRKL", page_icon="π¦", layout="wide", initial_sidebar_state="collapsed"
|
27 |
+
)
|
28 |
+
|
29 |
+
"# π¦π MRKL"
|
30 |
+
|
31 |
+
# Setup credentials in Streamlit
|
32 |
+
user_openai_api_key = st.sidebar.text_input(
|
33 |
+
"OpenAI API Key", type="password", help="Set this to run your own custom questions."
|
34 |
+
)
|
35 |
+
|
36 |
+
if user_openai_api_key:
|
37 |
+
openai_api_key = user_openai_api_key
|
38 |
+
enable_custom = True
|
39 |
+
else:
|
40 |
+
openai_api_key = "not_supplied"
|
41 |
+
enable_custom = False
|
42 |
+
|
43 |
+
# Tools setup
|
44 |
+
llm = OpenAI(temperature=0, openai_api_key=openai_api_key, streaming=True)
|
45 |
+
search = DuckDuckGoSearchAPIWrapper()
|
46 |
+
llm_math_chain = LLMMathChain.from_llm(llm)
|
47 |
+
db = SQLDatabase.from_uri(f"sqlite:///{DB_PATH}")
|
48 |
+
db_chain = SQLDatabaseChain.from_llm(llm, db)
|
49 |
+
tools = [
|
50 |
+
Tool(
|
51 |
+
name="Search",
|
52 |
+
func=search.run,
|
53 |
+
description="useful for when you need to answer questions about current events. You should ask targeted questions",
|
54 |
+
),
|
55 |
+
Tool(
|
56 |
+
name="Calculator",
|
57 |
+
func=llm_math_chain.run,
|
58 |
+
description="useful for when you need to answer questions about math",
|
59 |
+
),
|
60 |
+
Tool(
|
61 |
+
name="FooBar DB",
|
62 |
+
func=db_chain.run,
|
63 |
+
description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context",
|
64 |
+
),
|
65 |
+
]
|
66 |
+
|
67 |
+
# Initialize agent
|
68 |
+
mrkl = initialize_agent(
|
69 |
+
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
|
70 |
+
)
|
71 |
+
|
72 |
+
with st.form(key="form"):
|
73 |
+
if not enable_custom:
|
74 |
+
"Ask one of the sample questions, or enter your API Key in the sidebar to ask your own custom questions."
|
75 |
+
prefilled = st.selectbox("Sample questions", sorted(SAVED_SESSIONS.keys())) or ""
|
76 |
+
mrkl_input = ""
|
77 |
+
|
78 |
+
if enable_custom:
|
79 |
+
user_input = st.text_input("Or, ask your own question")
|
80 |
+
if not mrkl_input:
|
81 |
+
user_input = prefilled
|
82 |
+
submit_clicked = st.form_submit_button("Submit Question")
|
83 |
+
|
84 |
+
output_container = st.empty()
|
85 |
+
if with_clear_container(submit_clicked):
|
86 |
+
output_container = output_container.container()
|
87 |
+
output_container.chat_message("user").write(user_input)
|
88 |
+
|
89 |
+
answer_container = output_container.chat_message("assistant", avatar="π¦")
|
90 |
+
st_callback = StreamlitCallbackHandler(answer_container)
|
91 |
+
|
92 |
+
# If we've saved this question, play it back instead of actually running LangChain
|
93 |
+
# (so that we don't exhaust our API calls unnecessarily)
|
94 |
+
if user_input in SAVED_SESSIONS:
|
95 |
+
session_name = SAVED_SESSIONS[user_input]
|
96 |
+
session_path = Path(__file__).parent / "runs" / session_name
|
97 |
+
print(f"Playing saved session: {session_path}")
|
98 |
+
answer = playback_callbacks([st_callback], str(session_path), max_pause_time=2)
|
99 |
+
else:
|
100 |
+
answer = mrkl.run(user_input, callbacks=[st_callback])
|
101 |
+
|
102 |
+
answer_container.write(answer)
|
streamlit_agent/runs/alanis.pickle
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0a9e28abe936e327d1dbebcab8416f7d46a875ce9a0daf06073ecfd0b1c09414
|
3 |
+
size 60689
|
streamlit_agent/runs/leo.pickle
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0f2c0ae12968c6715c16d9af53cad58df80816406b0822fe19efc23748bf6ace
|
3 |
+
size 28543
|
streamlit_agent/search_and_chat.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.agents import initialize_agent, AgentType
|
2 |
+
from langchain.callbacks import StreamlitCallbackHandler
|
3 |
+
from langchain.chat_models import ChatOpenAI
|
4 |
+
from langchain.tools import DuckDuckGoSearchRun
|
5 |
+
import streamlit as st
|
6 |
+
|
7 |
+
st.set_page_config(page_title="LangChain: Chat with search", page_icon="π¦")
|
8 |
+
st.title("π¦ LangChain: Chat with search")
|
9 |
+
|
10 |
+
openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")
|
11 |
+
if "messages" not in st.session_state:
|
12 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
|
13 |
+
|
14 |
+
for msg in st.session_state.messages:
|
15 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
16 |
+
|
17 |
+
if prompt := st.chat_input(placeholder="Who won the Women's U.S. Open in 2018?"):
|
18 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
19 |
+
st.chat_message("user").write(prompt)
|
20 |
+
|
21 |
+
if not openai_api_key:
|
22 |
+
st.info("Please add your OpenAI API key to continue.")
|
23 |
+
st.stop()
|
24 |
+
|
25 |
+
llm = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True)
|
26 |
+
search_agent = initialize_agent(
|
27 |
+
tools=[DuckDuckGoSearchRun(name="Search")],
|
28 |
+
llm=llm,
|
29 |
+
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
30 |
+
handle_parsing_errors=True,
|
31 |
+
)
|
32 |
+
with st.chat_message("assistant"):
|
33 |
+
st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
|
34 |
+
response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
|
35 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
36 |
+
st.write(response)
|