Skip to main content

Python Interpreter

This component allows you to execute Python code with imported packages.

The Python Interpreter component can only import packages that are already installed in your Langflow environment. If you encounter an ImportError when trying to use a package, you need to install it first.

To install custom packages, see Install custom dependencies.

Use the Python Interpreter in a flow

  1. To use this component in a flow, in the Global Imports field, add the packages you want to import as a comma-separated list, such as math,pandas. At least one import is required.
  2. In the Python Code field, enter the Python code you want to execute. Use print() to see the output.
  3. Optional: Enable Tool Mode, and then connect the Python Interpreter component to an Agent component as a tool. For example, connect a Python Interpreter component and a Calculator component as tools for an Agent component, and then test how it chooses different tools to solve math problems. Python Interpreter and Calculator components connected to an Agent component
  4. Ask the agent an easier math question. The Calculator tool can add, subtract, multiple, divide, or perform exponentiation. The agent executes the evaluate_expression tool to correctly answer the question.

Result:


_10
Executed evaluate_expression
_10
Input:
_10
{
_10
"expression": "2+5"
_10
}
_10
Output:
_10
{
_10
"result": "7"
_10
}

  1. Give the agent complete Python code. This example creates a Pandas DataFrame table with the imported pandas packages, and returns the square root of the mean squares.

_12
import pandas as pd
_12
import math
_12
_12
# Create a simple DataFrame
_12
df = pd.DataFrame({
_12
'numbers': [1, 2, 3, 4, 5],
_12
'squares': [x**2 for x in range(1, 6)]
_12
})
_12
_12
# Calculate the square root of the mean
_12
result = math.sqrt(df['squares'].mean())
_12
print(f"Square root of mean squares: {result}")

The agent correctly chooses the run_python_repl tool to solve the problem.

Result:


_12
Executed run_python_repl
_12
_12
Input:
_12
_12
{
_12
"python_code": "import pandas as pd\nimport math\n\n# Create a simple DataFrame\ndf = pd.DataFrame({\n 'numbers': [1, 2, 3, 4, 5],\n 'squares': [x**2 for x in range(1, 6)]\n})\n\n# Calculate the square root of the mean\nresult = math.sqrt(df['squares'].mean())\nprint(f\"Square root of mean squares: {result}\")"
_12
}
_12
Output:
_12
_12
{
_12
"result": "Square root of mean squares: 3.3166247903554"
_12
}

If you don't include the package imports in the chat, the agent can still create the table using pd.DataFrame, because the pandas package is imported globally by the Python Interpreter component in the Global Imports field.

Pass inputs to the Python Interpreter

