LangChain Agents Guide
Agentby davila7 · Added 5mo ago
Claude
Install
npx claude-code-templates@latest --agent=cli-tool/components/skills/ai-research/agents-langchain/references --yesAdd to Claude
claude mcp add langchain-agents-guideAbout
LangChain Agents Guide
Complete guide to building agents with ReAct, tool calling, and streaming.
What are agents?
Agents combine language models with tools to solve complex tasks through reasoning and action:
- Reasoning: LLM decides what to do
- Acting: Execute tools based on reasoning
- Observation: Receive tool results
- Loop: Repeat until task complete
This is the ReAct pattern (Reasoning + Acting).
Basic agent creation
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def calculator(expression: str) -> str:
"""Evaluate a math expression."""
return str(eval(expression))
def search(query: str) -> str:
"""Search for information."""
return f"Results for: {query}"
# Create agent
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[calculator, search],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({
"messages": [{"role": "user", "content": "What is 25 * 17?"}]
})
print(result["messages"][-1].content)
Agent components
1. Model - The reasoning engine
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
# OpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# Anthropic (better for complex reasoning)
model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)
# Dynamic model selection
def select_model(task_complexity: str):
if task_complexity == "high":
return ChatAnthropic(model="claude-sonnet-4-5-20250929")
else:
return ChatOpenAI(model="gpt-4o-mini")
2. Tools - Actions the agent can take
from langchain.tools import tool
# Simple function tool
@tool
def get_current_time() -> str:
"""Get the current time."""
from datetime import datetime
return datetime.now().strftime("%H:%M:%S")
# Tool with parameters
@tool
def
Tags
FullStackaitmplclaude-code-templates