File size: 35,142 Bytes
67b3f9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "6234377a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Search Engine with Tools and Agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "adc1e419",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Arxiv --> Research papers\n",
    "from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun\n",
    "from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "3cc5635e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'arxiv'"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Used the inbuilt tool of arxiv\n",
    "api_wrapper_arxiv = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)\n",
    "arxiv = ArxivQueryRun(api_wrapper=api_wrapper_arxiv)\n",
    "arxiv.name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "d4884a4e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'wikipedia'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Used the inbuilt tool of wikipedia\n",
    "api_wrapper_wiki = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)\n",
    "wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)\n",
    "wiki.name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "adc0504e",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [wiki, arxiv]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "ffbfc26f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Custom tools[RAG Tool]\n",
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_google_genai import GoogleGenerativeAIEmbeddings\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "from langchain_groq import ChatGroq\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "40f95fec",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "\n",
    "# Load the GROQ API Key\n",
    "os.environ['OPENAI_API_KEY']=os.getenv(\"OPENAI_API_KEY\")\n",
    "os.environ['GROQ_API_KEY']=os.getenv(\"GROQ_API_KEY\")\n",
    "os.environ['GEMINI_API_KEY']=os.getenv(\"GEMINI_API_KEY\")\n",
    "groq_api_key = os.getenv(\"GROQ_API_KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "312981ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "embeddings = GoogleGenerativeAIEmbeddings(\n",
    "    google_api_key=os.getenv(\"GEMINI_API_KEY\"),\n",
    "    model = \"models/embedding-001\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "2862f070",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "VectorStoreRetriever(tags=['FAISS', 'GoogleGenerativeAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x0000022AE2136080>, search_kwargs={})"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "loader = WebBaseLoader(\"https://docs.smith.langchain.com/\")\n",
    "docs = loader.load()\n",
    "documents = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200).split_documents(docs)\n",
    "vectordb = FAISS.from_documents(documents=documents, embedding=embeddings)\n",
    "retriever = vectordb.as_retriever()\n",
    "retriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "88d52680",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'langsmith-search'"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.tools.retriever import create_retriever_tool\n",
    "retriever_tool = create_retriever_tool(retriever, \"langsmith-search\", \"Search any information about Langsmith\")\n",
    "\n",
    "retriever_tool.name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "c50aa396",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [wiki, arxiv, retriever_tool]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "2a336248",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[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",
       " 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",
       " 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'))]"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "357e0dc6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run all the above tools with Agents and LLM Models\n",
    "\n",
    "# Tools, LLM --> AgentExecutor\n",
    "llm = ChatGroq(groq_api_key=groq_api_key, model_name=\"Llama3-8b-8192\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "60f0191c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a helpful assistant'), additional_kwargs={}),\n",
       " MessagesPlaceholder(variable_name='chat_history', optional=True),\n",
       " HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], input_types={}, partial_variables={}, template='{input}'), additional_kwargs={}),\n",
       " MessagesPlaceholder(variable_name='agent_scratchpad')]"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Prompt Template\n",
    "from langchain import hub\n",
    "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
    "prompt.messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "ef269d2a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "RunnableAssign(mapper={\n",
       "  agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
       "})\n",
       "| 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",
       "| 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",
       "| OpenAIToolsAgentOutputParser()"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Agents \n",
    "from langchain.agents import create_openai_tools_agent\n",
    "agent = create_openai_tools_agent(llm, tools, prompt)\n",
    "agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "cf4e41ea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AgentExecutor(verbose=True, agent=RunnableMultiActionAgent(runnable=RunnableAssign(mapper={\n",
       "  agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
       "})\n",
       "| 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",
       "| 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",
       "| 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'))])"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Agent Executer\n",
    "from langchain.agents import AgentExecutor\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent_executor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "416831c8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `langsmith-search` with `{'query': 'what is Langsmith'}`\n",
      "\n",
      "\n",
      "\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",
      "LangSmith is a platform for building production-grade LLM applications.\n",
      "It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence.\n",
      "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",
      "\n",
      "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",
      "For more see the how-to guide for setting up LangSmith with LangChain or setting up LangSmith with LangGraph.\n",
      "Observability​\n",
      "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",
      "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",
      "\n",
      "Get started by adding tracing to your application.\n",
      "Create dashboards to view key metrics like RPS, error rates and costs.\n",
      "\n",
      "Evals​\n",
      "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",
      "\n",
      "Get started by creating your first evaluation.\n",
      "Quickly assess the performance of your application using our off-the-shelf evaluators as a starting point.\n",
      "Analyze results of evaluations in the LangSmith UI and compare results over time.\n",
      "Easily collect human feedback on your data to improve your application.\n",
      "\n",
      "Prompt Engineering​\n",
      "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",
      "\n",
      "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",
      "\n",
      "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",
      "\n",
      "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",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'Tell me about Langsmith',\n",
       " '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.'}"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\":\"Tell me about Langsmith\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "17245205",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `wikipedia` with `{'query': 'Machine Learning'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Machine learning\n",
      "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",
      "Invoking: `wikipedia` with `{'query': 'Artificial Intelligence'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Artificial intelligence\n",
      "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",
      "Invoking: `wikipedia` with `{'query': 'Machine learning algorithms'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Machine learning\n",
      "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",
      "\n",
      "Some 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",
      "\n",
      "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",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'Tell me about Machine Learning',\n",
       " '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.'}"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\":\"Tell me about Machine Learning\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "b21d0d0f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `arxiv` with `{'query': '1706.03762'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[33;1m\u001b[1;3mPublished: 2023-08-02\n",
      "Title: Attention Is All You Need\n",
      "Authors: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin\n",
      "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",
      "\n",
      "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",
      "\n",
      "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",
      "\n",
      "Would you like me to provide more information about this paper, or is there anything else I can help you with?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'Tell me more about this research paper 1706.03762',\n",
       " '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?'}"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\":\"Tell me more about this research paper 1706.03762\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b564ce83",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}