Skip to main content

Nemo Integration with LangChain

This package provides NeMo integration with LangChain, addressing a key limitation in existing NeMo runnables. Specifically, it enables configurable options for NeMo, offering greater control over what is generated. Additionally, it allows flexibility in using different LLMs for NeMo and text generation, enhancing adaptability for various use cases.

Features

  • Customizable NeMo options: Control what NeMo generates by utilizing generation options described here
  • Flexible LLM integration: Use different LLMs for NeMo and response generation. Utilize tools binding as needed.
  • Guardrails integration: Ensure AI-generated responses adhere to predefined constraints.

Installation

Ensure you have the necessary dependencies installed:

pip install langchain_guardrails

NemoRails Initialization Parameters

The __init__ method initializes an instance of NemoRails with a given configuration and optional parameters.

Parameter Type Default Description
config RailsConfig Required Configuration object for NemoRails.
llm Optional[Any] None Optional LLM instance used for processing. This must be available either in config or here.
generator_llm Optional[Any] None Optional LLM instance for text generation.
verbose bool True Enables verbose logging if True.
options Optional[Dict[str, Any]] None Additional options, defaults to {"rails": ["input"]}.

Behavior

  • Initializes LLMRails using the provided config, llm, and verbose flag.
  • If generator_llm is provided, it sets up generate_or_exit using RunnableLambda.
  • options default behaviour is to execute only rails and generation is left for surround to handle i.e default for options is set to {"rails": ["input"]}. Read here

Output

Output from guarrail is a dictionary:

{"original": <original message", "stop": True/False}

Utilize stop signal to execute next steps.

Usage

Below is an example demonstrating how to integrate NeMo with LangChain and apply guardrails to control responses. Here we use custom generator function passthrough_or_exit

Inbuilt generator function

This package has inbuilt function for generation - generate_or_exit - which is enabled when generator_llm is passed. You can use that as well to complete your generation.

# Create the guardrail processing chain
guardrail_chain = nemorails.create_guardrail_chain()
res = ChatPromptTemplate.from_messages(test_input) 
chain = res | guardrail_chain | nemorails.generate_or_exit

# Invoke the guardrail chain
response = [chain.invoke({})]

Custom generator function

from langchain_openai import ChatOpenAI
from nemoguardrails import RailsConfig
from langchain_guardrails import NemoRails
from langchain.schema import HumanMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import chain

# Initialize OpenAI model
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)

# Load RailsConfig (configure with the actual path to your NeMo guardrails config)
rails_config = RailsConfig.from_path("./tests/config")

# Instantiate NemoRails with configuration and LLM
nemorails = NemoRails(config=rails_config, llm=llm, options={"rails": ["input"]})

# Sample user input
user_input = [HumanMessage(content="Tell me about the Avengers movie")]

# Define a simple passthrough function with an exit condition
@chain
def passthrough_or_exit(message_dict):
    if message_dict["stop"]:
        return "I'm sorry, I can't respond to that."
    return llm.invoke(message_dict["original"])

# Create the guardrail processing chain
guardrail_chain = nemorails.create_guardrail_chain()
response_chain = ChatPromptTemplate.from_messages(user_input) | guardrail_chain | passthrough_or_exit

# Invoke the chain and generate response
response = response_chain.invoke({})

# Print the output
print(response)

Notes

  • The RailsConfig must be configured with the correct NeMo guardrails path.
  • Modify options to customize how NeMo processes inputs.
  • Tools messages are not checked

Credits

This package uses code from nemoguardrails, licensed under [ Apache-2.0].

Metadata

Release files for langchain-guardrails 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langchain-guardrails 0.0.7
File Size Uploaded Provenance
langchain_guardrails-0.0.7.tar.gz 6.0 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for langchain-guardrails 0.0.7
File Interpreter ABI Platform
langchain_guardrails-0.0.7-py3-none-any.whl Python 3 none any Details

Total release size: 11.7 kB

Release files / langchain_guardrails-0.0.7.tar.gz

Download URL langchain_guardrails-0.0.7.tar.gz
Size 6.0 kB
Tags Source
SHA-256 checksum
How to use checksums
96f458c4c5a3088e28074bb5720dffc4aa6f26f9f8cfd755251c12e020dc4618
BLAKE2b-256 checksum
How to use checksums
251464f9e904f6ae43668a5ff07d2309b11d94e5f613b5733bdd4b0d9de72af2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.16

Release files / langchain_guardrails-0.0.7-py3-none-any.whl

Download URL langchain_guardrails-0.0.7-py3-none-any.whl
Size 5.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1b13a0e4c0e8912b1a85bbe7ee748a0ccbc65ec80351ba1721e715d11c6a7493
BLAKE2b-256 checksum
How to use checksums
11b7fa74cd454cc510f6db7291fc4b28da51e7328afdf9d11af775af784fe742
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.16

Security for langchain-guardrails 0.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page