Langchain Agents : Getting Started

Jordan Mungujakisa
3 min readNov 30, 2023

--

langchain agents : getting started
Photo by Growtika on Unsplash

Langchain agents have emerged as a captivating area of research, promising to revolutionize the way we interact with AI. These sophisticated language models, trained on massive datasets of text and code, possess the remarkable ability to generate human-quality text, translate languages, and even write different kinds of creative content.

The agents consist of mainly two parts;

  1. The tools the agents will use.
  2. The agent which decides which action to take.

Getting Started

This guide will help you create your first AI Agent, so let us dive straight into the code.

In order to get started, let us begin by installing the following dependencies

pip install langchain
pip install google-search-results

Then we need to import the neccesary modules

 from langchain.agents import Tool, AgentExecutor, BaseSingleActionAgent
from langchain.utilities import SerpAPIWrapper
from typing import Any, List, Tuple, Union
from langchain.schema import AgentAction, AgentFinish
import os

Defining the tool

Then, we define the tool that the agent will need and in this case we will use the SearchEngineAPIWrapper

search = SerpAPIWrapper()

# We can use mutiple tools but in this case we are using a single tool, the search tool
# name == refers to the name by which we refer to the tool later
# func == is the function that will be called when the tool is being used
# description == Describes what the tool does
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events",
return_direct=True,
)
]

Creating the agent

Next, we create an agent class which inherits from BaseSingleActionAgent therefore it performs a single action.

class FakeAgent(BaseSingleActionAgent):

#Indicates that the agent expects an input labelled "Input" when running
@property
def input_keys(self) -> List[str]:
return ["input"]

# This method takes intermediate_steps and keyword arguments as parameter
# It returns either an AgentAction or an AgentFinish
# In this case it returns an AgentAction and uses the Search tool
# and uses the value of "input" in the kwargs dictionary as the tool_input
# then it logs an empty string
def plan(self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) -> Union[AgentAction, AgentFinish]:
return AgentAction(tool="Search", tool_input=kwargs["input"], log="")

# This is an asynchronous version of the plan method.
async def aplan(self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) -> Union[
AgentAction, AgentFinish]:
return AgentAction(
tool="Search",
tool_input=kwargs["input"],
log=""
)

**kwargs: is a way to collect all additional keyword arguments into a dictionary called kwargs

@property decorator is used to define a method that can be accessed like an attribute.

Then we create an instance of our FakeAgent class we defined above;

agent = FakeAgent()

Configuring the Agent Executioner

The agent executioner is responsible for running the agent and coordinating the interaction with the tools:

agent_executor = AgentExecutor.from_agent_and_tools(
agent=agent,
tools=tools,
verbose=True
)

To run the agent with a search query, use the run method:

agent_executor.run("What is the current population of Uganda?")

Obtaining a SERP API Key

To use the Search Engine API wrapper, you will need to obtain an API key from https://serpapi.com/dashboard register for an account if you do not have one and obtain an api key.

Then you can set the API key as an environment variable:

os.environ["SERPAPI_API_KEY"] = "<your_serpapi_key>"

Changes made to the os.environ are only valid for the duration of your python process

Then run the code

Expected output

langchain agent execution output

To view the source code used for in this blog, you can check out this repository: https://github.com/jordan-jakisa/langchain-agent

--

--

Jordan Mungujakisa

Mobile app alchemist who is trying to transmute elegant designs, into elegant code, into beautiful mobile app experiences.