Building Agents with LangChain
Basic Agent
from langchain.agents import AgentExecutor, create_react_agent
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain import hub
# Define tools
@tool
def calculator(expression: str) -> str:
"""Calculate a mathematical expression."""
return str(eval(expression))
@tool
def get_weather(city: str) -> str:
"""Get current weather for a city."""
# In production, call a real weather API
import requests
resp = requests.get(f"https://wttr.in/{city}?format=3")
return resp.text
# Set up the agent
llm = ChatOpenAI(model="gpt-4", temperature=0)
tools = [calculator, get_weather]
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Run the agent
result = executor.invoke({
"input": "What's the weather in Tokyo? If the temperature is above 25°C, calculate 25 * 1.8 + 32 to convert to Fahrenheit"
})
print(result["output"])
Multi-Tool Research Agent
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
@tool
def search_arxiv(query: str) -> str:
"""Search academic papers on arXiv."""
import arxiv
results = arxiv.Search(query=query, max_results=3)
papers = []
for r in results.results():
papers.append(f"Title: {r.title}\nSummary: {r.summary[:200]}\n")
return "\n".join(papers)
@tool
def search_web(query: str) -> str:
"""Search the internet for current information."""
from tavily import TavilyClient
client = TavilyClient()
results = client.search(query)
return str(results["results"][:3])
@tool
def write_file(filename: str, content: str) -> str:
"""Write content to a file."""
with open(filename, "w") as f:
f.write(content)
return f"Successfully wrote to {filename}"
# Create agent with system prompt
prompt = ChatPromptTemplate.from_messages([
("system", "You are a research assistant. Search for information, "
"synthesize findings, and save reports to files."),
("human", "{input}"),
MessagesPlaceholder("agent_scratchpad"),
])
llm = ChatOpenAI(model="gpt-4", temperature=0)
tools = [search_arxiv, search_web, write_file]
agent = create_openai_tools_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = executor.invoke({
"input": "Research the latest advances in agentic AI systems. "
"Find 3 academic papers and 3 industry articles, then "
"write a summary report to 'agentic_ai_report.md'"
})