f in x
LangChain Agents: Building Autonomous Agents with Tools and Memory — Hands-On Guide
> cd .. / HUB_EDITORIALE
Analisi dei dati e metriche

LangChain Agents: Building Autonomous Agents with Tools and Memory — Hands-On Guide

[2026-06-05] Author: Ing. Calogero Bono

You have an LLM that answers brilliantly but cannot fetch real-time data, perform calculations, or interact with your APIs. You need something that acts, not just talks. The LangChain agent is the answer: a system that decides which tools to use, in what order, and remembers conversation context. In this guide we build a working agent, with custom tools and memory, step by step. No abstract theory — just code you can copy, test, and adapt.

Why an agent instead of a simple chain

A chain executes a fixed sequence of steps: take input, pass to a prompt, get output. It is linear, predictable, but rigid. An agent, on the other hand, follows an observation-thought-action loop: it receives a task, chooses a tool, executes the action, observes the result, and decides the next step. It is like having an assistant who knows when to call an expert (tool) and when to reason alone.

Here at Meteora Web, we have applied this pattern in automation projects for SMEs: virtual assistants that check inventory, calculate quotes, and update CRMs. The result? Fewer manual interventions and faster responses. But beware: every LLM call costs time and money. Before deploying an agent to production, we always evaluate the ROI — just as we do with any digital tool.

Structure of a LangChain agent

An agent consists of four basic elements:

  • LLM: the brain that reasons and decides (e.g. GPT-4, Claude, Llama).
  • Prompt: instructions that describe how to use the tools, with examples and output format (typically ReAct style).
  • Tools: functions or APIs the agent can call. Each tool has a name, a description, and an associated function.
  • Memory: allows the agent to remember previous interactions. Without memory, every request starts from scratch.

The loop is managed by an AgentExecutor, which invokes the agent, executes the chosen tools, and repeats until a final answer is produced.

Creating a custom tool

A tool is simply a Python function with a clear description. LangChain provides decorators and classes to define them. Example: a tool that returns weather (simulated) for a city.

from langchain.tools import tool

@tool
def get_weather(city: str) -> str:
    """Returns the current weather for the specified city."""
    # Simulation: in production you would call an API
    weather = {
        "Rome": "Clear, 22°C",
        "Milan": "Cloudy, 18°C",
        "Palermo": "Sunny, 25°C"
    }
    return weather.get(city, "Data not available")

The docstring is crucial: the LLM reads it to understand when and how to use the tool. The more precise it is, the better the agent's decisions will be.

Adding memory

Memory transforms the agent from a static responder to a contextual interlocutor. LangChain offers different types: ConversationBufferMemory, ConversationSummaryMemory, etc. The simplest is the buffer, which keeps the entire chat history.

Integrating it requires two steps: (1) add the memory to the prompt as context variables, (2) pass the memory to the executor. Here is a complete example.

Building an agent with tools and memory

Let's start with a real case: an e-commerce assistant that can search for products (simulated) and remember customer preferences. At Meteora Web we have direct retail experience — we managed the ERP of a clothing store — and we know how valuable an agent that knows purchase history can be.

Installation and imports

pip install langchain langchain-openai
import os
from langchain.agents import AgentExecutor, create_react_agent
from langchain.tools import tool
from langchain.memory import ConversationBufferMemory
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate

Define the tools

@tool
def search_product(name: str) -> str:
    """Search for a product by name and return availability and price."""
    catalog = {
        "white t-shirt": {"price": 25, "available": True},
        "blue jeans": {"price": 60, "available": False},
        "running shoes": {"price": 120, "available": True}
    }
    product = catalog.get(name.lower())
    if not product:
        return f"Product '{name}' not found."
    status = "available" if product["available"] else "out of stock"
    return f"{name}: ${product['price']}, {status}."

