P-RajaRamesh commited on
Commit
3a62d3f
·
unverified ·
1 Parent(s): ed1d85a

Add files via upload

Browse files
Files changed (3) hide show
  1. app.py +56 -0
  2. requirements.txt +33 -0
  3. tools_agents.ipynb +478 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## Arxiv and Wikipedia Tools
11
+ api_wrapper_wiki=WikipediaAPIWrapper(top_k_results=1,doc_content_chars_max=200)
12
+ wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)
13
+
14
+ api_wrapper_arxiv=ArxivAPIWrapper(top_k_results=1,doc_content_chars_max=200)
15
+ arxiv=ArxivQueryRun(api_wrapper=api_wrapper_arxiv)
16
+
17
+ search=DuckDuckGoSearchRun(name="Search")
18
+
19
+ st.title("🔎 LangChain - Chat with search")
20
+
21
+ """
22
+ In this example, we're using `StreamlitCallbackHandler` to display the thoughts and actions of an agent in an interactive Streamlit app.
23
+ Try more LangChain 🤝 Streamlit Agent examples at [github.com/langchain-ai/streamlit-agent](https://github.com/langchain-ai/streamlit-agent).
24
+ """
25
+
26
+ ## Sidebar for settings
27
+ st.sidebar.title("Settings")
28
+ api_key=st.sidebar.text_input("Enter your Groq API Key:",type="password")
29
+
30
+ if "messages" not in st.session_state:
31
+ st.session_state["messages"]=[
32
+ {
33
+ "role":"assistant",
34
+ "content":"Hi I'm a chatbot who can search the web. How can I help you?"
35
+ }
36
+ ]
37
+
38
+ for msg in st.session_state.messages:
39
+ st.chat_message(msg["role"]).write(msg["content"])
40
+
41
+ if prompt:=st.chat_input(placeholder="What is machine learning?"):
42
+ st.session_state.messages.append({"role":"user","content":prompt})
43
+ st.chat_message("user").write(prompt)
44
+
45
+ llm=ChatGroq(groq_api_key=api_key,model_name="Llama3-8b-8192",streaming=True)
46
+ tools=[search,arxiv,wiki]
47
+
48
+ search_agent=initialize_agent(tools,llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,handle_parsing_errors=True)
49
+
50
+ with st.chat_message("assistant"):
51
+ st_cb=StreamlitCallbackHandler(st.container(),expand_new_thoughts=False)
52
+ response=search_agent.run(st.session_state.messages,callbacks=[st_cb])
53
+ st.session_state.messages.append({"role":"assistant","content":response})
54
+ st.write(response)
55
+
56
+
requirements.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ ipykernel
3
+ python-dotenv
4
+ langchain-community
5
+ pypdf
6
+ bs4
7
+ arxiv
8
+ pymupdf
9
+ wikipedia
10
+ pyowm
11
+ langchain-text-splitters
12
+ langchain-openai
13
+ chromadb
14
+ sentence-transformers
15
+ langchain-huggingface
16
+ faiss-cpu
17
+ langchain-chroma
18
+ streamlit
19
+ langchain-groq
20
+ langchain-core
21
+ fastapi
22
+ uvicorn
23
+ langserve
24
+ sse_starlette
25
+ duckduckgo-search
26
+ SQLAlchemy
27
+ mysql-connector-python
28
+ validators==0.28.1
29
+ youtube-transcript-api
30
+ unstructured
31
+ pytube
32
+ numexpr
33
+ huggingface_hub
tools_agents.ipynb ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Search Engine with Tools and Agents"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "markdown",
12
+ "metadata": {},
13
+ "source": [
14
+ "### Agents uses llm to choose the sequence of task. whereas in chain its hard coded. \n",
15
+ "### In Agents, allm is used as a reasoning model to determine which action to take and in which order.\n",
16
+ "\n",
17
+ "### Tools are interfaces that an LLM, Agents or cahin uses to interact with the world."
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "execution_count": 2,
23
+ "metadata": {},
24
+ "outputs": [],
25
+ "source": [
26
+ "from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun\n",
27
+ "from langchain_community.utilities import WikipediaAPIWrapper, ArxivAPIWrapper"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "metadata": {},
34
+ "outputs": [
35
+ {
36
+ "data": {
37
+ "text/plain": [
38
+ "'wikipedia'"
39
+ ]
40
+ },
41
+ "execution_count": 6,
42
+ "metadata": {},
43
+ "output_type": "execute_result"
44
+ }
45
+ ],
46
+ "source": [
47
+ "# using inbuilt tool of wikipedia\n",
48
+ "api_wrapper_wiki=WikipediaAPIWrapper(top_k_results=1,doc_content_chars_max=250)\n",
49
+ "wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)\n",
50
+ "wiki.name"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": 11,
56
+ "metadata": {},
57
+ "outputs": [
58
+ {
59
+ "data": {
60
+ "text/plain": [
61
+ "'arxiv'"
62
+ ]
63
+ },
64
+ "execution_count": 11,
65
+ "metadata": {},
66
+ "output_type": "execute_result"
67
+ }
68
+ ],
69
+ "source": [
70
+ "api_wrapper_arxiv=ArxivAPIWrapper(top_k_results=1,doc_content_chars_max=250)\n",
71
+ "arxiv=ArxivQueryRun(api_wrapper=api_wrapper_arxiv)\n",
72
+ "arxiv.name"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "execution_count": 20,
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "tools=[wiki,arxiv]"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": 13,
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "import os\n",
91
+ "from dotenv import load_dotenv\n",
92
+ "load_dotenv() #load all environment variables\n",
93
+ "\n",
94
+ "os.environ['HF_TOKEN']=os.getenv(\"HF_TOKEN\")"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "execution_count": 15,
100
+ "metadata": {},
101
+ "outputs": [],
102
+ "source": [
103
+ "# Custom tools [RAG Tool]\n",
104
+ "from langchain_community.document_loaders import WebBaseLoader\n",
105
+ "from langchain_community.vectorstores import FAISS\n",
106
+ "\n",
107
+ "from langchain_huggingface import HuggingFaceEmbeddings\n",
108
+ "embeddings=HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
109
+ "\n",
110
+ "from langchain_text_splitters import RecursiveCharacterTextSplitter\n"
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "execution_count": 16,
116
+ "metadata": {},
117
+ "outputs": [
118
+ {
119
+ "data": {
120
+ "text/plain": [
121
+ "VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x00000291BC1737F0>, search_kwargs={})"
122
+ ]
123
+ },
124
+ "execution_count": 16,
125
+ "metadata": {},
126
+ "output_type": "execute_result"
127
+ }
128
+ ],
129
+ "source": [
130
+ "loader=WebBaseLoader(\"https://docs.smith.langchain.com/\")\n",
131
+ "docs=loader.load()\n",
132
+ "documents=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200).split_documents(docs)\n",
133
+ "vectordb=FAISS.from_documents(documents,embeddings)\n",
134
+ "retriever=vectordb.as_retriever()\n",
135
+ "retriever"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "execution_count": 18,
141
+ "metadata": {},
142
+ "outputs": [
143
+ {
144
+ "data": {
145
+ "text/plain": [
146
+ "'langsmith-search'"
147
+ ]
148
+ },
149
+ "execution_count": 18,
150
+ "metadata": {},
151
+ "output_type": "execute_result"
152
+ }
153
+ ],
154
+ "source": [
155
+ "from langchain.tools.retriever import create_retriever_tool\n",
156
+ "retriever_tool=create_retriever_tool(\n",
157
+ " retriever,\n",
158
+ " \"langsmith-search\",\n",
159
+ " \"Search any information about Langsmith\"\n",
160
+ ")\n",
161
+ "retriever_tool.name"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": 22,
167
+ "metadata": {},
168
+ "outputs": [
169
+ {
170
+ "data": {
171
+ "text/plain": [
172
+ "[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=<module 'wikipedia' from 'd:\\\\udemy\\\\Langchain\\\\venvl\\\\lib\\\\site-packages\\\\wikipedia\\\\__init__.py'>, top_k_results=1, lang='en', load_all_available_meta=False, doc_content_chars_max=250)),\n",
173
+ " 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",
174
+ " 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 0x000002918E600C10>, retriever=VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x00000291BC1737F0>, 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 0x000002918E925E10>, retriever=VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x00000291BC1737F0>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n', response_format='content'))]"
175
+ ]
176
+ },
177
+ "execution_count": 22,
178
+ "metadata": {},
179
+ "output_type": "execute_result"
180
+ }
181
+ ],
182
+ "source": [
183
+ "tools=[wiki,arxiv,retriever_tool]\n",
184
+ "tools"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": 24,
190
+ "metadata": {},
191
+ "outputs": [],
192
+ "source": [
193
+ "# Run all the tools with Agents and LLM models\n",
194
+ "from langchain_groq import ChatGroq\n",
195
+ "load_dotenv()\n",
196
+ "groq_api_key=os.getenv(\"GROQ_API_KEY\")\n",
197
+ "\n",
198
+ "llm=ChatGroq(groq_api_key=groq_api_key,model_name=\"Llama3-8b-8192\")"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "execution_count": 25,
204
+ "metadata": {},
205
+ "outputs": [
206
+ {
207
+ "data": {
208
+ "text/plain": [
209
+ "[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template='You are a helpful assistant'), additional_kwargs={}),\n",
210
+ " MessagesPlaceholder(variable_name='chat_history', optional=True),\n",
211
+ " HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], input_types={}, partial_variables={}, template='{input}'), additional_kwargs={}),\n",
212
+ " MessagesPlaceholder(variable_name='agent_scratchpad')]"
213
+ ]
214
+ },
215
+ "execution_count": 25,
216
+ "metadata": {},
217
+ "output_type": "execute_result"
218
+ }
219
+ ],
220
+ "source": [
221
+ "# Prompt Template\n",
222
+ "from langchain import hub\n",
223
+ "\n",
224
+ "# Get the prompt to use - you can modify this!\n",
225
+ "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
226
+ "prompt.messages"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "execution_count": 26,
232
+ "metadata": {},
233
+ "outputs": [
234
+ {
235
+ "data": {
236
+ "text/plain": [
237
+ "RunnableAssign(mapper={\n",
238
+ " agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
239
+ "})\n",
240
+ "| 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 0x000002918E33E4D0>, 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 0x000002918E33E4D0>, 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",
241
+ "| RunnableBinding(bound=ChatGroq(client=<groq.resources.chat.completions.Completions object at 0x00000291BC70EAD0>, async_client=<groq.resources.chat.completions.AsyncCompletions object at 0x00000291BC70FE80>, 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",
242
+ "| OpenAIToolsAgentOutputParser()"
243
+ ]
244
+ },
245
+ "execution_count": 26,
246
+ "metadata": {},
247
+ "output_type": "execute_result"
248
+ }
249
+ ],
250
+ "source": [
251
+ "# Agents\n",
252
+ "from langchain.agents import create_openai_tools_agent\n",
253
+ "agent=create_openai_tools_agent(llm,tools,prompt)\n",
254
+ "agent"
255
+ ]
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "execution_count": 27,
260
+ "metadata": {},
261
+ "outputs": [
262
+ {
263
+ "data": {
264
+ "text/plain": [
265
+ "AgentExecutor(verbose=True, agent=RunnableMultiActionAgent(runnable=RunnableAssign(mapper={\n",
266
+ " agent_scratchpad: RunnableLambda(lambda x: format_to_openai_tool_messages(x['intermediate_steps']))\n",
267
+ "})\n",
268
+ "| 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 0x000002918E33E4D0>, 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 0x000002918E33E4D0>, 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",
269
+ "| RunnableBinding(bound=ChatGroq(client=<groq.resources.chat.completions.Completions object at 0x00000291BC70EAD0>, async_client=<groq.resources.chat.completions.AsyncCompletions object at 0x00000291BC70FE80>, 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",
270
+ "| OpenAIToolsAgentOutputParser(), input_keys_arg=[], return_keys_arg=[], stream_runnable=True), tools=[WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(wiki_client=<module 'wikipedia' from 'd:\\\\udemy\\\\Langchain\\\\venvl\\\\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 0x000002918E600C10>, retriever=VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x00000291BC1737F0>, 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 0x000002918E925E10>, retriever=VectorStoreRetriever(tags=['FAISS', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x00000291BC1737F0>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page_content'], input_types={}, partial_variables={}, template='{page_content}'), document_separator='\\n\\n', response_format='content'))])"
271
+ ]
272
+ },
273
+ "execution_count": 27,
274
+ "metadata": {},
275
+ "output_type": "execute_result"
276
+ }
277
+ ],
278
+ "source": [
279
+ "# Agent Executor\n",
280
+ "from langchain.agents import AgentExecutor\n",
281
+ "agent_executor=AgentExecutor(agent=agent,tools=tools,verbose=True)\n",
282
+ "agent_executor"
283
+ ]
284
+ },
285
+ {
286
+ "cell_type": "code",
287
+ "execution_count": 28,
288
+ "metadata": {},
289
+ "outputs": [
290
+ {
291
+ "name": "stdout",
292
+ "output_type": "stream",
293
+ "text": [
294
+ "\n",
295
+ "\n",
296
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
297
+ "\u001b[32;1m\u001b[1;3m\n",
298
+ "Invoking: `langsmith-search` with `{'query': 'Langsmith'}`\n",
299
+ "\n",
300
+ "\n",
301
+ "\u001b[0m\u001b[38;5;200m\u001b[1;3mGet started with LangSmith | 🦜️🛠️ LangSmith\n",
302
+ "\n",
303
+ "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",
304
+ "For more see the how-to guide for setting up LangSmith with LangChain or setting up LangSmith with LangGraph.\n",
305
+ "Observability​\n",
306
+ "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",
307
+ "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",
308
+ "\n",
309
+ "Skip to main contentJoin us at Interrupt: The Agent AI Conference by LangChain on May 13 & 14 in San Francisco!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",
310
+ "LangSmith is a platform for building production-grade LLM applications.\n",
311
+ "It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence.\n",
312
+ "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",
313
+ "\n",
314
+ "Get started by adding tracing to your application.\n",
315
+ "Create dashboards to view key metrics like RPS, error rates and costs.\n",
316
+ "\n",
317
+ "Evals​\n",
318
+ "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",
319
+ "\n",
320
+ "Get started by creating your first evaluation.\n",
321
+ "Quickly assess the performance of your application using our off-the-shelf evaluators as a starting point.\n",
322
+ "Analyze results of evaluations in the LangSmith UI and compare results over time.\n",
323
+ "Easily collect human feedback on your data to improve your application.\n",
324
+ "\n",
325
+ "Prompt Engineering​\n",
326
+ "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.\u001b[0m\u001b[32;1m\u001b[1;3mIt seems like Langsmith is a platform for building production-grade Large Language Model (LLM) applications, focusing on observability, evaluation, and prompt engineering. It provides tools for monitoring and evaluating LLM applications, as well as features for iterating on prompts and collecting human feedback.\n",
327
+ "\n",
328
+ "With Langsmith, developers can:\n",
329
+ "\n",
330
+ "1. Analyze traces and configure metrics, dashboards, and alerts for their LLM applications.\n",
331
+ "2. Evaluate their application over production traffic, scoring performance and getting human feedback on their data.\n",
332
+ "3. Iterate on prompts with automatic version control and collaboration features.\n",
333
+ "4. Create and run high-quality evaluations with Langsmith's SDK and UI.\n",
334
+ "5. Analyze evaluation results and compare them over time.\n",
335
+ "6. Collect human feedback on their data to improve their application.\n",
336
+ "\n",
337
+ "Langsmith seems to be a comprehensive platform for building and deploying LLM applications, providing a set of tools and features to help developers create high-quality, production-ready AI applications.\u001b[0m\n",
338
+ "\n",
339
+ "\u001b[1m> Finished chain.\u001b[0m\n"
340
+ ]
341
+ },
342
+ {
343
+ "data": {
344
+ "text/plain": [
345
+ "{'input': 'Tell me about Langsmith',\n",
346
+ " 'output': \"It seems like Langsmith is a platform for building production-grade Large Language Model (LLM) applications, focusing on observability, evaluation, and prompt engineering. It provides tools for monitoring and evaluating LLM applications, as well as features for iterating on prompts and collecting human feedback.\\n\\nWith Langsmith, developers can:\\n\\n1. Analyze traces and configure metrics, dashboards, and alerts for their LLM applications.\\n2. Evaluate their application over production traffic, scoring performance and getting human feedback on their data.\\n3. Iterate on prompts with automatic version control and collaboration features.\\n4. Create and run high-quality evaluations with Langsmith's SDK and UI.\\n5. Analyze evaluation results and compare them over time.\\n6. Collect human feedback on their data to improve their application.\\n\\nLangsmith seems to be a comprehensive platform for building and deploying LLM applications, providing a set of tools and features to help developers create high-quality, production-ready AI applications.\"}"
347
+ ]
348
+ },
349
+ "execution_count": 28,
350
+ "metadata": {},
351
+ "output_type": "execute_result"
352
+ }
353
+ ],
354
+ "source": [
355
+ "agent_executor.invoke(\n",
356
+ " {\"input\":\"Tell me about Langsmith\"}\n",
357
+ ")"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "execution_count": 29,
363
+ "metadata": {},
364
+ "outputs": [
365
+ {
366
+ "name": "stdout",
367
+ "output_type": "stream",
368
+ "text": [
369
+ "\n",
370
+ "\n",
371
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
372
+ "\u001b[32;1m\u001b[1;3m\n",
373
+ "Invoking: `wikipedia` with `{'query': 'Machine Learning'}`\n",
374
+ "\n",
375
+ "\n",
376
+ "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Machine learning\n",
377
+ "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 generalize to unseen data, and thus perform tasks wit\u001b[0m\u001b[32;1m\u001b[1;3m\n",
378
+ "Invoking: `wikipedia` with `{'query': 'Types of Machine Learning'}`\n",
379
+ "\n",
380
+ "\n",
381
+ "\u001b[0m\u001b[36;1m\u001b[1;3mPage: Machine learning\n",
382
+ "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 generalize to unseen data, and thus perform tasks wit\u001b[0m\u001b[32;1m\u001b[1;3mIt seems like the tool call didn't yield any new information. However, I can try to provide a summary based on the previous result.\n",
383
+ "\n",
384
+ "Machine learning is a type of artificial intelligence that enables systems to learn from data and improve their performance over time. There are several types of machine learning, including:\n",
385
+ "\n",
386
+ "* Supervised learning: This type of learning involves training a model on labeled data, where the correct output is already known. The model learns to map inputs to outputs based on the labeled data.\n",
387
+ "* Unsupervised learning: This type of learning involves training a model on unlabeled data, where the correct output is not known. The model learns to identify patterns and relationships in the data.\n",
388
+ "* Reinforcement learning: This type of learning involves training a model to make decisions based on rewards or penalties. The model learns to choose actions that maximize the reward.\n",
389
+ "\n",
390
+ "These are just a few examples, and there are many other types of machine learning as well.\u001b[0m\n",
391
+ "\n",
392
+ "\u001b[1m> Finished chain.\u001b[0m\n"
393
+ ]
394
+ },
395
+ {
396
+ "data": {
397
+ "text/plain": [
398
+ "{'input': 'Whant is Maching Learning',\n",
399
+ " 'output': \"It seems like the tool call didn't yield any new information. However, I can try to provide a summary based on the previous result.\\n\\nMachine learning is a type of artificial intelligence that enables systems to learn from data and improve their performance over time. There are several types of machine learning, including:\\n\\n* Supervised learning: This type of learning involves training a model on labeled data, where the correct output is already known. The model learns to map inputs to outputs based on the labeled data.\\n* Unsupervised learning: This type of learning involves training a model on unlabeled data, where the correct output is not known. The model learns to identify patterns and relationships in the data.\\n* Reinforcement learning: This type of learning involves training a model to make decisions based on rewards or penalties. The model learns to choose actions that maximize the reward.\\n\\nThese are just a few examples, and there are many other types of machine learning as well.\"}"
400
+ ]
401
+ },
402
+ "execution_count": 29,
403
+ "metadata": {},
404
+ "output_type": "execute_result"
405
+ }
406
+ ],
407
+ "source": [
408
+ "agent_executor.invoke(\n",
409
+ " {\"input\":\"Whant is Maching Learning\"}\n",
410
+ ")"
411
+ ]
412
+ },
413
+ {
414
+ "cell_type": "code",
415
+ "execution_count": 30,
416
+ "metadata": {},
417
+ "outputs": [
418
+ {
419
+ "name": "stdout",
420
+ "output_type": "stream",
421
+ "text": [
422
+ "\n",
423
+ "\n",
424
+ "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
425
+ "\u001b[32;1m\u001b[1;3m\n",
426
+ "Invoking: `arxiv` with `{'query': '1706.03762v7'}`\n",
427
+ "\n",
428
+ "\n",
429
+ "\u001b[0m\u001b[33;1m\u001b[1;3mPublished: 2023-08-02\n",
430
+ "Title: Attention Is All You Need\n",
431
+ "Authors: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin\n",
432
+ "Summary: The dominant sequence transduction models are based on c\u001b[0m\u001b[32;1m\u001b[1;3mBased on the output from the tool call, I can respond directly without using any further tools. The research paper \"Attention Is All You Need\" by Ashish Vaswani et al. was published on August 2, 2023.\u001b[0m\n",
433
+ "\n",
434
+ "\u001b[1m> Finished chain.\u001b[0m\n"
435
+ ]
436
+ },
437
+ {
438
+ "data": {
439
+ "text/plain": [
440
+ "{'input': 'Whant is this research paper 1706.03762v7 about?',\n",
441
+ " 'output': 'Based on the output from the tool call, I can respond directly without using any further tools. The research paper \"Attention Is All You Need\" by Ashish Vaswani et al. was published on August 2, 2023.'}"
442
+ ]
443
+ },
444
+ "execution_count": 30,
445
+ "metadata": {},
446
+ "output_type": "execute_result"
447
+ }
448
+ ],
449
+ "source": [
450
+ "# arXiv:1706.03762v7\n",
451
+ "agent_executor.invoke(\n",
452
+ " {\"input\":\"Whant is this research paper 1706.03762v7 about?\"}\n",
453
+ ")"
454
+ ]
455
+ }
456
+ ],
457
+ "metadata": {
458
+ "kernelspec": {
459
+ "display_name": "Python 3",
460
+ "language": "python",
461
+ "name": "python3"
462
+ },
463
+ "language_info": {
464
+ "codemirror_mode": {
465
+ "name": "ipython",
466
+ "version": 3
467
+ },
468
+ "file_extension": ".py",
469
+ "mimetype": "text/x-python",
470
+ "name": "python",
471
+ "nbconvert_exporter": "python",
472
+ "pygments_lexer": "ipython3",
473
+ "version": "3.10.0"
474
+ }
475
+ },
476
+ "nbformat": 4,
477
+ "nbformat_minor": 2
478
+ }