RashmiJanve0801 commited on
Commit
67b3f9b
·
unverified ·
1 Parent(s): fe52d78

Add files via upload

Browse files
Files changed (3) hide show
  1. app.py +54 -0
  2. requirements.txt +52 -0
  3. tools_agents.ipynb +511 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain_groq import ChatGroq
3
+ from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper
4
+ from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun, DuckDuckGoSearchRun
5
+ from langchain.agents import initialize_agent, AgentType
6
+ from langchain.callbacks import StreamlitCallbackHandler
7
+ import os
8
+ from dotenv import load_dotenv
9
+
10
+ # Used the inbuilt tools of Arxiv and Wikipedia
11
+ api_wrapper_arxiv = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)
12
+ arxiv = ArxivQueryRun(api_wrapper=api_wrapper_arxiv)
13
+
14
+ api_wrapper_wiki = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)
15
+ wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)
16
+
17
+ search = DuckDuckGoSearchRun(name="Search")
18
+
19
+ st.title("Langchain - Chat with Search")
20
+ """
21
+ In this example, we're using `StreamlitCallbackHandler` to display the thoughts and actions of an agent in an interactive Streamlit app.
22
+ Try more LangChain 🤝 Streamlit Agent examples at [github.com/langchain-ai/streamlit-agent](https://github.com/langchain-ai/streamlit-agent).
23
+ """
24
+
25
+ # Sidebar for settings
26
+ st.sidebar.title("Settings")
27
+ api_key = st.sidebar.text_input("Enter your Groq API Key:", type="password")
28
+
29
+ if "messages" not in st.session_state:
30
+ st.session_state["messages"] = [
31
+ {"role":"assistant", "content":"Hi, I am a Chatbot who can search the web. How can I help you ?"}
32
+ ]
33
+
34
+ for msg in st.session_state.messages:
35
+ st.chat_message(msg["role"]).write(msg["content"])
36
+
37
+ if prompt:=st.chat_input(placeholder="What is machine learning ?"):
38
+ st.session_state.messages.append({"role":"user", "content":prompt})
39
+ st.chat_message("user").write(prompt)
40
+
41
+ llm = ChatGroq(groq_api_key=api_key, model_name="Llama3-8b-8192", streaming=True)
42
+ tools = [search, arxiv, wiki]
43
+
44
+ search_agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True)
45
+
46
+ with st.chat_message("assistant"):
47
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
48
+ response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
49
+ st.session_state.messages.append({'role':'assistant', "content":response})
50
+ st.write(response)
51
+
52
+
53
+
54
+
requirements.txt ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ ipykernel
3
+ python-dotenv
4
+ langchain_community
5
+ langchain-community
6
+ pypdf
7
+ bs4
8
+ beautifulsoup4
9
+ arxiv
10
+ pymupdf
11
+ wikipedia
12
+ langchain-text-splitters
13
+ langchain-openai
14
+ chromadb
15
+ sentence_transformers
16
+ langchain_huggingface
17
+ faiss-cpu
18
+ langchain_chroma
19
+ langchain-chroma
20
+ streamlit
21
+ langchain-ollama
22
+ langchain_groq
23
+ langchain_core
24
+ uvicorn
25
+ fastapi
26
+ pydantic
27
+ langchain
28
+ langserve
29
+ uvicorn
30
+ sse_starlette
31
+ packaging
32
+ langchain-groq
33
+ pandas
34
+ duckdb
35
+ httpx
36
+ openai
37
+ duckduckgo-search
38
+ langchain-google-genai
39
+ google-generativeai
40
+ mysql-connector-python
41
+ SQLAlchemy
42
+ validators==0.28.1
43
+ youtube_transcript_api
44
+ pytube
45
+ unstructured
46
+ numexpr
47
+ huggingface_hub
48
+ cassio
49
+ datasets
50
+ tiktoken
51
+ PyPDF2
52
+ gradio
tools_agents.ipynb ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 36,
6
+ "id": "6234377a",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Search Engine with Tools and Agents"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": 37,
16
+ "id": "adc1e419",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "# Arxiv --> Research papers\n",
21
+ "from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun\n",
22
+ "from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": 38,
28
+ "id": "3cc5635e",
29
+ "metadata": {},
30
+ "outputs": [
31
+ {
32
+ "data": {
33
+ "text/plain": [
34
+ "'arxiv'"
35
+ ]
36
+ },
37
+ "execution_count": 38,
38
+ "metadata": {},
39
+ "output_type": "execute_result"
40
+ }
41
+ ],
42
+ "source": [
43
+ "# Used the inbuilt tool of arxiv\n",
44
+ "api_wrapper_arxiv = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)\n",
45
+ "arxiv = ArxivQueryRun(api_wrapper=api_wrapper_arxiv)\n",
46
+ "arxiv.name"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "execution_count": 39,
52
+ "id": "d4884a4e",
53
+ "metadata": {},
54
+ "outputs": [
55
+ {
56
+ "data": {
57
+ "text/plain": [
58
+ "'wikipedia'"
59
+ ]
60
+ },
61
+ "execution_count": 39,
62
+ "metadata": {},
63
+ "output_type": "execute_result"
64
+ }
65
+ ],
66
+ "source": [
67
+ "# Used the inbuilt tool of wikipedia\n",
68
+ "api_wrapper_wiki = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)\n",
69
+ "wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)\n",
70
+ "wiki.name"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": 40,
76
+ "id": "adc0504e",
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "tools = [wiki, arxiv]"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": 41,
86
+ "id": "ffbfc26f",
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "# Create Custom tools[RAG Tool]\n",
91
+ "from langchain_community.document_loaders import WebBaseLoader\n",
92
+ "from langchain_community.vectorstores import FAISS\n",
93
+ "from langchain_google_genai import GoogleGenerativeAIEmbeddings\n",
94
+ "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
95
+ "from langchain_groq import ChatGroq\n",
96
+ "import os"
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "execution_count": 42,
102
+ "id": "40f95fec",
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "from dotenv import load_dotenv\n",
107
+ "load_dotenv()\n",
108
+ "\n",
109
+ "# Load the GROQ API Key\n",
110
+ "os.environ['OPENAI_API_KEY']=os.getenv(\"OPENAI_API_KEY\")\n",
111
+ "os.environ['GROQ_API_KEY']=os.getenv(\"GROQ_API_KEY\")\n",
112
+ "os.environ['GEMINI_API_KEY']=os.getenv(\"GEMINI_API_KEY\")\n",
113
+ "groq_api_key = os.getenv(\"GROQ_API_KEY\")"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "execution_count": 43,
119
+ "id": "312981ac",
120
+ "metadata": {},
121
+ "outputs": [],
122
+ "source": [
123
+ "embeddings = GoogleGenerativeAIEmbeddings(\n",
124
+ " google_api_key=os.getenv(\"GEMINI_API_KEY\"),\n",
125
+ " model = \"models/embedding-001\"\n",
126
+ ")"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": 44,
132
+ "id": "2862f070",
133
+ "metadata": {},
134
+ "outputs": [
135
+ {
136
+ "data": {
137
+ "text/plain": [
138
+ "VectorStoreRetriever(tags=['FAISS', 'GoogleGenerativeAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000022AE2136080>, search_kwargs={})"
139
+ ]
140
+ },
141
+ "execution_count": 44,
142
+ "metadata": {},
143
+ "output_type": "execute_result"
144
+ }
145
+ ],
146
+ "source": [
147
+ "loader = WebBaseLoader(\"https://docs.smith.langchain.com/\")\n",
148
+ "docs = loader.load()\n",
149
+ "documents = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200).split_documents(docs)\n",
150
+ "vectordb = FAISS.from_documents(documents=documents, embedding=embeddings)\n",
151
+ "retriever = vectordb.as_retriever()\n",
152
+ "retriever"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": 45,
158
+ "id": "88d52680",
159
+ "metadata": {},
160
+ "outputs": [
161
+ {
162
+ "data": {
163
+ "text/plain": [
164
+ "'langsmith-search'"
165
+ ]
166
+ },
167
+ "execution_count": 45,
168
+ "metadata": {},
169
+ "output_type": "execute_result"
170
+ }
171
+ ],
172
+ "source": [
173
+ "from langchain.tools.retriever import create_retriever_tool\n",
174
+ "retriever_tool = create_retriever_tool(retriever, \"langsmith-search\", \"Search any information about Langsmith\")\n",
175
+ "\n",
176
+ "retriever_tool.name"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": 46,
182
+ "id": "c50aa396",
183
+ "metadata": {},
184
+ "outputs": [],
185
+ "source": [
186
+ "tools = [wiki, arxiv, retriever_tool]"
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "execution_count": 47,
192
+ "id": "2a336248",
193
+ "metadata": {},
194
+ "outputs": [
195
+ {
196
+ "data": {
197
+ "text/plain": [
198
+ "[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=<module 'wikipedia' from 'c:\\\\Users\\\\Rashmi Janve\\\\OneDrive\\\\Desktop\\\\Gen AI Tutorials - Krish Naik\\\\Langchain Projects\\\\Chatbots\\\\venv\\\\lib\\\\site-packages\\\\wikipedia\\\\__init__.py'>, top_k_results=1, lang='en', load_all_available_meta=False, doc_content_chars_max=250)),\n",
199
+ " 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=250)),\n",
200
+ " Tool(name='langsmith-search', description='Search any information about Langsmith', args_schema=<class 'langchain_core.tools.retriever.RetrieverInput'>, func=functools.partial(<function _get_relevant_documents at 0x0000022AE21B0670>, retriever=VectorStoreRetriever(tags=['FAISS', 'GoogleGenerativeAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000022AE2136080>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n', response_format='content'), coroutine=functools.partial(<function _aget_relevant_documents at 0x0000022AE21B09D0>, retriever=VectorStoreRetriever(tags=['FAISS', 'GoogleGenerativeAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000022AE2136080>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n', response_format='content'))]"
201
+ ]
202
+ },
203
+ "execution_count": 47,
204
+ "metadata": {},
205
+ "output_type": "execute_result"
206
+ }
207
+ ],
208
+ "source": [
209
+ "tools"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "execution_count": 48,
215
+ "id": "357e0dc6",
216
+ "metadata": {},
217
+ "outputs": [],
218
+ "source": [
219
+ "# Run all the above tools with Agents and LLM Models\n",
220
+ "\n",
221
+ "# Tools, LLM --> AgentExecutor\n",
222
+ "llm = ChatGroq(groq_api_key=groq_api_key, model_name=\"Llama3-8b-8192\")"
223
+ ]
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "execution_count": 49,
228
+ "id": "60f0191c",
229
+ "metadata": {},
230
+ "outputs": [
231
+ {
232
+ "data": {
233
+ "text/plain": [
234
+ "[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a helpful assistant'), additional_kwargs={}),\n",
235
+ " MessagesPlaceholder(variable_name='chat_history', optional=True),\n",
236
+ " HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], input_types={}, partial_variables={}, template='{input}'), additional_kwargs={}),\n",
237
+ " MessagesPlaceholder(variable_name='agent_scratchpad')]"
238
+ ]
239
+ },
240
+ "execution_count": 49,
241
+ "metadata": {},
242
+ "output_type": "execute_result"
243
+ }
244
+ ],
245
+ "source": [
246
+ "# Prompt Template\n",
247
+ "from langchain import hub\n",
248
+ "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
249
+ "prompt.messages"
250
+ ]
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "execution_count": 52,
255
+ "id": "ef269d2a",
256
+ "metadata": {},
257
+ "outputs": [
258
+ {
259
+ "data": {
260
+ "text/plain": [
261
+ "RunnableAssign(mapper={\n",
262
+ " agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
263
+ "})\n",
264
+ "| 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 0x0000022ACEC8B490>, 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 0x0000022ACEC8B490>, 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",
265
+ "| RunnableBinding(bound=ChatGroq(client=<groq.resources.chat.completions.Completions object at 0x0000022AFA6BD360>, async_client=<groq.resources.chat.completions.AsyncCompletions object at 0x0000022AFA6BE7D0>, model_name='Llama3-8b-8192', 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': 'langsmith-search', 'description': 'Search any information about Langsmith', 'parameters': {'properties': {'query': {'description': 'query to look up in retriever', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}]}, config={}, config_factories=[])\n",
266
+ "| OpenAIToolsAgentOutputParser()"
267
+ ]
268
+ },
269
+ "execution_count": 52,
270
+ "metadata": {},
271
+ "output_type": "execute_result"
272
+ }
273
+ ],
274
+ "source": [
275
+ "# Agents \n",
276
+ "from langchain.agents import create_openai_tools_agent\n",
277
+ "agent = create_openai_tools_agent(llm, tools, prompt)\n",
278
+ "agent"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 54,
284
+ "id": "cf4e41ea",
285
+ "metadata": {},
286
+ "outputs": [
287
+ {
288
+ "data": {
289
+ "text/plain": [
290
+ "AgentExecutor(verbose=True, agent=RunnableMultiActionAgent(runnable=RunnableAssign(mapper={\n",
291
+ " agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
292
+ "})\n",
293
+ "| 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 0x0000022ACEC8B490>, 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 0x0000022ACEC8B490>, 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",
294
+ "| RunnableBinding(bound=ChatGroq(client=<groq.resources.chat.completions.Completions object at 0x0000022AFA6BD360>, async_client=<groq.resources.chat.completions.AsyncCompletions object at 0x0000022AFA6BE7D0>, model_name='Llama3-8b-8192', 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': 'langsmith-search', 'description': 'Search any information about Langsmith', 'parameters': {'properties': {'query': {'description': 'query to look up in retriever', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}]}, config={}, config_factories=[])\n",
295
+ "| OpenAIToolsAgentOutputParser(), input_keys_arg=[], return_keys_arg=[], stream_runnable=True), tools=[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=<module 'wikipedia' from 'c:\\\\Users\\\\Rashmi Janve\\\\OneDrive\\\\Desktop\\\\Gen AI Tutorials - Krish Naik\\\\Langchain Projects\\\\Chatbots\\\\venv\\\\lib\\\\site-packages\\\\wikipedia\\\\__init__.py'>, top_k_results=1, lang='en', load_all_available_meta=False, doc_content_chars_max=250)), 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=250)), Tool(name='langsmith-search', description='Search any information about Langsmith', args_schema=<class 'langchain_core.tools.retriever.RetrieverInput'>, func=functools.partial(<function _get_relevant_documents at 0x0000022AE21B0670>, retriever=VectorStoreRetriever(tags=['FAISS', 'GoogleGenerativeAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000022AE2136080>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n', response_format='content'), coroutine=functools.partial(<function _aget_relevant_documents at 0x0000022AE21B09D0>, retriever=VectorStoreRetriever(tags=['FAISS', 'GoogleGenerativeAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000022AE2136080>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n', response_format='content'))])"
296
+ ]
297
+ },
298
+ "execution_count": 54,
299
+ "metadata": {},
300
+ "output_type": "execute_result"
301
+ }
302
+ ],
303
+ "source": [
304
+ "# Agent Executer\n",
305
+ "from langchain.agents import AgentExecutor\n",
306
+ "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
307
+ "agent_executor"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": 55,
313
+ "id": "416831c8",
314
+ "metadata": {},
315
+ "outputs": [
316
+ {
317
+ "name": "stdout",
318
+ "output_type": "stream",
319
+ "text": [
320
+ "\n",
321
+ "\n",
322
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
323
+ "\u001b[32;1m\u001b[1;3m\n",
324
+ "Invoking: `langsmith-search` with `{'query': 'what is Langsmith'}`\n",
325
+ "\n",
326
+ "\n",
327
+ "\u001b[0m\u001b[38;5;200m\u001b[1;3mSkip to main contentWe are growing and hiring for multiple roles for LangChain, LangGraph and LangSmith. Join our team!API ReferenceRESTPythonJS/TSSearchRegionUSEUGo to AppGet StartedObservabilityEvaluationPrompt EngineeringDeployment (LangGraph Platform)AdministrationSelf-hostingPricingReferenceCloud architecture and scalabilityAuthz and AuthnAuthentication methodsdata_formatsEvaluationDataset transformationsRegions FAQsdk_referenceGet StartedOn this pageGet started with LangSmith\n",
328
+ "LangSmith is a platform for building production-grade LLM applications.\n",
329
+ "It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence.\n",
330
+ "ObservabilityAnalyze traces in LangSmith and configure metrics, dashboards, alerts based on these.EvalsEvaluate your application over production traffic — score application performance and get human feedback on your data.Prompt EngineeringIterate on prompts, with automatic version control and collaboration features.\n",
331
+ "\n",
332
+ "LangSmith + LangChain OSSLangSmith is framework-agnostic — it can be used with or without LangChain's open source frameworks langchain and langgraph.If you are using either of these, you can enable LangSmith tracing with a single environment variable.\n",
333
+ "For more see the how-to guide for setting up LangSmith with LangChain or setting up LangSmith with LangGraph.\n",
334
+ "Observability​\n",
335
+ "Observability is important for any software application, but especially so for LLM applications. LLMs are non-deterministic by nature, meaning they can produce unexpected results. This makes them trickier than normal to debug.\n",
336
+ "This is where LangSmith can help! LangSmith has LLM-native observability, allowing you to get meaningful insights from your application. LangSmith’s observability features have you covered throughout all stages of application development - from prototyping, to beta testing, to production.\n",
337
+ "\n",
338
+ "Get started by adding tracing to your application.\n",
339
+ "Create dashboards to view key metrics like RPS, error rates and costs.\n",
340
+ "\n",
341
+ "Evals​\n",
342
+ "The quality and development speed of AI applications depends on high-quality evaluation datasets and metrics to test and optimize your applications on. The LangSmith SDK and UI make building and running high-quality evaluations easy.\n",
343
+ "\n",
344
+ "Get started by creating your first evaluation.\n",
345
+ "Quickly assess the performance of your application using our off-the-shelf evaluators as a starting point.\n",
346
+ "Analyze results of evaluations in the LangSmith UI and compare results over time.\n",
347
+ "Easily collect human feedback on your data to improve your application.\n",
348
+ "\n",
349
+ "Prompt Engineering​\n",
350
+ "While traditional software applications are built by writing code, AI applications involve writing prompts to instruct the LLM on what to do. LangSmith provides a set of tools designed to enable and facilitate prompt engineering to help you find the perfect prompt for your application.\n",
351
+ "\n",
352
+ "Get started with LangSmith | 🦜️🛠️ LangSmith\u001b[0m\u001b[32;1m\u001b[1;3mThank you for providing the tool call result for \"call_nhzk\". Based on the output, it seems that LangSmith is a platform for building production-grade LLM (Large Language Model) applications. It provides features such as observability, evaluation, and prompt engineering to help developers monitor, evaluate, and optimize their LLM applications.\n",
353
+ "\n",
354
+ "LangSmith allows developers to closely monitor and evaluate their applications, analyze traces, and configure metrics, dashboards, and alerts. It also provides features for evaluating application performance and getting human feedback on data. Additionally, LangSmith offers prompt engineering tools to help developers find the perfect prompt for their applications.\n",
355
+ "\n",
356
+ "It appears that LangSmith is a comprehensive platform for building and deploying LLM applications, and it seems to be a useful tool for developers working with AI and NLP.\u001b[0m\n",
357
+ "\n",
358
+ "\u001b[1m> Finished chain.\u001b[0m\n"
359
+ ]
360
+ },
361
+ {
362
+ "data": {
363
+ "text/plain": [
364
+ "{'input': 'Tell me about Langsmith',\n",
365
+ " 'output': 'Thank you for providing the tool call result for \"call_nhzk\". Based on the output, it seems that LangSmith is a platform for building production-grade LLM (Large Language Model) applications. It provides features such as observability, evaluation, and prompt engineering to help developers monitor, evaluate, and optimize their LLM applications.\\n\\nLangSmith allows developers to closely monitor and evaluate their applications, analyze traces, and configure metrics, dashboards, and alerts. It also provides features for evaluating application performance and getting human feedback on data. Additionally, LangSmith offers prompt engineering tools to help developers find the perfect prompt for their applications.\\n\\nIt appears that LangSmith is a comprehensive platform for building and deploying LLM applications, and it seems to be a useful tool for developers working with AI and NLP.'}"
366
+ ]
367
+ },
368
+ "execution_count": 55,
369
+ "metadata": {},
370
+ "output_type": "execute_result"
371
+ }
372
+ ],
373
+ "source": [
374
+ "agent_executor.invoke({\"input\":\"Tell me about Langsmith\"})"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "code",
379
+ "execution_count": 56,
380
+ "id": "17245205",
381
+ "metadata": {},
382
+ "outputs": [
383
+ {
384
+ "name": "stdout",
385
+ "output_type": "stream",
386
+ "text": [
387
+ "\n",
388
+ "\n",
389
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
390
+ "\u001b[32;1m\u001b[1;3m\n",
391
+ "Invoking: `wikipedia` with `{'query': 'Machine Learning'}`\n",
392
+ "\n",
393
+ "\n",
394
+ "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Machine learning\n",
395
+ "Summary: Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of statistical algorithms that can learn from data and generalise to unseen data, and thus perform tasks wit\u001b[0m\u001b[32;1m\u001b[1;3m\n",
396
+ "Invoking: `wikipedia` with `{'query': 'Artificial Intelligence'}`\n",
397
+ "\n",
398
+ "\n",
399
+ "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Artificial intelligence\n",
400
+ "Summary: Artificial intelligence (AI) refers to the capability of computational systems to perform tasks typically associated with human intelligence, such as learning, reasoning, problem-solving, perception, and decisio\u001b[0m\u001b[32;1m\u001b[1;3m\n",
401
+ "Invoking: `wikipedia` with `{'query': 'Machine learning algorithms'}`\n",
402
+ "\n",
403
+ "\n",
404
+ "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Machine learning\n",
405
+ "Summary: Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of statistical algorithms that can learn from data and generalise to unseen data, and thus perform tasks wit\u001b[0m\u001b[32;1m\u001b[1;3mMachine learning is a subset of artificial intelligence that involves the use of algorithms to analyze and learn from data. These algorithms can be trained on large datasets and can improve their performance over time, allowing them to make predictions, classify objects, and make decisions.\n",
406
+ "\n",
407
+ "Some common machine learning algorithms include:\n",
408
+ "\n",
409
+ "* Supervised learning algorithms, which learn from labeled data and can be used for tasks such as image classification and speech recognition.\n",
410
+ "* Unsupervised learning algorithms, which learn from unlabeled data and can be used for tasks such as clustering and anomaly detection.\n",
411
+ "* Reinforcement learning algorithms, which learn through trial and error and can be used for tasks such as game playing and robotics.\n",
412
+ "\n",
413
+ "Machine learning has many applications, including image and speech recognition, natural language processing, recommendation systems, and predictive modeling. It is a rapidly growing field, and is being used in a wide range of industries, including healthcare, finance, and marketing.\u001b[0m\n",
414
+ "\n",
415
+ "\u001b[1m> Finished chain.\u001b[0m\n"
416
+ ]
417
+ },
418
+ {
419
+ "data": {
420
+ "text/plain": [
421
+ "{'input': 'Tell me about Machine Learning',\n",
422
+ " 'output': 'Machine learning is a subset of artificial intelligence that involves the use of algorithms to analyze and learn from data. These algorithms can be trained on large datasets and can improve their performance over time, allowing them to make predictions, classify objects, and make decisions.\\n\\nSome common machine learning algorithms include:\\n\\n* Supervised learning algorithms, which learn from labeled data and can be used for tasks such as image classification and speech recognition.\\n* Unsupervised learning algorithms, which learn from unlabeled data and can be used for tasks such as clustering and anomaly detection.\\n* Reinforcement learning algorithms, which learn through trial and error and can be used for tasks such as game playing and robotics.\\n\\nMachine learning has many applications, including image and speech recognition, natural language processing, recommendation systems, and predictive modeling. It is a rapidly growing field, and is being used in a wide range of industries, including healthcare, finance, and marketing.'}"
423
+ ]
424
+ },
425
+ "execution_count": 56,
426
+ "metadata": {},
427
+ "output_type": "execute_result"
428
+ }
429
+ ],
430
+ "source": [
431
+ "agent_executor.invoke({\"input\":\"Tell me about Machine Learning\"})"
432
+ ]
433
+ },
434
+ {
435
+ "cell_type": "code",
436
+ "execution_count": 57,
437
+ "id": "b21d0d0f",
438
+ "metadata": {},
439
+ "outputs": [
440
+ {
441
+ "name": "stdout",
442
+ "output_type": "stream",
443
+ "text": [
444
+ "\n",
445
+ "\n",
446
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
447
+ "\u001b[32;1m\u001b[1;3m\n",
448
+ "Invoking: `arxiv` with `{'query': '1706.03762'}`\n",
449
+ "\n",
450
+ "\n",
451
+ "\u001b[0m\u001b[33;1m\u001b[1;3mPublished: 2023-08-02\n",
452
+ "Title: Attention Is All You Need\n",
453
+ "Authors: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin\n",
454
+ "Summary: The dominant sequence transduction models are based on c\u001b[0m\u001b[32;1m\u001b[1;3mIt seems like the tool call id \"call_m8hr\" was successful in retrieving information about the research paper with the ID \"1706.03762\".\n",
455
+ "\n",
456
+ "Based on the output, it appears to be the paper \"Attention Is All You Need\" published in 2023. The paper was authored by a group of researchers, and it seems to be a significant work in the field of sequence transduction models.\n",
457
+ "\n",
458
+ "Now that we have this information, I can respond directly to your original question without needing to use any further tools. The paper \"Attention Is All You Need\" is a well-known and influential work in the field of natural language processing, and it has been widely cited and built upon. It presents a new approach to sequence transduction models that relies solely on self-attention mechanisms, rather than the traditional encoder-decoder architecture.\n",
459
+ "\n",
460
+ "Would you like me to provide more information about this paper, or is there anything else I can help you with?\u001b[0m\n",
461
+ "\n",
462
+ "\u001b[1m> Finished chain.\u001b[0m\n"
463
+ ]
464
+ },
465
+ {
466
+ "data": {
467
+ "text/plain": [
468
+ "{'input': 'Tell me more about this research paper 1706.03762',\n",
469
+ " 'output': 'It seems like the tool call id \"call_m8hr\" was successful in retrieving information about the research paper with the ID \"1706.03762\".\\n\\nBased on the output, it appears to be the paper \"Attention Is All You Need\" published in 2023. The paper was authored by a group of researchers, and it seems to be a significant work in the field of sequence transduction models.\\n\\nNow that we have this information, I can respond directly to your original question without needing to use any further tools. The paper \"Attention Is All You Need\" is a well-known and influential work in the field of natural language processing, and it has been widely cited and built upon. It presents a new approach to sequence transduction models that relies solely on self-attention mechanisms, rather than the traditional encoder-decoder architecture.\\n\\nWould you like me to provide more information about this paper, or is there anything else I can help you with?'}"
470
+ ]
471
+ },
472
+ "execution_count": 57,
473
+ "metadata": {},
474
+ "output_type": "execute_result"
475
+ }
476
+ ],
477
+ "source": [
478
+ "agent_executor.invoke({\"input\":\"Tell me more about this research paper 1706.03762\"})"
479
+ ]
480
+ },
481
+ {
482
+ "cell_type": "code",
483
+ "execution_count": null,
484
+ "id": "b564ce83",
485
+ "metadata": {},
486
+ "outputs": [],
487
+ "source": []
488
+ }
489
+ ],
490
+ "metadata": {
491
+ "kernelspec": {
492
+ "display_name": "Python 3",
493
+ "language": "python",
494
+ "name": "python3"
495
+ },
496
+ "language_info": {
497
+ "codemirror_mode": {
498
+ "name": "ipython",
499
+ "version": 3
500
+ },
501
+ "file_extension": ".py",
502
+ "mimetype": "text/x-python",
503
+ "name": "python",
504
+ "nbconvert_exporter": "python",
505
+ "pygments_lexer": "ipython3",
506
+ "version": "3.10.0"
507
+ }
508
+ },
509
+ "nbformat": 4,
510
+ "nbformat_minor": 5
511
+ }