Artificial Intelligence

Agents In LangChain

Introduction

In this article, we will discuss Agents and their various types in LangChain. But before diving deep into Agents, let’s first understand what LangChain and Agents are.

What is LangChain?

LangChain is a powerful automation tool that can be used for a wide range of tasks. It provides a variety of tools that can be utilized to create agents.

  • Agents: An agent is a software program designed to interact with the real world. LangChain offers different types of agents.
  • Tools: LangChain provides tools that aid in the development of agents.

To learn more about LangChain, you can read the article – Getting Started With LangChain​​​​.

What are Agents?

Agents in LangChain are built to interact with the real world. They are powerful tools that automate tasks and engage with real-world scenarios. LangChain agents can be used for a variety of tasks such as answering questions, generating text, translating languages, summarizing text, and more.

Types of Agents in LangChain

Agents in LangChain use an LLM (Language Learning Model) to determine which actions to take and in what order.

1. Zero-shot ReAct

The Zero-shot ReAct Agent is a language generation model that can create realistic contexts even without being trained on specific data. It can be used for various tasks such as generating creative text formats, language translation, and generating different types of creative content.

Code

from langchain.agents import initialize_agent, load_tools, AgentType
from langchain.llms import OpenAI
llm = OpenAI(openai_api_key="your_api_key")
tools = load_tools(["wikipedia", "llm-math"], llm=llm)
agent = initialize_agent(tools , llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
output_1=agent.run("4 + 5 is ")
output_2=agent.run("when you add 4  and 5 the result comes 10.")
print(output_1)
print(output_2)

In the above code, the LangChain library is imported and an OpenAI language model (LLM) is initialized by setting the OpenAI API key. The code sets up an AI agent with tools for Wikipedia and mathematical information, specifying the agent type as a ZERO_SHOT_REACT_DESCRIPTION agent. The code then provides two prompts to demonstrate a one-time interaction with the agent.

Output

output_zero-shot_ReAct

2. Conversational ReAct

This agent is designed for use in conversational settings. It incorporates the React framework to determine which tool to use and utilizes memory to remember previous conversation interactions.

Code

from langchain.agents import initialize_agent, load_tools
from langchain.llms import OpenAI
from langchain.memory import ConversationBufferMemory
llm = OpenAI(openai_api_key="...")
tools = load_tools(["llm-math"],  llm=llm)
memory = ConversationBufferMemory(memory_key="chat_history")
conversational_agent = initialize_agent(
    agent="conversational-react-description", 
    tools=tools, 
    llm=llm,
    verbose=True,
    max_iterations=3,
    memory=memory,)
output_1=conversational_agent.run("when you add 4  and 5 the result comes 10.")
output_2=conversational_agent.run("4 + 5 is ")
print(output_1)
print(output_2)

The above code demonstrates the usage of the LangChain library by importing the necessary modules, setting up an OpenAI language model (LLM) with an API key, loading specific tools like llm-math for mathematical operations, and creating a conversation buffer memory. The conversational agent is then initialized with the specified agent type, tools, LLM, and other parameters. The code showcases two prompts to interact with the agent.

Output

output_conversation

3. ReAct Docstore

This agent utilizes the React framework to communicate with a docstore. It requires the availability of a Search tool and a Lookup tool with identical names. The Search tool is used to search for a document, while the Lookup tool looks up a term within the most recently found document.

Code

from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI
from langchain import Wikipedia
from langchain.agents.react.base import DocstoreExplorer
llm = OpenAI(openai_api_key="...")
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")]
react_agent= initialize_agent(tools, llm, agent="react-docstore")
print(react_agent.run("Full name of Narendra Modi is Narendra Damodardas Modi?")) # look on the keywords then go for search
print(react_agent.run("Full name of Narendra Modi is Narendra Damodardas Modi."))

The above code imports the necessary modules from LangChain and initializes an OpenAI language model (LLM) with an API key. It sets up a document store explorer utilizing Wikipedia as the source. Two tools, “Search” and “Lookup,” are defined, with the Search tool searching for a document and the Lookup tool performing term lookups.

Output

output_ReAct_Docstore

4. Self-ask with Search

This agent utilizes the Intermediate Answer tool for self-asking questions.

Code

from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI
from langchain import Wikipedia
llm = OpenAI(openai_api_key="...")
wikipedia = Wikipedia()
tools = [
    Tool(
        name="Intermediate Answer",
        func=wikipedia.search,
        description='wikipedia search'
    )]
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent="self-ask-with-search",
    verbose=True,
)
print(agent.run("what is the capital of Japan?"))

The above code imports necessary modules from the LangChain library, including agents and language models. It sets up a conversational agent with a specific agent configuration called “self-ask-with-search”. The agent utilizes the “Intermediate Answer” tool, which performs Wikipedia searches.

Output

output_self_ask_with_search

Summary

This article provides a comprehensive explanation of the Agents in the LangChain library, along with their types and examples.

FAQs

Q. What is the difference between a chain and an agent in LangChain?

A. The main difference between agents and chains in LangChain is that agents utilize a language model to determine their actions, while chains have pre-defined sequences of actions set by the developer. Agents use language models to generate responses based on user input and available tools, whereas chains follow a fixed input/output process.

Q. What does Verbose() do?

A. The verbose option enables detailed processing information to be displayed on the screen.

Q. What is the temperature in LangChain?

A. By default, LangChain chat models are created with a temperature value of 0.7. The temperature parameter controls the randomness of the output. Higher values like 0.7 make the output more random, while lower values like 0.2 make it more focused and deterministic.

Discover more about our company at Skrots. To explore the range of services that we offer, visit Skrots Services. Also, take a look at our other informative blogs on the Skrots Blog . Thank you for reading!

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button