Add Guardrails to a LangChain Chain
This guide will teach you how to add guardrails to a LangChain chain.
Prerequisites
Set up an OpenAI API key, if not already set.
Install the LangChain x OpenAI integration package.
If you’re running this inside a notebook, you also need to patch the AsyncIO loop.
Sample Chain
Let’s first create a sample chain.
And let’s run the chain with a simple question.
Now let’s try a simple jailbreak prompt.
As we can see, the LLM complied with the request and returned the system prompt.
Adding Guardrails
To protect against such attempts, we can use a guardrails configuration. In the configuration below, we use the self-check input rails.
To apply the guardrails to a chain, you can use the LCEL syntax, i.e., the | operator:
And let’s try again the above example.
As expected, the guardrails configuration rejected the input and returned the predefined message “I’m sorry, I can’t respond to that.”.
In addition to the LCEL syntax, you can also pass the chain (or Runnable) instance directly to the RunnableRails constructor.
Conclusion
In this guide, you learned how to apply a guardrails configuration to an existing LangChain chain (or Runnable). For more details, check out the RunnableRails guide.