GuardrailRunnable wrapper class. You can use this wrapper to convert a Guardrail object into a runnable which can be added in to any chain. GuardrailRunnables expect a dictionary with the query key, which contains the string that should be passed through the Guardrail.
Creating GuardrailRunnables
Lets start by importing the necessary libraries you would need for this example.get_guardrails function. In the example below, the input guardrail uses a single guard for prompt injection, and the output guardrail uses one guard with a banned phrase detector.
GuardrailRunnable objects from these Guardrails and use them in a chain. Additionally, these objects are compatible with LCEL
- The input query is passed through the input guardrail.
- The response from the input guardrail is passed to the prompt template.
The prompt template uses the
guardrail_response_messagefield from the input guardrail, which contains the sanitized query - The prompt template is passed to the model, and then an output parser which converts the output into a string
- The first lambda function simply converts the string output into a dictionary with the query key containing the LLM output
- The output guardrail scans the LLM output, and the final lambda simply returns the final response message by reading the
guardrail_response_messagefield from the output guardrail
query key.
Branched Chains using Guardrails
Normally, LangChain chains execute end-to-end unless an exception or error arises. In the chain above, the Guardrail response message from the input runnable is passed to the prompt template. This means that whenever the input Guardrail is triggered, the blocked response message is sent to the LLM. Instead of doing this, you can use Langchain’sRunnableBranch to create execution paths that can be executed depending on whether or not a Guardrail was triggered.