@tool
def calculate_shipping(city: str) -> str:
    """Calculate shipping cost for an Italian city."""
    costs = {"Rome": 5, "Milan": 7, "Palermo": 10}
    cost = costs.get(city, 15)
    return f"Shipping cost for {city}: ${cost}"

Configure LLM and prompt

llm = ChatOpenAI(model="gpt-4", temperature=0, openai_api_key=os.getenv("OPENAI_API_KEY"))

prompt = PromptTemplate.from_template(
    """You are an e-commerce assistant. You have access to the following tools:
{tools}

Do not use tools unnecessarily. Answer clearly and completely.

Conversation context:
{chat_history}

User request: {input}

{agent_scratchpad}"""
)

Create memory and executor

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

tools = [search_product, calculate_shipping]

agent = create_react_agent(llm, tools, prompt)

executor = AgentExecutor(
    agent=agent,
    tools=tools,
    memory=memory,
    verbose=True,
    handle_parsing_errors=True
)

Test the agent

# First interaction
executor.invoke({"input": "Search for a white t-shirt and tell me the shipping cost to Palermo"})
# Output: search_product -> calculate_shipping -> answer

# Second interaction (with memory)
executor.invoke({"input": "What product did I search before?"})
# The agent should remember the white t-shirt thanks to memory

Note: the {agent_scratchpad} field is where the agent logs its intermediate thoughts and actions. It is handled automatically by LangChain.

Common errors and how to avoid them

Infinite loops: the agent keeps calling tools without finding an answer. Solution: limit the maximum number of iterations with max_iterations in the executor (e.g. max_iterations=5).

Overly vague tool descriptions: the LLM does not understand when to use them. Be specific: “Search the catalog by exact product name” is better than “Search product”.

Non-persistent memory: in production, use external memory (Redis, database) to maintain state across sessions. ConversationBufferMemory is only in-memory.

Unexpected costs: each tool call can generate multiple LLM rounds. Monitor token usage and set a maximum budget.

When an agent makes sense and when it does not

An agent is powerful but comes with costs: higher latency, extra tokens for reasoning, debugging complexity. We recommend it when:

  • The task requires dynamic decisions (e.g., multi-domain customer support).
  • Tools are numerous and change frequently.
  • The conversation must be contextual and multi-turn.

If you have a fixed flow (e.g., “receive email, extract data, write to DB”), a chain is simpler and cheaper. Do not use a cannon to kill a mosquito. In our experience, many clients start with complex agents only to simplify later when they discover that 90% of cases are linear.

Also, remember: owning your stack (open-source LLM, custom tools) often beats renting ready-made solutions, especially for sensitive data. At Meteora Web, we built a proprietary platform to manage social media presence for multiple clients — a similar choice, total control.

In summary — what to do now

  1. Install LangChain and an LLM provider (OpenAI, or Ollama for local models).
  2. Define 2-3 tools related to your domain: search product, calculate price, send email.
  3. Build an agent with buffer memory following the code above.
  4. Test with 5-10 real conversations and verify that the agent chooses the right tools.
  5. Measure the cost per conversation (estimated tokens) and compare it with the value generated (time saved, conversions).
  6. Evaluate switching to a chain for simpler cases.

For more details, check the official LangChain documentation on agents. If you want to understand how to integrate agents into a broader business workflow, read our guide on AI Automation for SMEs.

Sponsored Protocol

Ing. Calogero Bono

> AUTHOR_EXTRACTED

Ing. Calogero Bono

Co-founder di Meteora Web. Ingegnere informatico, sviluppo ecosistemi digitali ad alte prestazioni. AI, automazione, SEO tecnica e infrastrutture web. Scrivo di tecnologia per rendere complesso… semplice.

[ Read Full Dossier ]

Hai bisogno di applicare questa strategia?

Esegui il protocollo di contatto per iniziare un progetto con noi.

> INIZIA_PROGETTO

Sponsored

> MW_JOURNAL

> READ_ALL()