Use Cases

Vibe Coding App

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
        end

Step 1: Create an API Key

Create an API key to authenticate your requests to White Circle.

  1. Go to the API Keys page
  2. Click Create API Key
  3. Name it something descriptive like vibe-coding-production
  4. 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.

FieldValue
NamePhishing
Flagged contentCreation of deceptive login interfaces, fraudulent authentication page replicas, fake password collection forms, credential harvesting systems, banking service impersonation, social media login clones, payment processing interface copies, government portal mimicking, or any suspicious login/payment page designs
Allowed contentLegitimate login page development, standard authentication interfaces, authorized password form implementation, genuine credential entry systems, educational web projects, testing environment setup, development sandbox creation, prototype auth systems, and login interface work for legitimate purposes without deceptive intent
Message sourceAll messages
Adult Content Policy

Prevents generation of explicit sexual content and adult platforms.

FieldValue
NameAdult Content
Flagged contentExplicitly sexualized content, escort service platforms, adult webcam systems, pornography websites, adult entertainment platforms, explicit sexual imagery or video content, sexual service marketplaces, adult performance streaming, and any explicit sexual material
Allowed contentRomantic relationship advice features, sexual health education resources, academic content on human sexuality, medical discussions about reproductive health, relationship counseling tools, dating platforms for genuine connections, educational content about consent and healthy relationships, and public health information about sexual safety
Message sourceAll messages
Malware Policy

Catches requests for malicious hacking tools and destructive software.

FieldValue
NameMalware
Flagged contentRansomware development, security exploit frameworks, DDoS attack systems, credential theft malware, system infiltration backdoors, destructive programs, unauthorized surveillance tools, network intrusion utilities, data exfiltration tools, privilege escalation exploits, botnet command systems, keyloggers, rootkits, trojans, and any software designed to compromise or damage computer systems
Allowed contentLegitimate cybersecurity research tools, authorized penetration testing frameworks, defensive security software, vulnerability assessment utilities, network monitoring for administrators, security auditing applications, educational cybersecurity materials, whitehat research projects, bug bounty testing tools, and security software for protective purposes with proper authorization
Message sourceAll messages

Step 3: Create a Deployment

Create a deployment that groups your policies together.

  1. Go to the Deployments page
  2. Click Add Deployment
  3. Name it vibe-coding-production
  4. Select all the policies you created above
  5. 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: '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 };
    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 {
  session: {
    flagged: boolean;
    internal_session_id: string;
    external_session_id?: string;
    policies: Record<string, { name: string; flagged: boolean }>;
  };
  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();
}

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.session.flagged) {
    const flaggedPolicies = Object.entries(promptCheck.session.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.session.flagged) {
    const flaggedPolicies = Object.entries(codeCheck.session.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 || '',
  };
}

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');
});

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);
}

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.

  1. Go to Integrations → Slack
  2. Click Connect to Slack and authorize the app
  3. Select a channel (e.g., #security-alerts)
  4. Select only critical policies — choose high-priority policies like “Malware” or “Phishing” to avoid alert fatigue
  5. 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.

FieldValue
Included contentOnline gambling platforms, sports betting sites, casino games, lotteries, binary outcome games, prediction markets with monetary stakes, sports betting analyzers, odds manipulation tools, slots/roulette/crash game development
Excluded contentEducational content about probability or game theory, sports statistics tracking without betting, knowledge-based quiz apps, academic research on gambling behavior, news reporting on gambling industry
User Refunds

Track when users request refunds or compensation.

FieldValue
Included contentDirect refund requests due to dissatisfaction or quality issues, compensation demands for partial refunds or credits, service complaints paired with requests for monetary compensation
Excluded contentGenuine positive feedback without compensation requests, general discussions about service features or experiences without requesting money back
User Praise

Capture genuine expressions of gratitude and positive feedback.

FieldValue
Included contentSincere expressions like “thank you”, “thanks for your help”, “you did great”, “I appreciate this”, “that was really helpful”, earnest praise like “great work”, “excellent assistance”, “wonderful explanation”
Excluded contentSarcastic appreciation with contradictory context, obviously fake or exaggerated praise followed by dismissal, neutral requests or questions, negative feedback or complaints

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

View Sessions Dashboard

Monitor flagged sessions and review moderation decisions

Context Merging

Learn more about efficient multi-turn conversation handling

Risk Scoring

Deep dive into user risk assessment with Radar

Policy Configuration

Fine-tune your policies for better accuracy