pythonintermediate
LangChain Agent with Tavily Web Search
Build a ReAct agent that searches the web in real-time using the Tavily search tool.
pythonPress ⌘/Ctrl + Shift + C to copy
from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import os
os.environ['TAVILY_API_KEY'] = 'YOUR_TAVILY_API_KEY'
tools = [TavilySearchResults(max_results=3)]
llm = ChatOpenAI(model='gpt-4o-mini')
prompt = ChatPromptTemplate.from_messages([
('system', 'You are a helpful assistant. Use web search to find current information.'),
('human', '{input}'),
MessagesPlaceholder('agent_scratchpad'),
])
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = executor.invoke({'input': 'What is the latest version of Python?'})
print(result['output'])Use Cases
- web search AI
- real-time information
- research agents
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
LangChain Tool-Using Agent
Build a LangChain agent with custom tools for web search, calculator, and Python REPL.
Best for: AI agents
#langchain#agent
pythonadvanced
LangChain SQL Database Agent
Create an AI agent that answers natural language questions by querying a SQL database.
Best for: NL2SQL
#langchain#sql
pythonadvanced
LangChain ReAct Agent Pattern
Implement a ReAct (Reason+Act) agent that thinks step-by-step before calling tools.
Best for: reasoning agents
#langchain#react
pythonadvanced
LangChain Agent with Persistent Memory
Build an AI agent that persists conversation context across sessions using LangChain memory stores.
Best for: persistent agents
#langchain#agent