Skip to main content
This guide shows how to add a Python REPL tool to a LangChain agent so it can perform exact computations (for example, date arithmetic) while still using the Tavily search tool for factual lookups. The agent will call Tavily for web/factual queries and call the Python REPL to run precise code when numeric or programmatic results are needed. Overview
  • 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.
Why add a Python REPL
  • 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.
Table: Tools used 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:
Explanation:
  • 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_KEY as environment variables (e.g., using os.getenv).
Step 2 — Build the chat prompt template and assemble LLM + tools Create a chat prompt template to structure system instructions, conversation history, and the human prompt. Then instantiate the LLM and list the tools the agent can call.
Notes:
  • The prompt keeps chat_history and agent_scratchpad placeholders 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).
Step 3 — Create the agent, executor, and runnable with history Wrap the agent in an executor and a runnable that preserves chat history across calls. The example below enables verbose output so you can inspect tool invocations.
Behavior:
  • RunnableWithMessageHistory maps a session_id to a ChatMessageHistory instance so multiple requests in the same session share context.
  • verbose=True outputs the agent’s intermediate steps (tool calls and tool outputs) which is useful for debugging.
Step 4 — Example: factual query (uses Tavily) Invoke the agent with a simple factual question; the agent should use Tavily for the lookup.
Example output:
Step 5 — Example: multi-step query mixing search + Python REPL Ask a question that requires both a factual lookup and exact computation. Example: “Today’s date is May 1st, 2024. How many days before the first match starts?” Flow:
  1. The agent may call Tavily to find the start date (e.g., June 1, 2024).
  2. The agent then generates Python code to compute the date difference.
  3. The Python REPL executes the code and returns the exact result.
  4. The agent synthesizes a natural-language response that includes the computed value.
Invoke the agent:
Example of the Python snippet the agent might generate and execute:
Execution output:
Because the agent used Python for the arithmetic, the numeric result is exact and reliable; the agent can then present that result in natural language.
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.
Concise recap — final setup
Final notes and references
  • 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:
With this configuration the agent combines web/factual search (Tavily) and exact computation (Python REPL) to answer complex, multi-step questions reliably.

Watch Video

Practice Lab