This guide teaches building a session-aware agent using the Tavily Search API in LangChain for step-by-step question answering.
In this guide, you’ll learn how to build a session-aware agent that leverages the Tavily Search API to answer questions step by step. We’ll set up message history, define a rich prompt template, instantiate an LLM and tools, and finally run the agent in a persistent session.
To maintain context across calls, wrap the executor with RunnableWithMessageHistory. In production, you can replace the in-memory store with Redis.
Copy
Ask AI
agent_chain = RunnableWithMessageHistory( agent_executor, # Map a session ID to the shared ChatMessageHistory instance lambda session_id: message_history, input_messages_key="input", history_messages_key="chat_history")
For scalable session storage, consider using a Redis-backed message history.
Pass a session_id with every call to preserve dialogue history and agent scratchpad.
Copy
Ask AI
# 1. Start the sessionresult = agent_chain.invoke( {"input": "hi!"}, config={"configurable": {"session_id": "session1"}})print(result["output"])# 2. Query the ICC Men's T20 2024 World Cup scheduleresp = agent_chain.invoke( {"input": "When is the ICC Men's T20 2024 World Cup scheduled?"}, config={"configurable": {"session_id": "session1"}})print(resp["output"])# 3. Ask which countries are hostingresp = agent_chain.invoke( {"input": "Which countries are hosting?"}, config={"configurable": {"session_id": "session1"}})print(resp["output"])# 4. Ask for days until first matchresp = agent_chain.invoke( {"input": "How many days before the first match starts?"}, config={"configurable": {"session_id": "session1"}})print(resp["output"])# → The LLM may approximate rather than calculate precisely.
The LLM’s arithmetic can be inaccurate. In the next section, we’ll add a Python REPL tool for exact calculations.
The agent effectively combines web search results and LLM reasoning for concise answers. To improve numeric accuracy (e.g., date calculations), integrate a Python REPL tool in the next lesson.