{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "984a8fca",
   "metadata": {},
   "source": [
    "# Python REPL\n",
    "\n",
    "Sometimes, for complex calculations, rather than have an LLM generate the answer directly, it can be better to have the LLM generate code to calculate the answer, and then run that code to get the answer. In order to easily do that, we provide a simple Python REPL to execute commands in.\n",
    "\n",
    "This interface will only return things that are printed - therefore, if you want to use it to calculate an answer, make sure to have it print out the answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f6593089",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import Tool\n",
    "from langchain.utilities import PythonREPL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6f21f0a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "python_repl = PythonREPL()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7ebbbaea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2\\n'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "python_repl.run(\"print(1+1)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54fc1f03",
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can create the tool to pass to an agent\n",
    "repl_tool = Tool(\n",
    "    name=\"python_repl\",\n",
    "    description=\"A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\",\n",
    "    func=python_repl.run,\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
