# Python Backend Code

The Python Backend Code step allows you to write Python code that will be run on the backend. The common use cases for the action step are data transforming and mapping, as well as execution of machine learning-related functions.

You can use a number of **pre-installed libraries** to utilize their functionality within your code:

```python
    abc,
    array,
    asyncio,
    azure-cosmos,
    base64,
    bs4,
    bson,
    builtins,
    collections,
    charset_normalizer,
    dateutil,
    errno,
    geopy,
    google.protobuf,
    gc,
    jinja2,
    jira,
    jwt,
    machine,
    math,
    matplotlib,
    music,
    neopixel,
    numpy,
    openai,
    packaging,
    pandas,
    power,
    pypdf,
    pytz,
    query7,
    radio,
    random,
    requests,
    rsa,
    scipy,
    seaborn,
    sklearn,
    speech,
    struct,
    tabulate,
    time,
    types,
    typeshed,
    typing,
    typing_extensions,
    uarray,
    ucollections,
    uerrno,
    urandom,
    ustructu,
    usys,
    utime,
    yaml,
    datetime,
    llama_index,
    tiktoken
```

## Variables in the code

If you want to use app variables in the Python code step, you must add them to the **Variables** section and NOT use directly in the code.&#x20;

<figure><img src="https://837703843-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUX6zPRMFFK0yrTghj7cY%2Fuploads%2Fhgev4frb8OFqtlx11XAj%2FCleanShot%202025-03-26%20at%2013.03.41%402x-min.png?alt=media&#x26;token=19199f36-053f-4f41-916b-2a1391f9f216" alt=""><figcaption></figcaption></figure>

There, you can pass values from UI components using `{{ui.input.value}}`.\
You can also use some **predefined variables** to access the result of the previous step or to get user-related information:

```python
# result of the previous step
return data

# error response of the previous step
return error

# incoming action params, passed in by components,
# the Execution/Loop action steps or when calling the action from the code
return params

# get roles of the current user
return user.get('roles')
```

While `data` and `error` are specific to a particular step, `params` is available in all steps.

### Merging results of multiple steps

In some cases, you may need to merge the results of multiple steps into a single object. This must also be done using the **Variables** section - pass this information to Python and access the output of any previous step using `{{steps.<step_name>.data}}`.

## Importing external modules

To import external libraries, such as *NumPy* or *Pandas*, you can use the `import` statement in your Python code. These libraries provide a wide range of useful functions and tools for data manipulation and analysis.

Here's an example of how to import *NumPy*:

```python
import numpy as np

# Now you can use NumPy functions and tools in your code, for example:
my_array = np.array([1, 2, 3])
```

Similarly, here's an example of how to import *Pandas*:

```python
import pandas as pd

# Now you can use Pandas functions and tools in your code, for example:
my_dataframe = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
```

## Data transformation

If the API returns its data in a different format than expected for the components, you can use the Python Backend Code step to transform it. \
Python offers several built-in methods for transforming data, such as `map(),` `filter()`, and `reduce()`.  For example, to add a new key to a list of dictionaries you can use the following code:

```python
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
new_data = [{'name': d['name'], 'age': d['age'], 'is_adult': d['age'] >= 18} for d in data]
```

This creates a new list of dictionaries with an additional key `is_adult` that is *true* if the age key is greater than or equal to 18. \
You can also use functions from external libraries such as NumPy and Pandas for more complex transformations.

## Debugging errors

In case the code is failing or produces unexpected results:

* [x] Make sure no linter errors are present in the code (exclamation mark in the left gutter).
* [x] Check the result of the previous step (the `data` variable) and of other variables (for example, `params`).
* [x] Comment out the code and add `return data` to see if the data is in the expected format.
* [x] Use `print` to print the data to the console (*Logs* tab at the bottom of the action):

```python
# commented to test
# if length(data) > 10:
#   return data
# 

print(data)
```
