RouterBase Model Gateway
Use routerbase when an application needs an OpenAI compatible gateway for chat, embeddings, image, video, audio, speech, model routing, or fallback behavior.
The goal is not to rewrite the whole AI layer. The goal is to move provider selection behind a clean server side boundary, keep credentials private, and make model choices reversible.
When To Use
Use this skill when the user asks to:
- Migrate an OpenAI compatible client to RouterBase.
- Add RouterBase to a backend API, worker, command line tool, or agent runtime.
- Route requests across multiple model providers through one API surface.
- Choose primary and fallback models for latency, quality, price, or availability.
- Add image, video, audio, speech, or embedding generation through a gateway.
- Debug RouterBase base URLs, model IDs, streaming, JSON output, or media job polling.
Do not use this skill for:
- General API gateway design unrelated to AI models.
- Direct provider SDK features that are not exposed through the OpenAI compatible API.
- Frontend only integrations that would expose API keys to users.
- Production security review of the whole application.
Implementation Principles
1. Keep The Gateway Server Side
All RouterBase calls should run in trusted code:
- backend route
- serverless function
- worker
- command line tool
- internal service
- agent runtime process
Never place ROUTERBASE_API_KEY in browser code, mobile applications, public logs, screenshots, or checked in examples.
2. Change Configuration Before Code Shape
Most migrations should start with configuration:
- base URL:
https://routerbase.com/v1
- API key variable:
ROUTERBASE_API_KEY
- chat model variable:
ROUTERBASE_CHAT_MODEL
- embedding model variable:
ROUTERBASE_EMBEDDING_MODEL
- media model variables for image, video, audio, or speech
Keep the OpenAI compatible request shape until there is a documented reason to change it.
3. Isolate Provider Choices
Do not scatter model IDs across product code. Put them in one adapter, config file, or environment mapping.
Good boundaries:
aiClient.ts
modelConfig.ts
llmGateway.ts
services/ai/routerbase.ts
Poor boundaries:
- hard coded model IDs in every route
- retries implemented differently in every feature
- media polling mixed into UI code
- provider errors returned directly to users
Quick Start Example
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.ROUTERBASE_API_KEY,
baseURL: process.env.ROUTERBASE_BASE_URL || "https://routerbase.com/v1",
});
export async function summarizeReleaseNote(text: string) {
const completion = await client.chat.completions.create({
model: process.env.ROUTERBASE_CHAT_MODEL || "openai/gpt-5.4-mini",
messages: [
{ role: "system", content: "Summarize clearly for product engineers." },
{ role: "user", content: text },
],
});
return completion.choices[0]?.message?.content || "";
}
Routing Checklist
Before choosing models, answer these questions:
- What is the workload: chat, JSON output, streaming, tools, embeddings, image, video, audio, or speech?
- What matters most: latency, output quality, cost, context length, availability, or modality support?
- Does the fallback model return the same output shape?
- Can the feature tolerate degraded quality, or should it fail closed?
- Are user prompts, uploaded files, or generated assets subject to privacy rules?
- What telemetry is needed: model ID, request ID, latency, status code, retry count, and fallback used?
- What should the user see when the primary model fails?
Fallback Pattern
Use fallbacks for availability, not to hide every error.
async function runWithFallback(messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]) {
const primary = process.env.ROUTERBASE_CHAT_MODEL || "openai/gpt-5.4-mini";
const fallback = process.env.ROUTERBASE_CHAT_FALLBACK_MODEL || "openai/gpt-5.4-mini";
try {
return await client.chat.completions.create({ model: primary, messages });
} catch (error) {
if (!isRetryableModelError(error)) throw error;
return client.chat.completions.create({
model: fallback,
messages,
});
}
}
Fallback only when:
- the error is temporary or provider specific
- the fallback model supports the same output contract
- the request does not require a provider that has a unique compliance rule
- the user experience is better with degraded output than with a clear failure
Media Generation Flow
Treat long running media as a job workflow, not as a chat completion.
- Validate the prompt and user permissions.
- Create a media generation job through the RouterBase compatible endpoint for the selected modality.
- Store the job ID, model ID, user ID, and requested output type.
- Poll with backoff instead of holding one long request open.
- Save generated assets to durable storage.
- Return a stable URL or asset reference to the user.
- Record failures with model ID, status code, and retry count.
Evaluation Rubric
Score the integration from 0 to 2 for each item.
| Area |
0 |
1 |
2 |
| Credential handling |
key exposed or hard coded |
key is server side but examples are unclear |
key is server side, documented, and scanned |
| Model configuration |
IDs scattered in code |
central config for some workloads |
central config for all workloads |
| Fallback design |
no fallback or unsafe fallback |
fallback exists without clear policy |
fallback policy is explicit and tested |
| Error handling |
provider errors leak to users |
common errors mapped |
auth, quota, rate, timeout, and model errors handled |
| Media workflow |
synchronous long request |
polling exists but storage is weak |
job, polling, storage, and status are separate |
| Observability |
no useful logs |
basic latency and status logs |
request ID, model ID, fallback, retry count, latency |
Recommended threshold before production: at least 10 out of 12.
Common Mistakes
- Putting RouterBase keys in frontend environment variables that are bundled for users.
- Hard coding one model ID in multiple product features.
- Assuming streaming and non streaming responses fail in the same way.
- Falling back to a model with a different JSON output contract.
- Treating image or video generation as a simple request response call.
- Logging full prompts, uploaded file contents, or generated private data.
- Retrying authentication or quota errors that should fail immediately.
- Returning raw provider error messages to end users.
Output Expectations
When completing a RouterBase task, provide:
- files changed
- environment variables required
- primary and fallback model IDs
- test or smoke check performed
- privacy notes for prompts, files, and generated assets
- any unsupported features or assumptions
Keep the final recommendation concise. Include code only where it changes the integration boundary.
1---2name: routerbase-model-gateway3description: Configure RouterBase as an OpenAI compatible model gateway for AI apps, with routing, fallback, media generation, and credential handling patterns.4---5
6# RouterBase Model Gateway
7
8Use [routerbase](https://routerbase.com/) when an application needs an OpenAI compatible gateway for chat, embeddings, image, video, audio, speech, model routing, or fallback behavior.
9
10The goal is not to rewrite the whole AI layer. The goal is to move provider selection behind a clean server side boundary, keep credentials private, and make model choices reversible.
11
12## When To Use
13
14Use this skill when the user asks to:
15
16- Migrate an OpenAI compatible client to RouterBase.
17- Add RouterBase to a backend API, worker, command line tool, or agent runtime.
18- Route requests across multiple model providers through one API surface.
19- Choose primary and fallback models for latency, quality, price, or availability.
20- Add image, video, audio, speech, or embedding generation through a gateway.
21- Debug RouterBase base URLs, model IDs, streaming, JSON output, or media job polling.
22
23Do not use this skill for:
24
25- General API gateway design unrelated to AI models.
26- Direct provider SDK features that are not exposed through the OpenAI compatible API.
27- Frontend only integrations that would expose API keys to users.
28- Production security review of the whole application.
29
30## Implementation Principles
31
32### 1. Keep The Gateway Server Side
33
34All RouterBase calls should run in trusted code:
35
36- backend route
37- serverless function
38- worker
39- command line tool
40- internal service
41- agent runtime process
42
43Never place `ROUTERBASE_API_KEY` in browser code, mobile applications, public logs, screenshots, or checked in examples.
44
45### 2. Change Configuration Before Code Shape
46
47Most migrations should start with configuration:
48
49- base URL: `https://routerbase.com/v1`
50- API key variable: `ROUTERBASE_API_KEY`
51- chat model variable: `ROUTERBASE_CHAT_MODEL`
52- embedding model variable: `ROUTERBASE_EMBEDDING_MODEL`
53- media model variables for image, video, audio, or speech
54
55Keep the OpenAI compatible request shape until there is a documented reason to change it.
56
57### 3. Isolate Provider Choices
58
59Do not scatter model IDs across product code. Put them in one adapter, config file, or environment mapping.
60
61Good boundaries:
62
63- `aiClient.ts`
64- `modelConfig.ts`
65- `llmGateway.ts`
66- `services/ai/routerbase.ts`
67
68Poor boundaries:
69
70- hard coded model IDs in every route
71- retries implemented differently in every feature
72- media polling mixed into UI code
73- provider errors returned directly to users
74
75## Quick Start Example
76
77```ts
78import OpenAI from "openai";
79
80const client = new OpenAI({
81 apiKey: process.env.ROUTERBASE_API_KEY,
82 baseURL: process.env.ROUTERBASE_BASE_URL || "https://routerbase.com/v1",
83});
84
85export async function summarizeReleaseNote(text: string) {
86 const completion = await client.chat.completions.create({
87 model: process.env.ROUTERBASE_CHAT_MODEL || "openai/gpt-5.4-mini",
88 messages: [
89 { role: "system", content: "Summarize clearly for product engineers." },
90 { role: "user", content: text },
91 ],
92 });
93
94 return completion.choices[0]?.message?.content || "";
95}
96```
97
98## Routing Checklist
99
100Before choosing models, answer these questions:
101
1021. What is the workload: chat, JSON output, streaming, tools, embeddings, image, video, audio, or speech?
1032. What matters most: latency, output quality, cost, context length, availability, or modality support?
1043. Does the fallback model return the same output shape?
1054. Can the feature tolerate degraded quality, or should it fail closed?
1065. Are user prompts, uploaded files, or generated assets subject to privacy rules?
1076. What telemetry is needed: model ID, request ID, latency, status code, retry count, and fallback used?
1087. What should the user see when the primary model fails?
109
110## Fallback Pattern
111
112Use fallbacks for availability, not to hide every error.
113
114```ts
115async function runWithFallback(messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]) {
116 const primary = process.env.ROUTERBASE_CHAT_MODEL || "openai/gpt-5.4-mini";
117 const fallback = process.env.ROUTERBASE_CHAT_FALLBACK_MODEL || "openai/gpt-5.4-mini";
118
119 try {
120 return await client.chat.completions.create({ model: primary, messages });
121 } catch (error) {
122 if (!isRetryableModelError(error)) throw error;
123
124 return client.chat.completions.create({
125 model: fallback,
126 messages,
127 });
128 }
129}
130```
131
132Fallback only when:
133
134- the error is temporary or provider specific
135- the fallback model supports the same output contract
136- the request does not require a provider that has a unique compliance rule
137- the user experience is better with degraded output than with a clear failure
138
139## Media Generation Flow
140
141Treat long running media as a job workflow, not as a chat completion.
142
1431. Validate the prompt and user permissions.
1442. Create a media generation job through the RouterBase compatible endpoint for the selected modality.
1453. Store the job ID, model ID, user ID, and requested output type.
1464. Poll with backoff instead of holding one long request open.
1475. Save generated assets to durable storage.
1486. Return a stable URL or asset reference to the user.
1497. Record failures with model ID, status code, and retry count.
150
151## Evaluation Rubric
152
153Score the integration from 0 to 2 for each item.
154
155| Area | 0 | 1 | 2 |
156|---|---|---|---|
157| Credential handling | key exposed or hard coded | key is server side but examples are unclear | key is server side, documented, and scanned |
158| Model configuration | IDs scattered in code | central config for some workloads | central config for all workloads |
159| Fallback design | no fallback or unsafe fallback | fallback exists without clear policy | fallback policy is explicit and tested |
160| Error handling | provider errors leak to users | common errors mapped | auth, quota, rate, timeout, and model errors handled |
161| Media workflow | synchronous long request | polling exists but storage is weak | job, polling, storage, and status are separate |
162| Observability | no useful logs | basic latency and status logs | request ID, model ID, fallback, retry count, latency |
163
164Recommended threshold before production: at least 10 out of 12.
165
166## Common Mistakes
167
168- Putting RouterBase keys in frontend environment variables that are bundled for users.
169- Hard coding one model ID in multiple product features.
170- Assuming streaming and non streaming responses fail in the same way.
171- Falling back to a model with a different JSON output contract.
172- Treating image or video generation as a simple request response call.
173- Logging full prompts, uploaded file contents, or generated private data.
174- Retrying authentication or quota errors that should fail immediately.
175- Returning raw provider error messages to end users.
176
177## Output Expectations
178
179When completing a RouterBase task, provide:
180
181- files changed
182- environment variables required
183- primary and fallback model IDs
184- test or smoke check performed
185- privacy notes for prompts, files, and generated assets
186- any unsupported features or assumptions
187
188Keep the final recommendation concise. Include code only where it changes the integration boundary.