Exploring LangChain: A Comprehensive Toolkit for Conversational Agents

Ebo Jackson
Level Up Coding
Published in
6 min readJul 12, 2023

--

Introduction:

LangChain, a powerful toolkit for conversational agents, offers a wide range of tools to facilitate interactions with the outside world. These tools enable developers to create custom agents that can perform tasks such as web searching, answering questions, and executing Python code. In this article, we will explore the different tool types available in LangChain and provide coding examples to illustrate their usage.

Importing the Required Libraries:

To begin, we import the necessary libraries and modules into our coding environment. These libraries include “langchain.llms” for language models, “langchain.agents” for agent-related functionalities, “langchain.utilities” for utility tools, “langchain.prompts” for prompt templates, and “langchain.chains” for creating chains.

from langchain.llms import OpenAI
from langchain.agents import Tool
from langchain.utilities import GoogleSearchAPIWrapper
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain.agents import initialize_agent, AgentTypeCopy

Creating a Text Summarization Chain:

In our example, we focus on creating a text summarization chain using the OpenAI language model (LLMChain). We instantiate the LLMChain specifically for text summarization and define a prompt template that takes a query as input.

llm = OpenAI(model="text-davinci-003", temperature=0)

prompt = PromptTemplate(
input_variables=["query"],
template="Write a summary of the following text: {query}"
)

summarize_chain = LLMChain(llm=llm, prompt=prompt)

Defining the Tools:

Next, we create the tools that our agent will utilize. In this case, we define two tools: “Search” and “Summarizer.” The “Search” tool leverages the GoogleSearchAPIWrapper to handle queries related to recent events. The “Summarizer” tool uses the LLMChain we instantiated earlier to summarize texts. Each tool is defined with a name, function, and description.

search = GoogleSearchAPIWrapper()

tools = [
Tool(
name="Search",
func=search.run,
description="useful for finding information about recent events"
),
Tool(
name='Summarizer',
func=summarize_chain.run,
description='useful for summarizing texts'
)
]

Initializing the Agent:

Once the tools are defined, we initialize our agent by passing the tools, language model, agent type, and verbosity settings. The agent in LangChain can leverage multiple tools to perform different actions based on the user’s query.

agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)

Running the Agent:

We then run the agent with a specific question or query. In our example, we ask for the latest news about the Mars rover and request a summary of the results. The agent internally utilizes the “Search” tool to find the relevant information and then applies the “Summarizer” tool to generate a concise summary.

response = agent("What's the latest news about the Mars rover? Then please summarize the results.")
print(response['output'])

Output and Analysis:

After running the agent, we examine the output, which includes the chain of actions and observations made by the agent. The agent initially suggests using the “Search” tool to find recent news about the Mars rover and then proceeds to use the “Summarizer” tool to summarize the obtained information. The final answer provides a summarized version of the news.

> Entering new AgentExecutor chain...
I should search for recent news about the Mars rover and then summarize the results.

Action: Search
Action Input: Latest news about the Mars rover

Observation: Mars 2020 Perseverance Rover · The largest and most capable rover ever sent to Mars. ... Curiosity Rover · Measures Mars' atmosphere to understand its climate ... Dec 15, 2021 ... Mars Sample Return is going to have great stuff to choose from!” Get the Latest JPL News. SUBSCRIBE TO THE NEWSLETTER. The mission has concluded that the solar-powered lander has run out of energy after more than four years on the Red Planet. Oct 19, 2022 ... NASA's Curiosity Mars rover used its Mast Camera, or Mastcam, to capture this panorama of a hill nicknamed ... Get the Latest JPL News. NASA's Mars 2020 Perseverance rover will look for signs of past microbial life, cache rock and soil samples, and prepare for future human exploration. Latest Updates · Curiosity rover finds water-carved 'book' rock on Mars (photo) · Curiosity rover on Mars gets a brain boost to think (and move) faster · Curiosity ... Feb 8, 2023 ... Curiosity Rover Finds New Clues to Mars' Watery Past ... at Gediz Vallis Ridge twice last year but could only survey it from a distance. Sep 16, 2022 ... Since July, NASA's Perseverance rover has drilled and collected four slim cores of sedimentary rock, formed in what was once a lake on Mars. Mar 7, 2023 ... 27, helps provide scientists with information about the particle sizes within the clouds. Sign up for National Breaking News Alerts. All the latest content about Nasa Perseverance Mars rover from the BBC. ... James Tytko presents science news and we're putting tuberculosis under the ...
Thought: I should summarize the results of the search.

