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=10andmax_execution_time=60in 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.