KimaniKibuthu commited on
Commit
55faf85
·
1 Parent(s): 99c7019

Initial commit

Browse files
Files changed (11) hide show
  1. .gitignore +161 -0
  2. .pre-commit-config.yaml +18 -0
  3. LICENSE +201 -0
  4. Mind map (1).png +0 -0
  5. README.md +65 -13
  6. app.py +98 -0
  7. notebooks/chat_over_docs.ipynb +455 -0
  8. poetry.lock +0 -0
  9. prompts.py +54 -0
  10. pyproject.toml +29 -0
  11. utils.py +23 -0
.gitignore ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ notebooks/db
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+ .env
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ #Pipfile.lock
97
+
98
+ # poetry
99
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103
+ #poetry.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/#use-with-ide
111
+ .pdm.toml
112
+
113
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114
+ __pypackages__/
115
+
116
+ # Celery stuff
117
+ celerybeat-schedule
118
+ celerybeat.pid
119
+
120
+ # SageMath parsed files
121
+ *.sage.py
122
+
123
+ # Environments
124
+ .env
125
+ .venv
126
+ env/
127
+ venv/
128
+ ENV/
129
+ env.bak/
130
+ venv.bak/
131
+
132
+ # Spyder project settings
133
+ .spyderproject
134
+ .spyproject
135
+
136
+ # Rope project settings
137
+ .ropeproject
138
+
139
+ # mkdocs documentation
140
+ /site
141
+
142
+ # mypy
143
+ .mypy_cache/
144
+ .dmypy.json
145
+ dmypy.json
146
+
147
+ # Pyre type checker
148
+ .pyre/
149
+
150
+ # pytype static type analyzer
151
+ .pytype/
152
+
153
+ # Cython debug symbols
154
+ cython_debug/
155
+
156
+ # PyCharm
157
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
158
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
159
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
160
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
161
+ #.idea/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v2.3.0
4
+ hooks:
5
+ - id: check-yaml
6
+ - id: end-of-file-fixer
7
+ - id: trailing-whitespace
8
+ - id: detect-private-key
9
+ - id: check-added-large-files
10
+ - repo: https://github.com/psf/black
11
+ rev: 22.10.0
12
+ hooks:
13
+ - id: black
14
+ - repo: https://github.com/PyCQA/autoflake
15
+ rev: v2.2.1
16
+ hooks:
17
+ - id: autoflake
18
+ args: [--remove-all-unused-imports, --in-place]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
Mind map (1).png ADDED
README.md CHANGED
@@ -1,13 +1,65 @@
1
- ---
2
- title: Chat Over Docs
3
- emoji: 🔥
4
- colorFrom: indigo
5
- colorTo: gray
6
- sdk: streamlit
7
- sdk_version: 1.32.1
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chatbot Developer Assistant
2
+
3
+ This is a Streamlit-based chatbot application designed to assist developers in building software by providing step-by-step guides on specific technologies or frameworks. The chatbot leverages an agent to search the internet based on user queries and returns a detailed guide to solve the query.
4
+
5
+ ![Basic Flow](<Mind map (1).png>)
6
+
7
+ ## Features
8
+
9
+ 1. User-friendly chat interface for developers to ask questions about specific technologies or frameworks.
10
+ 2. Intelligent agent that searches the web for relevant information based on the user's query.
11
+ 3. Step-by-step guides generated dynamically to help developers solve their programming problems.
12
+ 4. Markdown support for code snippets and formatting in the generated guides.
13
+
14
+ ## Installation
15
+
16
+ 1. Clone the repository:
17
+
18
+
19
+ `git clone https://github.com/KimaniKibuthu/chat_over_docs.git`
20
+
21
+ 2. Install Poetry (if not already installed):
22
+
23
+ `pip install poetry`
24
+
25
+ 3. Install the project dependencies:
26
+
27
+ `poetry install`
28
+
29
+ 4. Go into the virtual environment
30
+
31
+ `poetry shell`
32
+
33
+ 5. Setup environments by adding a .env file at the root directory and fill in these API keys:
34
+
35
+ ``` .env
36
+ LANGCHAIN_API_KEY=""
37
+ LANGCHAIN_PROJECT="chat_over_docs"
38
+ LANGCHAIN_TRACING_V2="true"
39
+ HUGGINGFACEHUB_API_TOKEN=""
40
+ TAVILY_API_KEY=""
41
+ ```
42
+
43
+ For the langchain API key, check: https://docs.smith.langchain.com/setup
44
+
45
+ For the huggingface API key, check: https://huggingface.co/docs/api-inference/en/quicktour#get-your-api-token
46
+
47
+ For the Tavily API key, check: https://app.tavily.com/
48
+
49
+
50
+ ## Usage
51
+
52
+ 1. Run the Streamlit app:
53
+
54
+ `poetry run streamlit run app.py`
55
+
56
+ 2. Open the provided URL in your web browser.
57
+
58
+ 3. Start chatting with the developer assistant by typing your query in the chat window.
59
+
60
+
61
+ ## Contributing
62
+ Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.
63
+
64
+ ## License
65
+ This project is licensed under the Apache 2.0 License
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import random
3
+ from dotenv import load_dotenv
4
+ from langchain_community.tools.tavily_search import TavilySearchResults
5
+ from langchain.agents import AgentExecutor, Tool, create_react_agent
6
+ from langchain_community.llms import HuggingFaceEndpoint
7
+ from langchain.prompts import PromptTemplate
8
+ from utils import RetryCallbackHandler
9
+ from prompts import prompt_two
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+
14
+ # Create prompts
15
+
16
+ prompt_template = PromptTemplate.from_template(prompt_two)
17
+
18
+
19
+ # Mixtral LLM
20
+
21
+ repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
22
+
23
+ mixtral = HuggingFaceEndpoint(repo_id=repo_id, temperature=0.3)
24
+
25
+ # Instantiate error handler
26
+ error_handler = RetryCallbackHandler()
27
+
28
+ # Instantiate tools
29
+ search = TavilySearchResults()
30
+
31
+ tool_search_item = Tool(
32
+ name="search internet",
33
+ description="Searches the internet for the documentation and examples in order to answer a query",
34
+ func=search.run,
35
+ handle_tool_error=True,
36
+ )
37
+
38
+ # List of all tools
39
+ tools = [tool_search_item]
40
+
41
+ # Instantiate agents
42
+
43
+
44
+ agent = create_react_agent(mixtral, tools, prompt_template)
45
+
46
+
47
+ agent_executor = AgentExecutor(
48
+ agent=agent,
49
+ tools=tools,
50
+ verbose=True,
51
+ return_intermediate_steps=True,
52
+ handle_parsing_errors=True,
53
+ callbacks=[error_handler],
54
+ )
55
+
56
+
57
+ def main():
58
+ st.set_page_config(
59
+ page_title="Price Range Predictor, powered by gemini",
60
+ page_icon="🧠",
61
+ layout="centered",
62
+ initial_sidebar_state="auto",
63
+ menu_items=None,
64
+ )
65
+
66
+ st.title("🧠 Your Docs Helper")
67
+ st.caption("📋 A Helper to aid you with your questions on development")
68
+
69
+ spinner_messages = [
70
+ "Spinning up some code magic...",
71
+ "Finding answers faster than a speeding bullet...",
72
+ "Cooking up some code soup...",
73
+ "Holding on tight, we're about to take off into the coding cosmos...",
74
+ "Gathering data faster than a caffeinated programmer...",
75
+ "Revving up the engine... Vroom Vroom!",
76
+ "Brace yourself, the code storm is coming...",
77
+ "Warp speed engaged! Hold on to your keyboard!",
78
+ "Loading... or as we like to call it, the digital equivalent of holding your breath...",
79
+ "Building castles in the cloud... of code!",
80
+ ]
81
+
82
+ if "messages" not in st.session_state:
83
+ st.session_state["messages"] = [
84
+ {"role": "assistant", "content": "How can I help you?"}
85
+ ]
86
+
87
+ if prompt := st.chat_input("How can I help?"):
88
+ st.session_state.messages.append({"role": "user", "content": prompt})
89
+ st.chat_message("user").write(prompt)
90
+ with st.spinner(random.choice(spinner_messages)):
91
+ agent_response = agent_executor.invoke({"input": prompt})
92
+ agent_output = agent_response["output"]
93
+ st.session_state.messages.append({"role": "assistant", "content": agent_output})
94
+ st.chat_message("assistant").write(agent_output)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
notebooks/chat_over_docs.ipynb ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Price Discovery Project Using Agents\n",
8
+ "\n",
9
+ "This is a notebook that contains the experimentation of prioce discovery using agents."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "## Import Libraries"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": 14,
22
+ "metadata": {},
23
+ "outputs": [],
24
+ "source": [
25
+ "import os\n",
26
+ "import json\n",
27
+ "from typing import Any, Union\n",
28
+ "\n",
29
+ "\n",
30
+ "import PIL\n",
31
+ "from dotenv import load_dotenv\n",
32
+ "\n",
33
+ "from langchain_community.tools.tavily_search import TavilySearchResults\n",
34
+ "from langchain.agents import AgentExecutor, Tool, create_react_agent\n",
35
+ "from langchain.agents.agent import AgentAction\n",
36
+ "from langchain_core.callbacks.base import BaseCallbackHandler\n",
37
+ "from langchain_core.messages import HumanMessage\n",
38
+ "from langchain_community.llms import HuggingFaceEndpoint\n",
39
+ "from langchain_community.utilities import SerpAPIWrapper\n",
40
+ "from langchain.prompts import PromptTemplate\n",
41
+ "from langchain.tools.retriever import create_retriever_tool\n",
42
+ "from langchain_core.output_parsers import JsonOutputParser\n",
43
+ "\n"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "metadata": {},
49
+ "source": [
50
+ "## Specify Variables"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": 13,
56
+ "metadata": {},
57
+ "outputs": [
58
+ {
59
+ "data": {
60
+ "text/plain": [
61
+ "True"
62
+ ]
63
+ },
64
+ "execution_count": 13,
65
+ "metadata": {},
66
+ "output_type": "execute_result"
67
+ }
68
+ ],
69
+ "source": [
70
+ "\n",
71
+ "# Load environment variables\n",
72
+ "load_dotenv()"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "metadata": {},
78
+ "source": [
79
+ "## Create agent for retrieval"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "markdown",
84
+ "metadata": {},
85
+ "source": [
86
+ "**Instatiate the llms**"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": 6,
92
+ "metadata": {},
93
+ "outputs": [
94
+ {
95
+ "name": "stdout",
96
+ "output_type": "stream",
97
+ "text": [
98
+ "Token has not been saved to git credential helper. Pass `add_to_git_credential=True` if you want to set the git credential as well.\n",
99
+ "Token is valid (permission: read).\n",
100
+ "Your token has been saved to C:\\Users\\Spectra\\.cache\\huggingface\\token\n",
101
+ "Login successful\n"
102
+ ]
103
+ }
104
+ ],
105
+ "source": [
106
+ "# Mixtral\n",
107
+ "\n",
108
+ "repo_id = \"mistralai/Mixtral-8x7B-Instruct-v0.1\"\n",
109
+ "\n",
110
+ "mixtral = HuggingFaceEndpoint(\n",
111
+ " repo_id=repo_id,\n",
112
+ " temperature=0.3\n",
113
+ ")\n",
114
+ "\n"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": 7,
120
+ "metadata": {},
121
+ "outputs": [],
122
+ "source": [
123
+ "\n",
124
+ "# Setup google api\n",
125
+ "# GOOGLE_API_KEY = os.getenv(\"GOOGLE_API_KEY\")\n",
126
+ "\n",
127
+ "# gemini = ChatGoogleGenerativeAI(model=\"gemini-pro\", google_api_key=GOOGLE_API_KEY, temperature=0.3)\n",
128
+ "# gemini_vision = ChatGoogleGenerativeAI(model=\"gemini-pro-vision\", google_api_key=GOOGLE_API_KEY, temperature=0.1)"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "markdown",
133
+ "metadata": {},
134
+ "source": [
135
+ "**Instantiate prompts**"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "execution_count": 35,
141
+ "metadata": {},
142
+ "outputs": [],
143
+ "source": [
144
+ "\n",
145
+ "# Create prompts\n",
146
+ "prompt = \"\"\"\n",
147
+ "You are an expert software developer proficient at writing code and building reliable software. Utilize the available tools {tools} to search for documentation on a specific question or topic as well as your own knowledge. \n",
148
+ "Then, synthesize the information gathered to provide a detailed step by step quide with code examples that one can easily follow.\n",
149
+ "\n",
150
+ "\n",
151
+ "Use the following format:\n",
152
+ "\n",
153
+ "Question: the input question you must answer.\n",
154
+ "Thought: you should always think about what to do. \n",
155
+ "Action: the action to take, should be ONE of or ALL of [{tool_names}]. \n",
156
+ "Action Input: the input to the action. It SHOULD be a string.\n",
157
+ "Action: choose another tool if a tool fails or handle its error.\n",
158
+ "Observation: the result of the action, including insights gained or findings.\n",
159
+ "... (this Thought/Action/Action Input/Observation can repeat N times). If no result is found, use your own knowledge.\n",
160
+ "Thought: I should recheck my answer and make sure it meets the specifications. If not, try again before coming up with the final answer.\n",
161
+ "Thought: I now know the final answer that is based on the indepth analysis of your findings and observations. \n",
162
+ "Final Answer: the final answer to the original input question, which must be as accurate as possible. NEVER say you can't answer. \n",
163
+ "Begin!\n",
164
+ "\n",
165
+ "Question: {input}\n",
166
+ "Thought: {agent_scratchpad}\n",
167
+ "\n",
168
+ "\"\"\"\n",
169
+ "prompt_two = \"\"\"\n",
170
+ "\n",
171
+ "You are an expert developer assistant trained to help programmers build software. I can access and process information from the web using {tools}. \n",
172
+ "When a developer asks a question about a specific technology or framework, I will use my knowledge and search capabilities to:\n",
173
+ "\n",
174
+ "1. Find relevant documentation and tutorials on that framework.\n",
175
+ "2. Identify and extract code examples from the retrieved resources.\n",
176
+ "3. Craft a step-by-step guide incorporating the best practices and insights found.\n",
177
+ "4. Ensure the guide is detailed and answers the question asked.\n",
178
+ "5. Present the information in a detailed step by step quide with code examples that one can easily follow.\n",
179
+ "\n",
180
+ "\n",
181
+ "Use the following format:\n",
182
+ "\n",
183
+ "Question: the input question you must answer.\n",
184
+ "Thought: you should always think about what to do. \n",
185
+ "Action: the action to take, should be ONE of or ALL of [{tool_names}]. \n",
186
+ "Action Input: the input to the action. It SHOULD be a string.\n",
187
+ "Action: choose another tool if a tool fails or handle its error.\n",
188
+ "Observation: the result of the action, including insights gained or findings.\n",
189
+ "... (this Thought/Action/Action Input/Observation can repeat N times). If no result is found, use your own knowledge.\n",
190
+ "Thought: I should recheck my answer and make sure it meets the specifications. If not, try again before coming up with the final answer.\n",
191
+ "Thought: I now know the final answer that is based on the indepth analysis of your findings and observations. \n",
192
+ "Final Answer: the final answer to the original input question, which must be as accurate as possible. NEVER say you can't answer. \n",
193
+ "Begin!\n",
194
+ "\n",
195
+ "Question: {input}\n",
196
+ "Thought: {agent_scratchpad}\n",
197
+ "\n",
198
+ "\"\"\"\n",
199
+ "\n",
200
+ "\n",
201
+ "\n"
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "execution_count": 41,
207
+ "metadata": {},
208
+ "outputs": [],
209
+ "source": [
210
+ "prompt_template = PromptTemplate.from_template(prompt_two)"
211
+ ]
212
+ },
213
+ {
214
+ "cell_type": "markdown",
215
+ "metadata": {},
216
+ "source": [
217
+ "**Instantiate Agents**"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": 37,
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "# Instantiate error handler\n",
227
+ "class RetryCallbackHandler(BaseCallbackHandler):\n",
228
+ " def on_tool_error(\n",
229
+ " self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any\n",
230
+ " ) -> Any:\n",
231
+ " # Log the error or perform any necessary actions\n",
232
+ " \n",
233
+ " # Retry logic\n",
234
+ " max_retries = 1\n",
235
+ " current_retry = kwargs.get('retry_count', 0)\n",
236
+ " if current_retry < max_retries:\n",
237
+ " print(f\"Retrying tool execution (Attempt {current_retry + 1})\")\n",
238
+ " # Increment retry count\n",
239
+ " kwargs['retry_count'] = current_retry + 1\n",
240
+ " # Re-run the tool\n",
241
+ " return AgentAction.RERUN\n",
242
+ " else:\n",
243
+ " print(\"Maximum retries reached. Switching to another tool.\")\n",
244
+ " return AgentAction.CHANGE_TOOL"
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": 11,
250
+ "metadata": {},
251
+ "outputs": [],
252
+ "source": [
253
+ "# The error handler\n",
254
+ "error_handler = RetryCallbackHandler()"
255
+ ]
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "execution_count": 30,
260
+ "metadata": {},
261
+ "outputs": [],
262
+ "source": [
263
+ "# Create tools\n",
264
+ "search = TavilySearchResults()\n",
265
+ "\n",
266
+ "tool_search_item = Tool(\n",
267
+ " name=\"search internet\",\n",
268
+ " description=\"Searches the internet for the documentation and examples in order to answer a query\",\n",
269
+ " func=search.run,\n",
270
+ " handle_tool_error=True\n",
271
+ ")\n",
272
+ "\n",
273
+ "# List of all tools\n",
274
+ "tools = [tool_search_item]"
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "execution_count": 42,
280
+ "metadata": {},
281
+ "outputs": [
282
+ {
283
+ "ename": "ValueError",
284
+ "evalue": "Prompt missing required variables: {'tool_names', 'agent_scratchpad'}",
285
+ "output_type": "error",
286
+ "traceback": [
287
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
288
+ "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
289
+ "Cell \u001b[1;32mIn[42], line 4\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# Instantiate agents\u001b[39;00m\n\u001b[1;32m----> 4\u001b[0m agent \u001b[38;5;241m=\u001b[39m \u001b[43mcreate_react_agent\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmixtral\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtools\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mprompt_template\u001b[49m\u001b[43m)\u001b[49m \n\u001b[0;32m 8\u001b[0m agent_executor \u001b[38;5;241m=\u001b[39m AgentExecutor(agent\u001b[38;5;241m=\u001b[39magent,\n\u001b[0;32m 9\u001b[0m tools\u001b[38;5;241m=\u001b[39mtools,\n\u001b[0;32m 10\u001b[0m verbose\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 11\u001b[0m return_intermediate_steps\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 12\u001b[0m handle_parsing_errors\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 13\u001b[0m callbacks\u001b[38;5;241m=\u001b[39m[error_handler])\n",
290
+ "File \u001b[1;32mc:\\Users\\Spectra\\chat_over_docs\\.venv\\Lib\\site-packages\\langchain\\agents\\react\\agent.py:105\u001b[0m, in \u001b[0;36mcreate_react_agent\u001b[1;34m(llm, tools, prompt, output_parser, tools_renderer)\u001b[0m\n\u001b[0;32m 101\u001b[0m missing_vars \u001b[38;5;241m=\u001b[39m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtools\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtool_names\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124magent_scratchpad\u001b[39m\u001b[38;5;124m\"\u001b[39m}\u001b[38;5;241m.\u001b[39mdifference(\n\u001b[0;32m 102\u001b[0m prompt\u001b[38;5;241m.\u001b[39minput_variables\n\u001b[0;32m 103\u001b[0m )\n\u001b[0;32m 104\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m missing_vars:\n\u001b[1;32m--> 105\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPrompt missing required variables: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mmissing_vars\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 107\u001b[0m prompt \u001b[38;5;241m=\u001b[39m prompt\u001b[38;5;241m.\u001b[39mpartial(\n\u001b[0;32m 108\u001b[0m tools\u001b[38;5;241m=\u001b[39mtools_renderer(\u001b[38;5;28mlist\u001b[39m(tools)),\n\u001b[0;32m 109\u001b[0m tool_names\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m, \u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;241m.\u001b[39mjoin([t\u001b[38;5;241m.\u001b[39mname \u001b[38;5;28;01mfor\u001b[39;00m t \u001b[38;5;129;01min\u001b[39;00m tools]),\n\u001b[0;32m 110\u001b[0m )\n\u001b[0;32m 111\u001b[0m llm_with_stop \u001b[38;5;241m=\u001b[39m llm\u001b[38;5;241m.\u001b[39mbind(stop\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124mObservation\u001b[39m\u001b[38;5;124m\"\u001b[39m])\n",
291
+ "\u001b[1;31mValueError\u001b[0m: Prompt missing required variables: {'tool_names', 'agent_scratchpad'}"
292
+ ]
293
+ }
294
+ ],
295
+ "source": [
296
+ "\n",
297
+ "# Instantiate agents\n",
298
+ "\n",
299
+ "\n",
300
+ "agent = create_react_agent(mixtral, tools, prompt_template) \n",
301
+ "\n",
302
+ "\n",
303
+ "\n",
304
+ "agent_executor = AgentExecutor(agent=agent,\n",
305
+ " tools=tools,\n",
306
+ " verbose=True,\n",
307
+ " return_intermediate_steps=True,\n",
308
+ " handle_parsing_errors=True,\n",
309
+ " callbacks=[error_handler])\n"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "markdown",
314
+ "metadata": {},
315
+ "source": [
316
+ "**Run the pipeline**"
317
+ ]
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "execution_count": 39,
322
+ "metadata": {},
323
+ "outputs": [],
324
+ "source": [
325
+ "query = \"How do I use agents in langchain in order to create a RAG system\""
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": 40,
331
+ "metadata": {},
332
+ "outputs": [
333
+ {
334
+ "name": "stdout",
335
+ "output_type": "stream",
336
+ "text": [
337
+ "\n",
338
+ "\n",
339
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
340
+ "\u001b[32;1m\u001b[1;3mTo answer this question, I need to find information about using agents in LangChain and how to create a RAG (Red, Amber, Green) system. I will search the internet for relevant documentation and examples.\n",
341
+ "\n",
342
+ "Action: search internet\n",
343
+ "Action Input: \"langchain agents rag system tutorial\"\n",
344
+ "Observation\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://cheatsheet.md/langchain-tutorials/llm-rag.en', 'content': \"This article provides an in-depth understanding of LLM RAG, a vital Language Model in AI, and its working process. We delve into various prompt engineering techniques and their role in enhancing the functionality of LLM RAG. The article also explores practical applications of prompt engineering and its potential to transform LLM RAG's performance.\"}, {'url': 'https://towardsdatascience.com/using-langchain-react-agents-for-answering-multi-hop-questions-in-rag-systems-893208c1847e', 'content': '[Source]\\n--\\n--\\n2\\nWritten by Dr. Varshita Sher\\nTowards Data Science\\nSenior Data Scientist | Explain like I am 5 | Oxford & SFU Alumni | https://podurama.com | Top writer on Medium\\nHelp\\nStatus\\nAbout\\nCareers\\nBlog\\nPrivacy\\nTerms\\nText to speech\\nTeams Sign up\\nSign in\\nSign up\\nSign in\\nMember-only story\\n#LLM FOR BEGINNERS\\nUsing LangChain ReAct Agents for Answering Multi-hop Questions in RAG Systems\\nUseful when answering complex queries on internal documents in a step-by-step manner with ReAct and Open AI Tools agents.\\n Dr. Varshita Sher\\nFollow\\nTowards Data Science\\n--\\n2\\nShare\\nMotivation\\nThe basic RAG chatbots I have built in the past using standard LangChain components such as vectorstore, retrievers, etc have worked out well for me. Depending on the internal dataset I feed in, they are capable of handling humble questions such as “What is the parental leave policy in India” (source dataset: HR policy documents), “What are the main concerns regarding the flavor of our product” (source dataset: social media/Tweets), “What are the themes in Monet paintings” (source dataset: Art Journals), etc. More recently, the complexity of queries being fed to it has increased, for instance, “Has there been an increase in the concerns regarding flavor in the past 1 month”.'}, {'url': 'https://blog.langchain.dev/using-a-knowledge-graph-to-implement-a-devops-rag-application/', 'content': 'Result is the following\\nOf course, you can also ask the chain to produce variable-length path traversals by asking questions like:\\nSome of the mentioned services are the same as in the directly dependent question. Knowledge graph agent\\nSince we have implemented separate tools for the structured and unstructured parts of the knowledge graph, we can add an agent that can use these two tools to explore the knowledge graph.\\n It relies on the following ascii-art type of syntax:\\nThis patterns describes a node with a label Person and the name property Tomaz that has a LIVES_IN relationship to the Country node of Slovenia.\\n The neat thing about LangChain is that it provides a GraphCypherQAChain, which generates the Cypher queries for you, so you don’t have to learn Cypher syntax in order to retrieve information from a graph database like Neo4j.\\n Result is the following\\nYou can also ask the chain to aggregate the data using various grouping keys, like the following example.\\n'}, {'url': 'https://medium.com/@prasadmahamulkar/introduction-to-retrieval-augmented-generation-rag-using-langchain-and-lamaindex-bd0047628e2a', 'content': 'Sign up\\nSign in\\nSign up\\nSign in\\nRetrieval-Augmented Generation (RAG) using LangChain and LlamaIndex\\nStep-by-step implementation\\nPrasad Mahamulkar\\nFollow\\n--\\nListen\\nShare\\nLarge Language Models (LLMs) demonstrate significant capabilities but sometimes generate incorrect but believable responses when they lack information, and this is known as “hallucination.” Website: https://prasadmahamulkar.com/\\nHelp\\nStatus\\nAbout\\nCareers\\nBlog\\nPrivacy\\nTerms\\nText to speech\\nTeams Reference:\\nRetrieval-Augmented Generation for LLMs: A Survey\\nParent Document Retriever langChain Documentation\\nParent Document Reteriver LlamaIndex Documentation\\n--\\n--\\nWritten by Prasad Mahamulkar\\nMSc. Step 8: Finally, set up a query engine by combining the retriever and service context, and add a user query to get a relevant response.\\n The system prioritizes and retrieves the top K chunks showing the highest similarity, using them as an expanded contextual basis to address the user’s request.\\n'}, {'url': 'https://scalexi.medium.com/implementing-a-retrieval-augmented-generation-rag-system-with-openais-api-using-langchain-ab39b60b4d9f', 'content': 'Sign up\\nSign in\\nSign up\\nSign in\\nImplementing a Retrieval-Augmented Generation (RAG) System with OpenAI’s API using LangChain\\nScaleX Innovation\\nFollow\\n--\\n1\\nListen\\nShare\\nAbstract\\nIn this comprehensive guide, you’ll learn how to implement a Retrieval-Augmented Generation (RAG) system using OpenAI’s API using LangChain. Here’s a list of the libraries we’ll be installing:\\nTo install these, run the following commands in your Colab notebook:\\nAfter running these commands, your environment will be equipped with all the necessary tools to build a state-of-the-art RAG system.\\n This approach allows conversational AI to deliver more precise and contextually relevant responses by drawing upon a vast array of external information sources in addition to the model’s internal knowledge\\u200b\\u200b\\u200b\\u200b.\\nIn practice, RAG operates by first formulating a user’s query, then scouring large databases to retrieve pertinent information, selecting the most relevant data, and finally generating a response that is informed by this external knowledge. This not only elevates the quality of the conversation by making it more informative and relevant but also showcases the potential of RAG to transform the capabilities of conversational AIs across various applications\\u200b\\u200b\\u200b\\u200b.\\nThe Intuition Behind Retrieval-Augmented Generation (RAG)\\n Creating the Vector Store: The Heart of RAG\\nAt the heart of our RAG system is the Vector Store, a critical component that powers the searchability and retrieval capabilities of the chatbot.'}]\u001b[0m\u001b[32;1m\u001b[1;3mBased on the search results, I can see that there are several tutorials and articles about using LangChain for RAG systems, but none of them specifically mention using agents for RAG systems. However, I can use the information provided in these resources to create a custom solution for using agents in a LangChain RAG system.\n",
345
+ "\n",
346
+ "First, I will create a retriever to fetch relevant documents based on the user's query. Then, I will create a LangChain agent that uses the retrieved documents to generate a response.\n",
347
+ "\n",
348
+ "Thought: I should now create a step-by-step guide for the developer to use agents in a LangChain RAG system.\n",
349
+ "\n",
350
+ "Final Answer:\n",
351
+ "\n",
352
+ "To use agents in a LangChain RAG system, follow these steps:\n",
353
+ "\n",
354
+ "1. Install the necessary libraries:\n",
355
+ "\n",
356
+ "```python\n",
357
+ "pip install langchain\n",
358
+ "pip install openai\n",
359
+ "pip install faiss-cpu\n",
360
+ "pip install chromadb\n",
361
+ "```\n",
362
+ "\n",
363
+ "2. Create a retriever to fetch relevant documents based on the user's query:\n",
364
+ "\n",
365
+ "```python\n",
366
+ "from langchain.vectorstores import Chroma\n",
367
+ "from langchain.embeddings.openai import OpenAIEmbeddings\n",
368
+ "from langchain.retrievers import VectorStoreRetriever\n",
369
+ "\n",
370
+ "embeddings = OpenAIEmbeddings()\n",
371
+ "vectorstore = Chroma(embedding_function=embeddings)\n",
372
+ "retriever = VectorStoreRetriever(vectorstore=vectorstore)\n",
373
+ "```\n",
374
+ "\n",
375
+ "3. Create a LangChain agent that uses the retrieved documents to generate a response:\n",
376
+ "\n",
377
+ "```python\n",
378
+ "from langchain.agents import initialize_agent\n",
379
+ "from langchain.agents.agent_toolkits import LangchainToolkit\n",
380
+ "from langchain.llms import OpenAI\n",
381
+ "\n",
382
+ "toolkit = LangchainToolkit(retriever=retriever)\n",
383
+ "agent = initialize_agent(toolkit, llm=OpenAI(temperature=0.7))\n",
384
+ "```\n",
385
+ "\n",
386
+ "4. Use the agent to generate a response:\n",
387
+ "\n",
388
+ "```python\n",
389
+ "user_query = \"How do I build agents with LangChain?\"\n",
390
+ "agent_response = agent.run(user_query)\n",
391
+ "print(agent_response)\n",
392
+ "```\n",
393
+ "\n",
394
+ "This solution combines the power of LangChain's retrievers and agents to create a RAG system that can generate\u001b[0m\n",
395
+ "\n",
396
+ "\u001b[1m> Finished chain.\u001b[0m\n"
397
+ ]
398
+ },
399
+ {
400
+ "data": {
401
+ "text/plain": [
402
+ "{'input': 'How do I use agents in langchain in order to create a RAG system',\n",
403
+ " 'output': 'To use agents in a LangChain RAG system, follow these steps:\\n\\n1. Install the necessary libraries:\\n\\n```python\\npip install langchain\\npip install openai\\npip install faiss-cpu\\npip install chromadb\\n```\\n\\n2. Create a retriever to fetch relevant documents based on the user\\'s query:\\n\\n```python\\nfrom langchain.vectorstores import Chroma\\nfrom langchain.embeddings.openai import OpenAIEmbeddings\\nfrom langchain.retrievers import VectorStoreRetriever\\n\\nembeddings = OpenAIEmbeddings()\\nvectorstore = Chroma(embedding_function=embeddings)\\nretriever = VectorStoreRetriever(vectorstore=vectorstore)\\n```\\n\\n3. Create a LangChain agent that uses the retrieved documents to generate a response:\\n\\n```python\\nfrom langchain.agents import initialize_agent\\nfrom langchain.agents.agent_toolkits import LangchainToolkit\\nfrom langchain.llms import OpenAI\\n\\ntoolkit = LangchainToolkit(retriever=retriever)\\nagent = initialize_agent(toolkit, llm=OpenAI(temperature=0.7))\\n```\\n\\n4. Use the agent to generate a response:\\n\\n```python\\nuser_query = \"How do I build agents with LangChain?\"\\nagent_response = agent.run(user_query)\\nprint(agent_response)\\n```\\n\\nThis solution combines the power of LangChain\\'s retrievers and agents to create a RAG system that can generate',\n",
404
+ " 'intermediate_steps': [(AgentAction(tool='search internet', tool_input='langchain agents rag system tutorial\"\\nObservation', log='To answer this question, I need to find information about using agents in LangChain and how to create a RAG (Red, Amber, Green) system. I will search the internet for relevant documentation and examples.\\n\\nAction: search internet\\nAction Input: \"langchain agents rag system tutorial\"\\nObservation'),\n",
405
+ " [{'url': 'https://cheatsheet.md/langchain-tutorials/llm-rag.en',\n",
406
+ " 'content': \"This article provides an in-depth understanding of LLM RAG, a vital Language Model in AI, and its working process. We delve into various prompt engineering techniques and their role in enhancing the functionality of LLM RAG. The article also explores practical applications of prompt engineering and its potential to transform LLM RAG's performance.\"},\n",
407
+ " {'url': 'https://towardsdatascience.com/using-langchain-react-agents-for-answering-multi-hop-questions-in-rag-systems-893208c1847e',\n",
408
+ " 'content': '[Source]\\n--\\n--\\n2\\nWritten by Dr. Varshita Sher\\nTowards Data Science\\nSenior Data Scientist | Explain like I am 5 | Oxford & SFU Alumni | https://podurama.com | Top writer on Medium\\nHelp\\nStatus\\nAbout\\nCareers\\nBlog\\nPrivacy\\nTerms\\nText to speech\\nTeams Sign up\\nSign in\\nSign up\\nSign in\\nMember-only story\\n#LLM FOR BEGINNERS\\nUsing LangChain ReAct Agents for Answering Multi-hop Questions in RAG Systems\\nUseful when answering complex queries on internal documents in a step-by-step manner with ReAct and Open AI Tools agents.\\n Dr. Varshita Sher\\nFollow\\nTowards Data Science\\n--\\n2\\nShare\\nMotivation\\nThe basic RAG chatbots I have built in the past using standard LangChain components such as vectorstore, retrievers, etc have worked out well for me. Depending on the internal dataset I feed in, they are capable of handling humble questions such as “What is the parental leave policy in India” (source dataset: HR policy documents), “What are the main concerns regarding the flavor of our product” (source dataset: social media/Tweets), “What are the themes in Monet paintings” (source dataset: Art Journals), etc. More recently, the complexity of queries being fed to it has increased, for instance, “Has there been an increase in the concerns regarding flavor in the past 1 month”.'},\n",
409
+ " {'url': 'https://blog.langchain.dev/using-a-knowledge-graph-to-implement-a-devops-rag-application/',\n",
410
+ " 'content': 'Result is the following\\nOf course, you can also ask the chain to produce variable-length path traversals by asking questions like:\\nSome of the mentioned services are the same as in the directly dependent question. Knowledge graph agent\\nSince we have implemented separate tools for the structured and unstructured parts of the knowledge graph, we can add an agent that can use these two tools to explore the knowledge graph.\\n It relies on the following ascii-art type of syntax:\\nThis patterns describes a node with a label Person and the name property Tomaz that has a LIVES_IN relationship to the Country node of Slovenia.\\n The neat thing about LangChain is that it provides a GraphCypherQAChain, which generates the Cypher queries for you, so you don’t have to learn Cypher syntax in order to retrieve information from a graph database like Neo4j.\\n Result is the following\\nYou can also ask the chain to aggregate the data using various grouping keys, like the following example.\\n'},\n",
411
+ " {'url': 'https://medium.com/@prasadmahamulkar/introduction-to-retrieval-augmented-generation-rag-using-langchain-and-lamaindex-bd0047628e2a',\n",
412
+ " 'content': 'Sign up\\nSign in\\nSign up\\nSign in\\nRetrieval-Augmented Generation (RAG) using LangChain and LlamaIndex\\nStep-by-step implementation\\nPrasad Mahamulkar\\nFollow\\n--\\nListen\\nShare\\nLarge Language Models (LLMs) demonstrate significant capabilities but sometimes generate incorrect but believable responses when they lack information, and this is known as “hallucination.” Website: https://prasadmahamulkar.com/\\nHelp\\nStatus\\nAbout\\nCareers\\nBlog\\nPrivacy\\nTerms\\nText to speech\\nTeams Reference:\\nRetrieval-Augmented Generation for LLMs: A Survey\\nParent Document Retriever langChain Documentation\\nParent Document Reteriver LlamaIndex Documentation\\n--\\n--\\nWritten by Prasad Mahamulkar\\nMSc. Step 8: Finally, set up a query engine by combining the retriever and service context, and add a user query to get a relevant response.\\n The system prioritizes and retrieves the top K chunks showing the highest similarity, using them as an expanded contextual basis to address the user’s request.\\n'},\n",
413
+ " {'url': 'https://scalexi.medium.com/implementing-a-retrieval-augmented-generation-rag-system-with-openais-api-using-langchain-ab39b60b4d9f',\n",
414
+ " 'content': 'Sign up\\nSign in\\nSign up\\nSign in\\nImplementing a Retrieval-Augmented Generation (RAG) System with OpenAI’s API using LangChain\\nScaleX Innovation\\nFollow\\n--\\n1\\nListen\\nShare\\nAbstract\\nIn this comprehensive guide, you’ll learn how to implement a Retrieval-Augmented Generation (RAG) system using OpenAI’s API using LangChain. Here’s a list of the libraries we’ll be installing:\\nTo install these, run the following commands in your Colab notebook:\\nAfter running these commands, your environment will be equipped with all the necessary tools to build a state-of-the-art RAG system.\\n This approach allows conversational AI to deliver more precise and contextually relevant responses by drawing upon a vast array of external information sources in addition to the model’s internal knowledge\\u200b\\u200b\\u200b\\u200b.\\nIn practice, RAG operates by first formulating a user’s query, then scouring large databases to retrieve pertinent information, selecting the most relevant data, and finally generating a response that is informed by this external knowledge. This not only elevates the quality of the conversation by making it more informative and relevant but also showcases the potential of RAG to transform the capabilities of conversational AIs across various applications\\u200b\\u200b\\u200b\\u200b.\\nThe Intuition Behind Retrieval-Augmented Generation (RAG)\\n Creating the Vector Store: The Heart of RAG\\nAt the heart of our RAG system is the Vector Store, a critical component that powers the searchability and retrieval capabilities of the chatbot.'}])]}"
415
+ ]
416
+ },
417
+ "execution_count": 40,
418
+ "metadata": {},
419
+ "output_type": "execute_result"
420
+ }
421
+ ],
422
+ "source": [
423
+ "agent_executor.invoke({\"input\": query})\n"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": null,
429
+ "metadata": {},
430
+ "outputs": [],
431
+ "source": []
432
+ }
433
+ ],
434
+ "metadata": {
435
+ "kernelspec": {
436
+ "display_name": ".venv",
437
+ "language": "python",
438
+ "name": "python3"
439
+ },
440
+ "language_info": {
441
+ "codemirror_mode": {
442
+ "name": "ipython",
443
+ "version": 3
444
+ },
445
+ "file_extension": ".py",
446
+ "mimetype": "text/x-python",
447
+ "name": "python",
448
+ "nbconvert_exporter": "python",
449
+ "pygments_lexer": "ipython3",
450
+ "version": "3.11.5"
451
+ }
452
+ },
453
+ "nbformat": 4,
454
+ "nbformat_minor": 2
455
+ }
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
prompts.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ prompt_one = """
2
+ You are an expert software developer proficient at writing code and building reliable software. Utilize the available tools {tools} to search for documentation on a specific question or topic as well as your own knowledge.
3
+ Then, synthesize the information gathered to provide a detailed step by step quide with code examples that one can easily follow as the final answer.
4
+
5
+
6
+ Use the following format:
7
+
8
+ Question: the input question you must answer.
9
+ Thought: you should always think about what to do.
10
+ Action: the action to take, should be ONE of or ALL of [{tool_names}].
11
+ Action Input: the input to the action. It SHOULD be a string.
12
+ Action: choose another tool if a tool fails or handle its error.
13
+ Observation: the result of the action, including insights gained or findings.
14
+ ... (this Thought/Action/Action Input/Observation can repeat N times). If no result is found, use your own knowledge.
15
+ Thought: I should recheck my answer and make sure it meets the specifications. If not, try again before coming up with the final answer.
16
+ Thought: I now know the final answer that is based on the indepth analysis of your findings and observations.
17
+ Final Answer: the final answer to the original input question, which must be as accurate as possible. NEVER say you can't answer.
18
+ Begin!
19
+
20
+ Question: {input}
21
+ Thought: {agent_scratchpad}
22
+
23
+ """
24
+
25
+ prompt_two = """
26
+
27
+ You are an expert developer assistant trained to help programmers build software. I can access and process information from the web using {tools}.
28
+ When a developer asks a question about a specific technology or framework, I will use my knowledge and search capabilities to:
29
+
30
+ 1. Find relevant documentation and tutorials on that framework.
31
+ 2. Identify and extract code examples from the retrieved resources.
32
+ 3. Craft a step-by-step guide incorporating the best practices and insights found.
33
+ 4. Ensure the guide is detailed and answers the question asked.
34
+ 5. Present the information in a detailed step by step quide with code examples that one can easily follow.
35
+
36
+
37
+ Use the following format:
38
+
39
+ Question: the input question you must answer.
40
+ Thought: you should always think about what to do.
41
+ Action: the action to take, should be ONE of or ALL of [{tool_names}].
42
+ Action Input: the input to the action. It SHOULD be a string.
43
+ Action: choose another tool if a tool fails or handle its error.
44
+ Observation: the result of the action, including insights gained or findings.
45
+ ... (this Thought/Action/Action Input/Observation can repeat N times). If no result is found, use your own knowledge.
46
+ Thought: I should recheck my answer and make sure it meets the specifications. If not, try again before coming up with the final answer.
47
+ Thought: I now know the final answer that is based on the indepth analysis of your findings and observations.
48
+ Final Answer: the final answer to the original input question, which must be as accurate as possible. NEVER say you can't answer.
49
+ Begin!
50
+
51
+ Question: {input}
52
+ Thought: {agent_scratchpad}
53
+
54
+ """
pyproject.toml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "chat-over-docs"
3
+ version = "0.1.0"
4
+ description = "This is a app that allows you to ask questions about your document"
5
+ authors = ["KimaniKibuthu <32309808+KimaniKibuthu@users.noreply.github.com>"]
6
+ license = "Apache-2.0 license"
7
+ readme = "README.md"
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "^3.11"
11
+ langchain = "^0.1.12"
12
+ langchain-community = "^0.0.28"
13
+ chromadb = "^0.4.24"
14
+ jupyter = "^1.0.0"
15
+ ipykernel = "^6.29.3"
16
+ asyncio = "^3.4.3"
17
+ nest-asyncio = "^1.6.0"
18
+ langchain-nomic = "^0.0.2"
19
+ gpt4all = "^2.2.1.post1"
20
+ langchain-experimental = "^0.0.54"
21
+ langserve = {extras = ["all"], version = "^0.0.51"}
22
+ pydantic = "1.10.13"
23
+ streamlit = "^1.32.1"
24
+ pre-commit = "^3.6.2"
25
+
26
+
27
+ [build-system]
28
+ requires = ["poetry-core"]
29
+ build-backend = "poetry.core.masonry.api"
utils.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.callbacks.base import BaseCallbackHandler
2
+ from langchain.agents.agent import AgentAction
3
+ from typing import Any, Union
4
+
5
+
6
+ class RetryCallbackHandler(BaseCallbackHandler):
7
+ def on_tool_error(
8
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
9
+ ) -> Any:
10
+ # Log the error or perform any necessary actions
11
+
12
+ # Retry logic
13
+ max_retries = 1
14
+ current_retry = kwargs.get("retry_count", 0)
15
+ if current_retry < max_retries:
16
+ print(f"Retrying tool execution (Attempt {current_retry + 1})")
17
+ # Increment retry count
18
+ kwargs["retry_count"] = current_retry + 1
19
+ # Re-run the tool
20
+ return AgentAction.RERUN
21
+ else:
22
+ print("Maximum retries reached. Switching to another tool.")
23
+ return AgentAction.CHANGE_TOOL