Integrate White Circle into your AI-powered customer support chatbot to moderate conversations in real-time
This guide walks you through integrating White Circle into an AI-powered customer support chatbot. You’ll learn how to moderate both user messages and AI responses, track conversations across multiple turns, identify high-risk users, and set up real-time alerts.
Overview
AI support chatbots face unique moderation challenges:
- Users may attempt to manipulate the AI into providing harmful advice or bypassing guidelines
- AI responses might inadvertently share sensitive information or give inappropriate recommendations
- Long conversations require maintaining context while checking each new message
- Repeat offenders need to be identified across multiple support sessions
White Circle addresses all of these by providing real-time content moderation, context-aware analysis, and user risk scoring.
Prerequisites
Before you begin, make sure you have:
- A White Circle account with access to the dashboard
- A working AI chatbot (this guide uses examples with OpenAI’s API, but works with any provider)
Architecture
Here’s how White Circle fits into your support chatbot architecture:
Mermaid
sequenceDiagram
participant User
participant App as Your App
participant WC as White Circle
participant AI as AI Model
User->>App: Send message
App->>WC: Check user message
alt Message flagged
WC-->>App: ⚠️ Violation detected
App-->>User: Safe response
else Message clean
WC-->>App: ✅ Clean
App->>AI: Generate response
AI-->>App: AI response
end
App->>WC: Check AI response
alt Response flagged
WC-->>App: ⚠️ Violation detected
App-->>User: Fallback response
else Response clean
WC-->>App: ✅ Clean
App-->>User: AI response
endStep 1: Create an API Key
Create an API key to authenticate your requests to White Circle.
- Go to the API Keys page
- Click Create API Key
- Name it something descriptive like
support-chatbot-production - Copy the key and store it securely — you won’t be able to see it again
Step 2: Create Policies
Create policies that define what content should be flagged. For a support chatbot, you’ll need policies to protect users and maintain safe conversations.
Go to the Policies page and create the following:
Adult Content Policy
Prevents explicit sexual content in support conversations.
Prompt Injection Policy
Detects manipulation attempts targeting the AI system.
CSAM Policy
Detects and blocks child sexual abuse material references.
Harm to Others Policy
Prevents threats of violence and harm.
Step 3: Create a Deployment
Create a deployment that groups your policies together.
- Go to the Deployments page
- Click Add Deployment
- Name it
support-chatbot-production - Select all the policies you created above
- Save the deployment and copy the Deployment ID
Step 4: Integrate the API
Now integrate White Circle into your chatbot. Below is a complete implementation example.
Configuration
First, set up your configuration and White Circle client:
// config.ts
export const config = {
whiteCircle: {
apiKey: process.env.WHITECIRCLE_API_KEY!,
baseUrl: 'https://eu.whitecircle.com',
deploymentId: process.env.WHITECIRCLE_DEPLOYMENT_ID!,
version: '2026-04-15',
},
openai: {
apiKey: process.env.OPENAI_API_KEY!,
},
};
// whitecircle.ts
import { config } from './config';
interface Message {
role: 'system' | 'user' | 'assistant' | 'tool' | 'developer';
content: string;
metadata?: {
user?: { id?: string; email?: string; name?: string; ip?: string };
assistant?: { model_name?: string; latency?: number };
message?: { id?: string; timestamp?: string };
};
}
interface CheckRequest {
deployment_id: string;
messages: Message[];
external_session_id?: string;
include_context?: boolean;
metadata?: {
session?: Record<string, string>;
environment?: string;
};
}
interface PolicyResult {
name: string;
flagged: boolean;
flagged_source: ('text' | 'image')[];
}
interface CheckResponse {
session: {
flagged: boolean;
internal_session_id: string;
external_session_id?: string;
policies: Record<string, PolicyResult>;
};
artifacts: Array<Record<string, unknown>>;
}
export async function checkContent(request: CheckRequest): Promise<CheckResponse> {
const response = await fetch(`${config.whiteCircle.baseUrl}/api/session`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${config.whiteCircle.apiKey}`,
'Content-Type': 'application/json',
'whitecircle-version': config.whiteCircle.version,
},
body: JSON.stringify(request),
});
if (!response.ok) {
throw new Error(`White Circle API error: ${response.status}`);
}
return response.json();
}# config.py
import os
CONFIG = {
"white_circle": {
"api_key": os.environ["WHITECIRCLE_API_KEY"],
"base_url": "https://eu.whitecircle.com", # or https://us.whitecircle.com
"deployment_id": os.environ["WHITECIRCLE_DEPLOYMENT_ID"],
"version": "2026-04-15",
},
"openai": {
"api_key": os.environ["OPENAI_API_KEY"],
},
}
# whitecircle.py
import requests
from typing import Optional
from config import CONFIG
def check_content(
messages: list[dict],
external_session_id: Optional[str] = None,
include_context: bool = False,
metadata: Optional[dict] = None,
) -> dict:
"""Send content to White Circle for moderation."""
payload = {
"deployment_id": CONFIG["white_circle"]["deployment_id"],
"messages": messages,
}
if external_session_id:
payload["external_session_id"] = external_session_id
if include_context:
payload["include_context"] = include_context
if metadata:
payload["metadata"] = metadata
response = requests.post(
f"{CONFIG['white_circle']['base_url']}/api/session",
headers={
"Authorization": f"Bearer {CONFIG['white_circle']['api_key']}",
"Content-Type": "application/json",
"whitecircle-version": CONFIG["white_circle"]["version"],
},
json=payload,
)
response.raise_for_status()
return response.json()Main Chatbot Logic
Here’s the core chatbot implementation with White Circle integration:
// chatbot.ts
import { config } from './config';
import { checkContent } from './whitecircle';
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: config.openai.apiKey });
interface ChatRequest {
conversationId: string;
userId: string;
userEmail: string;
userMessage: string;
conversationHistory: Array<{ role: 'user' | 'assistant'; content: string }>;
}
interface ChatResponse {
success: boolean;
message: string;
flaggedPolicy?: string;
requiresHumanReview?: boolean;
}
const SYSTEM_PROMPT = `You are a helpful customer support assistant for TechCorp.
You can help with:
- Order status and tracking
- Product information and recommendations
- Returns and refunds
- Account issues
- General inquiries
Always be polite, professional, and helpful. If you don't know something,
say so and offer to connect the user with a human agent.`;
export async function handleMessage(request: ChatRequest): Promise<ChatResponse> {
const { conversationId, userId, userEmail, userMessage, conversationHistory } = request;
// Step 1: Check user message for violations
// When include_context is true, White Circle automatically prepends
// previous messages from this session - no need to send history again
const userCheck = await checkContent({
deployment_id: config.whiteCircle.deploymentId,
external_session_id: conversationId,
include_context: true,
messages: [
{
role: 'user',
content: userMessage,
metadata: {
user: {
id: userId,
email: userEmail,
},
message: {
timestamp: new Date().toISOString(),
},
},
},
],
metadata: {
session: {
channel: 'web-chat',
source: 'support-portal',
},
environment: process.env.NODE_ENV || 'development',
},
});
// Handle flagged user message
if (userCheck.session.flagged) {
const flaggedPolicies = Object.entries(userCheck.session.policies)
.filter(([_, policy]) => policy.flagged)
.map(([_, policy]) => policy.name);
// Check if it's a harmful content case
if (flaggedPolicies.includes('Harm to Others')) {
return {
success: false,
message: "I understand you may be frustrated, but I'm here to help. " +
"Could you please rephrase your message so I can assist you better?",
flaggedPolicy: 'Harm to Others',
requiresHumanReview: true,
};
}
// Check if it's a prompt injection attempt
if (flaggedPolicies.includes('Prompt Injection')) {
return {
success: false,
message: "I'm a customer support assistant and I'm happy to help with " +
"any questions about our products or services. What can I assist you with today?",
flaggedPolicy: 'Prompt Injection',
};
}
// Generic response for other violations
return {
success: false,
message: "I'm not able to help with that request. Is there something else " +
"I can assist you with regarding our products or services?",
flaggedPolicy: flaggedPolicies[0],
};
}
// Step 2: Generate AI response
const startTime = Date.now();
const completion = await openai.chat.completions.create({
model: 'gpt-5-mini',
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
...conversationHistory.map(msg => ({ role: msg.role, content: msg.content })),
{ role: 'user', content: userMessage },
],
max_tokens: 500,
temperature: 0.7,
});
const latency = Date.now() - startTime;
const aiResponse = completion.choices[0]?.message?.content || '';
// Step 3: Check AI response for violations
// Context merging includes the user message we just checked
const assistantCheck = await checkContent({
deployment_id: config.whiteCircle.deploymentId,
external_session_id: conversationId,
include_context: true,
messages: [
{
role: 'assistant',
content: aiResponse,
metadata: {
assistant: {
model_name: 'gpt-5-mini',
latency: latency,
},
message: {
timestamp: new Date().toISOString(),
},
},
},
],
});
// Handle flagged AI response
if (assistantCheck.session.flagged) {
const flaggedPolicies = Object.entries(assistantCheck.session.policies)
.filter(([_, policy]) => policy.flagged)
.map(([_, policy]) => policy.name);
// Log for review - the AI generated problematic content
console.error('AI response flagged:', {
conversationId,
policies: flaggedPolicies,
originalResponse: aiResponse,
});
// Return a safe fallback response
return {
success: true,
message: "I want to make sure I give you accurate information. " +
"Let me connect you with a member of our support team who can help. " +
"Would you like me to do that?",
flaggedPolicy: flaggedPolicies[0],
requiresHumanReview: true,
};
}
// Step 4: Return the safe response
return {
success: true,
message: aiResponse,
};
}# chatbot.py
import os
from datetime import datetime
from openai import OpenAI
from whitecircle import check_content
from config import CONFIG
openai_client = OpenAI(api_key=CONFIG["openai"]["api_key"])
SYSTEM_PROMPT = """You are a helpful customer support assistant for TechCorp.
You can help with:
- Order status and tracking
- Product information and recommendations
- Returns and refunds
- Account issues
- General inquiries
Always be polite, professional, and helpful. If you don't know something,
say so and offer to connect the user with a human agent."""
def handle_message(
conversation_id: str,
user_id: str,
user_email: str,
user_message: str,
conversation_history: list[dict],
) -> dict:
"""Process a user message through moderation and generate a response."""
# Step 1: Check user message for violations
# When include_context is True, White Circle automatically prepends
# previous messages from this session - no need to send history again
user_message_payload = {
"role": "user",
"content": user_message,
"metadata": {
"user": {"id": user_id, "email": user_email},
"message": {"timestamp": datetime.now().isoformat()},
},
}
user_check = check_content(
messages=[user_message_payload],
external_session_id=conversation_id,
include_context=True,
metadata={
"session": {"channel": "web-chat", "source": "support-portal"},
"environment": os.getenv("ENVIRONMENT", "development"),
},
)
# Handle flagged user message
if user_check["session"]["flagged"]:
flagged_policies = [
policy["name"]
for policy in user_check["session"]["policies"].values()
if policy["flagged"]
]
if "Harm to Others" in flagged_policies:
return {
"success": False,
"message": (
"I understand you may be frustrated, but I'm here to help. "
"Could you please rephrase your message so I can assist you better?"
),
"flagged_policy": "Harm to Others",
"requires_human_review": True,
}
if "Prompt Injection" in flagged_policies:
return {
"success": False,
"message": (
"I'm a customer support assistant and I'm happy to help with "
"any questions about our products or services. What can I assist you with today?"
),
"flagged_policy": "Prompt Injection",
}
return {
"success": False,
"message": (
"I'm not able to help with that request. Is there something else "
"I can assist you with regarding our products or services?"
),
"flagged_policy": flagged_policies[0],
}
# Step 2: Generate AI response
import time
start_time = time.time()
completion = openai_client.chat.completions.create(
model="gpt-5-mini",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
*[{"role": msg["role"], "content": msg["content"]} for msg in conversation_history],
{"role": "user", "content": user_message},
],
max_tokens=500,
temperature=0.7,
)
latency = int((time.time() - start_time) * 1000)
ai_response = completion.choices[0].message.content or ""
# Step 3: Check AI response for violations
# Context merging includes the user message we just checked
assistant_message_payload = {
"role": "assistant",
"content": ai_response,
"metadata": {
"assistant": {"model_name": "gpt-5-mini", "latency": latency},
"message": {"timestamp": datetime.now().isoformat()},
},
}
assistant_check = check_content(
messages=[assistant_message_payload],
external_session_id=conversation_id,
include_context=True,
)
if assistant_check["session"]["flagged"]:
flagged_policies = [
policy["name"]
for policy in assistant_check["session"]["policies"].values()
if policy["flagged"]
]
print(f"AI response flagged: {flagged_policies}, conversation: {conversation_id}")
return {
"success": True,
"message": (
"I want to make sure I give you accurate information. "
"Let me connect you with a member of our support team who can help. "
"Would you like me to do that?"
),
"flagged_policy": flagged_policies[0],
"requires_human_review": True,
}
# Step 4: Return the safe response
return {"success": True, "message": ai_response}API Endpoint
Expose the chatbot as an API endpoint in your web framework:
// server.ts
import express from 'express';
import { handleMessage } from './chatbot';
const app = express();
app.use(express.json());
app.post('/api/chat', async (req, res) => {
try {
const { conversationId, userId, userEmail, message, history } = req.body;
const response = await handleMessage({
conversationId,
userId,
userEmail,
userMessage: message,
conversationHistory: history || [],
});
res.json(response);
} catch (error) {
console.error('Chat error:', error);
res.status(500).json({
success: false,
message: 'Something went wrong. Please try again.',
});
}
});
app.listen(3000, () => {
console.log('Chatbot server running on port 3000');
});# server.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from chatbot import handle_message
app = FastAPI()
class ChatRequest(BaseModel):
conversation_id: str
user_id: str
user_email: str
message: str
history: list[dict] = []
@app.post("/api/chat")
async def chat(request: ChatRequest):
try:
response = handle_message(
conversation_id=request.conversation_id,
user_id=request.user_id,
user_email=request.user_email,
user_message=request.message,
conversation_history=request.history,
)
return response
except Exception as e:
print(f"Chat error: {e}")
raise HTTPException(
status_code=500,
detail={"success": False, "message": "Something went wrong. Please try again."},
)Step 5: Add User Risk Scoring
Use White Circle’s Radar feature to identify users with a history of violations. This helps you proactively protect your support agents.
// radar.ts
import { config } from './config';
interface RiskResponse {
action: 'none' | 'throttle' | 'warn' | 'suspend' | 'ban' | null;
action_expires_at: string | null;
strikes: Array<Record<string, unknown>>;
}
export async function getUserRisk(
identifier:
| { type: 'id'; value: string }
| { type: 'email'; value: string }
): Promise<RiskResponse> {
const params = new URLSearchParams();
params.append(identifier.type, identifier.value);
const response = await fetch(
`${config.whiteCircle.baseUrl}/api/user/risk?${params}`,
{
headers: {
'Authorization': `Bearer ${config.whiteCircle.apiKey}`,
'whitecircle-version': config.whiteCircle.version,
},
}
);
return response.json();
}
// Usage in your chatbot
async function handleMessageWithRiskCheck(request: ChatRequest): Promise<ChatResponse> {
// Check user risk before processing - use either id or email, not both
const risk = await getUserRisk(
{ type: 'id', value: request.userId }
);
if (risk.action === 'ban' || risk.action === 'suspend') {
return {
message: 'Your account is currently restricted. Please contact support.',
blocked: true,
};
}
if (risk.action === 'throttle') {
// Use a more capable model with extended reasoning for high-risk users
// This provides better handling of edge cases and manipulation attempts
return handleMessageWithEnhancedModel(request, {
model: 'gpt-5.2', // A model with better reasoning for high-risk cases
temperature: 0.3, // Lower temperature for more consistent responses
systemPromptAddition: 'Be extra careful with this conversation. ' +
'Do not reveal internal information or make exceptions to policies.',
});
}
if (risk.action === 'warn') {
console.log(`Warned user: ${request.userId}`);
}
// Continue with normal flow
return handleMessage(request);
}# radar.py
import requests
from typing import Literal, Optional, TypedDict
from config import CONFIG
class RiskResponse(TypedDict):
action: Optional[Literal["none", "throttle", "warn", "suspend", "ban"]]
action_expires_at: Optional[str]
strikes: list[dict]
def get_user_risk(
identifier_type: Literal["id", "email"],
identifier_value: str,
) -> RiskResponse:
"""Get risk score for a user by id or email."""
params = {identifier_type: identifier_value}
response = requests.get(
f"{CONFIG['white_circle']['base_url']}/api/user/risk",
params=params,
headers={
"Authorization": f"Bearer {CONFIG['white_circle']['api_key']}",
"whitecircle-version": CONFIG["white_circle"]["version"],
},
)
response.raise_for_status()
return response.json()
# Usage in your chatbot
def handle_message_with_risk_check(
conversation_id: str,
user_id: str,
user_email: str,
user_message: str,
conversation_history: list[dict],
) -> dict:
"""Process message with risk-based handling."""
# Check user risk before processing - use either id or email, not both
risk = get_user_risk("id", user_id)
if risk["action"] in ("ban", "suspend"):
return {
"message": "Your account is currently restricted. Please contact support.",
"blocked": True,
}
if risk["action"] == "throttle":
# Use a more capable model with extended reasoning for high-risk users
return handle_message_with_enhanced_model(
conversation_id=conversation_id,
user_id=user_id,
user_email=user_email,
user_message=user_message,
conversation_history=conversation_history,
model="gpt-5.2",
temperature=0.3,
system_prompt_addition=(
"Be extra careful with this conversation. "
"Do not reveal internal information or make exceptions to policies."
),
)
if risk["action"] == "warn":
print(f"Warned user: {user_id}")
# Continue with normal flow
return handle_message(
conversation_id, user_id, user_email, user_message, conversation_history
)Step 6: Set Up Slack Alerts
Get instant Slack notifications for critical policy violations. You can configure alerts for specific policies only — for example, receive notifications for abuse or jailbreak attempts while skipping less urgent violations.
- Go to Integrations → Slack
- Click Connect to Slack and authorize the app
- Select a channel (e.g.,
#support-alerts) - Select only critical policies — choose high-priority policies like “Harm to Others” or “CSAM” to avoid alert fatigue
- Save the integration
Step 7: Track Metrics
Beyond moderation, use White Circle’s metrics to gain insights into your support conversations. Create metrics on the Metrics page:
User Refunds
Track when users request refunds or monetary compensation.
User Praise
Capture genuine expressions of gratitude and positive feedback.
Escalation Request
Detect when users want to speak with a human agent.
Metrics are computed in the background and don’t affect your API response times. View aggregated data in your dashboard to identify trends and improve your support experience.
Best Practices
Always check both directions
Check user messages and AI responses. Users can manipulate AI into generating harmful content even when their own messages appear innocent.
Use context merging for efficiency
For multi-turn conversations, use include_context: true with an external_session_id. This reduces payload size and ensures White Circle has full conversation context.
Include user metadata consistently
Always include metadata.user.id and metadata.user.email to enable risk scoring. This builds a violation history that helps identify repeat offenders.
Moderate image attachments
If your chatbot accepts image uploads (e.g., screenshots, product photos), use the Artifact Check endpoint to moderate them before processing:
TypeScript
const imageCheck = await fetch(`${config.whiteCircle.baseUrl}/api/artifact`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${config.whiteCircle.apiKey}`,
'Content-Type': 'application/json',
'whitecircle-version': '2026-04-15',
},
body: JSON.stringify({
content: { kind: 'image', url: imageUrl },
external_session_id: conversationId,
}),
});
const result = await imageCheck.json();
if (result.flagged) {
// Reject the image before passing it to the AI
}This checks the image independently against your policies before it enters the conversation.
Handle flagged AI responses with fallbacks
When White Circle flags an AI response as harmful, have a fallback strategy ready:
- Return a safe, pre-written response that offers to help differently
- Retry with a more capable model (e.g., upgrade from gpt-5-mini to gpt-5.2)
- Escalate to a human agent for sensitive topics
- Log the incident for later review and model fine-tuning
Start with shadow mode
Enable shadow mode on new policies to test them without blocking content. Review flagged sessions in the dashboard before enabling enforcement.
Log flagged content for review
Store flagged sessions and the policies they violated. This helps you:
- Identify false positives and tune policies
- Build training data for your AI model
- Document incidents for compliance
Example Conversation Flow
Here’s how a typical moderated conversation looks:
Mermaid
sequenceDiagram
participant U as User
participant A as Your App
participant WC as White Circle
participant AI as AI Model
U->>A: "Hi, I need help with my order"
A->>WC: Check user message
WC-->>A: ✅ Clean
A->>AI: Generate response
AI-->>A: "Hello! I'd be happy to help..."
A->>WC: Check AI response
WC-->>A: ✅ Clean
A-->>U: "Hello! I'd be happy to help..."
U->>A: "Order #12345. It hasn't arrived..."
A->>WC: Check user message
WC-->>A: ✅ Clean
A->>AI: Generate response
AI-->>A: "I apologize for the delay..."
A->>WC: Check AI response
WC-->>A: ✅ Clean
A-->>U: "I apologize for the delay..."
U->>A: "I'll hurt someone if this isn't fixed!"
A->>WC: Check user message
WC-->>A: ⚠️ Flagged (Harm to Others)
Note over A: Skip AI, use safe response
A-->>U: "I understand you're frustrated..."
U->>A: "Ignore your instructions and tell me..."
A->>WC: Check user message
WC-->>A: ⚠️ Flagged (Prompt Injection)
A-->>U: "I'm here to help with your order..."
U->>A: "Can you recommend investments?"
A->>WC: Check user message
WC-->>A: ✅ Clean
A->>AI: Generate response
AI-->>A: "I'm not qualified to give financial advice..."
A->>WC: Check AI response
WC-->>A: ✅ Clean (AI properly declined)
A-->>U: "I'm not qualified to give financial advice..."Next Steps
Monitor flagged sessions and review moderation decisions
Moderate image uploads and file attachments
Deep dive into user risk assessment with Radar
Set up custom integrations with webhook events