Langchain Agents

In LangChain, an Agent is an entity that can understand and generate text. These agents can be configured with specific behaviors and data sources and trained to perform various language-related tasks, making them versatile tools for a wide range of applications.

Langchain Agents Working:

Here’s a simplified breakdown of the process:

i) User Input: You provide instructions or ask a question in plain language.

ii) LLM Analysis: The Langchain agent utilizes an LLM to understand the intent behind your input.

iii) Action Determination: Based on the LLM’s analysis, the agent decides what actions to take. This might involve interacting with APIs, calling external tools, or retrieving information from various sources.

iv) Action Execution: The agent executes the chosen actions to complete the task or answer your question.

v) Feedback Loop (Optional): The results of the actions might be fed back to the LLM, allowing the agent to refine its understanding and potentially take further actions if needed.

Benefits of Langchain Agents:

  • Flexibility: Unlike traditional code-based automation, Langchain agents can adapt to dynamic situations. They can handle unforeseen circumstances and adjust their actions based on new information or user feedback.
  • Reduced Development Time: Building agents with Langchain often requires less coding expertise compared to traditional methods. The framework provides pre-built tools and a user-friendly interface for defining agent functionalities.
  • Improved User Experience: Interaction with Langchain agents feels natural as it happens through plain language.This makes it easier for users to access information, complete tasks, or get assistance without needing to learn complex scripting languages.

Examples of Setting Up LangChain Agents:

Install Libraries:

pip install langchain openai
pip install langchain_community

Example 1: Web Scraping Agent

A web scraping agent collects data from web pages.

  1. Import Libraries:
from langchain.chains import LLMChain # Import LLMChain instead of LangChain
from langchain.agents import Tool, AgentExecutor, ZeroShotAgent # Import AgentExecutor and ZeroShotAgent
from langchain.llms import OpenAI
import requests
from bs4 import BeautifulSoup

2. Define Web Scraping Tool:

def scrape_web(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    return soup.title.string if soup.title else 'No title found'

# Add a description to the Tool
tools = [Tool(
    name="WebScraper", 
    func=scrape_web, 
    description="A tool that scrapes websites and returns the title" 
)]

3. Create and Run Agent:

# Initialize an LLM
llm = OpenAI(temperature=0, openai_api_key='your openai key') 

# Create an LLMChain
from langchain.prompts import PromptTemplate
# Update the prompt to instruct the LLM to use the tool
prompt = PromptTemplate(
    input_variables = ["input"],
    template = """You have a tool called WebScraper that can scrape websites and return the title.
                 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 [WebScraper]
                 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!
                 
                 Question: {input}"""
)
llm_chain = LLMChain(llm=llm, prompt=prompt)

# Use ZeroShotAgent instead of Agent, and pass in the LLMChain
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools) 
# Pass handle_parsing_errors=True to allow the agent to retry on parsing errors
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
response = agent_executor.run("https://en.wikipedia.org/wiki/Baseball") 
print(response)

Example 2: Sentiment Analysis Agent

  1. Import Libraries:
from langchain.chains import LLMChain # Import LLMChain instead of LangChain
from langchain.agents import Tool, AgentExecutor, ZeroShotAgent # Import AgentExecutor and ZeroShotAgent
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate # Import PromptTemplate
import requests
from bs4 import BeautifulSoup
from textblob import TextBlob

2. Define Sentiment Analysis Tool:

def analyze_sentiment(text):
    blob = TextBlob(text)
    return blob.sentiment.polarity

# Add a description for the tool
tools = [Tool(
    name="SentimentAnalyzer", 
    func=analyze_sentiment, 
    description="A tool that analyzes the sentiment of a piece of text and returns a score between -1 and 1, where -1 is very negative and 1 is very positive."
)]

3. Create and Run Agent:

# Initialize the language model
llm = OpenAI(temperature=0, openai_api_key='your openai key') 

# Create a prompt template
prompt = PromptTemplate(
    input_variables = ["input", "agent_scratchpad"],
    template = """You are a helpful AI assistant. Analyze the sentiment of the input text using the SentimentAnalyzer tool.
    
    Input: {input}
    
    Agent Scratchpad: {agent_scratchpad}"""
)

# Create an LLMChain instance
llm_chain = LLMChain(llm=llm, prompt=prompt)

# Create a ZeroShotAgent instance
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True) 

# Use AgentExecutor to manage the agent's execution
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)

# Use the invoke method on the AgentExecutor instance
response = agent_executor.invoke("I love sunny days!") 
print(response)

Example 3: Translation Agent

A translation agent translates text between languages.

  1. Install and Import Libraries:
!pip install langchain openai
!pip install langchain_community
!pip install langchain openai deep-translator
!pip install langchain openai googletrans
from langchain.agents import Tool, AgentExecutor, ZeroShotAgent, Agent
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain # Import LLMChain
from googletrans import Translator
from deep_translator import GoogleTranslator

2. Define Translation Tool:

def translate_text(text, target_lang):
    # Use GoogleTranslator from deep-translator
    translator = GoogleTranslator(source='auto', target=target_lang)
    translation = translator.translate(text)
    return translation

# Define the translation tool
tools = [
    Tool(
        name="Translator",
        func=lambda x: translate_text(*x.split(";")),  # Split input and pass as arguments
        description="Useful for translating text to different languages. Input should be a text string and the desired target language in the format 'Translate <text> to <language_code>'. For example, 'Translate Hello to es' translates 'Hello' to Spanish.",
    )
]

3. Create and Run Agent:

# Initialize the language model (replace with your actual OpenAI API key)
llm = OpenAI(temperature=0, openai_api_key="your openai key")

# Define the prompt template
prompt = PromptTemplate(
    input_variables=["input"],
    template="""You are a helpful AI assistant that can translate text. You have access to the following tool:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the name of the tool you use
Action Input: the input to the tool, should be text and target language separated by ;
Observation: the output of the tool
... (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!

Question: {input}
""",
)

# Create the agent, passing in the LLMChain
llm_chain = LLMChain(llm=llm, prompt=prompt)

# Create a ZeroShotAgent instance
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)

# Use AgentExecutor to manage the agent's execution
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)

# Update the input to match the expected format
response = agent_executor.invoke({"input": "Translate Hello;hindi", "tools": tools})
print(response)

Related Posts

Setting Up Your First LangChain Project

LangChain offers a powerful framework for building applications that leverage large language models (LLMs) Here’s a step-by-step walkthrough to set up your first LangChain project: i. Install…

Introduction to LangChain

LangChain is an open-source framework designed to facilitate the development of applications powered by large language models (LLMs). It offers a suite of tools, components, and interfaces…

This Post Has One Comment

  1. 1win казино — популярная платформа для онлайн азартных игр. Оно предлагает широкий выбор слотов, настольных игр и ставок на спорт в удобном интерфейсе. Бонусы для новых игроков и регулярные акции делают игру выгодной и увлекательной. скачать 1win сегодня для скачивания приложения 1win сегодня. Стабильная работа сайта и быстрые выплаты делают 1win привлекательным выбором для любителей азарта.

Leave a Reply

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

Share via
Copy link