100% found this document useful (1 vote)
79 views

Agents in LangChain

Uploaded by

Vraj Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
79 views

Agents in LangChain

Uploaded by

Vraj Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

LangChain: Documentation for Using

Agents

Agents in LangChain

Introduction to Agents

An Agent is a program component that dynamically decides how to respond to a user's query
by selecting the best tool for the task. This enables flexibility and adaptability, allowing the
program to tackle a wide variety of questions and tasks.

How Agents Work

Agents don’t just follow preset instructions; instead, they analyze the user’s query and
determine:

1. What kind of question is being asked?


2. Which tool is best to answer it?
3. How should the tool be used?

Example

Imagine a digital assistant with multiple skills:

● Math Calculations
● Looking up facts online
● Language Translation

Scenario:

● You ask: "What’s 12 + 8?"


○ The assistant uses a calculator tool.
● You ask: "Who is the current president of France?"
○ The assistant uses a search engine.

Agents decide on the right tool based on the context of the question.
Types of Agents in LangChain

LangChain provides different types of agents tailored for various needs:

1. Zero-Shot Agents

● Description: These agents don’t require prior examples to generate responses.


● Use Case: Best for straightforward questions or tasks.
● Example:
○ Question: "What’s the capital of Italy?"
○ Response: The agent directly retrieves the answer using an appropriate tool.

2. Few-Shot Agents

● Description: These agents perform better with a few examples of how to solve a
problem.
● Use Case: Useful for tasks where context or format is essential.
● Example:
○ Question: "Translate words into French."
○ Provided Examples:
■ "Hello -> Bonjour"
■ "Goodbye -> Au revoir"
○ Response: Translates based on the provided examples.

3. Custom Agents

● Description: Agents designed for specialized tasks.


● Use Case: Ideal for domain-specific problems, such as booking flights or solving
equations.
● Example:
○ A math-focused agent uses a calculator for every query.
○ Question: "What is 45 times 2?"
○ Response: The agent calculates and returns "90."

Using Agents with Tools

Agents become powerful by connecting to tools. Tools act as the agent’s “abilities.”

Common Tools for Agents


● Calculator: Performs math operations.
● Search Engine: Finds real-time information online.
● Knowledge Base: Retrieves stored facts or structured data.
● Translation API: Translates text between languages.

How Agents Use Tools

Agents analyze a query’s context to pick the most relevant tool.

Examples of Tool Usage

● Math Question: "What is 7 × 6?"


○ The agent uses the calculator tool to return "42."
● Trivia Question: "What’s the tallest mountain in the world?"
○ The agent uses a search engine to find "Mount Everest."
● Language Question: "Translate ‘friend’ to Spanish."
○ The agent uses a translation tool to reply with "amigo."

Contextual Tool Selection

The agent dynamically selects a tool based on the query type.

Example

An agent with three tools (Calculator, Dictionary, Search Engine):

1. Math Query: "What’s 10 squared?"


○ Tool: Calculator
2. Vocabulary Query: "Define ‘serendipity.’"
○ Tool: Dictionary
3. Trivia Query: "Who founded Microsoft?"
○ Tool: Search Engine
Step-by-Step: Building an Agent

Here’s how to create your own agent in LangChain:

Step 1: Set Up Tools

Decide which tools your agent will use. For example:

● A calculator tool for math.


● A SerpAPI tool for internet search.

Step 2: Initialize the Agent

Link the tools to your agent and specify its type (e.g., Zero-shot).

Step 3: Test the Agent

Ask various questions to verify that the agent selects and uses tools correctly.

Example Code: LangChain Agent

Below is an example of creating an agent using LangChain:

Line-by-Line Explanation of the Code

Here’s a detailed breakdown of the code:

from langchain_community.utilities import SerpAPIWrapper

from langchain.agents import initialize_agent, AgentType, load_tools

from langchain_google_genai import ChatGoogleGenerativeAI


