- Goal: Combine factual search (Tavily) with exact computation (Python REPL).
- Outcome: The agent can perform multi-step workflows like “find the event start date” → “compute days until start” with reliable numeric results.
- LLMs are powerful at reasoning and retrieval but not always exact with arithmetic or programmatic logic.
- A Python REPL enables running actual code for date math, precise calculations, and custom logic, improving reliability of results.
Step 1 — Imports and tool initialization
Import the required modules and initialize the Tavily search and Python REPL tools. The consolidated, corrected initialization looks like this:
TavilySearchResults()provides web/factual search capability.PythonREPLTool()exposes a REPL that can run Python snippets returned by the LLM.- Store sensitive keys like
TAVILY_API_KEYas environment variables (e.g., usingos.getenv).
- The prompt keeps
chat_historyandagent_scratchpadplaceholders so the agent can use prior messages and intermediate reasoning. - Add or customize system instructions where appropriate for your use case (e.g., domain-specific constraints).
RunnableWithMessageHistorymaps asession_idto aChatMessageHistoryinstance so multiple requests in the same session share context.verbose=Trueoutputs the agent’s intermediate steps (tool calls and tool outputs) which is useful for debugging.
- The agent may call Tavily to find the start date (e.g., June 1, 2024).
- The agent then generates Python code to compute the date difference.
- The Python REPL executes the code and returns the exact result.
- The agent synthesizes a natural-language response that includes the computed value.
Using a Python REPL tool allows the agent to run exact computations (like date arithmetic, numeric calculations, or custom logic) instead of relying on the LLM to calculate, which improves accuracy.
Python REPL can execute arbitrary code. Only enable it in trusted environments and ensure you have safeguards for untrusted inputs.
- Use environment variables for API keys and avoid committing secrets.
- Limit Python REPL exposure to trusted sessions, or implement sandboxing and input validation.
- For more on LangChain tool calling and agents, see the official docs:
- LangChain Agents Documentation
- LangChain Tooling and Tools
- (If using Tavily, consult its API docs for authentication and usage.)