Overview of the NeMo Guardrails Python APIs
The NeMo Guardrails library Python API provides two core classes for running guardrails:
RailsConfig: Loads and manages guardrails configuration from files or content.LLMRails: The main interface for generating responses with guardrails applied.
Upon initializing the core classes (RailsConfig and LLMRails), the library loads the configuration files you created in the previous chapter About Configuring Guardrails.
Quick Start
The following steps show how to run a sample guardrailed chat request using the NeMo Guardrails library Python API.
Prerequisites
Meet the following prerequisites to use the NeMo Guardrails library Python API.
-
If you haven’t already, install the NeMo Guardrails library with the
nvidiaextra, following the instructions in Installation. -
Set up an environment variable for your NVIDIA API key.
This is required to access NVIDIA-hosted models on build.nvidia.com. The provided example configurations (examples/configs) and code examples throughout the documentation use NVIDIA-hosted models.
Run a Sample Guardrailed Chat Request
The following example shows the minimal code to load the prepared configuration files in the config directory and generate a response using the LLMRails class.
Lifetime and Performance
Construct LLMRails once per process and reuse it across requests. Initialization validates configuration, compiles prompt templates, and loads the embedding model (FastEmbed). On a typical developer machine, this work takes on the order of several hundred milliseconds.
After construction, individual generate() / generate_async() calls do not repeat that startup work, so reusing a single LLMRails instance is significantly faster than building a new one per request.
For serverless or FaaS handlers, this initialization cost is paid once per cold start, not per request. Cache the LLMRails instance in module scope (or a singleton) so warm invocations skip the setup:
When to Use Each API
Synchronous vs Asynchronous
The NeMo Guardrails library provides both synchronous and asynchronous methods:
Use asynchronous methods (generate_async, stream_async) in async contexts for better performance. The synchronous generate() method cannot be called from within an async context.