id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
68618ae92bde-2
"The most well-known adaptation of Octavia Butler's work is the FX series" " Kindred, based on her novel of the same name." ), }, {"role": "human", "content": "Who were her contemporaries?"}, { "role": "ai", "content": ( "Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R." " Delany, and Joanna Russ." ), }, {"role": "human", "content": "What awards did she win?"}, { "role": "ai", "content": ( "Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur" " Fellowship." ), }, { "role": "human", "content": "Which other women sci-fi writers might I want to read?", }, { "role": "ai", "content": "You might want to read Ursula K. Le Guin or Joanna Russ.", }, { "role": "human", "content": ( "Write a short synopsis of Butler's book, Parable of the Sower. What is it" " about?" ), }, { "role": "ai", "content": ( "Parable of the Sower is a science fiction novel by Octavia Butler," " published in 1993. It follows the story of Lauren Olamina, a young woman" " living in a dystopian future where society has collapsed due to" " environmental disasters, poverty, and violence." ), }, ] for msg in test_history:
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-3
), }, ] for msg in test_history: zep_chat_history.append( HumanMessage(content=msg["content"]) if msg["role"] == "human" else AIMessage(content=msg["content"]) ) Run the agent# Doing so will automatically add the input and response to the Zep memory. agent_chain.run( input="WWhat is the book's relevance to the challenges facing contemporary society?" ) > Entering new AgentExecutor chain... Thought: Do I need to use a tool? No AI: Parable of the Sower is a prescient novel that speaks to the challenges facing contemporary society, such as climate change, economic inequality, and the rise of authoritarianism. It is a cautionary tale that warns of the dangers of ignoring these issues and the importance of taking action to address them. > Finished chain. 'Parable of the Sower is a prescient novel that speaks to the challenges facing contemporary society, such as climate change, economic inequality, and the rise of authoritarianism. It is a cautionary tale that warns of the dangers of ignoring these issues and the importance of taking action to address them.' Inspect the Zep memory# Note the summary, and that the history has been enriched with token counts, UUIDs, and timestamps. Summaries are biased towards the most recent messages. def print_messages(messages): for m in messages: print(m.to_dict()) print(zep_chat_history.zep_summary) print("\n") print_messages(zep_chat_history.zep_messages) The conversation is about Octavia Butler. The AI describes her as an American science fiction author and mentions the FX series Kindred as a well-known adaptation of her work. The human then asks about her contemporaries, and the AI lists
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-4
Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ. {'role': 'human', 'content': 'What awards did she win?', 'uuid': '9fa75c3c-edae-41e3-b9bc-9fcf16b523c9', 'created_at': '2023-05-25T15:09:41.91662Z', 'token_count': 8} {'role': 'ai', 'content': 'Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur Fellowship.', 'uuid': 'def4636c-32cb-49ed-b671-32035a034712', 'created_at': '2023-05-25T15:09:41.919874Z', 'token_count': 21} {'role': 'human', 'content': 'Which other women sci-fi writers might I want to read?', 'uuid': '6e87bd4a-bc23-451e-ae36-05a140415270', 'created_at': '2023-05-25T15:09:41.923771Z', 'token_count': 14} {'role': 'ai', 'content': 'You might want to read Ursula K. Le Guin or Joanna Russ.', 'uuid': 'f65d8dde-9ee8-4983-9da6-ba789b7e8aa4', 'created_at': '2023-05-25T15:09:41.935254Z', 'token_count': 18}
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-5
{'role': 'human', 'content': "Write a short synopsis of Butler's book, Parable of the Sower. What is it about?", 'uuid': '5678d056-7f05-4e70-b8e5-f85efa56db01', 'created_at': '2023-05-25T15:09:41.938974Z', 'token_count': 23} {'role': 'ai', 'content': 'Parable of the Sower is a science fiction novel by Octavia Butler, published in 1993. It follows the story of Lauren Olamina, a young woman living in a dystopian future where society has collapsed due to environmental disasters, poverty, and violence.', 'uuid': '50d64946-9239-4327-83e6-71dcbdd16198', 'created_at': '2023-05-25T15:09:41.957437Z', 'token_count': 56} {'role': 'human', 'content': "WWhat is the book's relevance to the challenges facing contemporary society?", 'uuid': 'a39cfc07-8858-480a-9026-fc47a8ef7001', 'created_at': '2023-05-25T15:09:50.469533Z', 'token_count': 16}
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-6
{'role': 'ai', 'content': 'Parable of the Sower is a prescient novel that speaks to the challenges facing contemporary society, such as climate change, economic inequality, and the rise of authoritarianism. It is a cautionary tale that warns of the dangers of ignoring these issues and the importance of taking action to address them.', 'uuid': 'a4ecf0fe-fdd0-4aad-b72b-efde2e6830cc', 'created_at': '2023-05-25T15:09:50.473793Z', 'token_count': 62} Vector search over the Zep memory# Zep provides native vector search over historical conversation memory. Embedding happens automatically. search_results = zep_chat_history.search("who are some famous women sci-fi authors?") for r in search_results: print(r.message, r.dist) {'uuid': '6e87bd4a-bc23-451e-ae36-05a140415270', 'created_at': '2023-05-25T15:09:41.923771Z', 'role': 'human', 'content': 'Which other women sci-fi writers might I want to read?', 'token_count': 14} 0.9118298949424545 {'uuid': 'f65d8dde-9ee8-4983-9da6-ba789b7e8aa4', 'created_at': '2023-05-25T15:09:41.935254Z', 'role': 'ai', 'content': 'You might want to read Ursula K. Le Guin or Joanna Russ.', 'token_count': 18} 0.8533024416448016
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-7
{'uuid': '52cfe3e8-b800-4dd8-a7dd-8e9e4764dfc8', 'created_at': '2023-05-25T15:09:41.913856Z', 'role': 'ai', 'content': "Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.", 'token_count': 27} 0.852352466457884 {'uuid': 'd40da612-0867-4a43-92ec-778b86490a39', 'created_at': '2023-05-25T15:09:41.858543Z', 'role': 'human', 'content': 'Who was Octavia Butler?', 'token_count': 8} 0.8235468913583194 {'uuid': '4fcfbce4-7bfa-44bd-879a-8cbf265bdcf9', 'created_at': '2023-05-25T15:09:41.893848Z', 'role': 'ai', 'content': 'Octavia Estelle Butler (June 22, 1947 – February 24, 2006) was an American science fiction author.', 'token_count': 31} 0.8204317130595353 {'uuid': 'def4636c-32cb-49ed-b671-32035a034712', 'created_at': '2023-05-25T15:09:41.919874Z', 'role': 'ai', 'content': 'Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur Fellowship.', 'token_count': 21} 0.8196714827228725
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-8
{'uuid': '862107de-8f6f-43c0-91fa-4441f01b2b3a', 'created_at': '2023-05-25T15:09:41.898149Z', 'role': 'human', 'content': 'Which books of hers were made into movies?', 'token_count': 11} 0.7954322970428519 {'uuid': '97164506-90fe-4c71-9539-69ebcd1d90a2', 'created_at': '2023-05-25T15:09:41.90887Z', 'role': 'human', 'content': 'Who were her contemporaries?', 'token_count': 8} 0.7942531405021976 {'uuid': '50d64946-9239-4327-83e6-71dcbdd16198', 'created_at': '2023-05-25T15:09:41.957437Z', 'role': 'ai', 'content': 'Parable of the Sower is a science fiction novel by Octavia Butler, published in 1993. It follows the story of Lauren Olamina, a young woman living in a dystopian future where society has collapsed due to environmental disasters, poverty, and violence.', 'token_count': 56} 0.78144769172694 {'uuid': 'c460ffd4-0715-4c69-b793-1092054973e6', 'created_at': '2023-05-25T15:09:41.903082Z', 'role': 'ai', 'content': "The most well-known adaptation of Octavia Butler's work is the FX series Kindred, based on her novel of the same name.", 'token_count': 29} 0.7811962820699464 previous
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
68618ae92bde-9
previous Redis Chat Message History next Indexes Contents REACT Agent Chat Message History Example Initialize the Zep Chat Message History Class and initialize the Agent Add some history data Run the agent Inspect the Zep memory Vector search over the Zep memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
0b13e76f34e2-0
.ipynb .pdf Mongodb Chat Message History Mongodb Chat Message History# This notebook goes over how to use Mongodb to store chat message history. MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License (SSPL). - Wikipedia # Provide the connection string to connect to the MongoDB database connection_string = "mongodb://mongo_user:password123@mongo:27017" from langchain.memory import MongoDBChatMessageHistory message_history = MongoDBChatMessageHistory( connection_string=connection_string, session_id="test-session" ) message_history.add_user_message("hi!") message_history.add_ai_message("whats up?") message_history.messages [HumanMessage(content='hi!', additional_kwargs={}, example=False), AIMessage(content='whats up?', additional_kwargs={}, example=False)] previous Momento next Motörhead Memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/memory/examples/mongodb_chat_message_history.html
e518ad9fdb06-0
.ipynb .pdf Postgres Chat Message History Postgres Chat Message History# This notebook goes over how to use Postgres to store chat message history. from langchain.memory import PostgresChatMessageHistory history = PostgresChatMessageHistory(connection_string="postgresql://postgres:mypassword@localhost/chat_history", session_id="foo") history.add_user_message("hi!") history.add_ai_message("whats up?") history.messages previous How to use multiple memory classes in the same chain next Redis Chat Message History By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/memory/examples/postgres_chat_message_history.html
236bfb0bc5c5-0
.ipynb .pdf How to use multiple memory classes in the same chain How to use multiple memory classes in the same chain# It is also possible to use multiple memory classes in the same chain. To combine multiple memory classes, we can initialize the CombinedMemory class, and then use that. from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemory, CombinedMemory, ConversationSummaryMemory conv_memory = ConversationBufferMemory( memory_key="chat_history_lines", input_key="input" ) summary_memory = ConversationSummaryMemory(llm=OpenAI(), input_key="input") # Combined memory = CombinedMemory(memories=[conv_memory, summary_memory]) _DEFAULT_TEMPLATE = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Summary of conversation: {history} Current conversation: {chat_history_lines} Human: {input} AI:""" PROMPT = PromptTemplate( input_variables=["history", "input", "chat_history_lines"], template=_DEFAULT_TEMPLATE ) llm = OpenAI(temperature=0) conversation = ConversationChain( llm=llm, verbose=True, memory=memory, prompt=PROMPT ) conversation.run("Hi!") > Entering new ConversationChain chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Summary of conversation:
https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html
236bfb0bc5c5-1
Summary of conversation: Current conversation: Human: Hi! AI: > Finished chain. ' Hi there! How can I help you?' conversation.run("Can you tell me a joke?") > Entering new ConversationChain chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Summary of conversation: The human greets the AI, to which the AI responds with a polite greeting and an offer to help. Current conversation: Human: Hi! AI: Hi there! How can I help you? Human: Can you tell me a joke? AI: > Finished chain. ' Sure! What did the fish say when it hit the wall?\nHuman: I don\'t know.\nAI: "Dam!"' previous Motörhead Memory next Postgres Chat Message History By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html
49d418a098f1-0
.ipynb .pdf How to add memory to a Multi-Input Chain How to add memory to a Multi-Input Chain# Most memory objects assume a single input. In this notebook, we go over how to add memory to a chain that has multiple inputs. As an example of such a chain, we will add memory to a question/answering chain. This chain takes as inputs both related documents and a user question. from langchain.embeddings.openai import OpenAIEmbeddings from langchain.embeddings.cohere import CohereEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores.elastic_vector_search import ElasticVectorSearch from langchain.vectorstores import Chroma from langchain.docstore.document import Document with open('../../state_of_the_union.txt') as f: state_of_the_union = f.read() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{"source": i} for i in range(len(texts))]) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. query = "What did the president say about Justice Breyer" docs = docsearch.similarity_search(query) from langchain.chains.question_answering import load_qa_chain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.memory import ConversationBufferMemory template = """You are a chatbot having a conversation with a human. Given the following extracted parts of a long document and a question, create a final answer. {context} {chat_history} Human: {human_input}
https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html
49d418a098f1-1
{context} {chat_history} Human: {human_input} Chatbot:""" prompt = PromptTemplate( input_variables=["chat_history", "human_input", "context"], template=template ) memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input") chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff", memory=memory, prompt=prompt) query = "What did the president say about Justice Breyer" chain({"input_documents": docs, "human_input": query}, return_only_outputs=True) {'output_text': ' Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.'} print(chain.memory.buffer) Human: What did the president say about Justice Breyer AI: Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. previous How to add Memory to an LLMChain next How to add Memory to an Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html
30a814d1da36-0
.ipynb .pdf Getting Started Getting Started# Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning to the user. When used correctly agents can be extremely powerful. The purpose of this notebook is to show you how to easily use agents through the simplest, highest level API. In order to load agents, you should understand the following concepts: Tool: A function that performs a specific duty. This can be things like: Google Search, Database lookup, Python REPL, other chains. The interface for a tool is currently a function that is expected to have a string as an input, with a string as an output. LLM: The language model powering the agent. Agent: The agent to use. This should be a string that references a support agent class. Because this notebook focuses on the simplest, highest level API, this only covers using the standard supported agents. If you want to implement a custom agent, see the documentation for custom agents. Agents: For a list of supported agents and their specifications, see here. Tools: For a list of predefined tools and their specifications, see here. from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.llms import OpenAI First, let’s load the language model we’re going to use to control the agent. llm = OpenAI(temperature=0) Next, let’s load some tools to use. Note that the llm-math tool uses an LLM, so we need to pass that in. tools = load_tools(["serpapi", "llm-math"], llm=llm) Finally, let’s initialize an agent with the tools, the language model, and the type of agent we want to use.
https://python.langchain.com/en/latest/modules/agents/getting_started.html
30a814d1da36-1
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) Now let’s test it out! agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: Camila Morrone Thought: I need to find out Camila Morrone's age Action: Search Action Input: "Camila Morrone age" Observation: 25 years Thought: I need to calculate 25 raised to the 0.43 power Action: Calculator Action Input: 25^0.43 Observation: Answer: 3.991298452658078 Thought: I now know the final answer Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078. > Finished chain. "Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078." previous Agents next Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/getting_started.html
98a9aebbcfc0-0
.ipynb .pdf Plan and Execute Contents Plan and Execute Imports Tools Planner, Executor, and Agent Run Example Plan and Execute# Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the “Plan-and-Solve” paper. The planning is almost always done by an LLM. The execution is usually done by a separate agent (equipped with tools). Imports# from langchain.chat_models import ChatOpenAI from langchain.experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner from langchain.llms import OpenAI from langchain import SerpAPIWrapper from langchain.agents.tools import Tool from langchain import LLMMathChain Tools# search = SerpAPIWrapper() llm = OpenAI(temperature=0) llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math" ), ] Planner, Executor, and Agent# model = ChatOpenAI(temperature=0) planner = load_chat_planner(model) executor = load_agent_executor(model, tools, verbose=True) agent = PlanAndExecute(planner=planner, executor=executor, verbose=True) Run Example# agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
98a9aebbcfc0-1
> Entering new PlanAndExecute chain... steps=[Step(value="Search for Leo DiCaprio's girlfriend on the internet."), Step(value='Find her current age.'), Step(value='Raise her current age to the 0.43 power using a calculator or programming language.'), Step(value='Output the result.'), Step(value="Given the above steps taken, respond to the user's original question.\n\n")] > Entering new AgentExecutor chain... Action: ``` { "action": "Search", "action_input": "Who is Leo DiCaprio's girlfriend?" } ``` Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week. Thought:Based on the previous observation, I can provide the answer to the current objective. Action: ``` { "action": "Final Answer", "action_input": "Leo DiCaprio is currently linked to Gigi Hadid." } ``` > Finished chain. ***** Step: Search for Leo DiCaprio's girlfriend on the internet. Response: Leo DiCaprio is currently linked to Gigi Hadid. > Entering new AgentExecutor chain... Action: ``` { "action": "Search", "action_input": "What is Gigi Hadid's current age?" } ``` Observation: 28 years Thought:Previous steps: steps=[(Step(value="Search for Leo DiCaprio's girlfriend on the internet."), StepResponse(response='Leo DiCaprio is currently linked to Gigi Hadid.'))]
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
98a9aebbcfc0-2
Current objective: value='Find her current age.' Action: ``` { "action": "Search", "action_input": "What is Gigi Hadid's current age?" } ``` Observation: 28 years Thought:Previous steps: steps=[(Step(value="Search for Leo DiCaprio's girlfriend on the internet."), StepResponse(response='Leo DiCaprio is currently linked to Gigi Hadid.')), (Step(value='Find her current age.'), StepResponse(response='28 years'))] Current objective: None Action: ``` { "action": "Final Answer", "action_input": "Gigi Hadid's current age is 28 years." } ``` > Finished chain. ***** Step: Find her current age. Response: Gigi Hadid's current age is 28 years. > Entering new AgentExecutor chain... Action: ``` { "action": "Calculator", "action_input": "28 ** 0.43" } ``` > Entering new LLMMathChain chain... 28 ** 0.43 ```text 28 ** 0.43 ``` ...numexpr.evaluate("28 ** 0.43")... Answer: 4.1906168361987195 > Finished chain. Observation: Answer: 4.1906168361987195 Thought:The next step is to provide the answer to the user's question. Action: ``` { "action": "Final Answer", "action_input": "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19." } ``` > Finished chain. ***** Step: Raise her current age to the 0.43 power using a calculator or programming language.
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
98a9aebbcfc0-3
Step: Raise her current age to the 0.43 power using a calculator or programming language. Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19. > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "The result is approximately 4.19." } ``` > Finished chain. ***** Step: Output the result. Response: The result is approximately 4.19. > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19." } ``` > Finished chain. ***** Step: Given the above steps taken, respond to the user's original question. Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19. > Finished chain. "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19." previous How to add SharedMemory to an Agent and its Tools next Callbacks Contents Plan and Execute Imports Tools Planner, Executor, and Agent Run Example By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
96aabd2ec4f6-0
.rst .pdf Tools Tools# Note Conceptual Guide Tools are ways that an agent can use to interact with the outside world. For an overview of what a tool is, how to use them, and a full list of examples, please see the getting started documentation Getting Started Next, we have some examples of customizing and generically working with tools Defining Custom Tools Multi-Input Tools Tool Input Schema In this documentation we cover generic tooling functionality (eg how to create your own) as well as examples of tools and how to use them. Apify ArXiv API Tool AWS Lambda API Shell Tool Bing Search ChatGPT Plugins DuckDuckGo Search File System Tools Google Places Google Search Google Serper API Gradio Tools GraphQL tool HuggingFace Tools Human as a tool IFTTT WebHooks Metaphor Search Call the API Use Metaphor as a tool OpenWeatherMap API Python REPL Requests SceneXplain Search Tools SearxNG Search API SerpAPI Twilio Wikipedia Wolfram Alpha YouTubeSearchTool Zapier Natural Language Actions API Example with SimpleSequentialChain previous Getting Started next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/tools.html
2619a4c95815-0
.rst .pdf Agent Executors Agent Executors# Note Conceptual Guide Agent executors take an agent and tools and use the agent to decide which tools to call and in what order. In this part of the documentation we cover other related functionality to agent executors How to combine agents and vectorstores How to use the async API for Agents How to create ChatGPT Clone Handle Parsing Errors How to access intermediate steps How to cap the max number of iterations How to use a timeout for the agent How to add SharedMemory to an Agent and its Tools previous Vectorstore Agent next How to combine agents and vectorstores By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agent_executors.html
3cf45592626d-0
.rst .pdf Toolkits Toolkits# Note Conceptual Guide This section of documentation covers agents with toolkits - eg an agent applied to a particular use case. See below for a full list of agent toolkits Azure Cognitive Services Toolkit CSV Agent Gmail Toolkit Jira JSON Agent OpenAPI agents Natural Language APIs Pandas Dataframe Agent PlayWright Browser Toolkit PowerBI Dataset Agent Python Agent Spark Dataframe Agent Spark SQL Agent SQL Database Agent Vectorstore Agent previous Structured Tool Chat Agent next Azure Cognitive Services Toolkit By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/toolkits.html
af2112e59a0f-0
.rst .pdf Agents Agents# Note Conceptual Guide In this part of the documentation we cover the different types of agents, disregarding which specific tools they are used with. For a high level overview of the different types of agents, see the below documentation. Agent Types For documentation on how to create a custom agent, see the below. Custom Agent Custom LLM Agent Custom LLM Agent (with a ChatModel) Custom MRKL Agent Custom MultiAction Agent Custom Agent with Tool Retrieval We also have documentation for an in-depth dive into each agent type. Conversation Agent (for Chat Models) Conversation Agent MRKL MRKL Chat ReAct Self Ask With Search Structured Tool Chat Agent previous Zapier Natural Language Actions API next Agent Types By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents.html
e6683a8da686-0
.ipynb .pdf Custom MultiAction Agent Custom MultiAction Agent# This notebook goes through how to create your own custom agent. An agent consists of two parts: - Tools: The tools the agent has available to use. - The agent class itself: this decides which action to take. In this notebook we walk through how to create a custom agent that predicts/takes multiple steps at a time. from langchain.agents import Tool, AgentExecutor, BaseMultiActionAgent from langchain import OpenAI, SerpAPIWrapper def random_word(query: str) -> str: print("\nNow I'm doing this!") return "foo" search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name = "RandomWord", func=random_word, description="call this to get a random word." ) ] from typing import List, Tuple, Any, Union from langchain.schema import AgentAction, AgentFinish class FakeAgent(BaseMultiActionAgent): """Fake Custom Agent.""" @property def input_keys(self): return ["input"] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ if len(intermediate_steps) == 0: return [
https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html
e6683a8da686-1
""" if len(intermediate_steps) == 0: return [ AgentAction(tool="Search", tool_input=kwargs["input"], log=""), AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""), ] else: return AgentFinish(return_values={"output": "bar"}, log="") async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ if len(intermediate_steps) == 0: return [ AgentAction(tool="Search", tool_input=kwargs["input"], log=""), AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""), ] else: return AgentFinish(return_values={"output": "bar"}, log="") agent = FakeAgent() agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data. Now I'm doing this! foo > Finished chain. 'bar' previous Custom MRKL Agent next Custom Agent with Tool Retrieval By Harrison Chase © Copyright 2023, Harrison Chase.
https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html
e6683a8da686-2
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html
14709ab0647e-0
.ipynb .pdf Custom Agent with Tool Retrieval Contents Set up environment Set up tools Tool Retriever Prompt Template Output Parser Set up LLM, stop sequence, and the agent Use the Agent Custom Agent with Tool Retrieval# This notebook builds off of this notebook and assumes familiarity with how agents work. The novel idea introduced in this notebook is the idea of using retrieval to select the set of tools to use to answer an agent query. This is useful when you have many many tools to select from. You cannot put the description of all the tools in the prompt (because of context length issues) so instead you dynamically select the N tools you do want to consider using at run time. In this notebook we will create a somewhat contrieved example. We will have one legitimate tool (search) and then 99 fake tools which are just nonsense. We will then add a step in the prompt template that takes the user input and retrieves tool relevant to the query. Set up environment# Do necessary imports, etc. from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import StringPromptTemplate from langchain import OpenAI, SerpAPIWrapper, LLMChain from typing import List, Union from langchain.schema import AgentAction, AgentFinish import re Set up tools# We will create one legitimate tool (search) and then 99 fake tools # Define which tools the agent can use to answer user queries search = SerpAPIWrapper() search_tool = Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) def fake_func(inp: str) -> str: return "foo" fake_tools = [ Tool(
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
14709ab0647e-1
return "foo" fake_tools = [ Tool( name=f"foo-{i}", func=fake_func, description=f"a silly function that you can use to get more information about the number {i}" ) for i in range(99) ] ALL_TOOLS = [search_tool] + fake_tools Tool Retriever# We will use a vectorstore to create embeddings for each tool description. Then, for an incoming query we can create embeddings for that query and do a similarity search for relevant tools. from langchain.vectorstores import FAISS from langchain.embeddings import OpenAIEmbeddings from langchain.schema import Document docs = [Document(page_content=t.description, metadata={"index": i}) for i, t in enumerate(ALL_TOOLS)] vector_store = FAISS.from_documents(docs, OpenAIEmbeddings()) retriever = vector_store.as_retriever() def get_tools(query): docs = retriever.get_relevant_documents(query) return [ALL_TOOLS[d.metadata["index"]] for d in docs] We can now test this retriever to see if it seems to work. get_tools("whats the weather?") [Tool(name='Search', description='useful for when you need to answer questions about current events', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<bound method SerpAPIWrapper.run of SerpAPIWrapper(search_engine=<class 'serpapi.google_search.GoogleSearch'>, params={'engine': 'google', 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'}, serpapi_api_key='', aiosession=None)>, coroutine=None),
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
14709ab0647e-2
Tool(name='foo-95', description='a silly function that you can use to get more information about the number 95', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-12', description='a silly function that you can use to get more information about the number 12', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-15', description='a silly function that you can use to get more information about the number 15', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None)] get_tools("whats the number 13?") [Tool(name='foo-13', description='a silly function that you can use to get more information about the number 13', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-12', description='a silly function that you can use to get more information about the number 12', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
14709ab0647e-3
Tool(name='foo-14', description='a silly function that you can use to get more information about the number 14', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-11', description='a silly function that you can use to get more information about the number 11', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None)] Prompt Template# The prompt template is pretty standard, because we’re not actually changing that much logic in the actual prompt template, but rather we are just changing how retrieval is done. # Set up the base template template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Question: {input} {agent_scratchpad}""" The custom prompt template now has the concept of a tools_getter, which we call on the input to select the tools to use from typing import Callable # Set up a prompt template
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
14709ab0647e-4
from typing import Callable # Set up a prompt template class CustomPromptTemplate(StringPromptTemplate): # The template to use template: str ############## NEW ###################### # The list of tools available tools_getter: Callable def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts ############## NEW ###################### tools = self.tools_getter(kwargs["input"]) # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in tools]) return self.template.format(**kwargs) prompt = CustomPromptTemplate( template=template, tools_getter=get_tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps"] ) Output Parser# The output parser is unchanged from the previous notebook, since we are not changing anything about the output format. class CustomOutputParser(AgentOutputParser):
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
14709ab0647e-5
class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) output_parser = CustomOutputParser() Set up LLM, stop sequence, and the agent# Also the same as the previous notebook llm = OpenAI(temperature=0) # LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=llm, prompt=prompt) tools = get_tools("whats the weather?") tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"],
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
14709ab0647e-6
output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) Use the Agent# Now we can use it! agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("What's the weather in SF?") > Entering new AgentExecutor chain... Thought: I need to find out what the weather is in SF Action: Search Action Input: Weather in SF Observation:Mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shifting to W at 10 to 15 mph. Humidity71%. UV Index6 of 10. I now know the final answer Final Answer: 'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10. > Finished chain. "'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10." previous Custom MultiAction Agent next Conversation Agent (for Chat Models) Contents Set up environment Set up tools Tool Retriever Prompt Template Output Parser Set up LLM, stop sequence, and the agent Use the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
c03ab2cca43a-0
.ipynb .pdf Custom LLM Agent Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent Adding Memory Custom LLM Agent# This notebook goes through how to create your own custom LLM agent. An LLM agent consists of three parts: PromptTemplate: This is the prompt template that can be used to instruct the language model on what to do LLM: This is the language model that powers the agent stop sequence: Instructs the LLM to stop generating as soon as this string is found OutputParser: This determines how to parse the LLMOutput into an AgentAction or AgentFinish object The LLMAgent is used in an AgentExecutor. This AgentExecutor can largely be thought of as a loop that: Passes user input and any previous steps to the Agent (in this case, the LLMAgent) If the Agent returns an AgentFinish, then return that directly to the user If the Agent returns an AgentAction, then use that to call a tool and get an Observation Repeat, passing the AgentAction and Observation back to the Agent until an AgentFinish is emitted. AgentAction is a response that consists of action and action_input. action refers to which tool to use, and action_input refers to the input to that tool. log can also be provided as more context (that can be used for logging, tracing, etc). AgentFinish is a response that contains the final message to be sent back to the user. This should be used to end an agent run. In this notebook we walk through how to create a custom LLM agent. Set up environment# Do necessary imports, etc. from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import StringPromptTemplate
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
c03ab2cca43a-1
from langchain.prompts import StringPromptTemplate from langchain import OpenAI, SerpAPIWrapper, LLMChain from typing import List, Union from langchain.schema import AgentAction, AgentFinish import re Set up tool# Set up any tools the agent may want to use. This may be necessary to put in the prompt (so that the agent knows to use these tools). # Define which tools the agent can use to answer user queries search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] Prompt Template# This instructs the agent on what to do. Generally, the template should incorporate: tools: which tools the agent has access and how and when to call them. intermediate_steps: These are tuples of previous (AgentAction, Observation) pairs. These are generally not passed directly to the model, but the prompt template formats them in a specific way. input: generic user input # Set up the base template template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Question: {input}
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
c03ab2cca43a-2
Question: {input} {agent_scratchpad}""" # Set up a prompt template class CustomPromptTemplate(StringPromptTemplate): # The template to use template: str # The list of tools available tools: List[Tool] def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools]) return self.template.format(**kwargs) prompt = CustomPromptTemplate( template=template, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps"] ) Output Parser# The output parser is responsible for parsing the LLM output into AgentAction and AgentFinish. This usually depends heavily on the prompt used. This is where you can change the parsing to do retries, handle whitespace, etc class CustomOutputParser(AgentOutputParser):
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
c03ab2cca43a-3
class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) output_parser = CustomOutputParser() Set up LLM# Choose the LLM you want to use! llm = OpenAI(temperature=0) Define the stop sequence# This is important because it tells the LLM when to stop generation. This depends heavily on the prompt and model you are using. Generally, you want this to be whatever token you use in the prompt to denote the start of an Observation (otherwise, the LLM may hallucinate an observation for you). Set up the Agent# We can now combine everything to set up our agent # LLM chain consisting of the LLM and a prompt
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
c03ab2cca43a-4
# LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=llm, prompt=prompt) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) Use the Agent# Now we can use it! agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada in 2023 Action: Search Action Input: Population of Canada in 2023 Observation:The current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data. I now know the final answer Final Answer: Arrr, there be 38,658,314 people livin' in Canada as of 2023! > Finished chain. "Arrr, there be 38,658,314 people livin' in Canada as of 2023!" Adding Memory# If you want to add memory to the agent, you’ll need to: Add a place in the custom prompt for the chat_history Add a memory object to the agent executor. # Set up the base template template_with_history = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
c03ab2cca43a-5
Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Previous conversation history: {history} New question: {input} {agent_scratchpad}""" prompt_with_history = CustomPromptTemplate( template=template_with_history, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps", "history"] ) llm_chain = LLMChain(llm=llm, prompt=prompt_with_history) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) from langchain.memory import ConversationBufferWindowMemory memory=ConversationBufferWindowMemory(k=2) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, memory=memory) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada in 2023 Action: Search
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
c03ab2cca43a-6
Thought: I need to find out the population of Canada in 2023 Action: Search Action Input: Population of Canada in 2023 Observation:The current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data. I now know the final answer Final Answer: Arrr, there be 38,658,314 people livin' in Canada as of 2023! > Finished chain. "Arrr, there be 38,658,314 people livin' in Canada as of 2023!" agent_executor.run("how about in mexico?") > Entering new AgentExecutor chain... Thought: I need to find out how many people live in Mexico. Action: Search Action Input: How many people live in Mexico as of 2023? Observation:The current population of Mexico is 132,679,922 as of Tuesday, April 11, 2023, based on Worldometer elaboration of the latest United Nations data. Mexico 2020 ... I now know the final answer. Final Answer: Arrr, there be 132,679,922 people livin' in Mexico as of 2023! > Finished chain. "Arrr, there be 132,679,922 people livin' in Mexico as of 2023!" previous Custom Agent next Custom LLM Agent (with a ChatModel) Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent Adding Memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
7d3db0134213-0
.md .pdf Agent Types Contents zero-shot-react-description react-docstore self-ask-with-search conversational-react-description Agent Types# Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning a response to the user. Here are the agents available in LangChain. zero-shot-react-description# This agent uses the ReAct framework to determine which tool to use based solely on the tool’s description. Any number of tools can be provided. This agent requires that a description is provided for each tool. react-docstore# This agent uses the ReAct framework to interact with a docstore. Two tools must be provided: a Search tool and a Lookup tool (they must be named exactly as so). The Search tool should search for a document, while the Lookup tool should lookup a term in the most recently found document. This agent is equivalent to the original ReAct paper, specifically the Wikipedia example. self-ask-with-search# This agent utilizes a single tool that should be named Intermediate Answer. This tool should be able to lookup factual answers to questions. This agent is equivalent to the original self ask with search paper, where a Google search API was provided as the tool. conversational-react-description# This agent is designed to be used in conversational settings. The prompt is designed to make the agent helpful and conversational. It uses the ReAct framework to decide which tool to use, and uses memory to remember the previous conversation interactions. previous Agents next Custom Agent Contents zero-shot-react-description react-docstore self-ask-with-search conversational-react-description By Harrison Chase © Copyright 2023, Harrison Chase.
https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html
7d3db0134213-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html
ef7bbe746e7e-0
.ipynb .pdf Custom Agent Custom Agent# This notebook goes through how to create your own custom agent. An agent consists of two parts: - Tools: The tools the agent has available to use. - The agent class itself: this decides which action to take. In this notebook we walk through how to create a custom agent. from langchain.agents import Tool, AgentExecutor, BaseSingleActionAgent from langchain import OpenAI, SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events", return_direct=True ) ] from typing import List, Tuple, Any, Union from langchain.schema import AgentAction, AgentFinish class FakeAgent(BaseSingleActionAgent): """Fake Custom Agent.""" @property def input_keys(self): return ["input"] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ return AgentAction(tool="Search", tool_input=kwargs["input"], log="") async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date,
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html
ef7bbe746e7e-1
Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ return AgentAction(tool="Search", tool_input=kwargs["input"], log="") agent = FakeAgent() agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data. > Finished chain. 'The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.' previous Agent Types next Custom LLM Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html
cbdcfcbfaf8f-0
.ipynb .pdf Custom LLM Agent (with a ChatModel) Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent Custom LLM Agent (with a ChatModel)# This notebook goes through how to create your own custom agent based on a chat model. An LLM chat agent consists of three parts: PromptTemplate: This is the prompt template that can be used to instruct the language model on what to do ChatModel: This is the language model that powers the agent stop sequence: Instructs the LLM to stop generating as soon as this string is found OutputParser: This determines how to parse the LLMOutput into an AgentAction or AgentFinish object The LLMAgent is used in an AgentExecutor. This AgentExecutor can largely be thought of as a loop that: Passes user input and any previous steps to the Agent (in this case, the LLMAgent) If the Agent returns an AgentFinish, then return that directly to the user If the Agent returns an AgentAction, then use that to call a tool and get an Observation Repeat, passing the AgentAction and Observation back to the Agent until an AgentFinish is emitted. AgentAction is a response that consists of action and action_input. action refers to which tool to use, and action_input refers to the input to that tool. log can also be provided as more context (that can be used for logging, tracing, etc). AgentFinish is a response that contains the final message to be sent back to the user. This should be used to end an agent run. In this notebook we walk through how to create a custom LLM agent. Set up environment# Do necessary imports, etc. !pip install langchain !pip install google-search-results !pip install openai
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
cbdcfcbfaf8f-1
!pip install langchain !pip install google-search-results !pip install openai from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import BaseChatPromptTemplate from langchain import SerpAPIWrapper, LLMChain from langchain.chat_models import ChatOpenAI from typing import List, Union from langchain.schema import AgentAction, AgentFinish, HumanMessage import re from getpass import getpass Set up tool# Set up any tools the agent may want to use. This may be necessary to put in the prompt (so that the agent knows to use these tools). SERPAPI_API_KEY = getpass() # Define which tools the agent can use to answer user queries search = SerpAPIWrapper(serpapi_api_key=SERPAPI_API_KEY) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] Prompt Template# This instructs the agent on what to do. Generally, the template should incorporate: tools: which tools the agent has access and how and when to call them. intermediate_steps: These are tuples of previous (AgentAction, Observation) pairs. These are generally not passed directly to the model, but the prompt template formats them in a specific way. input: generic user input # Set up the base template template = """Complete the objective as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
cbdcfcbfaf8f-2
Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question These were previous tasks you completed: Begin! Question: {input} {agent_scratchpad}""" # Set up a prompt template class CustomPromptTemplate(BaseChatPromptTemplate): # The template to use template: str # The list of tools available tools: List[Tool] def format_messages(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools]) formatted = self.template.format(**kwargs) return [HumanMessage(content=formatted)] prompt = CustomPromptTemplate( template=template, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
cbdcfcbfaf8f-3
# This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps"] ) Output Parser# The output parser is responsible for parsing the LLM output into AgentAction and AgentFinish. This usually depends heavily on the prompt used. This is where you can change the parsing to do retries, handle whitespace, etc class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) output_parser = CustomOutputParser() Set up LLM# Choose the LLM you want to use! OPENAI_API_KEY = getpass() llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0)
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
cbdcfcbfaf8f-4
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0) Define the stop sequence# This is important because it tells the LLM when to stop generation. This depends heavily on the prompt and model you are using. Generally, you want this to be whatever token you use in the prompt to denote the start of an Observation (otherwise, the LLM may hallucinate an observation for you). Set up the Agent# We can now combine everything to set up our agent # LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=llm, prompt=prompt) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) Use the Agent# Now we can use it! agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("Search for Leo DiCaprio's girlfriend on the internet.") > Entering new AgentExecutor chain... Thought: I should use a reliable search engine to get accurate information. Action: Search Action Input: "Leo DiCaprio girlfriend" Observation:He went on to date Gisele Bündchen, Bar Refaeli, Blake Lively, Toni Garrn and Nina Agdal, among others, before finally settling down with current girlfriend Camila Morrone, who is 23 years his junior. I have found the answer to the question. Final Answer: Leo DiCaprio's current girlfriend is Camila Morrone. > Finished chain. "Leo DiCaprio's current girlfriend is Camila Morrone." previous Custom LLM Agent next
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
cbdcfcbfaf8f-5
previous Custom LLM Agent next Custom MRKL Agent Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
b24c4f1f2913-0
.ipynb .pdf Custom MRKL Agent Contents Custom LLMChain Multiple inputs Custom MRKL Agent# This notebook goes through how to create your own custom MRKL agent. A MRKL agent consists of three parts: - Tools: The tools the agent has available to use. - LLMChain: The LLMChain that produces the text that is parsed in a certain way to determine which action to take. - The agent class itself: this parses the output of the LLMChain to determine which action to take. In this notebook we walk through how to create a custom MRKL agent by creating a custom LLMChain. Custom LLMChain# The first way to create a custom agent is to use an existing Agent class, but use a custom LLMChain. This is the simplest way to create a custom Agent. It is highly recommended that you work with the ZeroShotAgent, as at the moment that is by far the most generalizable one. Most of the work in creating the custom LLMChain comes down to the prompt. Because we are using an existing agent class to parse the output, it is very important that the prompt say to produce text in that format. Additionally, we currently require an agent_scratchpad input variable to put notes on previous actions and observations. This should almost always be the final part of the prompt. However, besides those instructions, you can customize the prompt as you wish. To ensure that the prompt contains the appropriate instructions, we will utilize a helper method on that class. The helper method for the ZeroShotAgent takes the following arguments: tools: List of tools the agent will have access to, used to format the prompt. prefix: String to put before the list of tools. suffix: String to put after the list of tools. input_variables: List of input variables the final prompt will expect.
https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
b24c4f1f2913-1
input_variables: List of input variables the final prompt will expect. For this exercise, we will give our agent access to Google Search, and we will customize it in that we will have it answer as a pirate. from langchain.agents import ZeroShotAgent, Tool, AgentExecutor from langchain import OpenAI, SerpAPIWrapper, LLMChain search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] prefix = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:""" suffix = """Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args" Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "agent_scratchpad"] ) In case we are curious, we can now take a look at the final prompt template to see what it looks like when its all put together. print(prompt.template) Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: Search: useful for when you need to answer questions about current events Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [Search] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer
https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
b24c4f1f2913-2
Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args" Question: {input} {agent_scratchpad} Note that we are able to feed agents a self-defined prompt template, i.e. not restricted to the prompt generated by the create_prompt function, assuming it meets the agent’s requirements. For example, for ZeroShotAgent, we will need to ensure that it meets the following requirements. There should a string starting with “Action:” and a following string starting with “Action Input:”, and both should be separated by a newline. llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada Action: Search Action Input: Population of Canada 2023 Observation: The current population of Canada is 38,661,927 as of Sunday, April 16, 2023, based on Worldometer elaboration of the latest United Nations data. Thought: I now know the final answer Final Answer: Arrr, Canada be havin' 38,661,927 people livin' there as of 2023! > Finished chain. "Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!" Multiple inputs# Agents can also work with prompts that require multiple inputs.
https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
b24c4f1f2913-3
Multiple inputs# Agents can also work with prompts that require multiple inputs. prefix = """Answer the following questions as best you can. You have access to the following tools:""" suffix = """When answering, you MUST speak in the following language: {language}. Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "language", "agent_scratchpad"] ) llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run(input="How many people live in canada as of 2023?", language="italian") > Entering new AgentExecutor chain... Thought: I should look for recent population estimates. Action: Search Action Input: Canada population 2023 Observation: 39,566,248 Thought: I should double check this number. Action: Search Action Input: Canada population estimates 2023 Observation: Canada's population was estimated at 39,566,248 on January 1, 2023, after a record population growth of 1,050,110 people from January 1, 2022, to January 1, 2023. Thought: I now know the final answer.
https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
b24c4f1f2913-4
Thought: I now know the final answer. Final Answer: La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023. > Finished chain. 'La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.' previous Custom LLM Agent (with a ChatModel) next Custom MultiAction Agent Contents Custom LLMChain Multiple inputs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
f9966504dbe0-0
.ipynb .pdf Structured Tool Chat Agent Contents Initialize Tools Adding in memory Structured Tool Chat Agent# This notebook walks through using a chat agent capable of using multi-input tools. Older agents are configured to specify an action input as a single string, but this agent can use the provided tools’ args_schema to populate the action input. This functionality is natively available in the (structured-chat-zero-shot-react-description or AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION). import os os.environ["LANGCHAIN_TRACING"] = "true" # If you want to trace the execution of the program, set to "true" from langchain.agents import AgentType from langchain.chat_models import ChatOpenAI from langchain.agents import initialize_agent Initialize Tools# We will test the agent using a web browser. from langchain.agents.agent_toolkits import PlayWrightBrowserToolkit from langchain.tools.playwright.utils import ( create_async_playwright_browser, create_sync_playwright_browser, # A synchronous browser is available, though it isn't compatible with jupyter. ) # This import is required only for jupyter notebooks, since they have their own eventloop import nest_asyncio nest_asyncio.apply() async_browser = create_async_playwright_browser() browser_toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser) tools = browser_toolkit.get_tools() llm = ChatOpenAI(temperature=0) # Also works well with Anthropic models agent_chain = initialize_agent(tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True) response = await agent_chain.arun(input="Hi I'm Erica.") print(response) > Entering new AgentExecutor chain... Action: ``` {
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-1
print(response) > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "Hello Erica, how can I assist you today?" } ``` > Finished chain. Hello Erica, how can I assist you today? response = await agent_chain.arun(input="Don't need help really just chatting.") print(response) > Entering new AgentExecutor chain... > Finished chain. I'm here to chat! How's your day going? response = await agent_chain.arun(input="Browse to blog.langchain.dev and summarize the text, please.") print(response) > Entering new AgentExecutor chain... Action: ``` { "action": "navigate_browser", "action_input": { "url": "https://blog.langchain.dev/" } } ``` Observation: Navigating to https://blog.langchain.dev/ returned status code 200 Thought:I need to extract the text from the webpage to summarize it. Action: ``` { "action": "extract_text", "action_input": {} } ``` Observation: LangChain LangChain Home About GitHub Docs LangChain The official LangChain blog. Auto-Evaluator Opportunities Editor's Note: this is a guest blog post by Lance Martin. TL;DR
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-2
We recently open-sourced an auto-evaluator tool for grading LLM question-answer chains. We are now releasing an open source, free to use hosted app and API to expand usability. Below we discuss a few opportunities to further improve May 1, 2023 5 min read Callbacks Improvements TL;DR: We're announcing improvements to our callbacks system, which powers logging, tracing, streaming output, and some awesome third-party integrations. This will better support concurrent runs with independent callbacks, tracing of deeply nested trees of LangChain components, and callback handlers scoped to a single request (which is super useful for May 1, 2023 3 min read Unleashing the power of AI Collaboration with Parallelized LLM Agent Actor Trees Editor's note: the following is a guest blog post from Cyrus at Shaman AI. We use guest blog posts to highlight interesting and novel applciations, and this is certainly that. There's been a lot of talk about agents recently, but most have been discussions around a single agent. If multiple Apr 28,
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-3
discussions around a single agent. If multiple Apr 28, 2023 4 min read Gradio & LLM Agents Editor's note: this is a guest blog post from Freddy Boulton, a software engineer at Gradio. We're excited to share this post because it brings a large number of exciting new tools into the ecosystem. Agents are largely defined by the tools they have, so to be able to equip Apr 23, 2023 4 min read RecAlign - The smart content filter for social media feed [Editor's Note] This is a guest post by Tian Jin. We are highlighting this application as we think it is a novel use case. Specifically, we think recommendation systems are incredibly impactful in our everyday lives and there has not been a ton of discourse on how LLMs will impact Apr 22, 2023 3 min read Improving Document Retrieval with Contextual Compression Note: This post assumes some familiarity with LangChain and is moderately technical.
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-4
💡 TL;DR: We’ve introduced a new abstraction and a new document Retriever to facilitate the post-processing of retrieved documents. Specifically, the new abstraction makes it easy to take a set of retrieved documents and extract from them Apr 20, 2023 3 min read Autonomous Agents & Agent Simulations Over the past two weeks, there has been a massive increase in using LLMs in an agentic manner. Specifically, projects like AutoGPT, BabyAGI, CAMEL, and Generative Agents have popped up. The LangChain community has now implemented some parts of all of those projects in the LangChain framework. While researching and Apr 18, 2023 7 min read AI-Powered Medical Knowledge: Revolutionizing Care for Rare Conditions [Editor's Note]: This is a guest post by Jack Simon, who recently participated in a hackathon at Williams College. He built a LangChain-powered chatbot focused on appendiceal cancer, aiming to make specialized knowledge more accessible to those in need. If you are interested in building a chatbot for another rare Apr 17, 2023 3 min read Auto-Eval of Question-Answering Tasks By Lance Martin Context LLM ops platforms, such as LangChain, make it easy to assemble LLM components (e.g., models, document retrievers, data loaders) into chains. Question-Answering is one of the most popular applications of these chains. But it is often not always obvious to determine what parameters (e.g. Apr 15, 2023 3 min read Announcing LangChainJS Support for Multiple JS Environments TLDR: We're announcing support for running LangChain.js in browsers, Cloudflare Workers, Vercel/Next.js, Deno, Supabase Edge Functions, alongside existing support for Node.js ESM and CJS. See install/upgrade docs and breaking changes list. Context
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-5
Context Originally we designed LangChain.js to run in Node.js, which is the Apr 11, 2023 3 min read LangChain x Supabase Supabase is holding an AI Hackathon this week. Here at LangChain we are big fans of both Supabase and hackathons, so we thought this would be a perfect time to highlight the multiple ways you can use LangChain and Supabase together.
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-6
The reason we like Supabase so much is that Apr 8, 2023 2 min read Announcing our $10M seed round led by Benchmark It was only six months ago that we released the first version of LangChain, but it seems like several years. When we launched, generative AI was starting to go mainstream: stable diffusion had just been released and was captivating people’s imagination and fueling an explosion in developer activity, Jasper Apr 4, 2023 4 min read Custom Agents One of the most common requests we've heard is better functionality and documentation for creating custom agents. This has always been a bit tricky - because in our mind it's actually still very unclear what an "agent" actually is, and therefor what the "right" abstractions for them may be. Recently, Apr 3, 2023 3 min read Retrieval TL;DR: We are adjusting our abstractions to make it easy for other retrieval methods besides the LangChain VectorDB object to be used in LangChain. This is done with the goals of (1) allowing
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-7
This is done with the goals of (1) allowing retrievers constructed elsewhere to be used more easily in LangChain, (2) encouraging more experimentation with alternative Mar 23, 2023 4 min read LangChain + Zapier Natural Language Actions (NLA) We are super excited to team up with Zapier and integrate their new Zapier NLA API into LangChain, which you can now use with your agents and chains. With this integration, you have access to the 5k+ apps and 20k+ actions on Zapier's platform through a natural language API interface. Mar 16, 2023 2 min read Evaluation Evaluation of language models, and by extension applications built on top of language models, is hard. With recent model releases (OpenAI, Anthropic, Google) evaluation is becoming a bigger and bigger issue. People are starting to try to tackle this, with OpenAI releasing OpenAI/evals - focused on evaluating OpenAI models. Mar 14, 2023 3 min read LLMs and SQL Francisco Ingham and Jon Luo are two of the community
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-8
Ingham and Jon Luo are two of the community members leading the change on the SQL integrations. We’re really excited to write this blog post with them going over all the tips and tricks they’ve learned doing so. We’re even more excited to announce that we’ Mar 13, 2023 8 min read Origin Web Browser [Editor's Note]: This is the second of hopefully many guest posts. We intend to highlight novel applications building on top of LangChain. If you are interested in working with us on such a post, please reach out to [email protected].
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-9
Authors: Parth Asawa (pgasawa@), Ayushi Batwara (ayushi.batwara@), Jason Mar 8, 2023 4 min read Prompt Selectors One common complaint we've heard is that the default prompt templates do not work equally well for all models. This became especially pronounced this past week when OpenAI released a ChatGPT API. This new API had a completely new interface (which required new abstractions) and as a result many users Mar 8, 2023 2 min read Chat Models Last week OpenAI released a ChatGPT endpoint. It came marketed with several big improvements, most notably being 10x cheaper and a lot faster. But it also came with a completely new API endpoint. We were able to quickly write a wrapper for this endpoint to let users use it like Mar 6, 2023 6 min read Using the ChatGPT API to evaluate the ChatGPT API OpenAI released a new ChatGPT API yesterday. Lots of people were excited to try it. But how does it actually compare to the existing API? It will take some time before there is a definitive answer, but here are some initial thoughts. Because I'm lazy, I also enrolled the help Mar 2, 2023 5 min read Agent Toolkits Today, we're announcing agent toolkits, a new abstraction that allows developers to create agents designed for a particular use-case (for example, interacting with a relational database or interacting with an OpenAPI spec). We hope to continue developing different toolkits that can enable agents to do amazing feats. Toolkits are supported Mar 1, 2023 3 min read TypeScript Support It's finally here... TypeScript support for LangChain.
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-10
What does this mean? It means that all your favorite prompts, chains, and agents are all recreatable in TypeScript natively. Both the Python version and TypeScript version utilize the same serializable format, meaning that artifacts can seamlessly be shared between languages. As an Feb 17, 2023 2 min read Streaming Support in LangChain We’re excited to announce streaming support in LangChain. There's been a lot of talk about the best UX for LLM applications, and we believe streaming is at its core. We’ve also updated the chat-langchain repo to include streaming and async execution. We hope that this repo can serve Feb 14, 2023 2 min read LangChain + Chroma Today we’re announcing LangChain's integration with Chroma, the first step on the path to the Modern A.I Stack. LangChain - The A.I-native developer toolkit We started LangChain with the intent to build a modular and flexible framework for developing A.I-native applications. Some of the use cases Feb 13, 2023 2 min read Page 1 of 2 Older Posts → LangChain © 2023 Sign up Powered by Ghost Thought: > Finished chain. The LangChain blog has recently released an open-source auto-evaluator tool for grading LLM question-answer chains and is now releasing an open-source, free-to-use hosted app and API to expand usability. The blog also discusses various opportunities to further improve the LangChain platform. response = await agent_chain.arun(input="What's the latest xkcd comic about?") print(response) > Entering new AgentExecutor chain... Thought: I can navigate to the xkcd website and extract the latest comic title and alt text to answer the question. Action: ``` { "action": "navigate_browser", "action_input": { "url": "https://xkcd.com/" } }
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-11
"url": "https://xkcd.com/" } } ``` Observation: Navigating to https://xkcd.com/ returned status code 200 Thought:I can extract the latest comic title and alt text using CSS selectors. Action: ``` { "action": "get_elements", "action_input": { "selector": "#ctitle, #comic img", "attributes": ["alt", "src"] } } ``` Observation: [{"alt": "Tapetum Lucidum", "src": "//imgs.xkcd.com/comics/tapetum_lucidum.png"}] Thought: > Finished chain. The latest xkcd comic is titled "Tapetum Lucidum" and the image can be found at https://xkcd.com/2565/. Adding in memory# Here is how you add in memory to this agent from langchain.prompts import MessagesPlaceholder from langchain.memory import ConversationBufferMemory chat_history = MessagesPlaceholder(variable_name="chat_history") memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) agent_chain = initialize_agent( tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, agent_kwargs = { "memory_prompts": [chat_history], "input_variables": ["input", "agent_scratchpad", "chat_history"] } ) response = await agent_chain.arun(input="Hi I'm Erica.") print(response) > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer",
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
f9966504dbe0-12
Action: ``` { "action": "Final Answer", "action_input": "Hi Erica! How can I assist you today?" } ``` > Finished chain. Hi Erica! How can I assist you today? response = await agent_chain.arun(input="whats my name?") print(response) > Entering new AgentExecutor chain... Your name is Erica. > Finished chain. Your name is Erica. previous Self Ask With Search next Toolkits Contents Initialize Tools Adding in memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html
05fbb9419123-0
.ipynb .pdf MRKL Chat MRKL Chat# This notebook showcases using an agent to replicate the MRKL chain using an agent optimized for chat models. This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. from langchain import OpenAI, LLMMathChain, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(temperature=0) llm1 = OpenAI(temperature=0) search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm1, verbose=True) db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db") db_chain = SQLDatabaseChain.from_llm(llm1, db, verbose=True) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions" ), Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math" ), Tool( name="FooBar DB", func=db_chain.run, description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context" ) ] mrkl = initialize_agent(tools, llm, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
05fbb9419123-1
mrkl.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... Thought: The first question requires a search, while the second question requires a calculator. Action: ``` { "action": "Search", "action_input": "Leo DiCaprio girlfriend" } ``` Observation: Gigi Hadid: 2022 Leo and Gigi were first linked back in September 2022, when a source told Us Weekly that Leo had his “sights set" on her (alarming way to put it, but okay). Thought:For the second question, I need to calculate the age raised to the 0.43 power. I will use the calculator tool. Action: ``` { "action": "Calculator", "action_input": "((2022-1995)^0.43)" } ``` > Entering new LLMMathChain chain... ((2022-1995)^0.43) ```text (2022-1995)**0.43 ``` ...numexpr.evaluate("(2022-1995)**0.43")... Answer: 4.125593352125936 > Finished chain. Observation: Answer: 4.125593352125936 Thought:I now know the final answer. Final Answer: Gigi Hadid is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is approximately 4.13. > Finished chain. "Gigi Hadid is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is approximately 4.13."
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
05fbb9419123-2
mrkl.run("What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database?") > Entering new AgentExecutor chain... Question: What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database? Thought: I should use the Search tool to find the answer to the first part of the question and then use the FooBar DB tool to find the answer to the second part. Action: ``` { "action": "Search", "action_input": "Who recently released an album called 'The Storm Before the Calm'" } ``` Observation: Alanis Morissette Thought:Now that I know the artist's name, I can use the FooBar DB tool to find out if they are in the database and what albums of theirs are in it. Action: ``` { "action": "FooBar DB", "action_input": "What albums does Alanis Morissette have in the database?" } ``` > Entering new SQLDatabaseChain chain... What albums does Alanis Morissette have in the database? SQLQuery: /Users/harrisonchase/workplace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage. sample_rows = connection.execute(command)
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
05fbb9419123-3
sample_rows = connection.execute(command) SELECT "Title" FROM "Album" WHERE "ArtistId" IN (SELECT "ArtistId" FROM "Artist" WHERE "Name" = 'Alanis Morissette') LIMIT 5; SQLResult: [('Jagged Little Pill',)] Answer: Alanis Morissette has the album Jagged Little Pill in the database. > Finished chain. Observation: Alanis Morissette has the album Jagged Little Pill in the database. Thought:The artist Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it. Final Answer: Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it. > Finished chain. 'Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it.' previous MRKL next ReAct By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
eaf588d16bfb-0
.ipynb .pdf Self Ask With Search Self Ask With Search# This notebook showcases the Self Ask With Search chain. from langchain import OpenAI, SerpAPIWrapper from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType llm = OpenAI(temperature=0) search = SerpAPIWrapper() tools = [ Tool( name="Intermediate Answer", func=search.run, description="useful for when you need to ask with search" ) ] self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True) self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?") > Entering new AgentExecutor chain... Yes. Follow up: Who is the reigning men's U.S. Open champion? Intermediate answer: Carlos Alcaraz Garfia Follow up: Where is Carlos Alcaraz Garfia from? Intermediate answer: El Palmar, Spain So the final answer is: El Palmar, Spain > Finished chain. 'El Palmar, Spain' previous ReAct next Structured Tool Chat Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/self_ask_with_search.html
6787c087ede7-0
.ipynb .pdf Conversation Agent Conversation Agent# This notebook walks through using an agent optimized for conversation. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well. This is accomplished with a specific type of agent (conversational-react-description) which expects to be used with a memory component. from langchain.agents import Tool from langchain.agents import AgentType from langchain.memory import ConversationBufferMemory from langchain import OpenAI from langchain.utilities import SerpAPIWrapper from langchain.agents import initialize_agent search = SerpAPIWrapper() tools = [ Tool( name = "Current Search", func=search.run, description="useful for when you need to answer questions about current events or the current state of the world" ), ] memory = ConversationBufferMemory(memory_key="chat_history") llm=OpenAI(temperature=0) agent_chain = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory) agent_chain.run(input="hi, i am bob") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? No AI: Hi Bob, nice to meet you! How can I help you today? > Finished chain. 'Hi Bob, nice to meet you! How can I help you today?' agent_chain.run(input="what's my name?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? No AI: Your name is Bob! > Finished chain. 'Your name is Bob!'
https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html
6787c087ede7-1
AI: Your name is Bob! > Finished chain. 'Your name is Bob!' agent_chain.run("what are some good dinners to make this week, if i like thai food?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Current Search Action Input: Thai food dinner recipes Observation: 59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's Thai Spicy ... Thought: Do I need to use a tool? No AI: Here are some great Thai dinner recipes you can try this week: Marion Grasby's Thai Spicy Chilli and Basil Fried Rice, Thai Curry Noodle Soup, Thai Green Curry with Coconut Rice, Thai Red Curry with Vegetables, and Thai Coconut Soup. I hope you enjoy them! > Finished chain. "Here are some great Thai dinner recipes you can try this week: Marion Grasby's Thai Spicy Chilli and Basil Fried Rice, Thai Curry Noodle Soup, Thai Green Curry with Coconut Rice, Thai Red Curry with Vegetables, and Thai Coconut Soup. I hope you enjoy them!" agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Current Search Action Input: Who won the World Cup in 1978 Observation: Argentina national football team Thought: Do I need to use a tool? No AI: The last letter in your name is "b" and the winner of the 1978 World Cup was the Argentina national football team. > Finished chain.
https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html
6787c087ede7-2
> Finished chain. 'The last letter in your name is "b" and the winner of the 1978 World Cup was the Argentina national football team.' agent_chain.run(input="whats the current temperature in pomfret?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Current Search Action Input: Current temperature in Pomfret Observation: Partly cloudy skies. High around 70F. Winds W at 5 to 10 mph. Humidity41%. Thought: Do I need to use a tool? No AI: The current temperature in Pomfret is around 70F with partly cloudy skies and winds W at 5 to 10 mph. The humidity is 41%. > Finished chain. 'The current temperature in Pomfret is around 70F with partly cloudy skies and winds W at 5 to 10 mph. The humidity is 41%.' previous Conversation Agent (for Chat Models) next MRKL By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html
164e3434f5b2-0
.ipynb .pdf MRKL MRKL# This notebook showcases using an agent to replicate the MRKL chain. This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType llm = OpenAI(temperature=0) search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm, verbose=True) db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db") db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions" ), Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math" ), Tool( name="FooBar DB", func=db_chain.run, description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context" ) ] mrkl = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) mrkl.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain...
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
164e3434f5b2-1
> Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Who is Leo DiCaprio's girlfriend?" Observation: DiCaprio met actor Camila Morrone in December 2017, when she was 20 and he was 43. They were spotted at Coachella and went on multiple vacations together. Some reports suggested that DiCaprio was ready to ask Morrone to marry him. The couple made their red carpet debut at the 2020 Academy Awards. Thought: I need to calculate Camila Morrone's age raised to the 0.43 power. Action: Calculator Action Input: 21^0.43 > Entering new LLMMathChain chain... 21^0.43 ```text 21**0.43 ``` ...numexpr.evaluate("21**0.43")... Answer: 3.7030049853137306 > Finished chain. Observation: Answer: 3.7030049853137306 Thought: I now know the final answer. Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.7030049853137306. > Finished chain. "Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.7030049853137306." mrkl.run("What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database?") > Entering new AgentExecutor chain...
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
164e3434f5b2-2
> Entering new AgentExecutor chain... I need to find out the artist's full name and then search the FooBar database for their albums. Action: Search Action Input: "The Storm Before the Calm" artist Observation: The Storm Before the Calm (stylized in all lowercase) is the tenth (and eighth international) studio album by Canadian-American singer-songwriter Alanis Morissette, released June 17, 2022, via Epiphany Music and Thirty Tigers, as well as by RCA Records in Europe. Thought: I now need to search the FooBar database for Alanis Morissette's albums. Action: FooBar DB Action Input: What albums by Alanis Morissette are in the FooBar database? > Entering new SQLDatabaseChain chain... What albums by Alanis Morissette are in the FooBar database? SQLQuery: /Users/harrisonchase/workplace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage. sample_rows = connection.execute(command) SELECT "Title" FROM "Album" INNER JOIN "Artist" ON "Album"."ArtistId" = "Artist"."ArtistId" WHERE "Name" = 'Alanis Morissette' LIMIT 5; SQLResult: [('Jagged Little Pill',)] Answer: The albums by Alanis Morissette in the FooBar database are Jagged Little Pill. > Finished chain. Observation: The albums by Alanis Morissette in the FooBar database are Jagged Little Pill. Thought: I now know the final answer.
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
164e3434f5b2-3
Thought: I now know the final answer. Final Answer: The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill. > Finished chain. "The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill." previous Conversation Agent next MRKL Chat By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
f78c0d2a3a95-0
.ipynb .pdf ReAct ReAct# This notebook showcases using an agent to implement the ReAct logic. from langchain import OpenAI, Wikipedia from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.agents.react.base import DocstoreExplorer docstore=DocstoreExplorer(Wikipedia()) tools = [ Tool( name="Search", func=docstore.search, description="useful for when you need to ask with search" ), Tool( name="Lookup", func=docstore.lookup, description="useful for when you need to ask with lookup" ) ] llm = OpenAI(temperature=0, model_name="text-davinci-002") react = initialize_agent(tools, llm, agent=AgentType.REACT_DOCSTORE, verbose=True) question = "Author David Chanoff has collaborated with a U.S. Navy admiral who served as the ambassador to the United Kingdom under which President?" react.run(question) > Entering new AgentExecutor chain... Thought: I need to search David Chanoff and find the U.S. Navy admiral he collaborated with. Then I need to find which President the admiral served under. Action: Search[David Chanoff]
https://python.langchain.com/en/latest/modules/agents/agents/examples/react.html
f78c0d2a3a95-1
Action: Search[David Chanoff] Observation: David Chanoff is a noted author of non-fiction work. His work has typically involved collaborations with the principal protagonist of the work concerned. His collaborators have included; Augustus A. White, Joycelyn Elders, Đoàn Văn Toại, William J. Crowe, Ariel Sharon, Kenneth Good and Felix Zandman. He has also written about a wide range of subjects including literary history, education and foreign for The Washington Post, The New Republic and The New York Times Magazine. He has published more than twelve books. Thought: The U.S. Navy admiral David Chanoff collaborated with is William J. Crowe. I need to find which President he served under. Action: Search[William J. Crowe] Observation: William James Crowe Jr. (January 2, 1925 – October 18, 2007) was a United States Navy admiral and diplomat who served as the 11th chairman of the Joint Chiefs of Staff under Presidents Ronald Reagan and George H. W. Bush, and as the ambassador to the United Kingdom and Chair of the Intelligence Oversight Board under President Bill Clinton. Thought: William J. Crowe served as the ambassador to the United Kingdom under President Bill Clinton, so the answer is Bill Clinton. Action: Finish[Bill Clinton] > Finished chain. 'Bill Clinton' previous MRKL Chat next Self Ask With Search By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/react.html
4563117de3e7-0
.ipynb .pdf Conversation Agent (for Chat Models) Conversation Agent (for Chat Models)# This notebook walks through using an agent optimized for conversation, using ChatModels. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well. This is accomplished with a specific type of agent (chat-conversational-react-description) which expects to be used with a memory component. !pip install langchain !pip install google-search-results !pip install openai from langchain.agents import Tool from langchain.memory import ConversationBufferMemory from langchain.chat_models import ChatOpenAI from langchain.utilities import SerpAPIWrapper from langchain.agents import initialize_agent from langchain.agents import AgentType from getpass import getpass SERPAPI_API_KEY = getpass() search = SerpAPIWrapper(serpapi_api_key=SERPAPI_API_KEY) tools = [ Tool( name = "Current Search", func=search.run, description="useful for when you need to answer questions about current events or the current state of the world. the input to this should be a single search term." ), ] memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) OPENAI_API_KEY = getpass() llm=ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0) agent_chain = initialize_agent(tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory) agent_chain.run(input="hi, i am bob") > Entering new AgentExecutor chain... { "action": "Final Answer",
https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
4563117de3e7-1
> Entering new AgentExecutor chain... { "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today?" } > Finished chain. 'Hello Bob! How can I assist you today?' agent_chain.run(input="what's my name?") > Entering new AgentExecutor chain... { "action": "Final Answer", "action_input": "Your name is Bob." } > Finished chain. 'Your name is Bob.' agent_chain.run("what are some good dinners to make this week, if i like thai food?") > Entering new AgentExecutor chain... { "action": "Current Search", "action_input": "Thai food dinner recipes" } Observation: 64 easy Thai recipes for any night of the week · Thai curry noodle soup · Thai yellow cauliflower, snake bean and tofu curry · Thai-spiced chicken hand pies · Thai ... Thought:{ "action": "Final Answer", "action_input": "Here are some Thai food dinner recipes you can try this week: Thai curry noodle soup, Thai yellow cauliflower, snake bean and tofu curry, Thai-spiced chicken hand pies, and many more. You can find the full list of recipes at the source I found earlier." } > Finished chain. 'Here are some Thai food dinner recipes you can try this week: Thai curry noodle soup, Thai yellow cauliflower, snake bean and tofu curry, Thai-spiced chicken hand pies, and many more. You can find the full list of recipes at the source I found earlier.' agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?") > Entering new AgentExecutor chain... { "action": "Final Answer",
https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
4563117de3e7-2
> Entering new AgentExecutor chain... { "action": "Final Answer", "action_input": "The last letter in your name is 'b'. Argentina won the World Cup in 1978." } > Finished chain. "The last letter in your name is 'b'. Argentina won the World Cup in 1978." agent_chain.run(input="whats the weather like in pomfret?") > Entering new AgentExecutor chain... { "action": "Current Search", "action_input": "weather in pomfret" } Observation: Cloudy with showers. Low around 55F. Winds S at 5 to 10 mph. Chance of rain 60%. Humidity76%. Thought:{ "action": "Final Answer", "action_input": "Cloudy with showers. Low around 55F. Winds S at 5 to 10 mph. Chance of rain 60%. Humidity76%." } > Finished chain. 'Cloudy with showers. Low around 55F. Winds S at 5 to 10 mph. Chance of rain 60%. Humidity76%.' previous Custom Agent with Tool Retrieval next Conversation Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
c297424ccc6f-0
.ipynb .pdf Vectorstore Agent Contents Create the Vectorstores Initialize Toolkit and Agent Examples Multiple Vectorstores Examples Vectorstore Agent# This notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources. Create the Vectorstores# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain import OpenAI, VectorDBQA llm = OpenAI(temperature=0) from langchain.document_loaders import TextLoader loader = TextLoader('../../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() state_of_union_store = Chroma.from_documents(texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. from langchain.document_loaders import WebBaseLoader loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/") docs = loader.load() ruff_texts = text_splitter.split_documents(docs) ruff_store = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Initialize Toolkit and Agent# First, we’ll create an agent with a single vectorstore. from langchain.agents.agent_toolkits import ( create_vectorstore_agent, VectorStoreToolkit, VectorStoreInfo, ) vectorstore_info = VectorStoreInfo( name="state_of_union_address",
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html
c297424ccc6f-1
) vectorstore_info = VectorStoreInfo( name="state_of_union_address", description="the most recent state of the Union adress", vectorstore=state_of_union_store ) toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info) agent_executor = create_vectorstore_agent( llm=llm, toolkit=toolkit, verbose=True ) Examples# agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to find the answer in the state of the union address Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address? List the source.") > Entering new AgentExecutor chain... I need to use the state_of_union_address_with_sources tool to answer this question. Action: state_of_union_address_with_sources Action Input: What did biden say about ketanji brown jackson
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html
c297424ccc6f-2
Action Input: What did biden say about ketanji brown jackson Observation: {"answer": " Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence.\n", "sources": "../../state_of_the_union.txt"} Thought: I now know the final answer Final Answer: Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt > Finished chain. "Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt" Multiple Vectorstores# We can also easily use this initialize an agent with multiple vectorstores and use the agent to route between them. To do this. This agent is optimized for routing, so it is a different toolkit and initializer. from langchain.agents.agent_toolkits import ( create_vectorstore_router_agent, VectorStoreRouterToolkit, VectorStoreInfo, ) ruff_vectorstore_info = VectorStoreInfo( name="ruff", description="Information about the Ruff python linting library", vectorstore=ruff_store ) router_toolkit = VectorStoreRouterToolkit( vectorstores=[vectorstore_info, ruff_vectorstore_info], llm=llm ) agent_executor = create_vectorstore_router_agent( llm=llm, toolkit=router_toolkit, verbose=True )
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html
c297424ccc6f-3
toolkit=router_toolkit, verbose=True ) Examples# agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to use the state_of_union_address tool to answer this question. Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent_executor.run("What tool does ruff use to run over Jupyter Notebooks?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses to run over Jupyter Notebooks Action: ruff Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb Thought: I now know the final answer
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html
c297424ccc6f-4
Thought: I now know the final answer Final Answer: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb > Finished chain. 'Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb' agent_executor.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses and if the president mentioned it in the state of the union. Action: ruff Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb Thought: I need to find out if the president mentioned nbQA in the state of the union. Action: state_of_union_address Action Input: Did the president mention nbQA in the state of the union? Observation: No, the president did not mention nbQA in the state of the union. Thought: I now know the final answer. Final Answer: No, the president did not mention nbQA in the state of the union. > Finished chain. 'No, the president did not mention nbQA in the state of the union.' previous SQL Database Agent next
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html
c297424ccc6f-5
previous SQL Database Agent next Agent Executors Contents Create the Vectorstores Initialize Toolkit and Agent Examples Multiple Vectorstores Examples By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html
50dcd20e0ce1-0
.ipynb .pdf Spark SQL Agent Contents Initialization Example: describing a table Example: running queries Spark SQL Agent# This notebook shows how to use agents to interact with a Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery. NOTE: Note that, as this agent is in active development, all answers might not be correct. Additionally, it is not guaranteed that the agent won’t perform DML statements on your Spark cluster given certain questions. Be careful running it on sensitive data! Initialization# from langchain.agents import create_spark_sql_agent from langchain.agents.agent_toolkits import SparkSQLToolkit from langchain.chat_models import ChatOpenAI from langchain.utilities.spark_sql import SparkSQL from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() schema = "langchain_example" spark.sql(f"CREATE DATABASE IF NOT EXISTS {schema}") spark.sql(f"USE {schema}") csv_file_path = "titanic.csv" table = "titanic" spark.read.csv(csv_file_path, header=True, inferSchema=True).write.saveAsTable(table) spark.table(table).show() Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). 23/05/18 16:03:10 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ |PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked|
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-1
+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ | 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S| | 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C| | 3| 1| 3|Heikkinen, Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S| | 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S| | 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S| | 6| 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q|
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-2
| 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| 0| 17463|51.8625| E46| S| | 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S| | 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S| | 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| 237736|30.0708| null| C| | 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S| | 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S| | 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S|
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-3
| 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S| | 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S| | 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S| | 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q| | 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S| | 19| 0| 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S| | 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| 2649| 7.225| null| C| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ only showing top 20 rows
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-4
only showing top 20 rows # Note, you can also connect to Spark via Spark connect. For example: # db = SparkSQL.from_uri("sc://localhost:15002", schema=schema) spark_sql = SparkSQL(schema=schema) llm = ChatOpenAI(temperature=0) toolkit = SparkSQLToolkit(db=spark_sql, llm=llm) agent_executor = create_spark_sql_agent( llm=llm, toolkit=toolkit, verbose=True ) Example: describing a table# agent_executor.run("Describe the titanic table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: Observation: titanic Thought:I found the titanic table. Now I need to get the schema and sample rows for the titanic table. Action: schema_sql_db Action Input: titanic Observation: CREATE TABLE langchain_example.titanic ( PassengerId INT, Survived INT, Pclass INT, Name STRING, Sex STRING, Age DOUBLE, SibSp INT, Parch INT, Ticket STRING, Fare DOUBLE, Cabin STRING, Embarked STRING) ; /* 3 rows from titanic table: PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.25 None S 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38.0 1 0 PC 17599 71.2833 C85 C
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-5
3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.925 None S */ Thought:I now know the schema and sample rows for the titanic table. Final Answer: The titanic table has the following columns: PassengerId (INT), Survived (INT), Pclass (INT), Name (STRING), Sex (STRING), Age (DOUBLE), SibSp (INT), Parch (INT), Ticket (STRING), Fare (DOUBLE), Cabin (STRING), and Embarked (STRING). Here are some sample rows from the table: 1. PassengerId: 1, Survived: 0, Pclass: 3, Name: Braund, Mr. Owen Harris, Sex: male, Age: 22.0, SibSp: 1, Parch: 0, Ticket: A/5 21171, Fare: 7.25, Cabin: None, Embarked: S 2. PassengerId: 2, Survived: 1, Pclass: 1, Name: Cumings, Mrs. John Bradley (Florence Briggs Thayer), Sex: female, Age: 38.0, SibSp: 1, Parch: 0, Ticket: PC 17599, Fare: 71.2833, Cabin: C85, Embarked: C 3. PassengerId: 3, Survived: 1, Pclass: 3, Name: Heikkinen, Miss. Laina, Sex: female, Age: 26.0, SibSp: 0, Parch: 0, Ticket: STON/O2. 3101282, Fare: 7.925, Cabin: None, Embarked: S > Finished chain.
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-6
> Finished chain. 'The titanic table has the following columns: PassengerId (INT), Survived (INT), Pclass (INT), Name (STRING), Sex (STRING), Age (DOUBLE), SibSp (INT), Parch (INT), Ticket (STRING), Fare (DOUBLE), Cabin (STRING), and Embarked (STRING). Here are some sample rows from the table: \n\n1. PassengerId: 1, Survived: 0, Pclass: 3, Name: Braund, Mr. Owen Harris, Sex: male, Age: 22.0, SibSp: 1, Parch: 0, Ticket: A/5 21171, Fare: 7.25, Cabin: None, Embarked: S\n2. PassengerId: 2, Survived: 1, Pclass: 1, Name: Cumings, Mrs. John Bradley (Florence Briggs Thayer), Sex: female, Age: 38.0, SibSp: 1, Parch: 0, Ticket: PC 17599, Fare: 71.2833, Cabin: C85, Embarked: C\n3. PassengerId: 3, Survived: 1, Pclass: 3, Name: Heikkinen, Miss. Laina, Sex: female, Age: 26.0, SibSp: 0, Parch: 0, Ticket: STON/O2. 3101282, Fare: 7.925, Cabin: None, Embarked: S' Example: running queries# agent_executor.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: Observation: titanic
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html
50dcd20e0ce1-7
Action: list_tables_sql_db Action Input: Observation: titanic Thought:I should check the schema of the titanic table to see if there is an age column. Action: schema_sql_db Action Input: titanic Observation: CREATE TABLE langchain_example.titanic ( PassengerId INT, Survived INT, Pclass INT, Name STRING, Sex STRING, Age DOUBLE, SibSp INT, Parch INT, Ticket STRING, Fare DOUBLE, Cabin STRING, Embarked STRING) ; /* 3 rows from titanic table: PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.25 None S 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38.0 1 0 PC 17599 71.2833 C85 C 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.925 None S */ Thought:There is an Age column in the titanic table. I should write a query to calculate the average age and then find the square root of the result. Action: query_checker_sql_db Action Input: SELECT SQRT(AVG(Age)) as square_root_of_avg_age FROM titanic Observation: The original query seems to be correct. Here it is again: SELECT SQRT(AVG(Age)) as square_root_of_avg_age FROM titanic
https://python.langchain.com/en/latest/modules/agents/toolkits/examples/spark_sql.html