> ## Documentation Index
> Fetch the complete documentation index at: https://docs.whitecircle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Vibe Coding App

> Integrate White Circle into your AI-powered code generation app to moderate prompts and generated code in real-time

export const domain = 'https://eu.whitecircle.com';

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.

<Info>
  **Only the last message is evaluated for violations.** When you send a conversation with multiple messages, White Circle evaluates only the final message against your policies. Previous messages provide context but are not flagged. This means you should send user prompts and AI-generated code separately for individual moderation.
</Info>

***

## 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 theme={null}
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 <Link href={`${domain}/settings/api-keys`} target="_blank">API Keys page</Link>
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 <Link href={`${domain}/policies`} target="_blank">Policies page</Link> and create the following:

<AccordionGroup>
  <Accordion title="Phishing Policy">
    Detects attempts to create deceptive interfaces designed to steal credentials.

    | Field               | Value                                                                                                                                                                                                                                                                                                                                  |
    | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Name**            | Phishing                                                                                                                                                                                                                                                                                                                               |
    | **Flagged content** | Creation 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 content** | Legitimate 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 source**  | All messages                                                                                                                                                                                                                                                                                                                           |
  </Accordion>

  <Accordion title="Adult Content Policy">
    Prevents generation of explicit sexual content and adult platforms.

    | Field               | Value                                                                                                                                                                                                                                                                                                                                                 |
    | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Name**            | Adult Content                                                                                                                                                                                                                                                                                                                                         |
    | **Flagged content** | Explicitly 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 content** | Romantic 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 source**  | All messages                                                                                                                                                                                                                                                                                                                                          |
  </Accordion>

  <Accordion title="Malware Policy">
    Catches requests for malicious hacking tools and destructive software.

    | Field               | Value                                                                                                                                                                                                                                                                                                                                                                                                    |
    | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Name**            | Malware                                                                                                                                                                                                                                                                                                                                                                                                  |
    | **Flagged content** | Ransomware 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 content** | Legitimate 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 source**  | All messages                                                                                                                                                                                                                                                                                                                                                                                             |
  </Accordion>
</AccordionGroup>

<Tip>
  Use **Shadow mode** when first creating policies to test them without affecting your production traffic. You can monitor flagged content in the dashboard before enabling enforcement.
</Tip>

***

## Step 3: Create a Deployment

Create a deployment that groups your policies together.

1. Go to the <Link href={`${domain}/deployments`} target="_blank">Deployments page</Link>
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**

<Info>
  Consider creating separate deployments for different environments:

  * `vibe-coding-development` — for dev and QA testing
  * `vibe-coding-production` — for live traffic
</Info>

***

## Step 4: Integrate the API

Now integrate White Circle into your code generation app. Below is a complete implementation example.

<Tip>
  **Context merging reduces payload size.** Use this recommended flow:

  1. **First request in a session**: Send the full conversation history to establish context
  2. **Subsequent requests**: Set `include_context: true` and send only the new message — White Circle automatically prepends previous messages from the session

  This approach minimizes data transfer while maintaining full conversation context for accurate moderation.
</Tip>

### Configuration

First, set up your configuration and White Circle client:

<CodeGroup>
  ```typescript TypeScript theme={null}
  // 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();
  }
  ```

  ```python Python theme={null}
  # 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()
  ```
</CodeGroup>

### Main Code Generation Logic

Here's the core implementation with White Circle integration:

<CodeGroup>
  ```typescript TypeScript expandable theme={null}
  // 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 || '',
    };
  }
  ```

  ```python Python expandable theme={null}
  # 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["session"]["flagged"]:
          flagged_policies = [
              policy["name"]
              for policy in prompt_check["session"]["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["session"]["flagged"]:
          flagged_policies = [
              policy["name"]
              for policy in code_check["session"]["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 ""}
  ```
</CodeGroup>

### API Endpoint

Expose the code generator as an API endpoint in your web framework:

<CodeGroup>
  ```typescript TypeScript (Express) theme={null}
  // 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');
  });
  ```

  ```python Python (FastAPI) theme={null}
  # 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."},
          )
  ```
</CodeGroup>

***

## 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.

<CodeGroup>
  ```typescript TypeScript expandable theme={null}
  // 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);
  }
  ```

  ```python Python expandable theme={null}
  # 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
      )
  ```
</CodeGroup>

***

## 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 <Link href={`${domain}/integrations/slack`} target="_blank">Integrations → Slack</Link>
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

<Tip>
  Keep your alert channel focused by enabling notifications only for policies that require immediate attention. You can always review all violations in the dashboard.
</Tip>

<Info>
  For private channels, first invite the bot with `/invite @White Circle Notifications`
</Info>

***

## Step 7: Track Metrics

Beyond moderation, use White Circle's metrics to gain insights into your code generation sessions. Create metrics on the <Link href={`${domain}/metrics`} target="_blank">Metrics page</Link>:

<AccordionGroup>
  <Accordion title="Gambling">
    Detect requests related to gambling platforms and betting systems.

    | Field                | Value                                                                                                                                                                                                                             |
    | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Included content** | Online 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 content** | Educational 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                          |
  </Accordion>

  <Accordion title="User Refunds">
    Track when users request refunds or compensation.

    | Field                | Value                                                                                                                                                                                   |
    | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Included content** | Direct refund requests due to dissatisfaction or quality issues, compensation demands for partial refunds or credits, service complaints paired with requests for monetary compensation |
    | **Excluded content** | Genuine positive feedback without compensation requests, general discussions about service features or experiences without requesting money back                                        |
  </Accordion>

  <Accordion title="User Praise">
    Capture genuine expressions of gratitude and positive feedback.

    | Field                | Value                                                                                                                                                                                                            |
    | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Included content** | Sincere 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 content** | Sarcastic appreciation with contradictory context, obviously fake or exaggerated praise followed by dismissal, neutral requests or questions, negative feedback or complaints                                    |
  </Accordion>
</AccordionGroup>

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

<AccordionGroup>
  <Accordion title="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.
  </Accordion>

  <Accordion title="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.
  </Accordion>

  <Accordion title="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.
  </Accordion>

  <Accordion title="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
  </Accordion>

  <Accordion title="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.
  </Accordion>

  <Accordion title="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.
  </Accordion>
</AccordionGroup>

***

## Example Generation Flow

Here's how a typical moderated code generation session looks:

```mermaid theme={null}
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

<CardGroup cols={2}>
  <Card title="View Sessions Dashboard" icon="chart-line" href={`${domain}/sessions`}>
    Monitor flagged sessions and review moderation decisions
  </Card>

  <Card title="Context Merging" icon="layer-group" href="/2026-04-15/session/context">
    Learn more about efficient multi-turn conversation handling
  </Card>

  <Card title="Risk Scoring" icon="radar" href="/2026-04-15/user/radar">
    Deep dive into user risk assessment with Radar
  </Card>

  <Card title="Policy Configuration" icon="shield" href="/2026-04-15/first-steps/policies">
    Fine-tune your policies for better accuracy
  </Card>
</CardGroup>
