Saltar al contenido

← IA en compliance sin tercerizar la decisión: lo que aprendí construyendo un SaaS de PIF para cosmética europea

IA en compliance sin tercerizar la decisión: lo que aprendí construyendo un SaaS de PIF para cosmética europea

Español ↔ English

Este proyecto me enseñó que "parece correcto" no es una propiedad de compliance

En Eurologado, el producto ayuda a empresas de cosméticos a organizar información usada en el Product Information File para el mercado europeo.

Ese dominio cambió mi forma de pensar software asistido por IA.

Un párrafo fluido puede ser excelente en marketing. En compliance, la fluidez puede esconder una fuente faltante, un dato viejo o una afirmación sin evidencia.

La pregunta central no era "¿cómo hago que el modelo escriba mejor?", sino:

¿cómo hago que el sistema distinga lenguaje generado, hechos verificados y evidencia obligatoria?

Primera separación: documento no es dato

Un PDF es una salida. No debería ser la única fuente de verdad.

Si todo existe solo como documento generado, responder preguntas estructuradas se vuelve difícil:

  • ¿qué sección obligatoria falta?
  • ¿qué dato originó este párrafo?
  • ¿qué versión de la fuente se usó?
  • ¿qué cambió entre revisiones?
  • ¿qué escribió la IA y qué confirmó una persona?

Prefiero guardar el dominio estructurado y generar el documento desde esa estructura.

txt
datos estructurados
        ↓
reglas de validación
        ↓
redacción asistida por IA
        ↓
revisión humana
        ↓
documento versionado

La IA redacta; la regla decide

Evité convertir el LLM en motor de compliance.

La IA puede resumir, reescribir, sugerir borradores, clasificar texto o señalar inconsistencias. Pero si una condición dice que cierto campo debe existir antes de avanzar, eso pertenece al código o al schema.

ts
const missing = requiredFields.filter(
  field => product[field] == null || product[field] === ''
)

if (missing.length > 0) {
  return { status: 'incomplete', missing }
}

El modelo puede explicar el problema. No debería redefinir si el requisito existe.

El mejor prompt no arregla un mal modelo de datos

Es tentador solucionar todo agregando instrucciones como "no inventes", "usa solo las fuentes" o "indica lo que falta".

Sirven, pero no reemplazan estructura.

Si identidad del producto, documentos, versiones y estados están mezclados en texto libre, el modelo tiene que reconstruir el dominio en cada llamada.

Un buen modelo de datos le quita trabajo al prompt.

"No alucines" no es un mecanismo de seguridad

Una instrucción al modelo es probabilística. Un control de compliance necesita garantías adicionales.

txt
salida del LLM
   ↓
parsear a schema
   ↓
validar tipos y campos
   ↓
comparar con fuente de verdad
   ↓
marcar ausencias o soporte insuficiente
   ↓
revisión humana cuando corresponda

Schema validation no demuestra que un hecho sea verdadero, pero impide que un texto bonito salte por encima del software.

La ausencia es dato de primera clase

Hay una diferencia enorme entre:

json
{
  "safetyReport": null,
  "safetyReportStatus": "missing"
}

y generar una sección que visualmente parece completa.

Cuando la ausencia se modela, puede filtrarse y medirse: qué clientes están incompletos, qué requisito bloquea más casos, cuánto lleva pendiente y qué fuente todavía falta.

Eso es más útil que un chatbot diciendo que no encontró algo.

Versionar el documento sin versionar sus fuentes es media auditoría

Si la revisión 7 se generó con datos que luego cambiaron, conservar solo el PDF final no alcanza.

ts
type DocumentRevision = {
  id: string
  productId: string
  version: number
  generatedAt: Date
  sourceSnapshotId: string
  templateVersion: string
  modelId?: string
  promptVersion?: string
  reviewedBy?: string
  approvedAt?: Date
}

El principio es simple: la salida debe poder rastrearse hasta los datos y lógica que la produjeron.

La edición humana no es "fracaso de la IA"

En dominios de riesgo, la corrección humana es parte del diseño.

Lo que importa es hacer la revisión eficiente: mostrar cambios, destacar pasajes de baja confianza, enlazar afirmaciones a sus fuentes, conservar decisiones y no volver a preguntar lo que ya fue respondido.

La meta no es eliminar al especialista, sino mover su tiempo desde ensamblaje repetitivo hacia juicio profesional.

El feedback humano puede convertirse en dataset de mejora

