AI News

Building AI Agents with LangChain: A Practical Guide

ekaji
June 13, 2026
4 min read
0
Building AI Agents with LangChain: A Practical Guide

AI agents are transforming how we interact with machine learning models. Unlike simple chatbots that respond to single prompts, agents can reason, use tools, and maintain context over multiple steps. LangChain, a popular framework for building LLM-powered applications, provides a robust foundation for creating such agents. In this guide, we'll walk through building a practical AI agent step by step.

What Are AI Agents?

An AI agent is an autonomous system that can perceive its environment, make decisions, and take actions to achieve a goal. In the context of LLMs, an agent typically uses a language model as its reasoning engine, selects from a set of available tools (like web search, calculators, or databases), and executes actions iteratively until the task is complete.

Setting Up Your Environment

First, install LangChain and necessary dependencies. We'll use OpenAI's GPT-4 for reasoning and a few simple tools.

pip install langchain openai python-dotenv

Create a .env file with your OpenAI API key:

OPENAI_API_KEY=your_key_here

Creating Custom Tools

Tools are the actions an agent can perform. LangChain provides a Tool class that wraps a function with metadata. Let's create two tools: a simple calculator and a web search tool (we'll simulate the search).

from langchain.tools import Tool
import requests

def calculator(expression: str) -> str:
    try:
        result = eval(expression)
        return str(result)
    except:
        return "Invalid expression"

calculator_tool = Tool(
    name="Calculator",
    func=calculator,
    description="Useful for mathematical calculations. Input should be a mathematical expression."
)

def search(query: str) -> str:
    # Simulated search; in production, use a real search API
    return f"Results for '{query}': LangChain is a framework for developing LLM applications."

search_tool = Tool(
    name="WebSearch",
    func=search,
    description="Search the web for current information. Input should be a search query."
)

tools = [calculator_tool, search_tool]

Building the Agent

LangChain's initialize_agent function creates an agent from a language model and a list of tools. We'll use the "zero-shot-react-description" agent type, which uses the ReAct framework (Reasoning + Acting).

from langchain.agents import initialize_agent, AgentType
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(model="gpt-4", temperature=0)

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

Adding Memory

Agents often need to remember previous interactions. LangChain provides memory classes like ConversationBufferMemory that store the chat history.

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

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

Running the Agent

Now let's test our agent with a multi-step task.

response = agent.run("What is 25 * 4 + 10? Also, search for LangChain updates.")
print(response)

You should see the agent's reasoning process: it first decides to use the calculator, then the web search tool, and finally combines the results.

Advanced: Custom Agent with Multiple Tools

For more complex scenarios, you can create a custom agent using LangChain's AgentExecutor and Agent classes. This gives you full control over the prompt and tool selection logic.

from langchain.agents import AgentExecutor, ZeroShotAgent
from langchain.prompts import PromptTemplate

prefix = """You are an AI assistant. You have access to the following tools:
{tools}

Use the following format:
Question: the input question
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
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
"""

suffix = """Begin!

Question: {input}
Thought:{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(
    tools,
    prefix=prefix,
    suffix=suffix,
    input_variables=["input", "agent_scratchpad"]
)

llm_chain = LLMChain(llm=llm, prompt=prompt)
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)

agent_executor.run("What's the capital of France? Use the search tool.")

Best Practices and Pitfalls

  • Tool Descriptions Matter: The agent relies on tool descriptions to decide which tool to use. Be specific.
  • Error Handling: Use handle_parsing_errors=True to avoid crashes when the LLM outputs malformed JSON.
  • Limit Iterations: Set max_iterations to prevent infinite loops.
  • Cost Management: Each step consumes tokens. Monitor usage.

Conclusion

LangChain simplifies building AI agents by abstracting the complex orchestration logic. With tools, memory, and customizable prompts, you can create agents that perform real-world tasks. Start small, test thoroughly, and gradually add complexity. The future of AI is autonomous, and LangChain is your toolkit to build it.

Sponsored Content