Using External Libraries

Your Noventa project is a standard Python environment, which means you can import and use any external library just as you would in any other Python project. Install packages using pip and add them to your requirements.txt file for dependency management.

Installation

Add libraries to your project by installing them with pip:

BASH
pip install requests openai pillow

Then add them to requirements.txt:

REQUIREMENTS.TXT
requests==2.31.0
openai==1.3.0
pillow==10.0.0

Example: Using the OpenAI API

Once a library is installed, you can import it directly into your component's _logic.py file to add powerful functionality.

Here is an example of a component that uses the OpenAI API to generate text based on a prompt. The component has a simple form to take user input and displays the result.

PYTHON
# your_component_logic.py
import os
from openai import OpenAI

# Best practice: Load API key from environment variables or a config file.
# client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
client = OpenAI(api_key="YOUR_API_KEY_HERE")

def load_template_context(request, session, db, **props):
    """
    Handles the initial GET request.
    Returns empty strings for prompt and completion on first load.
    """
    return {"completion": "", "prompt": ""}

def action_generate_text(request, session, db, **props):
    """
    Handles the form submission and calls the OpenAI API.
    """
    prompt = request.form.get("prompt", "Tell me a joke.")
    completion_text = ""

    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
            ]
        )
        completion_text = response.choices[0].message.content
    except Exception as e:
        completion_text = f"An error occurred: {e}"

    # Return the result to be displayed on the page
    return {"completion": completion_text, "prompt": prompt}

The corresponding _template.html for this component would have a form that triggers the generate_text action and a place to display the completion variable.

YOUR_COMPONENT_TEMPLATE.HTML
<!-- In your_component_template.html -->
<form method="POST">
    <input type="hidden" name="action" value="generate_text">
    <label for="prompt">Enter your prompt:</label>
    <textarea name="prompt" class="w-full p-2 border rounded">{{ prompt or "" }}</textarea>
    <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded mt-2">Generate</button>
</form>

{% if completion %}
<div class="mt-6 p-4 bg-gray-100 rounded">
    <h3 class="font-semibold">API Response:</h3>
    <p>{{ completion }}</p>
</div>
{% endif %}