To pass inputs to the Python Interpreter component, you need to customize the component's code to add input fields. After the input field is added to the component code, the port becomes available for connections. For example, to connect a Text component and pass a URL value to the Python Interpreter component, do the following:

  1. Add a Python Interpreter component to your flow.

  2. To modify the Python Interpreter component's code, click Edit Code.

  3. To pass a URL input to the Python Interpreter component, make the following changes to the code:

    a. Add the URL input field to the inputs list. This creates the input port that other components can connect to.

    b. Update the get_globals method to extract the URL value and add it to the globals dictionary. This makes the url variable available in the component's Python code.

    c. Update the default Python code value to use the url variable.

    The following example demonstrates these modifications.

    Python code example

    _121
    import importlib
    _121
    _121
    from langchain_experimental.utilities import PythonREPL
    _121
    from lfx.custom.custom_component.component import Component
    _121
    from lfx.io import MultilineInput, Output, StrInput
    _121
    from lfx.schema.data import Data
    _121
    from lfx.schema.message import Message # Needed to extract text from Message objects
    _121
    _121
    class PythonREPLComponent(Component):
    _121
    display_name = "Python Interpreter"
    _121
    description = "Run Python code with optional imports. Use print() to see the output."
    _121
    documentation: str = "https://docs.langflow.org/python-interpreter"
    _121
    icon = "square-terminal"
    _121
    _121
    inputs = [
    _121
    StrInput(
    _121
    name="global_imports",
    _121
    display_name="Global Imports",
    _121
    info="A comma-separated list of modules to import globally, e.g. 'math,numpy,pandas'.",
    _121
    value="math,pandas",
    _121
    required=True,
    _121
    ),
    _121
    MultilineInput(
    _121
    name="python_code",
    _121
    display_name="Python Code",
    _121
    info="The Python code to execute. Only modules specified in Global Imports can be used. Use 'url' variable if URL input is connected.",
    _121
    value="print(f'URL: {url}')", # Updated to make the URL variable available to the Python code execution
    _121
    input_types=["Message"],
    _121
    tool_mode=True,
    _121
    required=True,
    _121
    ),
    _121
    # Add the URL input field to inputs list
    _121
    StrInput(
    _121
    name="url",
    _121
    display_name="URL",
    _121
    info="URL variable that can be used in Python code. Connect a Text component or enter manually.",
    _121
    value="",
    _121
    input_types=["Text", "Message"],
    _121
    required=False,
    _121
    ),
    _121
    ]
    _121
    _121
    outputs = [
    _121
    Output(
    _121
    display_name="Results",
    _121
    name="results",
    _121
    type_=Data,
    _121
    method="run_python_repl",
    _121
    ),
    _121
    ]
    _121
    _121
    def get_globals(self, global_imports: str | list[str]) -> dict:
    _121
    """Create a globals dictionary with only the specified allowed imports and input variables."""
    _121
    global_dict = {}
    _121
    _121
    try:
    _121
    if isinstance(global_imports, str):
    _121
    modules = [module.strip() for module in global_imports.split(",")]
    _121
    elif isinstance(global_imports, list):
    _121
    modules = global_imports
    _121
    else:
    _121
    msg = "global_imports must be either a string or a list"
    _121
    raise TypeError(msg)
    _121
    _121
    for module in modules:
    _121
    try:
    _121
    imported_module = importlib.import_module(module)
    _121
    global_dict[imported_module.__name__] = imported_module
    _121
    except ImportError as e:
    _121
    msg = f"Could not import module {module}: {e!s}"
    _121
    raise ImportError(msg) from e
    _121
    _121
    # Add the URL variable to the component's globals dictionary
    _121
    # Extract from Message object or use the string directly
    _121
    if hasattr(self, "url") and self.url:
    _121
    url_value = self.url.text if isinstance(self.url, Message) else str(self.url)
    _121
    if url_value:
    _121
    global_dict["url"] = url_value # Makes 'url' available in Python code
    _121
    self.log(f"URL variable set: {url_value}")
    _121
    _121
    except Exception as e:
    _121
    self.log(f"Error in global imports: {e!s}")
    _121
    raise
    _121
    else:
    _121
    self.log(f"Successfully imported modules: {list(global_dict.keys())}")
    _121
    return global_dict
    _121
    _121
    def run_python_repl(self) -> Data:
    _121
    try:
    _121
    # Extract Python code text if it's a Message object
    _121
    python_code_text = self.python_code
    _121
    if isinstance(python_code_text, Message):
    _121
    python_code_text = python_code_text.text if python_code_text.text else ""
    _121
    elif not isinstance(python_code_text, str):
    _121
    python_code_text = str(python_code_text)
    _121
    _121
    globals_ = self.get_globals(self.global_imports)
    _121
    python_repl = PythonREPL(_globals=globals_)
    _121
    result = python_repl.run(python_code_text)
    _121
    result = result.strip() if result else ""
    _121
    _121
    self.log("Code execution completed successfully")
    _121
    return Data(data={"result": result})
    _121
    _121
    except ImportError as e:
    _121
    error_message = f"Import Error: {e!s}"
    _121
    self.log(error_message)
    _121
    return Data(data={"error": error_message})
    _121
    _121
    except SyntaxError as e:
    _121
    error_message = f"Syntax Error: {e!s}"
    _121
    self.log(error_message)
    _121
    return Data(data={"error": error_message})
    _121
    _121
    except (NameError, TypeError, ValueError) as e:
    _121
    error_message = f"Error during execution: {e!s}"
    _121
    self.log(error_message)
    _121
    return Data(data={"error": error_message})
    _121
    _121
    def build(self):
    _121
    return self.run_python_repl

  4. To save the modifications, click Check & Save.

  5. Add a Text component to your flow and set its value, such as google.com.

  6. Connect the Text component's output to the new URL input field on your customized Python Interpreter component.

The Python Interpreter component can now use the url variable in the Python code that it executes.

Python Interpreter parameters

NameTypeDescription
global_importsStringInput parameter. A comma-separated list of modules to import globally, such as math,pandas,numpy.
python_codeCodeInput parameter. The Python code to execute. Only modules specified in Global Imports can be used.
resultsDataOutput parameter. The output of the executed Python code, including any printed results or errors.
Search