pythonintermediate

LangChain Agent with Tavily Web Search

Build a ReAct agent that searches the web in real-time using the Tavily search tool.

python
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.