Runtime Exception Handling
Runtime Exception Handling
When using Udility Diffuser, several factors—ranging from environment configuration to remote API availability—can impact the image generation process. The library uses standard Python exceptions to signal these issues.
Environment Configuration Errors
The most common failure occurs during initialization if the required API credentials are missing.
- Exception:
EnvironmentError - Trigger: Raised when the
OPENROUTER_API_KEYenvironment variable is not set. - Resolution: Ensure you have exported your key before importing the library or within your script before calling any diffuser functions.
import os
# This must be set before calling Udility functions
os.environ['OPENROUTER_API_KEY'] = 'your_api_key_here'
API and Generation Failures
The generation process involves two distinct calls to the Meta Llama-3.5 model (via OpenRouter). If the service is unreachable or the model fails to respond, the library raises a RuntimeError.
- Exception:
RuntimeError - Common Messages:
Failed to get detailed instructions: <error_detail>Failed to generate SVG code: <error_detail>
- Causes:
- Invalid or expired OpenRouter API key.
- Network connectivity issues.
- API rate limits exceeded.
- Remote model downtime.
Rendering and Display Errors
Once the SVG code is generated, it must be converted to a PNG and rendered to the screen. Failures here usually relate to the content of the generated SVG or local system dependencies.
- Exception:
RuntimeError - Common Messages:
Failed to convert SVG to PNG: <error_detail>: Occurs if the LLM generates syntactically invalid SVG code thatcairosvgcannot parse.Failed to display image: <error_detail>: Occurs if there is an issue withmatplotliborPillowrendering the resulting file.
Implementation Example: Defensive Coding
To ensure your application remains stable during generation, it is recommended to wrap the generate_image_from_text call in a try-except block:
from Udility import diffuser
prompt = "A diagram of the human heart"
try:
diffuser.generate_image_from_text(prompt, output_filename="heart_diagram.png")
print("Image generated successfully.")
except EnvironmentError as env_err:
print(f"Configuration Error: {env_err}")
except RuntimeError as run_err:
print(f"Generation or Rendering Error: {run_err}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Summary of Exceptions
| Exception | Phase | Description |
| :--- | :--- | :--- |
| EnvironmentError | Initialization | Missing OPENROUTER_API_KEY in environment variables. |
| RuntimeError | Inference | Failure to communicate with the Llama-3.5 model via OpenRouter. |
| RuntimeError | Processing | Failure to convert the raw SVG string into a valid PNG image. |
| RuntimeError | Display | Failure to open or plot the image file using matplotlib. |