AI agents combine LLMs with tools and decision-making logic to autonomously complete complex tasks.
Basic Agent Pattern
from langchain.agents import AgentExecutor, create_react_agent
from langchain.llms import OpenAI
from langchain import hub
# Define tools
from langchain.tools import Tool
def calculator(query):
return eval(query)
def search_web(query):
# Call search API
return f"Search results for: {query}"
tools = [
Tool(name="Calculator", func=calculator, description="Useful for math"),
Tool(name="Search", func=search_web, description="Search the web")
]
# Create agent
llm = OpenAI(temperature=0)
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Run agent
result = agent_executor.invoke({"input": "What is 25 * 4 plus 10?"})
ReAct (Reasoning + Acting)
Thought: I need to calculate this step by step
Action: Calculator
Action Input: 25 * 4
Observation: 100
Thought: Now I need to add 10
Action: Calculator
Action Input: 100 + 10
Observation: 110
Thought: I have the final answer
Final Answer: 110
Custom Tools
from langchain.tools import BaseTool
class DatabaseQueryTool(BaseTool):
name = "database_query"
description = "Query the database for information"
def _run(self, query: str) -> str:
# Execute database query
results = execute_sql(query)
return str(results)
class EmailSenderTool(BaseTool):
name = "send_email"
description = "Send an email to a recipient"
def _run(self, to: str, subject: str, body: str) -> str:
# Send email
send_email_api(to, subject, body)
return "Email sent successfully"
# Add to agent
tools = [DatabaseQueryTool(), EmailSenderTool()]
Multi-Agent Systems
# Coordinator agent
coordinator = Agent(
role="Project Manager",
goal="Coordinate tasks between agents",
tools=[]
)
# Specialized agents
researcher = Agent(
role="Researcher",
goal="Research information",
tools=[search_tool, scrape_tool]
)
writer = Agent(
role="Writer",
goal="Write content",
tools=[write_tool, edit_tool]
)
# Execute workflow
task = "Research AI trends and write a blog post"
result = coordinator.delegate(task, [researcher, writer])
AI agents enable autonomous task completion. Build sophisticated systems today!