AI Security
AI models ko protect karna zaroori hai � adversarial attacks, data leakage, unauthorized access sab ko handle karna padta hai.
Prerequisite: Monitoring
Key Concepts
Authentication
Identity verify karo � kaun request kar raha hai, ye confirm karo pehle.
Rate Limiting
Abuse prevent karo � zyada requests aane se system crash na ho.
Input Validation
Malicious input roko � dangerous characters aur commands filter karo.
Encryption
Data protect karo � sensitive information ko secure rakho.
Code Examples
Security Middleware
# Security middleware
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
import time
app = FastAPI()
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["https://dswallah.com"],
allow_methods=["GET", "POST"],
)
# Rate limiting
request_counts = {}
@app.middleware("http")
async def rate_limit(request: Request):
client_ip = request.client.host
current_time = time.time()
if client_ip not in request_counts:
request_counts[client_ip] = []
# Keep requests from last minute
request_counts[client_ip] = [
t for t in request_counts[client_ip]
if current_time - t < 60
]
if len(request_counts[client_ip]) > 100:
raise HTTPException(status_code=429, detail="Rate limit exceeded")
request_counts[client_ip].append(current_time)
# Input validation
def validate_input(text: str) -> bool:
dangerous = ["
Frequently Asked Questions
What is prompt injection?
Prompt injection is an attack where malicious input in a prompt or document tricks an LLM into ignoring its system instructions and executing unintended actions. It is the top OWASP LLM security risk today.
How do I prevent data leakage in LLM apps?
Never send secrets or PII to the model. Redact sensitive fields, use role-based access control, audit logs, and consider self-hosted or private models for regulated data.
What is RAG poisoning and how do you defend against it?
Attackers inject malicious text into documents that a RAG system retrieves, steering answers or exfiltrating data. Defenses include sanitizing sources, permission-scoped retrieval, and validating outputs before they reach users.
Should AI engineers learn security?
Yes. Production AI systems handle real user data and money. Basic security hygiene � input validation, rate limiting, prompt safety, and monitoring � is now expected in AI Engineer interviews and job descriptions.
Have more questions? Chat with us on WhatsApp