Action: Summarizer
Action Input: Mars 2020 Perseverance Rover is the largest and most capable rover ever sent to Mars. It measures Mars' atmosphere to understand its climate and has run out of energy after more than four years on the Red Planet. NASA's Curiosity Mars rover used its Mast Camera to capture a panorama of a hill nicknamed "Book Rock". NASA's Mars 2020 Perseverance rover will look for signs of past microbial life, cache rock and soil samples, and prepare for future human exploration. Curiosity rover finds water-carved 'book' rock on Mars, Curiosity rover on Mars gets a brain boost to think (and move) faster, Curiosity Rover Finds New Clues to Mars' Watery Past, and NASA's Perseverance rover has drilled and collected four slim cores of sedimentary rock.

Observation:
NASA's Mars 2020 Perseverance rover is the largest and most capable rover ever sent to Mars. It has been on the Red Planet for more than four years, measuring the atmosphere to understand its climate and searching for signs of past microbial life. The Curiosity rover has captured a panorama of a hill nicknamed "Book Rock" and has been given a brain boost to think and move faster. It has also found new clues to Mars' watery past. The Perseverance rover has drilled and collected four slim cores of sedimentary rock, which will be used to cache rock and soil samples and prepare for future human exploration.

Thought: I now know the final answer.
Final Answer: NASA's Mars 2020 Perseverance rover is the largest and most capable rover ever sent to Mars. It has been on the Red Planet for more than four years, measuring the atmosphere to understand its climate and searching for signs of past microbial life. The Curiosity rover has captured a panorama of a hill nicknamed "Book Rock" and has been given a brain boost to think and move faster. It has also found new clues to Mars' watery past. The Perseverance rover has drilled and collected four slim cores of sedimentary rock, which will be used to cache rock and soil samples and prepare for future human exploration.

> Finished chain.
NASA's Mars 2020 Perseverance rover is the largest and most capable rover ever sent to Mars. It has been on the Red Planet for more than four years, measuring the atmosphere to understand its climate and searching for signs of past microbial life. The Curiosity rover has captured a panorama of a hill nicknamed "Book Rock" and has been given a brain boost to think and move faster. It has also found new clues to Mars' watery past. The Perseverance rover has drilled and collected four slim cores of sedimentary rock, which will be used to cache rock and soil samples and prepare for future human exploration.

Exploring Additional Tools:

Apart from the tools demonstrated in the example, LangChain offers a diverse range of tools for different functionalities. Two such tools mentioned are the SerpAPI tool for performing robust online searches and the PythonREPLTool for executing Python code within an agent. These tools provide enhanced capabilities for data retrieval and advanced computations within conversations.

Custom Tools and Conclusion:

LangChain also provides the flexibility to create custom tools based on specific requirements. By following the guidelines in the LangChain documentation, developers can develop tools tailored to their application’s needs.

In conclusion, LangChain is an extensive toolkit that empowers developers to build advanced conversational agents. With its rich set of tools and integrations, LangChain simplifies the development process and enables the creation of sophisticated AI workflows. Whether you’re a beginner or an experienced AI developer, LangChain offers a solid foundation to build upon.

Level Up Coding

Thanks for being a part of our community! Before you go:

🔔 Follow us: Twitter | LinkedIn | Newsletter

🚀👉 Join the Level Up talent collective and find an amazing job

--

--