Si guardo contexto, borrador, edición, motivo y versión aceptada, las correcciones empiezan a servir para evaluación y mejora.

txt
contexto
borrador del modelo
edición humana
motivo / categoría
versión final aceptada

No saltaría directo a fine-tuning. Primero buscaría patrones de error. Muchas veces la solución correcta es una regla nueva, un campo mejor o un template más claro.

Seguridad multi-tenant no depende de prompt

"Usa solo documentos del cliente actual" no es autorización.

La consulta debe estar limitada antes de enviar contexto al modelo.

sql
SELECT *
FROM product_documents
WHERE tenant_id = $1
  AND product_id = $2;

El prompt orienta comportamiento. La aplicación y la base controlan acceso. Son problemas distintos.

El modelo también debe ser reemplazable

Proveedores y modelos cambian rápido. Prefiero una interfaz de dominio estable y adapters por proveedor.

ts
interface ComplianceDraftingService {
  draftSection(input: DraftSectionInput): Promise<DraftSectionResult>
}

Eso reduce acoplamiento y permite comparar modelos con los mismos casos.

La evaluación necesita casos reales del dominio

Benchmarks genéricos no responden si un flujo es confiable para este producto.

Me interesan escenarios como fuente obligatoria ausente, documentos contradictorios, datos viejos, una excepción crítica en texto largo, ambigüedad que debería escalarse y casos completos donde la IA no debe inventar advertencias.

Puedo medir detección de ausencias, claims sin soporte, extracción, validez de schema y aceptación por el revisor.

El aprendizaje mayor fue separar plausibilidad de conformidad

La regulación europea de cosméticos define obligaciones concretas alrededor del Product Information File. Por eso el software necesita más que texto profesional.

El patrón que me quedó es:

txt
IA para interpretar y redactar
código para invariantes
schema para contrato
evidencia para explicar
humano como autoridad final cuando corresponda

Es menos mágico que "sube documentos al chatbot".

También es mucho más útil cuando existen auditoría, riesgo regulatorio o impacto financiero. Ahí la IA empieza a dejar de ser demo y pasa a ser software.

Referencias

This project taught me that "looks correct" is not a compliance property

In Eurologado, the product helps cosmetics businesses organize information used in a Product Information File for the European market.

That domain changed the way I think about AI-assisted software.

A fluent paragraph is useful in marketing content. In compliance, fluency can become dangerous if it hides missing evidence, outdated source data or an unsupported statement.

So the core design question was never "how do I make the model write better?". It was:

how do I make the system distinguish generated language from verified facts and required evidence?

The first separation: a document is not the data

A PDF is an output format. It should not be the only source of truth.

If the only representation of a regulatory artifact is a long generated document, the application has a hard time answering structured questions:

  • which required sections are missing?
  • which ingredient or product record produced this paragraph?
  • which version of the source data was used?
  • what changed between revisions?
  • which statement was written by AI and which was explicitly confirmed by a person?

I prefer storing structured domain data first and generating the document from that data.

txt
structured product data
        ↓
validation rules
        ↓
AI-assisted drafting
        ↓
human review
        ↓
versioned document

That order makes the system inspectable.

AI drafts; rules decide

One of the strongest architecture principles in the project was to avoid turning an LLM into the compliance engine.

The model can be good at:

  • summarizing source material;
  • rewriting technical text;
  • suggesting a draft section;
  • classifying free text;
  • highlighting potential inconsistency.

But a deterministic requirement such as "field X must exist before this stage can be completed" belongs in code or schema.

ts
const missing = requiredFields.filter(
  field => product[field] == null || product[field] === ''
)

if (missing.length > 0) {
  return {
    status: 'incomplete',
    missing,
  }
}

The LLM can help a person understand the problem. It should not redefine whether the requirement exists.

A better prompt cannot repair a weak data model

It is tempting to solve every AI problem by expanding the prompt:

txt
Do not invent.
Do not omit mandatory data.
Use only provided facts.
If something is missing, say it is missing.
...

Those instructions are useful, but they are not a substitute for structure.

If product identity, responsible person, source documents, versions and validation states are all mixed into free text, the model is forced to infer the system's domain every time it runs.

A good data model removes work from the prompt.

I would rather give the model a compact structured context with explicit missing values than a giant document and ask it to "be careful".

"Do not hallucinate" is not a safety mechanism

A model instruction is probabilistic. Compliance controls need stronger guarantees.

So I separate concerns:

txt
LLM output
   ↓
