> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Adding Pyton REPL to Tool

> This guide extends a LangChain agent with Python REPL functionality for seamless data retrieval and computation.

In this guide, we'll extend a LangChain-based agent with **Python REPL** functionality. By combining the **Tavily Search Results** tool for information lookup with a Python REPL tool for on-the-fly calculations, your agent can handle both data retrieval and computation seamlessly.

<Callout icon="lightbulb" color="#1CB2FE">
  Make sure you have Python 3.8+ installed and the necessary packages (`langchain`, `langchain-experimental`, `langchain-openai`, `langchain-community`) available in your environment.
</Callout>

## Prerequisites

* Tavily API key stored in the `TAVILY_API_KEY` environment variable
* Access to OpenAI's Chat API via `langchain-openai`

<Callout icon="triangle-alert" color="#FF6B6B">
  Without a valid **TAVILY\_API\_KEY**, the search tool will fail to retrieve tournament data. Use `export TAVILY_API_KEY=your_api_key` to configure it.
</Callout>

## 1. Import Modules and Initialize Tools

```python theme={null}
from langchain_core.prompts.chat import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_experimental.tools import PythonREPLTool

from langchain.agents import create_tool_calling_agent
from langchain.agents import AgentExecutor

import os

# Set your Tavily API key
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")

search = TavilySearchResults()
python_repl = PythonREPLTool()
```

## 2. Build the Chat Prompt Template

```python theme={null}
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Think step by step before responding."),
    ("placeholder", "{chat_history}"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])
```

## 3. Initialize the Agent Executor

```python theme={null}
llm = ChatOpenAI()
tools = [search, python_repl]
message_history = ChatMessageHistory()

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
```

## 4. Example Queries

Below are common examples demonstrating search and computation capabilities.

| Tool         | Use Case              | Initialization          |
| ------------ | --------------------- | ----------------------- |
| search       | Fetch tournament data | `TavilySearchResults()` |
| python\_repl | Execute Python code   | `PythonREPLTool()`      |

1. **Tournament Schedule**
   ```python theme={null}
   response = agent_executor.invoke({"input": "When is the ICC Men's T20 World Cup scheduled?"})
   print(response["output"])
   ```

2. **Hosting Countries**
   ```python theme={null}
   response = agent_executor.invoke(
       {"input": "Which countries are hosting?"}, 
       config={"configurable": {"$session_id": "session"}}
   )
   print(response["output"])
   ```

3. **Date Calculation**
   ```python theme={null}
   response = agent_executor.invoke({
       "input": "Today's date is May 1st, 2024. How many days before the first match starts?"
   })
   print(response["output"])
   ```

## Under the Hood: Python REPL Execution

```python theme={null}
# Code executed in the Python REPL environment
from datetime import datetime

start_date = datetime(2024, 6, 1)
today_date = datetime(2024, 5, 1)
days_until_start = (start_date - today_date).days
print(days_until_start)
```

This code prints:

```text theme={null}
31
```

And the agent returns:

> There are 31 days left before the first match of the ICC Men's T20 World Cup 2024 starts on June 1, 2024.

By combining the Tavily search tool for tournament data and the Python REPL tool for on-the-fly math, the agent can answer complex queries accurately and interactively.

***

## Links and References

* [LangChain Documentation](https://langchain.readthedocs.io/)
* [OpenAI Chat API](https://platform.openai.com/docs/api-reference/chat)
* [Tavily Search Results Tool](https://github.com/langchain-community/langchain-community)

Stay tuned for more demos and advanced capabilities in upcoming articles!

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/530ad7de-8948-4806-8824-19eb10923d1d/lesson/36589ae2-a513-4802-a9c4-7890498a4018" />

  <Card title="Practice Lab" icon="installation" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/530ad7de-8948-4806-8824-19eb10923d1d/lesson/81d50dee-7ffb-4092-95c2-3f8b8b07686b" />
</CardGroup>
