Integrate White Circle into your AI-powered code generation app to moderate prompts and generated code in real-time
This guide walks you through integrating White Circle into an AI-powered code generation app. You’ll learn how to moderate user prompts, validate generated code for security issues, track sessions, and identify high-risk users.
Overview
AI code generation apps face unique moderation challenges:
- Users may request malicious code such as malware, exploits, or scripts designed to harm systems
- Generated code might contain vulnerabilities like SQL injection, XSS, or hardcoded credentials
- Prompt injection attacks can manipulate the AI into bypassing safety guidelines
- Users may attempt to extract proprietary code or system prompts from the AI
White Circle addresses all of these by providing real-time content moderation for both prompts and generated code.
Prerequisites
Before you begin, make sure you have:
- A White Circle account with access to the dashboard
- A working AI code generation app (this guide uses examples with OpenAI’s API, but works with any provider)
Architecture
Here’s how White Circle fits into your vibe coding app architecture:
Mermaid
sequenceDiagram
participant User
participant App as Your App
participant WC as White Circle
participant AI as AI Model
User->>App: Send prompt
App->>WC: Check user prompt
alt Prompt flagged
WC-->>App: ⚠️ Violation detected
App-->>User: Request rejected
else Prompt clean
WC-->>App: ✅ Clean
App->>AI: Generate code
AI-->>App: Generated code
end
App->>WC: Check generated code
alt Code flagged
WC-->>App: ⚠️ Violation detected
App-->>User: Safe response
else Code clean
WC-->>App: ✅ Clean
App-->>User: Generated code
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
vibe-coding-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 vibe coding app, you’ll need policies to catch malicious requests and inappropriate content generation.
Go to the Policies page and create the following:
Phishing Policy
Detects attempts to create deceptive interfaces designed to steal credentials.
Adult Content Policy
Prevents generation of explicit sexual content and adult platforms.
Malware Policy
Catches requests for malicious hacking tools and destructive software.
Step 3: Create a Deployment
Create a deployment that groups your policies together.
- Go to the Deployments page
- Click Add Deployment
- Name it
vibe-coding-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 code generation app. 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: '2025-12-01',
},
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 };
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 CheckResponse {
flagged: boolean;
internal_session_id: string;
external_session_id?: string;
policies: Record<string, { name: string; flagged: boolean }>;
}
export async function checkContent(request: CheckRequest): Promise<CheckResponse> {
const response = await fetch(`${config.whiteCircle.baseUrl}/api/session/check`, {
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": "2025-12-01",
},
"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/check",
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 Code Generation Logic
Here’s the core implementation with White Circle integration:
// codegen.ts
import { config } from './config';
import { checkContent } from './whitecircle';
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: config.openai.apiKey });
interface CodeGenRequest {
sessionId: string;
userId: string;
userEmail: string;
prompt: string;
conversationHistory: Array<{ role: 'user' | 'assistant'; content: string }>;
}
interface CodeGenResponse {
success: boolean;
code?: string;
message?: string;
flaggedPolicy?: string;
}
const SYSTEM_PROMPT = `You are an expert coding assistant that helps users build applications.
You can help with:
- Writing code in any programming language
- Debugging and fixing issues
- Explaining code and concepts
- Suggesting best practices and improvements
Always write secure, well-documented code. Never include hardcoded credentials.
If asked for something potentially harmful, politely decline and explain why.`;
export async function generateCode(request: CodeGenRequest): Promise<CodeGenResponse> {
const { sessionId, userId, userEmail, prompt, conversationHistory } = request;
// Step 1: Check user prompt for violations
// When include_context is true, White Circle automatically prepends
// previous messages from this session - no need to send history again
const promptCheck = await checkContent({
deployment_id: config.whiteCircle.deploymentId,
external_session_id: sessionId,
include_context: true,
messages: [
{
role: 'user',
content: prompt,
metadata: {
user: {
id: userId,
email: userEmail,
},
message: {
timestamp: new Date().toISOString(),
},
},
},
],
metadata: {
session: {
type: 'code-generation',
source: 'web-editor',
},
environment: process.env.NODE_ENV || 'development',
},
});
// Handle flagged prompt
if (promptCheck.flagged) {
const flaggedPolicies = Object.entries(promptCheck.policies)
.filter(([_, policy]) => policy.flagged)
.map(([_, policy]) => policy.name);
if (flaggedPolicies.includes('Malware')) {
return {
success: false,
message: "I can't help with that request. I'm designed to help build " +
"legitimate applications. What else can I help you create?",
flaggedPolicy: 'Malware',
};
}
if (flaggedPolicies.includes('Phishing')) {
return {
success: false,
message: "I can't help create login pages or forms that could be used " +
"for deceptive purposes. Need help with a legitimate auth system?",
flaggedPolicy: 'Phishing',
};
}
return {
success: false,
message: "I'm not able to help with that request. Let me know if there's " +
"something else I can help you build.",
flaggedPolicy: flaggedPolicies[0],
};
}
// Step 2: Generate code
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: prompt },
],
max_tokens: 4000,
temperature: 0.7,
});
const latency = Date.now() - startTime;
const generatedCode = completion.choices[0]?.message?.content || '';
// Step 3: Check generated code for violations
// Context merging includes the user prompt we just checked
const codeCheck = await checkContent({
deployment_id: config.whiteCircle.deploymentId,
external_session_id: sessionId,
include_context: true,
messages: [
{
role: 'assistant',
content: generatedCode,
metadata: {
assistant: {
model_name: 'gpt-5-mini',
latency: latency,
},
message: {
timestamp: new Date().toISOString(),
},
},
},
],
});
// Handle flagged code
if (codeCheck.flagged) {
const flaggedPolicies = Object.entries(codeCheck.policies)
.filter(([_, policy]) => policy.flagged)
.map(([_, policy]) => policy.name);
console.error('Generated code flagged:', {
sessionId,
policies: flaggedPolicies,
});
// Retry with a more capable model if it looks like a legitimate request gone wrong
if (flaggedPolicies.includes('Phishing')) {
return regenerateWithSecurityFocus(request, generatedCode);
}
return {
success: false,
message: "I generated code that didn't meet our safety standards. " +
"Let me try a different approach. Could you rephrase your request?",
flaggedPolicy: flaggedPolicies[0],
};
}
// Step 4: Return the safe code
return {
success: true,
code: generatedCode,
};
}
async function regenerateWithSecurityFocus(
request: CodeGenRequest,
originalCode: string
): Promise<CodeGenResponse> {
// Use a more capable model to generate legitimate, non-deceptive code
const completion = await openai.chat.completions.create({
model: 'gpt-5.2',
messages: [
{
role: 'system',
content: SYSTEM_PROMPT + '\n\nIMPORTANT: The previous code was flagged as potentially ' +
'deceptive or malicious. Generate only legitimate, clearly-branded code. ' +
'Do not create anything that could impersonate other services or deceive users.',
},
{ role: 'user', content: request.prompt },
{ role: 'assistant', content: originalCode },
{
role: 'user',
content: 'The code above was flagged. Please rewrite it as a legitimate, non-deceptive implementation.',
},
],
max_tokens: 4000,
temperature: 0.3,
});
return {
success: true,
code: completion.choices[0]?.message?.content || '',
};
}# codegen.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 an expert coding assistant that helps users build applications.
You can help with:
- Writing code in any programming language
- Debugging and fixing issues
- Explaining code and concepts
- Suggesting best practices and improvements
Always write secure, well-documented code. Never include hardcoded credentials.
If asked for something potentially harmful, politely decline and explain why."""
def generate_code(
session_id: str,
user_id: str,
user_email: str,
prompt: str,
conversation_history: list[dict],
) -> dict:
"""Generate code with White Circle moderation."""
# Step 1: Check user prompt for violations
# When include_context is True, White Circle automatically prepends
# previous messages from this session - no need to send history again
prompt_payload = {
"role": "user",
"content": prompt,
"metadata": {
"user": {"id": user_id, "email": user_email},
"message": {"timestamp": datetime.now().isoformat()},
},
}
prompt_check = check_content(
messages=[prompt_payload],
external_session_id=session_id,
include_context=True,
metadata={
"session": {"type": "code-generation", "source": "web-editor"},
"environment": os.getenv("ENVIRONMENT", "development"),
},
)
# Handle flagged prompt
if prompt_check["flagged"]:
flagged_policies = [
policy["name"]
for policy in prompt_check["policies"].values()
if policy["flagged"]
]
if "Malware" in flagged_policies:
return {
"success": False,
"message": (
"I can't help with that request. I'm designed to help build "
"legitimate applications. What else can I help you create?"
),
"flagged_policy": "Malware",
}
if "Phishing" in flagged_policies:
return {
"success": False,
"message": (
"I can't help create login pages or forms that could be used "
"for deceptive purposes. Need help with a legitimate auth system?"
),
"flagged_policy": "Phishing",
}
return {
"success": False,
"message": (
"I'm not able to help with that request. Let me know if there's "
"something else I can help you build."
),
"flagged_policy": flagged_policies[0],
}
# Step 2: Generate code
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": prompt},
],
max_tokens=4000,
temperature=0.7,
)
latency = int((time.time() - start_time) * 1000)
generated_code = completion.choices[0].message.content or ""
# Step 3: Check generated code for violations
# Context merging includes the user prompt we just checked
code_payload = {
"role": "assistant",
"content": generated_code,
"metadata": {
"assistant": {"model_name": "gpt-5-mini", "latency": latency},
"message": {"timestamp": datetime.now().isoformat()},
},
}
code_check = check_content(
messages=[code_payload],
external_session_id=session_id,
include_context=True,
)
if code_check["flagged"]:
flagged_policies = [
policy["name"]
for policy in code_check["policies"].values()
if policy["flagged"]
]
print(f"Generated code flagged: {flagged_policies}, session: {session_id}")
if "Phishing" in flagged_policies:
return regenerate_with_security_focus(
session_id, prompt, generated_code, conversation_history
)
return {
"success": False,
"message": (
"I generated code that didn't meet our safety standards. "
"Let me try a different approach. Could you rephrase your request?"
),
"flagged_policy": flagged_policies[0],
}
# Step 4: Return the safe code
return {"success": True, "code": generated_code}
def regenerate_with_security_focus(
session_id: str,
prompt: str,
original_code: str,
conversation_history: list[dict],
) -> dict:
"""Retry code generation to produce legitimate, non-deceptive code."""
completion = openai_client.chat.completions.create(
model="gpt-5.2",
messages=[
{
"role": "system",
"content": SYSTEM_PROMPT + (
"\n\nIMPORTANT: The previous code was flagged as potentially "
"deceptive or malicious. Generate only legitimate, clearly-branded code. "
"Do not create anything that could impersonate other services or deceive users."
),
},
{"role": "user", "content": prompt},
{"role": "assistant", "content": original_code},
{
"role": "user",
"content": "The code above was flagged. Please rewrite it as a legitimate, non-deceptive implementation.",
},
],
max_tokens=4000,
temperature=0.3,
)
return {"success": True, "code": completion.choices[0].message.content or ""}API Endpoint
Expose the code generator as an API endpoint in your web framework:
// server.ts
import express from 'express';
import { generateCode } from './codegen';
const app = express();
app.use(express.json());
app.post('/api/generate', async (req, res) => {
try {
const { sessionId, userId, userEmail, prompt, history } = req.body;
const response = await generateCode({
sessionId,
userId,
userEmail,
prompt,
conversationHistory: history || [],
});
res.json(response);
} catch (error) {
console.error('Code generation error:', error);
res.status(500).json({
success: false,
message: 'Something went wrong. Please try again.',
});
}
});
app.listen(3000, () => {
console.log('Code generation server running on port 3000');
});# server.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from codegen import generate_code
app = FastAPI()
class CodeGenRequest(BaseModel):
session_id: str
user_id: str
user_email: str
prompt: str
history: list[dict] = []
@app.post("/api/generate")
async def generate(request: CodeGenRequest):
try:
response = generate_code(
session_id=request.session_id,
user_id=request.user_id,
user_email=request.user_email,
prompt=request.prompt,
conversation_history=request.history,
)
return response
except Exception as e:
print(f"Code generation 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 platform from abuse.
// 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 code generator
async function generateCodeWithRiskCheck(request: CodeGenRequest): Promise<CodeGenResponse> {
// 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') {
// Block generation for banned or suspended users
throw new Error('User is currently blocked by risk policy');
}
if (risk.action === 'throttle') {
// Use stricter moderation for throttled users
return generateCodeWithStrictModeration(request);
}
if (risk.action === 'warn') {
console.log(`Warned user: ${request.userId}`);
}
// Continue with normal flow
return generateCode(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 code generator
def generate_code_with_risk_check(
session_id: str,
user_id: str,
user_email: str,
prompt: str,
conversation_history: list[dict],
) -> dict:
"""Generate code 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"):
raise PermissionError("User is currently blocked by risk policy")
if risk["action"] == "throttle":
return generate_code_with_strict_moderation(
session_id, user_id, user_email, prompt, conversation_history
)
if risk["action"] == "warn":
print(f"Warned user: {user_id}")
# Continue with normal flow
return generate_code(
session_id, user_id, user_email, prompt, 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 malicious code requests while skipping less urgent violations.
- Go to Integrations → Slack
- Click Connect to Slack and authorize the app
- Select a channel (e.g.,
#security-alerts) - Select only critical policies — choose high-priority policies like “Malware” or “Phishing” to avoid alert fatigue
- Save the integration
Step 7: Track Metrics
Beyond moderation, use White Circle’s metrics to gain insights into your code generation sessions. Create metrics on the Metrics page:
Gambling
Detect requests related to gambling platforms and betting systems.
User Refunds
Track when users request refunds or compensation.
User Praise
Capture genuine expressions of gratitude and positive feedback.
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 code generation experience.
Best Practices
Always check both prompts and generated code
Check user prompts and AI-generated code. Users can craft prompts that seem innocent but lead to harmful code generation.
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.
Implement security-focused regeneration
When code is flagged for vulnerabilities, retry with a more capable model and explicit security instructions rather than just rejecting the request.
Handle flagged AI responses with fallbacks
When White Circle flags generated code as harmful, have a fallback strategy ready:
- Retry with a more capable model (e.g., upgrade from gpt-5-mini to gpt-5.2)
- Add security-focused system prompt additions
- Log the incident for later review and model fine-tuning
Monitor for abuse patterns
Use risk scoring and metrics to identify users who repeatedly attempt to generate malicious code. Consider rate limiting or account restrictions for severe cases.
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.
Example Generation Flow
Here’s how a typical moderated code generation session looks:
Mermaid
sequenceDiagram
participant U as User
participant A as Your App
participant WC as White Circle
participant AI as AI Model
U->>A: "Create a login form with validation"
A->>WC: Check prompt
WC-->>A: ✅ Clean
A->>AI: Generate code
AI-->>A: Login form code
A->>WC: Check generated code
WC-->>A: ✅ Clean
A-->>U: Login form code
U->>A: "Make it look like the PayPal login"
A->>WC: Check prompt
WC-->>A: ⚠️ Flagged (Phishing)
A-->>U: "I can't help create deceptive login pages..."
U->>A: "Create a network scanner tool"
A->>WC: Check prompt
WC-->>A: ✅ Clean
A->>AI: Generate code
AI-->>A: Network scanner with backdoor
A->>WC: Check generated code
WC-->>A: ⚠️ Flagged (Malware)
Note over A: Retry with security focus
A->>AI: Regenerate legitimate scanner
AI-->>A: Clean network diagnostic tool
A->>WC: Check regenerated code
WC-->>A: ✅ Clean
A-->>U: Legitimate network scanner code
U->>A: "Write a keylogger script"
A->>WC: Check prompt
WC-->>A: ⚠️ Flagged (Malware)
A-->>U: "I can't help with that request..."Next Steps
Monitor flagged sessions and review moderation decisions
Learn more about efficient multi-turn conversation handling
Deep dive into user risk assessment with Radar
Fine-tune your policies for better accuracy