PythonTools enable an Agent to write and run python code.

Example

The following agent will write a python script that creates the fibonacci series, save it to a file, run it and return the result.

cookbook/tools/python_tools.py
from phi.agent import Agent
from phi.tools.python import PythonTools

agent = Agent(tools=[PythonTools()], show_tool_calls=True)
agent.print_response("Write a python script for fibonacci series and display the result till the 10th number")

Toolkit Params

ParameterTypeDefaultDescription
base_dirPathNoneSpecifies the base directory for operations. Default is None, indicating the current working directory.
save_and_runboolTrueIf True, saves and runs the code. Useful for execution of scripts after saving.
pip_installboolFalseEnables pip installation of required packages before running the code.
run_codeboolFalseDetermines whether the code should be executed.
list_filesboolFalseIf True, lists all files in the specified base directory.
run_filesboolFalseIf True, runs the Python files found in the specified directory.
read_filesboolFalseIf True, reads the contents of the files in the specified directory.
safe_globalsdict-Specifies a dictionary of global variables that are considered safe to use during the execution.
safe_localsdict-Specifies a dictionary of local variables that are considered safe to use during the execution.

Toolkit Functions

FunctionDescription
save_to_file_and_runThis function saves Python code to a file called file_name and then runs it. If successful, returns the value of variable_to_return if provided otherwise returns a success message. If failed, returns an error message. Make sure the file_name ends with .py
run_python_file_return_variableThis function runs code in a Python file. If successful, returns the value of variable_to_return if provided otherwise returns a success message. If failed, returns an error message.
read_fileReads the contents of the file file_name and returns the contents if successful.
list_filesReturns a list of files in the base directory
run_python_codeThis function runs Python code in the current environment. If successful, returns the value of variable_to_return if provided otherwise returns a success message. If failed, returns an error message.
pip_install_packageThis function installs a package using pip in the current environment. If successful, returns a success message. If failed, returns an error message.

Information