Use this file to discover all available pages before exploring further.
Agents are autonomous systems that use language models to choose a sequence of actions to take. Unlike chains with predetermined steps, agents dynamically decide which tools to use and in what order based on the input.
Modern LangChain agents are built using LangGraph, which provides more control and flexibility. The legacy AgentExecutor is maintained for backwards compatibility but new development should use LangGraph.
Reasoning: LLM analyzes the situation and decides next action
Action: Execute a tool with specific inputs
Repeat: Continue until task is complete
Finish: Return final answer
# Example agent loop flow:User: "What's the weather in SF and what should I wear?" ↓Agent: Calls weather_tool(location="San Francisco") ↓Tool Result: "72°F, sunny" ↓Agent: Analyzes result, generates clothing recommendation ↓Final Answer: "It's 72°F and sunny in SF. You should wear..."
from langchain_core.agents import AgentActionMessageLogfrom langchain_core.messages import AIMessageaction = AgentActionMessageLog( tool="search", tool_input="LangChain documentation", log="Searching for info", message_log=[AIMessage(content="I should search for this")])
Useful for chat models where you need the complete message context.See: /libs/core/langchain_core/agents.py:105
from langchain_core.agents import AgentFinishfinish = AgentFinish( return_values={"output": "The answer is 110"}, log="Final Answer: The answer is 110")
Fields:
return_values (dict): Final output values
log (str): Complete LLM response including reasoning
from langchain_core.tools import tool@tooldef risky_operation(value: int) -> str: """Operation that might fail.""" try: if value < 0: raise ValueError("Value must be positive") return f"Result: {value * 2}" except Exception as e: return f"Error: {str(e)}"# Agent receives error message and can retry or choose different approach
from langchain_core.prompts import ChatPromptTemplatefrom langgraph.prebuilt import create_react_agentsystem_prompt = """You are a helpful assistant.When using tools:1. Always explain your reasoning2. Use tools one at a time3. Verify results before answering"""model = ChatOpenAI(model="gpt-4")model = model.bind(system=system_prompt)agent = create_react_agent(model, tools)
# With LangGraph, state includes full message historyresult = agent.invoke({"messages": [("user", "Question")]})for message in result["messages"]: print(f"Type: {type(message).__name__}") print(f"Content: {message.content}") if hasattr(message, "tool_calls"): print(f"Tool calls: {message.tool_calls}")
Clear, detailed tool descriptions help the LLM choose the right tool:
@tooldef search(query: str) -> str: """Search the web for current information. Use this when you need: - Recent news or events - Real-time data - Information not in your training data Args: query: Specific search terms, be precise """ return search_api(query)
Limit tool count
Too many tools confuse the agent. Group related functions or use hierarchical agents:
# Instead of 20 individual tools:tools = [weather, stocks, news, ...]# Use specialized sub-agents:weather_agent = create_react_agent(model, [weather, forecast, alerts])finance_agent = create_react_agent(model, [stocks, crypto, forex])# Route to appropriate agent
Set iteration limits
Always configure max iterations to prevent runaway costs:
result = agent.invoke( input, config={"recursion_limit": 15} # Reasonable limit)
Validate tool inputs
Use Pydantic models for type safety:
from pydantic import BaseModel, Fieldfrom langchain_core.tools import toolclass SearchInput(BaseModel): query: str = Field(..., min_length=1, max_length=200) max_results: int = Field(default=5, ge=1, le=20)@tool(args_schema=SearchInput)def search(query: str, max_results: int = 5) -> str: """Search with validated inputs.""" return search_api(query, max_results)
The legacy AgentExecutor class is maintained for backwards compatibility but is deprecated. New agent development should use LangGraph for better control, observability, and debugging capabilities.