Back to AI App Dev Series

LangChain SDK Track Part 4: Agents & Tools

May 22, 2026 Wasil Zafar 45 min read

Build LangChain agents from scratch — AgentExecutor, the @tool decorator, tool binding with bind_tools(), built-in toolkits (Search, Python REPL, SQL), structured tool outputs, and the create_tool_calling_agent pattern for production agent systems.

Table of Contents

  1. Tool Creation
  2. Tool Binding
  3. Agent Types
  4. AgentExecutor
  5. Built-in Tools
  6. Production Patterns
  7. Summary & Next Steps
What You’ll Learn: LangChain agents go beyond chains by adding decision-making: the agent observes, thinks, and acts in a loop, choosing which tools to use at each step. This article covers agent architectures (ReAct, OpenAI function-calling, plan-and-execute), tool definition, and the agent executor that manages the loop. Think of a chain as a recipe (fixed steps), and an agent as a chef (decides what to cook based on what’s in the fridge).

1. Tool Creation

SDK Track Note: This is the LangChain SDK Track — a hands-on companion to Foundation Track Part 7 (Agents). Read that article first for agent concepts.

1.1 The @tool Decorator

from langchain_core.tools import tool

@tool
def calculate_bmi(weight_kg: float, height_m: float) -> str:
    """Calculate Body Mass Index given weight in kg and height in meters."""
    bmi = weight_kg / (height_m ** 2)
    if bmi < 18.5:
        category = "underweight"
    elif bmi < 25:
        category = "normal"
    elif bmi < 30:
        category = "overweight"
    else:
        category = "obese"
    return f"BMI: {bmi:.1f} ({category})"

# The tool automatically gets name, description, and schema from the function
print(f"Name: {calculate_bmi.name}")
print(f"Description: {calculate_bmi.description}")
print(f"Schema: {calculate_bmi.args_schema.schema()}")

1.2 StructuredTool Class

from langchain_core.tools import StructuredTool
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description="The search query")
    max_results: int = Field(default=5, description="Maximum number of results")
    date_filter: str = Field(default="all", description="Filter: today, week, month, all")

def search_function(query: str, max_results: int = 5, date_filter: str = "all") -> str:
    """Search the web for information."""
    # Simulated search
    return f"Found {max_results} results for '{query}' (filter: {date_filter})"

search_tool = StructuredTool.from_function(
    func=search_function,
    name="web_search",
    description="Search the web for current information",
    args_schema=SearchInput
)

result = search_tool.invoke({"query": "LangChain latest release", "max_results": 3})
print(result)
Real-World Application

Automated Data Analysis

An analytics firm built a LangChain agent that analyzes datasets on demand: it reads CSV files, writes and executes Python code for statistics, generates visualizations, and writes narrative summaries. Analysts describe what they want in plain English; the agent figures out the pandas/matplotlib code. Result: data exploration time reduced by 70%.

Agent LoopTool CallingCode Execution

3. Agent Types

3.1 create_tool_calling_agent

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor

@tool
def get_weather(city: str) -> str:
    """Get current weather for a city."""
    # Simulated API call
    return f"Weather in {city}: 22°C, partly cloudy"

@tool
def get_time(timezone: str) -> str:
    """Get current time in a timezone."""
    from datetime import datetime
    return f"Current time in {timezone}: {datetime.now().strftime('%H:%M')}"

# Setup
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [get_weather, get_time]

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant with access to tools."),
    MessagesPlaceholder("chat_history", optional=True),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad")
])

# Create agent
agent = create_tool_calling_agent(model, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Run
result = executor.invoke({"input": "What's the weather in London and what time is it there?"})
print(result["output"])

Summary & Next Steps

This completes the LangChain SDK implementation for the concepts covered in Part 7: Agents — Core of Modern AI Apps.

Try It Yourself: Build a ‘personal research assistant’ agent with 4 tools: web_search (Tavily), wikipedia_search, python_repl (for calculations), and file_writer. Ask it to: ‘Research the population of the 5 largest cities in Japan, calculate the total, and save a summary to research.md.’ Trace the agent’s thought process and count how many tool calls it makes.

Next in the LangChain SDK Track

Continue with LC Part 5: LangGraph Workflows.