Introduction

AI Agents have gained remarkable popularity recently. I was both amazed and confused with the whole concept, and therefore decided to dive deep into the Langchain codebase to see how the Agents work under the hood. I set the dev environment up and followed the code execution of the basic MRKL agent.

I am thrilled to present this document. Its purpose is to provide you with a comprehensive understanding of how Langchain controls the operations of these remarkable Agents.

Important Note: I won’t consider much of llms and tools code that Langchain has. Stay tuned, perhaps I will make some documents about them!

Main Content

I have used the v0.0.266 version.

We will be investigating this simple snippet:

import os
from langchain.llms import OpenAI
from langchain.agents import AgentType, initialize_agent, load_tools

os.environ["OPENAI_API_KEY"] = "my api key. use yours:)"
llm = OpenAI(temperature=0.6)

tools = load_tools(["wikipedia", "llm-math"], llm=llm)

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

agent.run("When was Queen Elizabeth II born? What's her age right now in 2023? Square it and show the result")

I am specifically interested in code from libs/langchain/langchain/agents folder

We can notice that all agents are stored in libs/langchain/langchain/agents/types.py folder. This file contains this dictionary:

AGENT_TYPE = Union[Type[BaseSingleActionAgent], Type[OpenAIMultiFunctionsAgent]]

AGENT_TO_CLASS: Dict[AgentType, AGENT_TYPE] = {
    AgentType.ZERO_SHOT_REACT_DESCRIPTION: ZeroShotAgent,
    AgentType.REACT_DOCSTORE: ReActDocstoreAgent,
    AgentType.SELF_ASK_WITH_SEARCH: SelfAskWithSearchAgent,
    AgentType.CONVERSATIONAL_REACT_DESCRIPTION: ConversationalAgent,
    AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION: ChatAgent,
    AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION: ConversationalChatAgent,
    AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION: StructuredChatAgent,
    AgentType.OPENAI_FUNCTIONS: OpenAIFunctionsAgent,
    AgentType.OPENAI_MULTI_FUNCTIONS: OpenAIMultiFunctionsAgent,
}

The ZeroShotAgent is created in the snippet.

In the beginning, we create an agent in our sample using the initialize_agent.

Initialize Agent

File: libs/langchain/langchain/agents/initialize.py