Data Processing & Validation
Prepare, validate, and protect the data that flows into and out of your AI models
Last reviewed
What You'll Learn#
Data Handling
- • Processing different data types and formats
- • Validating inputs and model output with Zod
- • Chunking and embedding content for RAG
- • Handling errors and edge cases gracefully
Best Practices
- • Data quality assessment and monitoring
- • Redacting PII before it reaches a model
- • Storing vectors alongside your data
- • Backup, retention, and deletion
Data Types & Challenges#
Structured Data
Organized data with a defined schema
Examples
- • Database records
- • CSV exports
- • CRM and booking records
Challenges
- • Schema validation
- • Data type consistency
- • Keeping records in sync
Tools
Unstructured Data
Text, documents, and media with no predefined format
Examples
- • Website pages and PDFs
- • Emails and support tickets
- • Images and audio
Challenges
- • Clean text extraction
- • Chunking for retrieval
- • PII hidden in free text
Tools
Semi-structured Data
Partially organized data, including what an AI model returns
Examples
- • JSON API responses
- • Log files
- • Model output (JSON)
Challenges
- • Format variations
- • Malformed or incomplete model output
- • Schema evolution
Tools
Validation Framework#
Data Quality
- Validate every input at the boundary with a schema (Zod)
- Check for null, empty, or truncated values
- Detect and remove duplicates before they reach your index
- Track freshness so stale content gets re-read
Model Output
- Ask for JSON that matches a schema, then validate it anyway
- Reject or retry when output fails validation
- Constrain enums and ranges instead of trusting free text
- Never pass raw model output to SQL, shell, or HTML
Security & Privacy
- Redact PII before text is sent to a model or a log
- Encrypt sensitive fields at rest
- Validate data source authenticity (signatures, allowlists)
- Apply retention and deletion policies, including to embeddings
Implementation Steps#
Data Ingestion Setup
Configure reliable data input mechanisms
- Set up data source connections with credentials in environment variables
- Choose batch or event-driven processing (queues or background jobs)
- Make ingestion idempotent so retries never create duplicates
- Add monitoring for data pipeline health
Validation & Redaction
Validate inputs and strip sensitive data early
- Define validation schemas once and share them across services
- Redact PII (emails, phone numbers, IDs) before any model call
- Report validation errors without echoing the raw data
- Set up alerts for critical validation failures
Chunking & Embeddings
Prepare unstructured content for retrieval (RAG)
- Split text on natural boundaries (headings, paragraphs) with some overlap
- Store source URL and section metadata with every chunk
- Generate embeddings in batches and record the model name used
- Re-embed everything when you switch embedding models
Storage & Backup
Ensure reliable data persistence and recovery
- Store vectors next to your data (e.g. Postgres with pgvector and an HNSW index)
- Implement automated backups and test restores
- Delete chunks and embeddings when the source data is deleted
- Monitor storage growth, index size, and query latency
RAG Ingestion & Output Validation Example#
// Example: RAG ingestion pipeline + model output validation
// Node 20+, ES modules. npm install zod openai pg
import OpenAI from 'openai';
import pg from 'pg';
import { z } from 'zod';
const openai = new OpenAI(); // reads OPENAI_API_KEY from the environment
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
// 1536 dimensions by default. Pass `dimensions` to store shorter vectors.
const EMBEDDING_MODEL = 'text-embedding-3-small';
// 1. Validate input at the boundary. Reject bad data before it costs tokens.
const DocumentSchema = z.object({
id: z.string().min(1),
sourceUrl: z.url(),
text: z.string().min(1).max(500_000),
});
// 2. Redact obvious PII before text leaves your system.
// Regexes are a baseline. Use a dedicated tool (e.g. Microsoft Presidio) for names/addresses.
const PII_PATTERNS = [
[/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]'],
[/[\w.+-]+@[\w-]+\.[\w.-]+/g, '[EMAIL]'],
[/(?:\+?1[\s.-]?)?\(?\b\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\b/g, '[PHONE]'],
];
export function redactPII(text) {
return PII_PATTERNS.reduce((out, [pattern, label]) => out.replace(pattern, label), text);
}
// 3. Chunk on paragraph boundaries with overlap, so an answer that spans
// two chunks is still retrievable. Sizes are in characters.
export function chunkText(text, { size = 1200, overlap = 200 } = {}) {
const chunks = [];
let current = '';
for (const paragraph of text.split(/\n{2,}/)) {
if (current && current.length + paragraph.length > size) {
chunks.push(current.trim());
current = current.slice(-overlap);
}
current += `\n\n${paragraph}`;
}
if (current.trim()) chunks.push(current.trim());
return chunks;
}
// 4. Embed in one batch call and store in Postgres with pgvector:
// CREATE EXTENSION IF NOT EXISTS vector;
// CREATE TABLE chunks (id text PRIMARY KEY, doc_id text NOT NULL,
// content text NOT NULL, embedding vector(1536) NOT NULL);
// CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
export async function ingestDocument(raw) {
const doc = DocumentSchema.parse(raw);
const chunks = chunkText(redactPII(doc.text));
const { data } = await openai.embeddings.create({
model: EMBEDDING_MODEL,
input: chunks,
});
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('DELETE FROM chunks WHERE doc_id = $1', [doc.id]);
for (const item of data) {
await client.query(
'INSERT INTO chunks (id, doc_id, content, embedding) VALUES ($1, $2, $3, $4)',
[`${doc.id}:${item.index}`, doc.id, chunks[item.index], JSON.stringify(item.embedding)],
);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
// Log IDs and counts. Never log the document text.
console.info(JSON.stringify({ event: 'document_ingested', docId: doc.id, chunks: chunks.length }));
return chunks.length;
}
// 5. Validate model output before anything downstream trusts it.
export const LeadSchema = z.object({
service: z.string().min(1),
intent: z.enum(['quote', 'booking', 'support', 'other']),
urgency: z.number().int().min(1).max(5),
});
export function parseModelOutput(rawText) {
let json;
try {
json = JSON.parse(rawText);
} catch {
return { ok: false, error: 'Model did not return valid JSON' };
}
const result = LeadSchema.safeParse(json);
if (!result.success) {
return { ok: false, error: z.prettifyError(result.error) };
}
return { ok: true, data: result.data };
}
// Tip: z.toJSONSchema(LeadSchema) gives you a JSON Schema to pass to your
// provider's structured output mode. Keep the safeParse check anyway.Or skip the build
If your goal is answering questions from your own content, the AI Chat Agent runs this whole pipeline for you.
- • Reads your website and builds the knowledge base automatically
- • Chunking, embeddings, and retrieval already set up
- • Refresh your content from the dashboard whenever it changes
Next Steps#
With data processing fundamentals covered, learn how to build automated workflows that use your processed data.