langchain/docs/extras/integrations/tools/python.ipynb

104 lines
2.5 KiB
Plaintext
Raw Normal View History

{
"cells": [
{
"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": "0196a12d-f716-4622-84e4-86fc27fa797c",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import Tool\n",
"from langchain.utilities import PythonREPL"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "b4058942-c31f-45c6-8bb7-30402f6cc193",
"metadata": {},
"outputs": [],
"source": [
"python_repl = PythonREPL()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b1bcfa15-ff35-49bf-a986-c40eec3b65fb",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Python REPL can execute arbitrary code. Use with caution.\n"
]
},
{
"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": 4,
"id": "488542d8-5566-4f28-aaf7-b28a3373ab62",
"metadata": {
"tags": []
},
"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.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}