AI Insights Blogs
HomeBlogsAboutContact
Explore Blogs
General

Building Your First AI Agent with Python and LangChain

A hands-on tutorial showing you how to build a real AI agent that can search the web, run Python code, and answer complex questions — step by step with LangChain and GPT-4.
May 19, 2026

12 min read

7.8k views

612
289
0

Why LangChain?

LangChain is the most widely-adopted framework for building LLM-powered applications. Its agent module gives you a clean abstraction over the tool-selection → execution → observation loop, so you can focus on what your agent should do rather than plumbing.

Setting Up

pip install langchain langchain-openai langchain-community duckduckgo-search
export OPENAI_API_KEY="sk-..."

Defining Tools

Tools are functions your agent can call. LangChain provides dozens out of the box — web search, Python REPL, Wikipedia — and custom ones are trivial:

from langchain.tools import tool

@tool
def get_word_count(text: str) -> int:
    """Count the number of words in a text string."""
    return len(text.split())

Creating the Agent

from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent, AgentExecutor
from langchain_community.tools import DuckDuckGoSearchRun
from langchain import hub

llm      = ChatOpenAI(model="gpt-4o", temperature=0)
tools    = [DuckDuckGoSearchRun(), get_word_count]
prompt   = hub.pull("hwchase17/react")
agent    = create_react_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

Running Your First Agent

result = executor.invoke({
    "input": "What is the latest news about AI agents? Summarise in 3 bullet points."
})
print(result["output"])

With verbose=True you watch every Thought → Action → Observation in real time — invaluable for debugging.

Adding Memory

from langchain.memory import ConversationBufferWindowMemory

memory   = ConversationBufferWindowMemory(memory_key="chat_history", k=5, return_messages=True)
executor = AgentExecutor(agent=agent, tools=tools, memory=memory)

Always set max_iterations=10 and max_execution_time=60 in development. Unconstrained agents burn through API credits fast.

Common Pitfalls

  • Infinite loops: Set hard limits on iterations and execution time.
  • Tool errors: Wrap functions in try/except and return meaningful error strings.
  • Prompt injection: Sanitise web content before passing it to agent context.
  • Cost overruns: Use gpt-4o-mini for development, gpt-4o for production.
Tags
AI Agents
Python
LangChain
Tutorial


Other Articles
Unlocking the Potential of Tool-Augmented LLMs: Giving AI Agents the Ability to Browse and Compute
Unlocking the Potential of Tool-Augmented LLMs: Giving AI Agents the Ability to Browse and Compute
4 min