parse into schema
   ↓
validate types and required fields
   ↓
compare against source-of-truth data
   ↓
flag unsupported or missing items
   ↓
human review when required

Pydantic, JSON Schema or equivalent contracts are useful here because they force generated output into a known shape.

Schema validation does not prove a statement is true. It does, however, prevent "beautiful prose" from bypassing the rest of the software.

Missing information is first-class data

A surprisingly important design choice is to represent absence explicitly.

There is a major difference between:

json
{
  "safetyReport": null,
  "safetyReportStatus": "missing"
}

and a model silently producing language that makes the section look complete.

Missing data should be queryable, filterable and visible on dashboards.

Once absence becomes data, the product can answer useful questions:

  • which customers have incomplete files?
  • which requirement blocks completion most often?
  • how long has an item been pending?
  • which source document still needs to be uploaded?

That is much more valuable than a chatbot apologizing that it could not find something.

Versioning the document without versioning its sources is only half an audit trail

If revision 7 of a document was generated from product data that later changed, keeping only the final PDF is not enough.

I want the system to know, at minimum:

ts
type DocumentRevision = {
  id: string
  productId: string
  version: number
  generatedAt: Date
  sourceSnapshotId: string
  templateVersion: string
  modelId?: string
  promptVersion?: string
  reviewedBy?: string
  approvedAt?: Date
}

Not every field is required for every product, but the principle matters: an output should be traceable to the inputs and logic that created it.

That becomes especially valuable when a customer asks why a section changed months later.

Human editing is not "AI failure"

I do not measure an AI workflow by how often a person touches the output.

In high-stakes domains, human correction is part of the product design.

A better question is whether the system makes the review efficient:

  • show what changed;
  • highlight low-confidence or unsupported passages;
  • link claims back to source data;
  • preserve reviewer decisions;
  • avoid asking the same question twice when the answer is already known.

The goal is not to remove the specialist. It is to move their time away from repetitive assembly and toward judgment.

Human feedback can become an improvement dataset

When a reviewer changes generated text, that correction can be valuable—if stored with context and permission.

Instead of saving only the final paragraph, I can retain a structured record:

txt
input context
model draft
human edit
reason / category
accepted final version

Over time, that supports better prompts, regression tests and evaluation sets.

I would not jump directly to fine-tuning. First I want to understand recurring error classes.

Often the best improvement is a validation rule, a better source field or a clearer template, not a new model.

Multi-tenant security cannot depend on the prompt

A prompt such as "only use documents from the current customer" is not authorization.

Tenant boundaries belong in the application and database layers.

The retrieval query should already be scoped before anything reaches the model.

sql
SELECT *
FROM product_documents
WHERE tenant_id = $1
  AND product_id = $2;

The AI should receive only the data it is allowed to see.

This is one of the most important distinctions in enterprise AI: prompt instructions influence model behavior; authorization controls data access.

They solve different problems.

The model itself must remain replaceable

AI providers and model quality change quickly.

I avoid coupling the business workflow to one provider-specific response format deep inside the domain.

A boundary such as this is easier to evolve:

ts
interface ComplianceDraftingService {
  draftSection(input: DraftSectionInput): Promise<DraftSectionResult>
}

The adapter can use one provider today and another later. The domain should care about the contract, not the SDK.

This also makes evaluation much easier because two models can be run against the same cases.

Evaluation needs real domain cases

Generic benchmarks tell me very little about whether a model is safe enough for my workflow.

I care about cases such as:

  • required source missing;
  • contradictory values across documents;
  • outdated product information;
  • long input with one critical exception;
  • ambiguous wording that should be escalated instead of confidently rewritten;
  • complete case where the system should avoid inventing extra warnings.

An evaluation suite can score structured properties: missing-field detection, unsupported claims, extraction accuracy, schema validity and reviewer acceptance.

That gives me a regression signal when prompts, models or parsers change.

The biggest lesson was separating plausibility from compliance

European cosmetics regulation defines concrete obligations around the Product Information File and the information it contains. A system in this domain therefore needs more than text that sounds professional.

What I took from Eurologado is a pattern I now reuse in other enterprise AI work:

txt
AI for interpretation and drafting
code for invariants
schemas for contracts
evidence for explanation
humans for final authority when required

That combination is less magical than "upload your documents to a chatbot".

It is also much more useful when audits, regulatory risk or financial impact are involved.

In practice, that is where AI starts becoming software instead of a demo.

References