Python Code

What is the Python Node?

The Python node in Stack AI lets you write and execute custom Python code as part of your workflow. It’s perfect for advanced data processing, custom logic, or integrating with APIs and libraries not natively supported by Stack AI. This node gives you the flexibility of Python right inside your automated workflow.


Key Features

  • Custom Python Execution: Write and run any Python code within your workflow.

  • Multiple Inputs: Access results from any connected nodes as Python variables.

  • Pre-Imported Libraries: Common libraries like pandas, numpy, requests, and more are available by default—no need to import them manually.

  • Flexible Output: The value you assign to the output variable (or return) becomes the node’s output, which can be used by downstream nodes.

  • Templates Support: You can use Template nodes to format and combine outputs from the Python node and other nodes, making your results more readable and structured.

  • Run Code Independently: You can run the Python node by itself to test your code, without executing the entire workflow. This is useful for debugging and rapid iteration.


How the Python Node Works

Input Variables

  • Each connected node’s output is available as a variable in your Python code.

  • The variable name is the node ID with dashes replaced by underscores. For example, if you connect a node with ID llm-0, you can access its output as llm_0.

Output Handling

  • The value of the variable output (or the value returned by a return statement) is passed to downstream nodes.

  • Best Practice: Use a return statement for clarity and reliability.


Pre-Imported Python Libraries

You do not need to import common libraries—they are already available. Do not write import statements in your code, as this may cause errors.

Available libraries include:

  • import json

  • import pandas as pd

  • import io

  • import requests

  • import tiktoken

  • from fuzzywuzzy import fuzz

  • from tabulate import tabulate

  • import datetime

  • import sklearn

  • import aiohttp

  • import matplotlib.pyplot as plt

  • import seaborn as sns

  • import asyncio

  • import base64

  • import time

  • import re

  • import random

  • import numpy as np

  • import plotly.express as px

  • import plotly.graph_objects as go

  • import weaviate


Example Usage

Suppose you want to send a message to a hypothetical API endpoint (e.g., https://api.example.com/message) using user input from your input node (in-0). The Python node will:

  1. Read the user’s message from the input node.

  2. Construct a JSON payload for the API.

  3. Send a POST request using requests.

  4. Return the API’s response (as text or JSON).


Example Python Node Code

# Assume in_0 contains the user's message from the input node
user_message = in_0

# Construct the request payload
payload = {
    "message": user_message,
    "sender": "StackAI Workflow"
}

# Set the API endpoint URL
url = "https://api.example.com/message"

# Optionally, set headers (e.g., for JSON)
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"  # Remove if not needed
}

# Send the POST request
response = requests.post(url, json=payload, headers=headers)

# Check for success and return the result
if response.status_code == 200:
    # If the API returns JSON, you can parse it:
    return response.json()
else:
    # Return error details
    return f"Error {response.status_code}: {response.text}"

How This Works

  • in_0: This variable contains the output from your input node (in-0). In Stack AI, you access it as in_0 (dashes replaced by underscores).

  • payload: The body of the request, constructed using the user’s input.

  • requests.post: Sends the POST request to the API endpoint.

  • headers: Optional, but often needed for APIs (especially for JSON and authentication).

  • response.json(): Parses the API’s JSON response and returns it to downstream nodes.

  • Error handling: If the request fails, the error code and message are returned.

Customization Tips

  • Change the url to your actual API endpoint.

  • Adjust the payload structure to match your API’s requirements.

  • Add or remove headers as needed (e.g., for authentication).

  • You can use any HTTP method (get, post, put, etc.) supported by requests.


Real-World Use Cases

  • Sending user feedback to a backend service.

  • Creating a new record in a database via a REST API.

  • Triggering a webhook with dynamic data from your workflow.


Running the Python Node Independently

You can run the Python node by itself to test your code, without executing the entire workflow. This is especially useful for debugging or when you want to quickly check the output of your code before connecting it to other nodes.


Best Practices

  • No Import Statements: All common libraries are pre-imported.

  • Use Return Statements: Always use return to specify the output.

  • Variable Naming: Use node IDs with dashes replaced by underscores to access inputs.

  • Debugging: Test your code with sample inputs to ensure reliability.

  • Leverage Templates: Use Template nodes to format and present your Python node’s output in a user-friendly way.


Frequently Asked Questions

1. Can I use external Python packages?

Only the pre-imported libraries are available. If you need a specific package, check if it’s already included.

2. How do I access inputs from other nodes?

Connect the desired node to your Python node. Its output will be available as a variable named after its node ID (dashes replaced by underscores).

3. What happens if my code has an error?

The workflow will stop at the Python node, and you’ll see an error message in the node’s output.

4. Can I test my Python code without running the whole workflow?

Yes! You can run the Python node independently to test and debug your code. Click Run Code at the top right.


Conclusion

The Python node in Stack AI unlocks limitless customization for your AI workflows. Whether you need to process data, apply business logic, or integrate with external systems, the Python node gives you the flexibility and power of Python—right inside your automated workflow. Combine it with Template nodes for beautiful, structured output, and take advantage of the ability to run and test your code independently for a smooth development experience.


Last updated

Was this helpful?