Agents

LangChain Agents

Build autonomous agents with LangChain tools and the create_react_agent interface.

LangChain Agents

LangChain provides high-level abstractions for building agents:

  • create_react_agent: Classic ReAct pattern
  • create_tool_calling_agent: Uses native tool calling APIs
  • AgentExecutor: Runs the agent loop with error handling
  • LangGraph: For complex multi-step agent workflows

Tool Creation

LangChain tools can be created from:

  • Plain functions with the @tool decorator
  • Pydantic models for structured inputs
  • Existing LangChain tools (search, calculator, etc.)

Built-in Tools

LangChain includes many pre-built tools:

  • DuckDuckGoSearchRun: Web search
  • WikipediaQueryRun: Wikipedia lookup
  • PythonREPLTool: Execute Python code
  • RequestsGetTool: HTTP requests

Example

python
from langchain_anthropic import ChatAnthropic
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, AIMessage

llm = ChatAnthropic(model="claude-3-5-haiku-20241022")

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

@tool
def convert_temperature(value: float, from_unit: str, to_unit: str) -> float:
    """Convert temperature between Celsius, Fahrenheit, and Kelvin.
    from_unit and to_unit should be 'celsius', 'fahrenheit', or 'kelvin'.
    """
    if from_unit == "celsius" and to_unit == "fahrenheit":
        return value * 9/5 + 32
    elif from_unit == "fahrenheit" and to_unit == "celsius":
        return (value - 32) * 5/9
    elif from_unit == "celsius" and to_unit == "kelvin":
        return value + 273.15
    elif from_unit == "kelvin" and to_unit == "celsius":
        return value - 273.15
    return value

@tool
def search_dictionary(word: str) -> str:
    """Look up the definition of a word. Returns a simple definition."""
    definitions = {
        "python": "A high-level programming language known for readability",
        "agent": "An autonomous system that perceives its environment and takes actions",
        "llm": "Large Language Model - an AI model trained on vast text data",
    }
    return definitions.get(word.lower(), f"Definition not found for '{word}'")

tools = [get_word_count, convert_temperature, search_dictionary]

# Create agent prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Use tools when they can help answer questions accurately."),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

# Create agent and executor
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=5,
    return_intermediate_steps=True
)

# Run agent
result = executor.invoke({
    "input": "How many words are in this sentence: 'The quick brown fox jumps over the lazy dog'? Also, what is 100°C in Fahrenheit?",
    "chat_history": []
})
print(result["output"])

# Multi-turn conversation
chat_history = []
for user_input in ["What does 'agent' mean?", "And what about 'llm'?"]:
    result = executor.invoke({"input": user_input, "chat_history": chat_history})
    chat_history.extend([HumanMessage(content=user_input), AIMessage(content=result["output"])])
    print(f"User: {user_input}")
    print(f"Agent: {result['output']}
")
Try it yourself — PYTHON