Ankit93 commited on
Commit
b676995
·
1 Parent(s): cbedaf0

Add application file

Browse files
.idea/vcs.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ <mapping directory="$PROJECT_DIR$/Agent" vcs="Git" />
6
+ </component>
7
+ </project>
.idea/workspace.xml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="a48d03e0-1f99-4f52-8413-a14f7c8fac9f" name="Changes" comment="" />
8
+ <option name="SHOW_DIALOG" value="false" />
9
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
10
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
11
+ <option name="LAST_RESOLUTION" value="IGNORE" />
12
+ </component>
13
+ <component name="FileTemplateManagerImpl">
14
+ <option name="RECENT_TEMPLATES">
15
+ <list>
16
+ <option value="Python Script" />
17
+ </list>
18
+ </option>
19
+ </component>
20
+ <component name="Git.Settings">
21
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
22
+ </component>
23
+ <component name="ProjectColorInfo">{
24
+ &quot;associatedIndex&quot;: 8
25
+ }</component>
26
+ <component name="ProjectId" id="2oLsoBlphhNNS3RDyOnSVa2EGbu" />
27
+ <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
28
+ <component name="ProjectViewState">
29
+ <option name="hideEmptyMiddlePackages" value="true" />
30
+ <option name="showLibraryContents" value="true" />
31
+ </component>
32
+ <component name="PropertiesComponent">{
33
+ &quot;keyToString&quot;: {
34
+ &quot;Python.app.executor&quot;: &quot;Run&quot;,
35
+ &quot;Python.data_ingestion.executor&quot;: &quot;Run&quot;,
36
+ &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
37
+ &quot;git-widget-placeholder&quot;: &quot;main&quot;,
38
+ &quot;last_opened_file_path&quot;: &quot;C:/Users/ruchi/PycharmProjects/Project/PycharmProjects/Gen AI/Tools&quot;,
39
+ &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
40
+ &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
41
+ &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
42
+ &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
43
+ &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
44
+ &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
45
+ }
46
+ }</component>
47
+ <component name="RecentsManager">
48
+ <key name="MoveFile.RECENT_KEYS">
49
+ <recent name="C:\Users\ruchi\PycharmProjects\Project\PycharmProjects\Gen AI\Tools" />
50
+ </key>
51
+ </component>
52
+ <component name="RunManager">
53
+ <configuration name="app" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
54
+ <module name="Tools" />
55
+ <option name="ENV_FILES" value="" />
56
+ <option name="INTERPRETER_OPTIONS" value="" />
57
+ <option name="PARENT_ENVS" value="true" />
58
+ <envs>
59
+ <env name="PYTHONUNBUFFERED" value="1" />
60
+ </envs>
61
+ <option name="SDK_HOME" value="" />
62
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
63
+ <option name="IS_MODULE_SDK" value="true" />
64
+ <option name="ADD_CONTENT_ROOTS" value="true" />
65
+ <option name="ADD_SOURCE_ROOTS" value="true" />
66
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
67
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/app.py" />
68
+ <option name="PARAMETERS" value="" />
69
+ <option name="SHOW_COMMAND_LINE" value="false" />
70
+ <option name="EMULATE_TERMINAL" value="false" />
71
+ <option name="MODULE_MODE" value="false" />
72
+ <option name="REDIRECT_INPUT" value="false" />
73
+ <option name="INPUT_FILE" value="" />
74
+ <method v="2" />
75
+ </configuration>
76
+ <recent_temporary>
77
+ <list>
78
+ <item itemvalue="Python.app" />
79
+ </list>
80
+ </recent_temporary>
81
+ </component>
82
+ <component name="SharedIndexes">
83
+ <attachedChunks>
84
+ <set>
85
+ <option value="bundled-js-predefined-d6986cc7102b-5c90d61e3bab-JavaScript-PY-242.23339.19" />
86
+ <option value="bundled-python-sdk-0029f7779945-399fe30bd8c1-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-242.23339.19" />
87
+ </set>
88
+ </attachedChunks>
89
+ </component>
90
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
91
+ <component name="TaskManager">
92
+ <task active="true" id="Default" summary="Default task">
93
+ <changelist id="a48d03e0-1f99-4f52-8413-a14f7c8fac9f" name="Changes" comment="" />
94
+ <created>1730660362928</created>
95
+ <option name="number" value="Default" />
96
+ <option name="presentableId" value="Default" />
97
+ <updated>1730660362928</updated>
98
+ <workItem from="1730660363969" duration="6306000" />
99
+ <workItem from="1731161016363" duration="4447000" />
100
+ </task>
101
+ <servers />
102
+ </component>
103
+ <component name="TypeScriptGeneratedFilesManager">
104
+ <option name="version" value="3" />
105
+ </component>
106
+ <component name="Vcs.Log.Tabs.Properties">
107
+ <option name="TAB_STATES">
108
+ <map>
109
+ <entry key="MAIN">
110
+ <value>
111
+ <State />
112
+ </value>
113
+ </entry>
114
+ </map>
115
+ </option>
116
+ </component>
117
+ <component name="com.intellij.coverage.CoverageDataManagerImpl">
118
+ <SUITE FILE_PATH="coverage/Tools$app.coverage" NAME="app Coverage Results" MODIFIED="1730667511954" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
119
+ <SUITE FILE_PATH="coverage/Tools$data_ingestion.coverage" NAME="data_ingestion Coverage Results" MODIFIED="1731161065909" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
120
+ </component>
121
+ </project>
agent-tools.ipynb ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "metadata": {
5
+ "ExecuteTime": {
6
+ "end_time": "2024-10-29T18:32:27.617760Z",
7
+ "start_time": "2024-10-29T18:32:26.626308Z"
8
+ }
9
+ },
10
+ "cell_type": "code",
11
+ "source": [
12
+ "from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun\n",
13
+ "from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper"
14
+ ],
15
+ "id": "a435d5aeb3924884",
16
+ "outputs": [],
17
+ "execution_count": 1
18
+ },
19
+ {
20
+ "metadata": {
21
+ "ExecuteTime": {
22
+ "end_time": "2024-10-29T18:32:27.686190Z",
23
+ "start_time": "2024-10-29T18:32:27.629994Z"
24
+ }
25
+ },
26
+ "cell_type": "code",
27
+ "source": [
28
+ "wiki_api = WikipediaAPIWrapper(top_k_results=1, max_tokens=500 )\n",
29
+ "wiki_api = WikipediaQueryRun(api_wrapper=wiki_api)\n",
30
+ "wiki_api.name"
31
+ ],
32
+ "id": "b14caadf6783a38a",
33
+ "outputs": [
34
+ {
35
+ "data": {
36
+ "text/plain": [
37
+ "'wikipedia'"
38
+ ]
39
+ },
40
+ "execution_count": 2,
41
+ "metadata": {},
42
+ "output_type": "execute_result"
43
+ }
44
+ ],
45
+ "execution_count": 2
46
+ },
47
+ {
48
+ "metadata": {
49
+ "ExecuteTime": {
50
+ "end_time": "2024-10-29T18:32:27.894026Z",
51
+ "start_time": "2024-10-29T18:32:27.850869Z"
52
+ }
53
+ },
54
+ "cell_type": "code",
55
+ "source": [
56
+ "arxiv_api = ArxivAPIWrapper(top_k_results=1, max_tokens=500 )\n",
57
+ "arxiv_api = ArxivQueryRun(api_wrapper=arxiv_api)\n",
58
+ "arxiv_api.name"
59
+ ],
60
+ "id": "26841fb3cc762f14",
61
+ "outputs": [
62
+ {
63
+ "data": {
64
+ "text/plain": [
65
+ "'arxiv'"
66
+ ]
67
+ },
68
+ "execution_count": 3,
69
+ "metadata": {},
70
+ "output_type": "execute_result"
71
+ }
72
+ ],
73
+ "execution_count": 3
74
+ },
75
+ {
76
+ "metadata": {
77
+ "ExecuteTime": {
78
+ "end_time": "2024-10-29T18:32:33.606669Z",
79
+ "start_time": "2024-10-29T18:32:33.591504Z"
80
+ }
81
+ },
82
+ "cell_type": "code",
83
+ "source": "tools = [wiki_api, arxiv_api]",
84
+ "id": "41a663232fd8c090",
85
+ "outputs": [],
86
+ "execution_count": 4
87
+ },
88
+ {
89
+ "metadata": {
90
+ "ExecuteTime": {
91
+ "end_time": "2024-10-29T18:33:57.464755Z",
92
+ "start_time": "2024-10-29T18:33:57.442645Z"
93
+ }
94
+ },
95
+ "cell_type": "code",
96
+ "source": [
97
+ "## Custom tool\n",
98
+ "from langchain.document_loaders import WebBaseLoader\n",
99
+ "from langchain.vectorstores import FAISS\n",
100
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
101
+ "from langchain_groq import ChatGroq\n",
102
+ "from langchain_huggingface import HuggingFaceEmbeddings\n",
103
+ "from dotenv import load_dotenv\n",
104
+ "load_dotenv()"
105
+ ],
106
+ "id": "ae3e6152572b015a",
107
+ "outputs": [
108
+ {
109
+ "data": {
110
+ "text/plain": [
111
+ "True"
112
+ ]
113
+ },
114
+ "execution_count": 9,
115
+ "metadata": {},
116
+ "output_type": "execute_result"
117
+ }
118
+ ],
119
+ "execution_count": 9
120
+ },
121
+ {
122
+ "metadata": {
123
+ "ExecuteTime": {
124
+ "end_time": "2024-10-29T18:34:05.220937Z",
125
+ "start_time": "2024-10-29T18:33:59.455568Z"
126
+ }
127
+ },
128
+ "cell_type": "code",
129
+ "source": [
130
+ "webloader = WebBaseLoader(\"https://jalammar.github.io/illustrated-transformer/\")\n",
131
+ "docs = webloader.load()\n",
132
+ "splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)\n",
133
+ "document = splitter.split_documents(docs)\n",
134
+ "vectorstore = FAISS.from_documents(document, HuggingFaceEmbeddings())\n",
135
+ "retriever = vectorstore.as_retriever()"
136
+ ],
137
+ "id": "d0c2eabc73039a74",
138
+ "outputs": [],
139
+ "execution_count": 10
140
+ },
141
+ {
142
+ "metadata": {
143
+ "ExecuteTime": {
144
+ "end_time": "2024-10-29T18:33:24.573845Z",
145
+ "start_time": "2024-10-29T18:33:24.556040Z"
146
+ }
147
+ },
148
+ "cell_type": "code",
149
+ "source": [
150
+ "from langchain.tools.retriever import create_retriever_tool\n",
151
+ "retriever_tool = create_retriever_tool(retriever, \"Transformer Study\", \"Search anything about Transformers\")"
152
+ ],
153
+ "id": "11679e0bd4ca5d42",
154
+ "outputs": [],
155
+ "execution_count": 7
156
+ },
157
+ {
158
+ "metadata": {
159
+ "ExecuteTime": {
160
+ "end_time": "2024-10-29T18:34:06.409793Z",
161
+ "start_time": "2024-10-29T18:34:05.908259Z"
162
+ }
163
+ },
164
+ "cell_type": "code",
165
+ "source": [
166
+ "tools = [wiki_api, arxiv_api, retriever_tool]\n",
167
+ "model = ChatGroq(model=\"Gemma2-9B-It\")"
168
+ ],
169
+ "id": "cf0ab84b67702818",
170
+ "outputs": [],
171
+ "execution_count": 11
172
+ },
173
+ {
174
+ "metadata": {
175
+ "ExecuteTime": {
176
+ "end_time": "2024-10-29T18:38:51.485068Z",
177
+ "start_time": "2024-10-29T18:38:50.500300Z"
178
+ }
179
+ },
180
+ "cell_type": "code",
181
+ "source": [
182
+ "from langchain import hub\n",
183
+ "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
184
+ "prompt.messages"
185
+ ],
186
+ "id": "e831cdeb54d5f34",
187
+ "outputs": [
188
+ {
189
+ "data": {
190
+ "text/plain": [
191
+ "[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a helpful assistant'), additional_kwargs={}),\n",
192
+ " MessagesPlaceholder(variable_name='chat_history', optional=True),\n",
193
+ " HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], input_types={}, partial_variables={}, template='{input}'), additional_kwargs={}),\n",
194
+ " MessagesPlaceholder(variable_name='agent_scratchpad')]"
195
+ ]
196
+ },
197
+ "execution_count": 14,
198
+ "metadata": {},
199
+ "output_type": "execute_result"
200
+ }
201
+ ],
202
+ "execution_count": 14
203
+ },
204
+ {
205
+ "metadata": {
206
+ "ExecuteTime": {
207
+ "end_time": "2024-10-29T18:34:20.708077Z",
208
+ "start_time": "2024-10-29T18:34:20.437439Z"
209
+ }
210
+ },
211
+ "cell_type": "code",
212
+ "source": [
213
+ "from langchain.agents import create_openai_tools_agent\n",
214
+ "agent = create_openai_tools_agent(model, tools, prompt)"
215
+ ],
216
+ "id": "53dd0b6d56abefde",
217
+ "outputs": [],
218
+ "execution_count": 13
219
+ },
220
+ {
221
+ "metadata": {
222
+ "ExecuteTime": {
223
+ "end_time": "2024-10-29T20:42:26.355456Z",
224
+ "start_time": "2024-10-29T20:42:26.330918Z"
225
+ }
226
+ },
227
+ "cell_type": "code",
228
+ "source": [
229
+ "from langchain.agents import AgentExecutor\n",
230
+ "agent_exe = AgentExecutor(agent = agent,tools = tools, verbose = True)\n",
231
+ "agent_exe"
232
+ ],
233
+ "id": "cbbab60dac13e8d9",
234
+ "outputs": [
235
+ {
236
+ "data": {
237
+ "text/plain": [
238
+ "AgentExecutor(verbose=True, agent=RunnableMultiActionAgent(runnable=RunnableAssign(mapper={\n",
239
+ " agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
240
+ "})\n",
241
+ "| ChatPromptTemplate(input_variables=['agent_scratchpad', 'input'], optional_variables=['chat_history'], input_types={'chat_history': list[typing.Annotated[typing.Union[typing.Annotated[langchain_core.messages.ai.AIMessage, Tag(tag='ai')], typing.Annotated[langchain_core.messages.human.HumanMessage, Tag(tag='human')], typing.Annotated[langchain_core.messages.chat.ChatMessage, Tag(tag='chat')], typing.Annotated[langchain_core.messages.system.SystemMessage, Tag(tag='system')], typing.Annotated[langchain_core.messages.function.FunctionMessage, Tag(tag='function')], typing.Annotated[langchain_core.messages.tool.ToolMessage, Tag(tag='tool')], typing.Annotated[langchain_core.messages.ai.AIMessageChunk, Tag(tag='AIMessageChunk')], typing.Annotated[langchain_core.messages.human.HumanMessageChunk, Tag(tag='HumanMessageChunk')], typing.Annotated[langchain_core.messages.chat.ChatMessageChunk, Tag(tag='ChatMessageChunk')], typing.Annotated[langchain_core.messages.system.SystemMessageChunk, Tag(tag='SystemMessageChunk')], typing.Annotated[langchain_core.messages.function.FunctionMessageChunk, Tag(tag='FunctionMessageChunk')], typing.Annotated[langchain_core.messages.tool.ToolMessageChunk, Tag(tag='ToolMessageChunk')]], FieldInfo(annotation=NoneType, required=True, discriminator=Discriminator(discriminator=<function _get_type at 0x0000028AF9CFADE0>, custom_error_type=None, custom_error_message=None, custom_error_context=None))]], 'agent_scratchpad': list[typing.Annotated[typing.Union[typing.Annotated[langchain_core.messages.ai.AIMessage, Tag(tag='ai')], typing.Annotated[langchain_core.messages.human.HumanMessage, Tag(tag='human')], typing.Annotated[langchain_core.messages.chat.ChatMessage, Tag(tag='chat')], typing.Annotated[langchain_core.messages.system.SystemMessage, Tag(tag='system')], typing.Annotated[langchain_core.messages.function.FunctionMessage, Tag(tag='function')], typing.Annotated[langchain_core.messages.tool.ToolMessage, Tag(tag='tool')], typing.Annotated[langchain_core.messages.ai.AIMessageChunk, Tag(tag='AIMessageChunk')], typing.Annotated[langchain_core.messages.human.HumanMessageChunk, Tag(tag='HumanMessageChunk')], typing.Annotated[langchain_core.messages.chat.ChatMessageChunk, Tag(tag='ChatMessageChunk')], typing.Annotated[langchain_core.messages.system.SystemMessageChunk, Tag(tag='SystemMessageChunk')], typing.Annotated[langchain_core.messages.function.FunctionMessageChunk, Tag(tag='FunctionMessageChunk')], typing.Annotated[langchain_core.messages.tool.ToolMessageChunk, Tag(tag='ToolMessageChunk')]], FieldInfo(annotation=NoneType, required=True, discriminator=Discriminator(discriminator=<function _get_type at 0x0000028AF9CFADE0>, custom_error_type=None, custom_error_message=None, custom_error_context=None))]]}, partial_variables={'chat_history': []}, metadata={'lc_hub_owner': 'hwchase17', 'lc_hub_repo': 'openai-functions-agent', 'lc_hub_commit_hash': 'a1655024b06afbd95d17449f21316291e0726f13dcfaf990cc0d18087ad689a5'}, messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a helpful assistant'), additional_kwargs={}), MessagesPlaceholder(variable_name='chat_history', optional=True), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], input_types={}, partial_variables={}, template='{input}'), additional_kwargs={}), MessagesPlaceholder(variable_name='agent_scratchpad')])\n",
242
+ "| RunnableBinding(bound=ChatGroq(client=<groq.resources.chat.completions.Completions object at 0x0000028AEF40AED0>, async_client=<groq.resources.chat.completions.AsyncCompletions object at 0x0000028AEF40A210>, model_name='Gemma2-9B-It', model_kwargs={}, groq_api_key=SecretStr('**********')), kwargs={'tools': [{'type': 'function', 'function': {'name': 'wikipedia', 'description': 'A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.', 'parameters': {'properties': {'query': {'description': 'query to look up on wikipedia', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}, {'type': 'function', 'function': {'name': 'arxiv', 'description': 'A wrapper around Arxiv.org Useful for when you need to answer questions about Physics, Mathematics, Computer Science, Quantitative Biology, Quantitative Finance, Statistics, Electrical Engineering, and Economics from scientific articles on arxiv.org. Input should be a search query.', 'parameters': {'properties': {'query': {'description': 'search query to look up', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}, {'type': 'function', 'function': {'name': 'Transformer Study', 'description': 'Search anything about Transformers', 'parameters': {'properties': {'query': {'description': 'query to look up in retriever', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}]}, config={}, config_factories=[])\n",
243
+ "| OpenAIToolsAgentOutputParser(), input_keys_arg=[], return_keys_arg=[], stream_runnable=True), tools=[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=<module 'wikipedia' from 'C:\\\\Users\\\\ruchi\\\\PycharmProjects\\\\genai_env\\\\Lib\\\\site-packages\\\\wikipedia\\\\__init__.py'>, top_k_results=1, lang='en', load_all_available_meta=False, doc_content_chars_max=4000)), ArxivQueryRun(api_wrapper=ArxivAPIWrapper(arxiv_search=<class 'arxiv.Search'>, arxiv_exceptions=(<class 'arxiv.ArxivError'>, <class 'arxiv.UnexpectedEmptyPageError'>, <class 'arxiv.HTTPError'>), top_k_results=1, ARXIV_MAX_QUERY_LENGTH=300, continue_on_failure=False, load_max_docs=100, load_all_available_meta=False, doc_content_chars_max=4000)), Tool(name='Transformer Study', description='Search anything about Transformers', args_schema=<class 'langchain_core.tools.retriever.RetrieverInput'>, func=functools.partial(<function _get_relevant_documents at 0x0000028AFA80CEA0>, retriever=VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000028AD2CDD580>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n'), coroutine=functools.partial(<function _aget_relevant_documents at 0x0000028AFAB6AD40>, retriever=VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000028AD2CDD580>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n'))])"
244
+ ]
245
+ },
246
+ "execution_count": 16,
247
+ "metadata": {},
248
+ "output_type": "execute_result"
249
+ }
250
+ ],
251
+ "execution_count": 16
252
+ },
253
+ {
254
+ "metadata": {
255
+ "ExecuteTime": {
256
+ "end_time": "2024-10-29T20:45:17.698060Z",
257
+ "start_time": "2024-10-29T20:45:16.439652Z"
258
+ }
259
+ },
260
+ "cell_type": "code",
261
+ "source": "response = agent_exe.invoke({\"input\" : \"Tell me about transformer\"})",
262
+ "id": "51163b1023b7f93f",
263
+ "outputs": [
264
+ {
265
+ "name": "stdout",
266
+ "output_type": "stream",
267
+ "text": [
268
+ "\n",
269
+ "\n",
270
+ "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
271
+ "\u001B[32;1m\u001B[1;3m\n",
272
+ "Invoking: `Transformer Study` with `{'query': 'transformer'}`\n",
273
+ "\n",
274
+ "\n",
275
+ "\u001B[0m\u001B[38;5;200m\u001B[1;3mAcknowledgements\n",
276
+ "Thanks to Illia Polosukhin, Jakob Uszkoreit, Llion Jones , Lukasz Kaiser, Niki Parmar, and Noam Shazeer for providing feedback on earlier versions of this post.\n",
277
+ "Please hit me up on Twitter for any corrections or feedback.\n",
278
+ "\n",
279
+ "\n",
280
+ " Written on June 27, 2018\n",
281
+ " \n",
282
+ "\n",
283
+ "\n",
284
+ "\n",
285
+ "\n",
286
+ "\n",
287
+ "\n",
288
+ "\n",
289
+ "\n",
290
+ "Subscribe to get notified about upcoming posts by email\n",
291
+ "\n",
292
+ "Email Address \n",
293
+ "\n",
294
+ "\n",
295
+ "\n",
296
+ "\n",
297
+ "\n",
298
+ " \n",
299
+ "\n",
300
+ "\n",
301
+ "\n",
302
+ "\n",
303
+ "\n",
304
+ "\n",
305
+ "\n",
306
+ "\n",
307
+ "This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.\n",
308
+ "\n",
309
+ "\n",
310
+ "Attribution example:\n",
311
+ "\n",
312
+ "Alammar, J (2018). The Illustrated Transformer [Blog post]. Retrieved from https://jalammar.github.io/illustrated-transformer/\n",
313
+ "\n",
314
+ "Note: If you translate any of the posts, let me know so I can link your translation to the original post. My email is in the about page.\n",
315
+ "\n",
316
+ "Go Forth And Transform\n",
317
+ "I hope you’ve found this a useful place to start to break the ice with the major concepts of the Transformer. If you want to go deeper, I’d suggest these next steps:\n",
318
+ "\n",
319
+ "The Transformer was proposed in the paper Attention is All You Need. A TensorFlow implementation of it is available as a part of the Tensor2Tensor package. Harvard’s NLP group created a guide annotating the paper with PyTorch implementation. In this post, we will attempt to oversimplify things a bit and introduce the concepts one by one to hopefully make it easier to understand to people without in-depth knowledge of the subject matter.\n",
320
+ "2020 Update: I’ve created a “Narrated Transformer” video which is a gentler approach to the topic:\n",
321
+ "\n",
322
+ "The Illustrated Transformer – Jay Alammar – Visualizing machine learning one concept at a time.\n",
323
+ "\n",
324
+ "\n",
325
+ "\n",
326
+ "\n",
327
+ "\n",
328
+ "\n",
329
+ "\n",
330
+ "\n",
331
+ "\n",
332
+ "\n",
333
+ "\n",
334
+ "\n",
335
+ "\n",
336
+ "\n",
337
+ "\n",
338
+ "\n",
339
+ "\n",
340
+ "\n",
341
+ "\n",
342
+ "\n",
343
+ "\n",
344
+ "\n",
345
+ "\n",
346
+ "\n",
347
+ "\n",
348
+ "\n",
349
+ "\n",
350
+ "\n",
351
+ "\n",
352
+ "\n",
353
+ "\n",
354
+ "\n",
355
+ "\n",
356
+ "\n",
357
+ "\n",
358
+ "\n",
359
+ "\n",
360
+ "Jay Alammar\n",
361
+ "Visualizing machine learning one concept at a time.@JayAlammar on Twitter. YouTube Channel\n",
362
+ "\n",
363
+ "\n",
364
+ "Blog\n",
365
+ "About\n",
366
+ "\n",
367
+ "\n",
368
+ "\n",
369
+ "\n",
370
+ "\n",
371
+ "\n",
372
+ "The Illustrated Transformer\n",
373
+ "\n",
374
+ "Discussions:\n",
375
+ "Hacker News (65 points, 4 comments), Reddit r/MachineLearning (29 points, 3 comments)\n",
376
+ "\n",
377
+ "\n",
378
+ "Translations: Arabic, Chinese (Simplified) 1, Chinese (Simplified) 2, French 1, French 2, Italian, Japanese, Korean, Persian, Russian, Spanish 1, Spanish 2, Vietnamese\n",
379
+ "\n",
380
+ "Watch: MIT’s Deep Learning State of the Art lecture referencing this post\u001B[0m\u001B[32;1m\u001B[1;3mThe Illustrated Transformer is a blog post by Jay Alammar that visualizes and explains the concepts of the Transformer model. \n",
381
+ "\n",
382
+ "\n",
383
+ "\u001B[0m\n",
384
+ "\n",
385
+ "\u001B[1m> Finished chain.\u001B[0m\n"
386
+ ]
387
+ }
388
+ ],
389
+ "execution_count": 18
390
+ },
391
+ {
392
+ "metadata": {
393
+ "ExecuteTime": {
394
+ "end_time": "2024-10-29T20:45:26.188517Z",
395
+ "start_time": "2024-10-29T20:45:26.180377Z"
396
+ }
397
+ },
398
+ "cell_type": "code",
399
+ "source": "response",
400
+ "id": "c6013c6493022641",
401
+ "outputs": [
402
+ {
403
+ "data": {
404
+ "text/plain": [
405
+ "{'input': 'Tell me about transformer',\n",
406
+ " 'output': 'The Illustrated Transformer is a blog post by Jay Alammar that visualizes and explains the concepts of the Transformer model. \\n\\n\\n'}"
407
+ ]
408
+ },
409
+ "execution_count": 19,
410
+ "metadata": {},
411
+ "output_type": "execute_result"
412
+ }
413
+ ],
414
+ "execution_count": 19
415
+ },
416
+ {
417
+ "metadata": {
418
+ "ExecuteTime": {
419
+ "end_time": "2024-10-29T20:47:43.485054Z",
420
+ "start_time": "2024-10-29T20:47:40.665170Z"
421
+ }
422
+ },
423
+ "cell_type": "code",
424
+ "source": "response = agent_exe.invoke({\"input\" : \"Tell me about Suchitra Sen\"})",
425
+ "id": "25f808c54136151c",
426
+ "outputs": [
427
+ {
428
+ "name": "stdout",
429
+ "output_type": "stream",
430
+ "text": [
431
+ "\n",
432
+ "\n",
433
+ "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
434
+ "\u001B[32;1m\u001B[1;3m\n",
435
+ "Invoking: `wikipedia` with `{'query': 'Suchitra Sen'}`\n",
436
+ "\n",
437
+ "\n",
438
+ "\u001B[0m\u001B[36;1m\u001B[1;3mPage: Suchitra Sen\n",
439
+ "Summary: Suchitra Sen (Bengali: [ʃuˈt͡ʃitːra ˈʃen] ; born Roma Dasgupta, Bengali: [ˈrɔma ˈdaʃɡupto] ; 6 April 1931 – 17 January 2014), widely known as the Mahanayika (lit. 'Great actress'), was an Indian actress who worked in Bengali and Hindi cinema. The movies in which she was paired opposite Uttam Kumar became classics in the history of Bengali cinema.\n",
440
+ "Sen was the first Indian actress to receive an award at an international film festival when, at the 1963 Moscow International Film Festival, she won the Silver Prize for Best Actress for Saat Pake Bandha. She was catapulted to stardom after she was cast as Vishnupriya by Devaki Kumar Bose in his Bhagaban Shree Krishna Chaitanya (1953).\n",
441
+ "In 1972, she was awarded the Padma Shri, the fourth highest civilian award in India. From 1979 on, she retreated from public life and shunned all forms of public contact; for this she is often compared to Greta Garbo. In 2005, she refused the Dadasaheb Phalke Award, the highest cinematic award in India, to stay out of the public eye. In 2012, she was conferred the West Bengal Government's highest honour: Banga Bibhushan. Her first official release was Sukumar Dasgupta's Saat Number Kayedi (1953).\n",
442
+ "\n",
443
+ "\u001B[0m\u001B[32;1m\u001B[1;3mSuchitra Sen was a renowned Indian actress known for her work in Bengali and Hindi cinema. She is often referred to as the \"Mahanayika\" (Great actress). \n",
444
+ "\u001B[0m\n",
445
+ "\n",
446
+ "\u001B[1m> Finished chain.\u001B[0m\n"
447
+ ]
448
+ }
449
+ ],
450
+ "execution_count": 21
451
+ },
452
+ {
453
+ "metadata": {
454
+ "ExecuteTime": {
455
+ "end_time": "2024-10-29T20:48:10.067023Z",
456
+ "start_time": "2024-10-29T20:48:10.060333Z"
457
+ }
458
+ },
459
+ "cell_type": "code",
460
+ "source": "response",
461
+ "id": "187d9800533a7307",
462
+ "outputs": [
463
+ {
464
+ "data": {
465
+ "text/plain": [
466
+ "{'input': 'Tell me about Suchitra Sen',\n",
467
+ " 'output': 'Suchitra Sen was a renowned Indian actress known for her work in Bengali and Hindi cinema. She is often referred to as the \"Mahanayika\" (Great actress). \\n'}"
468
+ ]
469
+ },
470
+ "execution_count": 22,
471
+ "metadata": {},
472
+ "output_type": "execute_result"
473
+ }
474
+ ],
475
+ "execution_count": 22
476
+ },
477
+ {
478
+ "metadata": {
479
+ "ExecuteTime": {
480
+ "end_time": "2024-10-29T20:49:16.523064Z",
481
+ "start_time": "2024-10-29T20:49:13.246455Z"
482
+ }
483
+ },
484
+ "cell_type": "code",
485
+ "source": "response = agent_exe.invoke({\"input\" : \"Tell me about llama index ?\"})",
486
+ "id": "a6bb37f59ca20c9b",
487
+ "outputs": [
488
+ {
489
+ "name": "stdout",
490
+ "output_type": "stream",
491
+ "text": [
492
+ "\n",
493
+ "\n",
494
+ "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
495
+ "\u001B[32;1m\u001B[1;3m\n",
496
+ "Invoking: `wikipedia` with `{'query': 'Llama Index'}`\n",
497
+ "\n",
498
+ "\n",
499
+ "\u001B[0m\u001B[36;1m\u001B[1;3mPage: Vector database\n",
500
+ "Summary: A vector database, vector store or vector search engine is a database that can store vectors (fixed-length lists of numbers) along with other data items. Vector databases typically implement one or more Approximate Nearest Neighbor algorithms, so that one can search the database with a query vector to retrieve the closest matching database records.\n",
501
+ "Vectors are mathematical representations of data in a high-dimensional space. In this space, each dimension corresponds to a feature of the data, with the number of dimensions ranging from a few hundred to tens of thousands, depending on the complexity of the data being represented. A vector's position in this space represents its characteristics. Words, phrases, or entire documents, as well as images, audio, and other types of data, can all be vectorized.\n",
502
+ "These feature vectors may be computed from the raw data using machine learning methods such as feature extraction algorithms, word embeddings or deep learning networks. The goal is that semantically similar data items receive feature vectors close to each other.\n",
503
+ "Vector databases can be used for similarity search, semantic search, multi-modal search, recommendations engines, large language models (LLMs), object detection, etc.\n",
504
+ "Vector databases are also often used to implement retrieval-augmented generation (RAG), a method to improve domain-specific responses of large language models. The retrieval component of a RAG can be any search system, but is most often implemented as a vector database. Text documents describing the domain of interest are collected, and for each document or document section, a feature vector (known as an \"embedding\") is computed, typically using a deep learning network, and stored in a vector database. Given a user prompt, the feature vector of the prompt is computed, and the database is queried to retrieve the most relevant documents. These are then automatically added into the context window of the large language model, and the large language model proceeds to create a response to the prompt given this context.\u001B[0m\u001B[32;1m\u001B[1;3mLlama Index is an open-source framework that makes it easy to build applications powered by large language models (LLMs). \n",
505
+ "\n",
506
+ "It simplifies the process of connecting LLMs to your own data, allowing them to access and understand information specific to your needs.\n",
507
+ "\n",
508
+ "Think of Llama Index as a bridge between your data and powerful LLMs like those from OpenAI or Google. \n",
509
+ "\n",
510
+ "\n",
511
+ "\n",
512
+ "It's designed to make working with LLMs more practical and accessible, especially for tasks like:\n",
513
+ "\n",
514
+ "* **Question Answering:** Build systems that can answer questions based on your own documents or datasets.\n",
515
+ "* **Summarization:** Generate concise summaries of large amounts of text.\n",
516
+ "* **Code Generation:** Use LLMs to assist in writing and understanding code.\n",
517
+ "* **Data Analysis:** Leverage LLMs to uncover insights and patterns in your data.\n",
518
+ "\n",
519
+ "\n",
520
+ "\n",
521
+ "Llama Index achieves this by:\n",
522
+ "\n",
523
+ "* **Indexing your data:** It transforms your data (text, code, PDFs, etc.) into a format that LLMs can understand.\n",
524
+ "* **Providing efficient search:** It allows you to quickly retrieve relevant information from your indexed data.\n",
525
+ "* **Integrating with LLMs:** It seamlessly connects your data to various LLMs, enabling powerful applications.\n",
526
+ "\n",
527
+ "\n",
528
+ "\n",
529
+ "Essentially, Llama Index empowers you to harness the capabilities of LLMs for a wide range of tasks while keeping your data secure and under your control.\n",
530
+ "\u001B[0m\n",
531
+ "\n",
532
+ "\u001B[1m> Finished chain.\u001B[0m\n"
533
+ ]
534
+ }
535
+ ],
536
+ "execution_count": 23
537
+ },
538
+ {
539
+ "metadata": {
540
+ "ExecuteTime": {
541
+ "end_time": "2024-10-29T20:49:23.177361Z",
542
+ "start_time": "2024-10-29T20:49:23.170856Z"
543
+ }
544
+ },
545
+ "cell_type": "code",
546
+ "source": "response",
547
+ "id": "eda4ef8e765d9781",
548
+ "outputs": [
549
+ {
550
+ "data": {
551
+ "text/plain": [
552
+ "{'input': 'Tell me about llama index ?',\n",
553
+ " 'output': \"Llama Index is an open-source framework that makes it easy to build applications powered by large language models (LLMs). \\n\\nIt simplifies the process of connecting LLMs to your own data, allowing them to access and understand information specific to your needs.\\n\\nThink of Llama Index as a bridge between your data and powerful LLMs like those from OpenAI or Google. \\n\\n\\n\\nIt's designed to make working with LLMs more practical and accessible, especially for tasks like:\\n\\n* **Question Answering:** Build systems that can answer questions based on your own documents or datasets.\\n* **Summarization:** Generate concise summaries of large amounts of text.\\n* **Code Generation:** Use LLMs to assist in writing and understanding code.\\n* **Data Analysis:** Leverage LLMs to uncover insights and patterns in your data.\\n\\n\\n\\nLlama Index achieves this by:\\n\\n* **Indexing your data:** It transforms your data (text, code, PDFs, etc.) into a format that LLMs can understand.\\n* **Providing efficient search:** It allows you to quickly retrieve relevant information from your indexed data.\\n* **Integrating with LLMs:** It seamlessly connects your data to various LLMs, enabling powerful applications.\\n\\n\\n\\nEssentially, Llama Index empowers you to harness the capabilities of LLMs for a wide range of tasks while keeping your data secure and under your control.\\n\"}"
554
+ ]
555
+ },
556
+ "execution_count": 24,
557
+ "metadata": {},
558
+ "output_type": "execute_result"
559
+ }
560
+ ],
561
+ "execution_count": 24
562
+ },
563
+ {
564
+ "metadata": {},
565
+ "cell_type": "code",
566
+ "outputs": [],
567
+ "execution_count": null,
568
+ "source": "",
569
+ "id": "6619ae4fd40179df"
570
+ }
571
+ ],
572
+ "metadata": {
573
+ "kernelspec": {
574
+ "display_name": "Python 3",
575
+ "language": "python",
576
+ "name": "python3"
577
+ },
578
+ "language_info": {
579
+ "codemirror_mode": {
580
+ "name": "ipython",
581
+ "version": 2
582
+ },
583
+ "file_extension": ".py",
584
+ "mimetype": "text/x-python",
585
+ "name": "python",
586
+ "nbconvert_exporter": "python",
587
+ "pygments_lexer": "ipython2",
588
+ "version": "2.7.6"
589
+ }
590
+ },
591
+ "nbformat": 4,
592
+ "nbformat_minor": 5
593
+ }
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from dotenv import load_dotenv
4
+ from langchain_groq import ChatGroq
5
+ from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun, DuckDuckGoSearchRun
6
+ from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper
7
+ from langchain import hub
8
+ from langchain.agents import create_openai_tools_agent
9
+ from langchain.agents import AgentExecutor
10
+ from langchain.prompts import PromptTemplate
11
+ from langchain_community.vectorstores import FAISS
12
+ from langchain_huggingface import HuggingFaceEmbeddings
13
+ from langchain.tools import Tool
14
+ from pydantic import BaseModel, Field
15
+ from typing import List, Dict
16
+
17
+ # Load environment variables
18
+ load_dotenv()
19
+ #git remote set-url origin https://<user_name>:<token>@huggingface.co/<repo_path>
20
+ # Define a query condensing template
21
+ condense_prompt_template = PromptTemplate(
22
+ input_variables=["original_question", "conversation_history"],
23
+ template="""
24
+ Given the conversation history below, condense the user's query into a clear and specific question.
25
+
26
+ Conversation History:
27
+ {conversation_history}
28
+
29
+ Original Question:
30
+ {original_question}
31
+
32
+ Condensed Question:"""
33
+ )
34
+
35
+ def condense_query(llm_model, original_question, conversation_history):
36
+ # Format the prompt with conversation history and original question
37
+ prompt = condense_prompt_template.format(
38
+ original_question=original_question,
39
+ conversation_history=conversation_history
40
+ )
41
+ # Generate the condensed query
42
+ resp = llm_model.predict(prompt)
43
+ return resp.strip() # Clean up whitespace
44
+
45
+ # Initialize HuggingFace embeddings and FAISS vectorstore
46
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
47
+ vector_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
48
+ retriever_tool = vector_db.as_retriever()
49
+
50
+ # Define input/output models for OpenAI function-calling compliance
51
+ class RetrieveDocumentsInput(BaseModel):
52
+ query: str = Field(..., description="Query to retrieve relevant documents.")
53
+
54
+ class RetrieveDocumentsOutput(BaseModel):
55
+ documents: List[Dict[str, str]] = Field(..., description="List of retrieved documents, each containing 'content'.")
56
+
57
+ # Wrapper function for FAISS retriever
58
+ def retrieve_documents(query: str) -> List[Dict[str, str]]:
59
+ results = retriever_tool.get_relevant_documents(query)
60
+ return [{"content": doc.page_content} for doc in results]
61
+
62
+ # Define the custom FAISS tool using Tool
63
+ faiss_tool = Tool(
64
+ name="retrieve_documents",
65
+ description="Retrieve documents from FAISS vectorstore.",
66
+ func=retrieve_documents,
67
+ )
68
+
69
+ # Arxiv, Wikipedia, and Search tool setup
70
+ arxiv_wrapper = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)
71
+ arxiv_tool = ArxivQueryRun(api_wrapper=arxiv_wrapper)
72
+
73
+ wiki_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)
74
+ wiki_tool = WikipediaQueryRun(api_wrapper=wiki_wrapper)
75
+
76
+ search_tool = DuckDuckGoSearchRun(name="Search")
77
+
78
+ # Define tools, including the wrapped FAISS tool
79
+ tools = [
80
+ arxiv_tool,
81
+ wiki_tool,
82
+ search_tool,
83
+ faiss_tool
84
+ ]
85
+
86
+ # Set up the agent with prompt and LLM model
87
+ prompt = hub.pull("hwchase17/openai-functions-agent")
88
+ llm = ChatGroq(model="Gemma2-9B-It", streaming=True)
89
+ agent = create_openai_tools_agent(llm, tools, prompt)
90
+ agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
91
+
92
+ # Initialize session state for messages
93
+ if 'messages' not in st.session_state:
94
+ st.session_state['messages'] = [{"role": "assistant", "content": "How can I help you?"}]
95
+
96
+ # Display chat messages
97
+ for msg in st.session_state['messages']:
98
+ st.chat_message(msg["role"]).write(msg["content"])
99
+
100
+ # Extract conversation history
101
+ conversation_history = "\n".join(
102
+ [f"{msg['role']}: {msg['content']}" for msg in st.session_state['messages']]
103
+ )
104
+
105
+ # CSS to fix the input box at the bottom of the screen
106
+ st.markdown("""
107
+ <style>
108
+ .fixed-bottom-input-container {
109
+ position: fixed;
110
+ bottom: 0;
111
+ width: 100%;
112
+ background-color: white;
113
+ padding: 10px 0;
114
+ border-top: 1px solid #ddd;
115
+ }
116
+ .fixed-bottom-input {
117
+ width: 100%;
118
+ padding: 10px;
119
+ font-size: 16px;
120
+ }
121
+ </style>
122
+ """, unsafe_allow_html=True)
123
+
124
+ # Create the input field
125
+ user_input = st.text_input("Type your message here...", key="user_input", label_visibility="collapsed")
126
+
127
+ # If there's input, process it
128
+ if user_input:
129
+ condensed_question = condense_query(llm, user_input, conversation_history)
130
+ response = agent_executor.invoke({"input": condensed_question})
131
+
132
+ # Append user input and assistant response to messages
133
+ st.session_state.messages.append({"role": "user", "content": user_input})
134
+ st.session_state.messages.append({"role": "assistant", "content": response.get("output", "")})
135
+
136
+ # Display the user input and response
137
+ st.chat_message("user").write(user_input)
138
+ st.chat_message("assistant").write(response.get("output", ""))
139
+
140
+ # Clear the input box by creating a new one
141
+ st.text_input("Type your message here...", key="user_input_", value="", label_visibility="collapsed") # Recreate input to clear it
data_ingestion.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os.path
3
+ from tqdm import tqdm
4
+ from logger import logger
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain_huggingface import HuggingFaceEmbeddings
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.document_loaders import PyPDFLoader, WebBaseLoader
9
+
10
+
11
+ embeddings = HuggingFaceEmbeddings(model_name = "all-MiniLM-L6-v2")
12
+ if not os.path.exists("faiss_index"):
13
+ files = os.listdir("dataset")
14
+ for file in tqdm(files):
15
+ try:
16
+ path = os.path.join(os.path.join("dataset", file))
17
+ docs = PyPDFLoader(path)
18
+ documents = docs.load()
19
+ splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
20
+ splitted_docs = splitter.split_documents(documents)
21
+ vector_db = FAISS.from_documents(splitted_docs, embedding=embeddings)
22
+ vector_db.save_local("faiss_index")
23
+ logger.info(f"Success for file :{file}")
24
+ except Exception as e:
25
+ logger.error(f"Error {e} for file :{file}")
26
+ else:
27
+ vector_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
28
+ retriever = vector_db.as_retriever()
29
+ logger.info(retriever.invoke("what is machine learning"))
30
+ print("#"*90)
faiss_index/index.faiss ADDED
Binary file (36.9 kB). View file
 