1. from langchain_community.utilities import SerpAPIWrapper:
○ Imports the SerpAPIWrapper utility, which is used to interact with the SerpAPI
tool for performing search engine queries.
2. from langchain.agents import initialize_agent, AgentType,
load_tools:
○ initialize_agent: Used to set up an agent by combining tools and a
language model.
○ AgentType: Enum that defines the type of agent to create (e.g.,
ZERO_SHOT_REACT_DESCRIPTION).
○ load_tools: A helper function to load predefined tools, such as serpapi.
3. from langchain_google_genai import ChatGoogleGenerativeAI:
○ Imports ChatGoogleGenerativeAI, which is LangChain's wrapper for
interacting with Google Generative AI models (like Gemini).

google_api_key = "your_google_api_key" # Replace with your Google API


key

model_name = "gemini-1.5-flash"

temperature = 0 # Adjust temperature for creativity

4. google_api_key:
○ The API key for authenticating with Google Generative AI.
○ Replace "your_google_api_key" with your actual API key from Google.
5. model_name = "gemini-1.5-flash":
○ Specifies the Google Generative AI model to use. gemini-1.5-flash is an
example of a fast-response model.
○ You can replace it with another supported model name if required.
6. temperature = 0:
○ Controls the randomness of the language model's output.
○ A lower value (e.g., 0) makes responses more deterministic, while a higher value
(e.g., 1) makes responses more creative.

llm = ChatGoogleGenerativeAI(

google_api_key=google_api_key,

model=model_name,

temperature=temperature

7. llm = ChatGoogleGenerativeAI(...):
○ Initializes the Google Generative AI language model.
○ Parameters:
■ google_api_key: Your API key for authentication.
■ model: Specifies which model to use (gemini-1.5-flash).
■ temperature: Sets the creativity level of responses.

tools = load_tools(["serpapi"],
serpapi_api_key="your_serpapi_api_key")

8. tools = load_tools(["serpapi"], ...):


○ Loads the SerpAPI tool, which enables the agent to perform real-time internet
searches.
○ Parameters:
■ ["serpapi"]: Specifies that the serpapi tool should be loaded.
■ serpapi_api_key: Your API key for SerpAPI. Replace
"your_serpapi_api_key" with your actual key.
agent = initialize_agent(

tools=tools,

llm=llm,

agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,

verbose=True

9. agent = initialize_agent(...):
○ Combines the tools (serpapi) and the language model (llm) to create an
agent.
○ Parameters:
■ tools: Passes the loaded tools (in this case, SerpAPI).
■ llm: The initialized language model (Google Generative AI).
■ agent: Specifies the type of agent to use. Here,
AgentType.ZERO_SHOT_REACT_DESCRIPTION:
■ A Zero-Shot Agent reacts to queries without requiring prior
examples.
■ It interprets the query, decides on the required tool, and generates
a response.
■ verbose=True: Enables detailed logging of the agent’s internal
decision-making process. Useful for debugging.

result = agent.run("Tell me the latest news about artificial


intelligence.")
print("Agent Result:", result)

10. result = agent.run(...):


○ Executes a query through the agent.
○ Parameters:
1. "Tell me the latest news about artificial
intelligence.": The input question/query for the agent.
○ The agent:
1. Analyzes the query.
2. Decides which tool(s) to use. In this case, it will likely use the SerpAPI
tool to search for the latest news about AI.
3. Generates and returns a response.
11. print("Agent Result:", result):
○ Prints the response generated by the agent.

What the Code Does

1. Setup:
○ Configures a Google Generative AI model and SerpAPI tool.
○ Combines them into an agent.
2. Functionality:
○ Allows the agent to:
■ Analyze the user's query.
■ Use the SerpAPI tool to retrieve real-time information from the web.
■ Generate a final, coherent response using the Google Generative AI
model.
3. Example Execution:
○ If you ask for the "latest news about artificial intelligence," the agent:
■ Uses SerpAPI to search the web for relevant news.
■ Processes the search results and formulates a response using the
language model.
■ Outputs the result.
This makes the agent dynamic, capable of answering a wide variety of queries by leveraging
both its tools and the language model.

Key Takeaways

● Flexibility: Agents dynamically decide which tools to use based on context.


● Scalability: Easily expand agents with new tools and capabilities.
● Applications: Agents are ideal for tasks like question answering, data retrieval, and
more.

By leveraging LangChain agents, you can build intelligent and adaptable applications that mimic
the decision-making processes of a real assistant.

You might also like