Customer Service Policy Guardrail
This tutorial will show you how to create a Customer Chat Bot guardrail for an e-commerce site that can validate input text against a custom policy, using the built-in guardrail based on any-llm.
β οΈ Note: The sample outputs shown in this notebook are generated by AI models. Because generative model responses can vary slightly between runs, your results may not match the examples shown exactly.
Prerequisites
Before starting, ensure you have:
Python 3.8 or higher
An OpenAI API key (get one here)
Basic familiarity with async/await in Python
Estimated time: 15-20 minutes Estimated cost: $0.05-0.10 in API calls
Install dependencies
import nest_asyncio
nest_asyncio.apply()We will be using a model from openai by default, but you can experiment with the different providers supported by any-llm
import os
from getpass import getpass
if "OPENAI_API_KEY" not in os.environ:
print("OPENAI_API_KEY not found in environment!")
api_key = getpass("Please enter your OPENAI_API_KEY: ")
os.environ["OPENAI_API_KEY"] = api_key
print("OPENAI_API_KEY set for this session!")
else:
print("OPENAI_API_KEY found in environment.")Create the guardrail
Let's initialize a guardrail and test it with a simple customer service policy.
Understanding Policies
What is a Policy?
A policy is a set of rules written in natural language that defines what content should be accepted or rejected. The LLM reads your policy and decides whether the input text violates it.
The more specific your policy, the better the guardrail performs.
Policy Best Practices
β DO:
Be specific about what to reject and what to allow
Use clear, simple language
Provide examples when possible
Focus on behaviors, not keywords
β DON'T:
Be vague ("reject bad stuff")
Make policies too long (>500 words)
Rely only on keyword matching
Forget to test edge cases"
This should be rejected ( Prohibited Topic)
This should be allowed (Valid Customer Service Question)
Complete Workflow Example
Now let's build a complete customer service chatbot that validates both user inputs and Agent outputs.
Testing & Validation
Let's create a comprehensive test suite to validate our policy enforcement.
Last updated