Client SDK v1.0.0

📦 Instalación

El SDK de NERHIA es un archivo único, sin dependencias npm. Cópialo a tu proyecto y empieza a usarlo.

🟨 JavaScript / Node.js

Compatible con Node 18+, browsers modernos y cualquier bundler. Solo requiere fetch nativo.

🐍 Python

Compatible con Python 3.7+. Usa solo urllib de la stdlib — cero pip installs.

JavaScript

# Descarga el SDK
curl -O https://raw.githubusercontent.com/leoncanales23/refactored-waffle/main/sdk/nerhia-client.js

# O cópialo manualmente a tu proyecto
cp nerhia-client.js ./lib/

Python

# Descarga el SDK
curl -O https://raw.githubusercontent.com/leoncanales23/refactored-waffle/main/sdk/nerhia_client.py

# O cópialo a tu proyecto
cp nerhia_client.py ./lib/

🚀 Quickstart

const { NerhiaClient } = require('./nerhia-client');

const nerhia = new NerhiaClient({
  apiKey: process.env.NERHIA_API_KEY,
});

// Ping rápido
const ping = await nerhia.ping();
console.log(ping); // { ok: true, version: '2.9.0', uptime: 3600 }

// Lanzar un render y esperar resultado
const job = await nerhia.render({
  location:    'Santiago',
  template:    'NERHIAReport',
  pm25:        42,
  temperatura: 22,
}, { wait: true });

console.log(job.videoUrl); // URL del video generado
from nerhia_client import NerhiaClient
import os

nerhia = NerhiaClient(api_key=os.environ["NERHIA_API_KEY"])

# Ping rápido
ping = nerhia.ping()
print(ping)  # {'ok': True, 'version': '2.9.0', 'uptime': 3600}

# Lanzar render y esperar resultado
job = nerhia.render(
    location="Santiago",
    template="NERHIAReport",
    pm25=42,
    temperatura=22,
    wait=True,
    on_progress=lambda j: print(f"Status: {j['status']}"),
)

print(job["videoUrl"])  # URL del video generado

🔑 Autenticación

Todas las rutas protegidas requieren la MASTER_API_KEY. El SDK la envía automáticamente como header X-Api-Key.

⚠️ Seguridad: Nunca escribas la API key directamente en el código. Usa variables de entorno: process.env.NERHIA_API_KEY (JS) o os.environ["NERHIA_API_KEY"] (Python).
# .env (nunca commitear este archivo)
NERHIA_API_KEY=nerhia-xxxxxxxxxxxxxxxxxxxxxxxxxx

# Cloud Run (pasar al deploy)
--set-env-vars NERHIA_API_KEY=nerhia-xxxx

🎬 Renders

El módulo renders permite crear, monitorear y listar renders de video.

Métodos

MétodoDescripciónHTTP
renders.create(params, opts)Crear render. opts.wait=true para esperarPOST /render
renders.get(jobId)Estado de un renderGET /render/:id
renders.list(filters)Listar rendersGET /renders
renders.batch(renders[])Múltiples rendersPOST /batch
renders.waitFor(jobId, opts)Polling hasta completarPolling
// Render con polling — onProgress callback
const job = await nerhia.renders.waitFor(jobId, {
  pollMs: 3000,
  onProgress: (j) => console.log(`→ ${j.status}`),
});

// Batch de renders
const batch = await nerhia.renders.batch([
  { compositionId: 'NERHIAReport', location: 'Lima',     pm25: 65 },
  { compositionId: 'NERHIAShort',  location: 'Bogotá',   pm25: 30 },
  { compositionId: 'NERHIAAlert',  location: 'Caracas',  pm25: 180 },
]);
console.log(batch.batchId, batch.jobs);
# Batch de renders
batch = nerhia.renders.batch([
    {"compositionId": "NERHIAReport", "location": "Lima",    "pm25": 65},
    {"compositionId": "NERHIAShort",  "location": "Bogotá",  "pm25": 30},
])
print(batch["batchId"], len(batch["jobs"]), "jobs")

📥 Ingest Studio

Sube PDFs o imágenes para extraer contexto automáticamente y lanzar renders.

// Solo extraer contexto
const ctx = await nerhia.ingest.upload('/ruta/informe.pdf');
console.log(ctx.context); // { location, pm25, no2, confidence }

// Subir + render automático
const result = await nerhia.ingest.uploadAndRender('/ruta/datos.pdf');
console.log(result.jobId, result.renderParams);
# Subir PDF → contexto
ctx = nerhia.ingest.upload("/ruta/informe.pdf")
print(ctx["context"])

# Subir + render automático
result = nerhia.ingest.upload_and_render("/ruta/datos.pdf")
job = nerhia.renders.wait_for(result["jobId"])

🔔 Webhooks

Registra URLs para recibir notificaciones cuando ocurren eventos en NERHIA.

// Registrar webhook
const hook = await nerhia.webhooks.register(
  'https://mi-app.com/hooks/nerhia',
  ['render.completed', 'render.failed', 'ingest.completed'],
  { secret: 'mi-secreto-hmac' }
);
console.log(hook.webhook.id);

// Disparar evento manual
await nerhia.webhooks.fire('render.completed', { jobId: 'test-123' });
# Registrar webhook
hook = nerhia.webhooks.register(
    url="https://mi-app.com/hooks/nerhia",
    events=["render.completed", "render.failed"],
    secret="mi-secreto-hmac",
)
print(hook["webhook"]["id"])

⚠️ Manejo de errores

const { NerhiaClient, NerhiaError } = require('./nerhia-client');

try {
  const job = await nerhia.render({ location: 'Lima' }, { wait: true });
} catch (err) {
  if (err instanceof NerhiaError) {
    console.error(`Error ${err.statusCode}: ${err.message}`);
    if (err.statusCode === 401) console.error('API key inválida');
    if (err.statusCode === 408) console.error('Timeout de render');
  }
}
from nerhia_client import NerhiaClient, NerhiaError

try:
    job = nerhia.render(location="Lima", wait=True)
except NerhiaError as e:
    print(f"Error {e.status_code}: {e}")
    if e.status_code == 401: print("API key inválida")
    if e.status_code == 408: print("Timeout de render")

📋 Referencia rápida

MóduloMétodos principales
nerhia.renderscreate, get, list, batch, waitFor
nerhia.queuestats, list, get, enqueue, cancel, retry, pause, resume
nerhia.ingestupload, uploadAndRender, templates
nerhia.webhooksregister, list, create, test, fire, delete
nerhia.analyticsoverview, templates, trends, recent, performance
nerhia.contextslist, get, update, delete, render, addTag
nerhia.workflowslist, create, run, runs, delete
nerhia.variantscreate, track, winner, conclude, listTests
nerhia.aigenerate, suggestTemplate, analyze, render
🔗 API Base URL: https://nerhia-api-852702111467.us-central1.run.app
📖 API Explorer: /api-explorer — prueba todas las rutas en el browser.