2026-04-06 · DATA ROOM
RAGGuard
RAGGuard: De Prototipo a IA Fiable, Monitoreada y Rentable
ELEVATOR PITCH
RAGGuard es un microservicio API-first que transforma prototipos RAG en productos de IA fiables, permitiendo a startups SaaS monitorear la calidad de recuperación, precisión de respuestas y costos en producción. Con un Health Score del 88% y un impresionante Profit Margin del 89%, garantiza fiabilidad y rentabilidad.
VALUE PROPOSITION
Nuestra solución plug-and-play, agnóstica al stack, se integra sin esfuerzo en tu infraestructura existente, ofreciendo una evaluación RAG robusta y reduciendo drásticamente la barrera para la IA en producción.
EXPLAINER.md
RAGGuard API — Explainer
Production-quality observability and evaluation for RAG pipelines.
Micro-startup MVP · Spring Boot 4.0.4 · Java 25 · API-first SaaS
1. Concept
Modern teams can prototype a RAG (Retrieval-Augmented Generation) system in an afternoon using Dify, LangChain or LlamaIndex — but moving that prototype to production is a different story. Without tooling to measure quality, teams ship chatbots that hallucinate, retrieve irrelevant documents, or give answers that bear no relation to the user's question.
RAGGuard is a lightweight microservice that sits alongside any RAG stack and provides:
- Automated quality evaluation using an LLM-as-a-judge pattern (three RAG-specific metrics).
- Per-trace observability — every RAG interaction is stored and inspectable.
- Aggregate analytics — mean quality scores, cost per query, latency and token usage over time.
2. Architecture
┌─────────────────────────────────────────────────────┐
│ Client / RAG Pipeline │
└─────────────────────┬───────────────────────────────┘
│ POST /v1/traces
▼
┌─────────────────────────────────────────────────────┐
│ TraceController ──► TraceService │
│ │ │
│ ▼ │
│ TraceLog saved (PENDING) │
│ │ │
│ @Async (Virtual Thread) │
│ │ │
│ ▼ │
│ EvaluationService │
│ ┌──────────────────┐ │
│ │ RestClient │──► OpenAI API │
│ │ LLM-Judge Prompt │ │
│ └──────────────────┘ │
│ │ │
│ EvaluationResult saved (EVALUATED) │
│ │
│ MetricsController ──► TraceService.getMetricsSummary│
└─────────────────────────────────────────────────────┘
│
▼
PostgreSQL Database
┌────────────────┐ ┌──────────────────────┐
│ trace_logs │◄──│ evaluation_results │
└────────────────┘ └──────────────────────┘
Key design decisions
| Decision | Rationale |
|---|---|
| Virtual Threads (%%INLINE0%% + %%INLINE1%%) | LLM API calls block for 1–10 s. Virtual threads allow thousands of concurrent evaluations without OS thread exhaustion. |
| %%INLINE2%% (Spring 7) | Modern, fluent, non-reactive HTTP client. Replaces %%INLINE3%% without requiring reactive programming. |
| LLM-as-a-Judge | Reference-free evaluation — no labelled dataset required. The LLM scores faithfulness, context relevance and answer relevance from the raw trace data. |
| Async ingestion (202 Accepted) | The ingest endpoint returns immediately. Evaluation happens in the background, keeping p99 ingest latency well under 100 ms regardless of LLM latency. |
| Demo mode (no API key) | When ragguard.openai.api-key is empty, the service generates plausible simulated scores so the full pipeline can be tested without real LLM costs. |
3. Domain Model
TraceLog
Stores one complete RAG pipeline execution.
| Column | Type | Description |
|---|---|---|
id | UUID | Primary key |
user_prompt | TEXT | The question from the end-user |
retrieved_contexts | TEXT | JSON array of document chunks |
final_response | TEXT | The LLM-generated answer |
model_name | VARCHAR | Generative model identifier |
input_tokens | INT | Prompt token count |
output_tokens | INT | Completion token count |
latency_ms | BIGINT | End-to-end pipeline latency |
cost_usd | DOUBLE | Estimated API cost |
status | VARCHAR | Evaluation lifecycle status |
created_at | TIMESTAMP | Ingestion time |
EvaluationResult
LLM-judge scores for a trace (1-to-1 with TraceLog).
| Column | Type | Description |
|---|---|---|
id | UUID | Primary key |
| %%INLINE20%% | UUID | FK → %%INLINE21%% |
faithfulness | DOUBLE | [0–1] Answer grounded in context |
context_relevance | DOUBLE | [0–1] Context relevant to query |
answer_relevance | DOUBLE | [0–1] Answer relevant to query |
evaluated_at | TIMESTAMP | Evaluation completion time |
judge_model | VARCHAR | Model used as judge |
4. API Endpoints
POST /v1/traces — Ingest a RAG trace
Accepts a trace payload, persists it, fires async evaluation. Returns 202 Accepted.
Request body:
{
"userPrompt": "What is retrieval-augmented generation?",
"retrievedContexts": [
"RAG is a technique that retrieves external documents before generation...",
"The retrieval step uses dense vector search over a knowledge base..."
],
"finalResponse": "RAG combines a retrieval system with a language model to ground responses in factual documents.",
"modelName": "gpt-4o-mini",
"inputTokens": 512,
"outputTokens": 128,
"latencyMs": 1340,
"costUsd": 0.00042
}
Response (202 Accepted):
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"status": "PENDING_EVALUATION",
"userPrompt": "...",
"faithfulness": null,
"contextRelevance": null,
"answerRelevance": null,
"createdAt": "2026-04-06T14:30:00"
}
GET /v1/traces/{id} — Retrieve a trace
Returns the full trace with evaluation scores once available.
Response (200 OK):
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"status": "EVALUATED",
"userPrompt": "What is retrieval-augmented generation?",
"retrievedContexts": ["...chunk 1...", "...chunk 2..."],
"finalResponse": "RAG combines...",
"faithfulness": 0.94,
"contextRelevance": 0.87,
"answerRelevance": 0.91,
"createdAt": "2026-04-06T14:30:00",
"evaluatedAt": "2026-04-06T14:30:03",
"judgeModel": "gpt-4o-mini"
}
GET /v1/metrics/summary — Analytics dashboard
Aggregated metrics across all historical traces.
Response (200 OK):
{
"totalTraces": 1500,
"evaluatedTraces": 1480,
"pendingTraces": 12,
"failedTraces": 8,
"avgFaithfulness": 0.872,
"avgContextRelevance": 0.811,
"avgAnswerRelevance": 0.896,
"avgCostUsd": 0.00038,
"avgLatencyMs": 1245.3,
"totalInputTokens": 768000,
"totalOutputTokens": 192000,
"generatedAt": "2026-04-06T14:35:00"
}
Swagger UI
Available athttp://localhost:8080/swagger-ui/index.html when the application is running.
5. LLM-as-a-Judge: Evaluation Metrics
RAGGuard implements the three canonical RAGAS-style metrics:
| Metric | Definition | Range |
|---|---|---|
| Faithfulness | Does every claim in the answer appear in the retrieved contexts? | 0 = hallucination, 1 = fully grounded |
| Context Relevance | How much of the retrieved context is actually needed to answer the question? | 0 = irrelevant noise, 1 = perfectly on-topic |
| Answer Relevance | Does the answer directly address the user's question? | 0 = off-topic, 1 = fully responsive |
6. Configuration
Add to application.yml (or use environment variables):
ragguard:
openai:
api-key: ${OPENAI_API_KEY:} # leave empty for demo/simulated mode
base-url: https://api.openai.com/v1 # override for Azure OpenAI or proxies
model: gpt-4o-mini # any model with JSON mode support
spring:
datasource:
url: jdbc:postgresql://localhost:5432/ragguard
username: postgres
password: secret
jpa:
hibernate:
ddl-auto: update
show-sql: false
threads:
virtual:
enabled: true # enables virtual threads for Tomcat in Spring Boot 4
Environment variables:
| Variable | Description |
|---|---|
OPENAI_API_KEY | OpenAI secret key. Omit to run in demo mode. |
SPRING_DATASOURCE_URL | JDBC URL for PostgreSQL |
SPRING_DATASOURCE_USERNAME | DB username |
SPRING_DATASOURCE_PASSWORD | DB password |
7. How to Run
Prerequisites
- Java 25+
- PostgreSQL 15+ (or Docker)
- Maven 3.9+
Quick start with Docker PostgreSQL
# Start PostgreSQL
docker run -d \
--name ragguard-pg \
-e POSTGRES_DB=ragguard \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=secret \
-p 5432:5432 \
postgres:16
# Build and run
cd solutions/2026-04-06-rag-guard-api
mvn clean package -DskipTests
java -jar target/rag-guard-api-0.0.1-SNAPSHOT.jar \
--spring.datasource.url=jdbc:postgresql://localhost:5432/ragguard \
--spring.datasource.username=postgres \
--spring.datasource.password=secret \
--ragguard.openai.api-key=$OPENAI_API_KEY
Demo mode (no DB, no LLM)
The service starts in demo mode when no API key is provided. All evaluations return plausible simulated scores. Swap PostgreSQL for H2 by adding the H2 dependency and setting:spring:
datasource:
url: jdbc:h2:mem:ragguard;DB_CLOSE_DELAY=-1
jpa:
hibernate:
ddl-auto: create-drop
Ingest a test trace
curl -X POST http://localhost:8080/v1/traces \
-H 'Content-Type: application/json' \
-d '{
"userPrompt": "What is RAG?",
"retrievedContexts": [
"RAG stands for Retrieval-Augmented Generation.",
"It combines retrieval from a knowledge base with LLM generation."
],
"finalResponse": "RAG is a technique that augments LLM generation with retrieved documents.",
"modelName": "gpt-4o-mini",
"inputTokens": 256,
"outputTokens": 64,
"latencyMs": 980,
"costUsd": 0.00021
}'
8. Business Analysis
Problem
RAG prototypes fail in production because teams lack visibility into:- Quality — are answers faithful to the retrieved context?
- Retrieval effectiveness — is the vector search returning relevant chunks?
- Cost — how much does each query actually cost?
Target audience
CTOs and AI/ML engineering leads at Series A–C SaaS startups shipping AI features to customers.Monetization (API-first SaaS)
| Tier | Price | Limits |
|---|---|---|
| Free | $0/mo | 500 traces/mo, 7-day retention |
| Starter | $49/mo | 10 000 traces/mo, 90-day retention |
| Pro | $199/mo | 100 000 traces/mo, 1-year retention, webhook alerts |
| Enterprise | Custom | Unlimited, BYOK, self-hosted option |
Competitive moat
- Framework-agnostic — works with Dify, LangChain, LlamaIndex, custom stacks.
- Zero schema changes — integrates with any existing RAG pipeline via a single POST.
- Reference-free evaluation — no labelled dataset required.
- Async-first design — negligible overhead on the critical path of the RAG pipeline.
9. References
- Top AI GitHub Repositories in 2026 (ByteByteGo) — Dify trend context
- RAGAS: Automated Evaluation of RAG Pipelines — foundational metrics paper
- Spring Framework 7 RestClient docs
- Spring Boot 4 Virtual Threads
- OpenAI Chat Completions API
FinOps Analysis
1. Resumen de Costos y Rentabilidad
RAGGuard, como micro-startup, presenta un modelo de negocio con una estructura de costos operativos excepcionalmente lean y un alto margen de beneficio potencial en su fase inicial. La dependencia principal recae en los servicios de LLM-as-a-judge y una infraestructura cloud básica.
2. Desglose de Costos Operativos Mensuales (Estimación MVP)
- Tokens LLM (OpenAI gpt-4o-mini): ~$15/mes
gpt-4o-mini: $0.15 por millón de tokens de entrada, $0.60 por millón de tokens de salida.
Cálculo: (60M tokens de entrada $0.15/1M) + (10M tokens de salida * $0.60/1M) = $9.00 + $6.00 = $15.00.
- Infraestructura Cloud (AWS/GCP/Azure equivalente): ~$40/mes
Costo Operativo Mensual Total Estimado: ~$55
3. Estimación de Ingresos Mensuales
- Modelo de Monetización: API-first SaaS.
- Precio Asumido: $25/cliente/mes (nivel de entrada para un producto que resuelve un problema crítico de calidad).
- Clientes Iniciales (Objetivo MVP): 20 clientes.
4. Margen de Beneficio
- Ingresos: $500/mes
- Costos Operativos: $55/mes
- Beneficio Bruto Operativo: $500 - $55 = $445/mes
Este margen de beneficio operativo es excepcionalmente alto, lo que indica que la propuesta de valor de RAGGuard puede ser muy rentable desde el punto de vista de los costos de infraestructura y LLM. Es crucial notar que este cálculo no incluye otros costos asociados a la operación de un negocio (salarios fundadores, marketing, ventas, herramientas de desarrollo, etc.), que serían significativos en una etapa posterior.
5. Optimizaciones FinOps Concretas para Reducir Costos
- Optimización de Prompts LLM:
- Caching de Evaluaciones LLM:
- Procesamiento Asíncrono y Batching:
- Arquitectura Serverless para la Evaluación:
EvaluationService (la parte que llama al LLM) a una función serverless (ej. AWS Lambda, Google Cloud Functions). Esto es ideal para cargas de trabajo intermitentes.
* Impacto: Se paga solo por el tiempo de cómputo real utilizado, lo que puede ser más económico que mantener una instancia EC2/VM siempre encendida para tareas asíncronas.
- Monitoreo Continuo de Uso y Costos:
6. Consideraciones Futuras
- Escalabilidad: A medida que la base de clientes crezca, los costos de LLM e infraestructura aumentarán. Será crucial optimizar la selección de modelos LLM (explorar modelos open-source auto-hosteados para volúmenes muy altos) y escalar la infraestructura de manera eficiente (ej. con auto-scaling groups y bases de datos elásticas).
- Costos de Adquisición de Clientes (CAC): El alto margen operativo permite una mayor inversión en marketing y ventas para escalar la adquisición de clientes, lo cual será el próximo gran desafío FinOps.
- Descuentos por Compromiso: Una vez que el uso se estabilice, considerar planes de ahorro (ej. AWS Savings Plans, Google Committed Use Discounts) para la infraestructura y contactar a proveedores de LLM para descuentos por volumen.
MVP FEATURES
- 01API Endpoint para ingesta de trazas: Un endpoint para recibir el prompt del usuario, los contextos recuperados, la respuesta final y metadatos del modelo.
- 02Evaluación Automatizada de Métricas RAG: Cálculo automático de métricas clave (fidelidad, relevancia del contexto, relevancia de la respuesta) usando un enfoque de LLM-as-a-judge.
- 03Dashboard Analítico Básico: Una API que expone métricas agregadas a lo largo del tiempo: puntuaciones medias, coste por consulta, latencia y uso de tokens.
- 04Visor de Trazas Individuales: Un endpoint para recuperar una traza completa por ID, mostrando el flujo desde la consulta del usuario hasta la respuesta final para una depuración sencilla.
“Transforma tus prototipos RAG en productos de IA fiables y monitoreados con precisión.”
Explora la documentación de nuestra API y prueba RAGGuard para asegurar la calidad de tu IA hoy mismo.
NetSentry AI
85NetSentry AI capacita a los equipos de SRE y DevOps para convertir el vasto ruido de la telemetría en análisis de causa raíz instantáneos, ahorrando millones en tiempo de inactividad. Nuestra innovadora arquitectura de agentes colaborativos, validada con un Health Score del 87%, ofrece claridad y eficiencia sin precedentes.
RootCause AI
81RootCause AI es una API que utiliza agentes de IA colaborativos para diagnosticar la causa raíz de fallos de red en segundos, no en horas, eliminando la fatiga de alertas para equipos SRE/DevOps. Con un Health Score del 87% y un Margen de Beneficio del 92%, ofrecemos una solución escalable y financieramente sólida.
CogniFlow AI
80CogniFlow AI es un motor de orquestación de agentes 'headless' vía API para CTOs y Lead Engineers, eliminando el complejo código 'pegamento'. Con un Health Score del 87% y un margen de beneficio del 91%, permite a tus agentes construir y actuar de forma autónoma con una escalabilidad del 94%.