AI Gateway¶
Brandvelia exposes AI through an internal OpenRouter gateway in packages/ai. The app
never calls OpenRouter (or any model provider) directly — every AI feature routes through
this gateway, which handles provider selection, credential isolation, and cost tracking.
Components¶
┌───────────────┐ GET/POST ┌───────────────────┐ POST ┌───────────────┐
│ Next.js app │ ───────────────> │ packages/ai │ ────────────> │ OpenRouter │
│ (api routes) │ auth + models │ (gateway) │ key + chat │ (provider) │
└───────────────┘ └───────────────────┘ └───────────────┘
│ │
└──────────────► getAiProvider() / logAiRun() ───────────────────────────────┘
getAiProvider()— resolves the active provider configuration from server env.getActiveAiModel()— resolves the active model id frombv_ai_models.provider.complete()— sends the chat request and returns content + usage.logAiRun()— persists the run tobv_ai_runswith pricing and latency.
Security model¶
- Server-only. The gateway reads the OpenRouter key from a server secret; no key is ever exposed to the client.
- Provider isolation. Feature credentials are isolated per provider, and a
$AI_LINKERlinker can trace every request to its originating feature. - Feature isolation. The gateway isolates which features may call which providers.
Request / response¶
provider.complete({ model, system, messages, temperature, maxTokens, jsonSchema })
returns:
interface Result {
content: string; // text / JSON
model: string;
usage: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
latencyMs?: number;
}
Cost accounting¶
Every model row in bv_ai_models carries per-million pricing (input_price_per_m,
output_price_per_m). The gateway records input/output token counts and the resulting
cost per run — the basis for the finance page's AI cost lines.
Available tasks¶
| Task | Endpoint | Purpose |
|---|---|---|
copilot |
POST /api/ai/copilot |
Business-data Q&A assistant. |
creative_generation |
POST /api/ai/creative |
Compliant direct-response copy. |
opportunity_score |
ClickBank adapter | Marketplace product scoring. |