faiss_index/index.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1bfa91938fdbddcd0453aa2847c228e4b45a48f8f0b4f8588ba1a8b033f379f8
3
+ size 18367
logger.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ # Create a logger and set its level
4
+ logger = logging.getLogger("app_logger")
5
+ logger.setLevel(logging.DEBUG) # Capture all levels
6
+
7
+ # Check if the logger already has handlers to avoid duplicates
8
+ if not logger.handlers:
9
+ # Console handler to output logs to the console
10
+ console_handler = logging.StreamHandler()
11
+ console_handler.setLevel(logging.DEBUG)
12
+
13
+ # Define log format including the filename
14
+ formatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s')
15
+ console_handler.setFormatter(formatter)
16
+
17
+ # Add the console handler to the logger
18
+ logger.addHandler(console_handler)
logs/app.log ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ 2024-11-04 01:39:47,152 - app_logger - INFO - [Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 202}, page_content='Chapter 11. Machine Learning\nI am always r eady to learn although I do not always like being taught.\n� W inston Churchill\nMany people imagine that data science is mostly machine learning and that\ndata scientists mostly build and train and tweak machine learning models all\nday long. (Then again, many of those people don� t actually know what\nmachine learning is .) In fact, data science is mostly turning business\nproblems into data problems and collecting data and understanding data and\ncleaning data and formatting data, after which machine learning is almost\nan afterthought. Even so, it� s an interesting and essential afterthought that\nyou pretty much have to know about in order to do data science.\nM o d e l i n g\nBefore we can talk about machine learning, we need to talk about models .\nWhat is a model? It� s simply a specification of a mathematical (or\nprobabilistic) relationship that exists between dif ferent variables.'), Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 500}, page_content='Products\nk-nearest neighbors , k-Nearest Neighbors - For Further Exploration\nlogistic regression , Logistic Regression - Support V ector Machines\nmachine learning and , What Is Machine Learning?\nmultiple regression , Multiple Regression - For Further Exploration'), Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 505}, page_content='reinforcement models , What Is Machine Learning?\nrelational databases , Databases and SQL\nrequests library , HTML and the Parsing Thereof\nrescaling data , Rescaling\nrobots.txt files , Example: Keeping T abs on Congress\nS\nscalar multiplication , V ectors\nscale , Rescaling\nscatterplot matrix , Many Dimensions\nscatterplots , Scatterplots - For Further Exploration\nscikit-learn , For Further Exploration , For Further Exploration , For Further\nExploration , For Further Exploration , For Further Investigation , For Further\nExploration , For Further Exploration , scikit-learn\nSciPy , For Further Exploration , For Further Exploration\nscipy .stats , For Further Exploration\nScrapy , For Further Exploration\nseaborn , For Further Exploration , V isualization\nSELECT statement , SELECT\nsemisupervised models , What Is Machine Learning?\nserialization , JSON and XML\nsets , Sets\nsigmoid function , Feed-Forward Neural Networks , Other Activation\nFunctions'), Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 494}, page_content='logistic function , The Logistic Function\nmodel application , Applying the Model\nproblem example , The Problem\nsupport vector machines , Support V ector Machines\ntools for , For Further Investigation\nloss functions , Using Gradient Descent to Fit Models , Loss and\nOptimization , Softmaxes and Cross-Entropy\nLSTM (long short-term memory) , Recurrent Neural Networks\nM\nmachine learning\nbias-variance tradeof f , The Bias-V ariance T radeof f\ncorrectness , Correctness\ndefinition of term , What Is Machine Learning?\nfeature extraction and selection , Feature Extraction and Selection\nmodeling , Modeling\noverfitting and underfitting , Overfitting and Underfitting\nresources for learning about , For Further Exploration\nmagnitude, computing , V ectors\nmanipulating data , Manipulating Data\nMapReduce\nanalyzing status updates example , Example: Analyzing Status Updates\nbasic algorithm , MapReduce')]
2
+ 2024-11-04 01:40:36,256 - app_logger - INFO - [Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 202}, page_content='Chapter 11. Machine Learning\nI am always r eady to learn although I do not always like being taught.\n� W inston Churchill\nMany people imagine that data science is mostly machine learning and that\ndata scientists mostly build and train and tweak machine learning models all\nday long. (Then again, many of those people don� t actually know what\nmachine learning is .) In fact, data science is mostly turning business\nproblems into data problems and collecting data and understanding data and\ncleaning data and formatting data, after which machine learning is almost\nan afterthought. Even so, it� s an interesting and essential afterthought that\nyou pretty much have to know about in order to do data science.\nM o d e l i n g\nBefore we can talk about machine learning, we need to talk about models .\nWhat is a model? It� s simply a specification of a mathematical (or\nprobabilistic) relationship that exists between dif ferent variables.'), Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 500}, page_content='Products\nk-nearest neighbors , k-Nearest Neighbors - For Further Exploration\nlogistic regression , Logistic Regression - Support V ector Machines\nmachine learning and , What Is Machine Learning?\nmultiple regression , Multiple Regression - For Further Exploration'), Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 505}, page_content='reinforcement models , What Is Machine Learning?\nrelational databases , Databases and SQL\nrequests library , HTML and the Parsing Thereof\nrescaling data , Rescaling\nrobots.txt files , Example: Keeping T abs on Congress\nS\nscalar multiplication , V ectors\nscale , Rescaling\nscatterplot matrix , Many Dimensions\nscatterplots , Scatterplots - For Further Exploration\nscikit-learn , For Further Exploration , For Further Exploration , For Further\nExploration , For Further Exploration , For Further Investigation , For Further\nExploration , For Further Exploration , scikit-learn\nSciPy , For Further Exploration , For Further Exploration\nscipy .stats , For Further Exploration\nScrapy , For Further Exploration\nseaborn , For Further Exploration , V isualization\nSELECT statement , SELECT\nsemisupervised models , What Is Machine Learning?\nserialization , JSON and XML\nsets , Sets\nsigmoid function , Feed-Forward Neural Networks , Other Activation\nFunctions'), Document(metadata={'source': 'dataset/Data Science from Scratch by Joel Grus.pdf', 'page': 494}, page_content='logistic function , The Logistic Function\nmodel application , Applying the Model\nproblem example , The Problem\nsupport vector machines , Support V ector Machines\ntools for , For Further Investigation\nloss functions , Using Gradient Descent to Fit Models , Loss and\nOptimization , Softmaxes and Cross-Entropy\nLSTM (long short-term memory) , Recurrent Neural Networks\nM\nmachine learning\nbias-variance tradeof f , The Bias-V ariance T radeof f\ncorrectness , Correctness\ndefinition of term , What Is Machine Learning?\nfeature extraction and selection , Feature Extraction and Selection\nmodeling , Modeling\noverfitting and underfitting , Overfitting and Underfitting\nresources for learning about , For Further Exploration\nmagnitude, computing , V ectors\nmanipulating data , Manipulating Data\nMapReduce\nanalyzing status updates example , Example: Analyzing Status Updates\nbasic algorithm , MapReduce')]