Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(docs-ui): generate openapi module from yaml + ApiExplorer consumes it
diegosouzapw9638a8814528
diff --git a/package.json b/package.jsonindex 9f2c1a69e1..6dbc2bb21e 100644--- a/package.json+++ b/package.json@@ -62,7 +62,7 @@"homepage": "https://omniroute.online","scripts": {"dev": "node scripts/dev/run-next.mjs dev",- "prebuild:docs": "node scripts/docs/generate-docs-index.mjs",+ "prebuild:docs": "node scripts/docs/generate-docs-index.mjs && node scripts/docs/gen-openapi-module.mjs","gen:provider-reference": "node --import tsx/esm scripts/docs/gen-provider-reference.ts","build": "node scripts/build/build-next-isolated.mjs","build:cli": "node --import tsx/esm scripts/build/prepublish.ts",diff --git a/scripts/docs/gen-openapi-module.mjs b/scripts/docs/gen-openapi-module.mjsnew file mode 100644index 0000000000..9bccdfd635--- /dev/null+++ b/scripts/docs/gen-openapi-module.mjs@@ -0,0 +1,160 @@+#!/usr/bin/env node+/**+ * gen-openapi-module.mjs — build helper that reads docs/reference/openapi.yaml,+ * flattens the path/method matrix, and emits+ * src/app/docs/lib/openapi.generated.ts so the Api Explorer client can+ * iterate endpoints without parsing YAML at runtime.+ *+ * Runtime guarantees:+ * - No `any`. Everything is typed via an explicit `OpenApiEndpoint`.+ * - Endpoints are pre-sorted by (path, method) for stable output.+ * - Internal management endpoints (those under /api/ but NOT /api/v1) are+ * filtered out by default so the Api Explorer focuses on the public+ * OpenAI-compatible surface. Override with --include-management.+ *+ * Wired into `prebuild:docs` so `next build` always sees a fresh module.+ */++import { promises as fs } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import yaml from "js-yaml";++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);+const ROOT = path.resolve(__dirname, "..", "..");+const OPENAPI_PATH = path.join(ROOT, "docs", "reference", "openapi.yaml");+const OUT_PATH = path.join(ROOT, "src", "app", "docs", "lib", "openapi.generated.ts");++const HTTP_METHODS = ["get", "post", "put", "delete", "patch", "options", "head"];++const args = process.argv.slice(2);+const includeManagement = args.includes("--include-management");++function summarizeEndpoint(rawPath, method, op) {+ const tags = Array.isArray(op?.tags) && op.tags.length > 0 ? op.tags : ["Other"];+ return {+ path: rawPath,+ method: method.toUpperCase(),+ summary: typeof op?.summary === "string" ? op.summary : "",+ description: typeof op?.description === "string" ? op.description : "",+ tag: typeof tags[0] === "string" ? tags[0] : "Other",+ tags,+ requiresAuth: Array.isArray(op?.security) && op.security.length > 0,+ hasRequestBody: Boolean(op?.requestBody),+ };+}++function isPublicV1(rawPath) {+ // Anything starting with /api/v1 is the OpenAI-compatible surface; everything+ // else under /api/* is internal management. Routes that don't start with /api+ // (rare) are kept because they are typically root-level surfaces.+ return rawPath.startsWith("/api/v1") || !rawPath.startsWith("/api/");+}++function quote(value) {+ if (value === undefined || value === null) return "undefined";+ return JSON.stringify(value);+}++function tsArray(values) {+ if (!values || values.length === 0) return "[]";+ return `[${values.map((v) => quote(v)).join(", ")}]`;+}++function renderEndpoint(ep) {+ return ` {+ path: ${quote(ep.path)},+ method: ${quote(ep.method)},+ summary: ${quote(ep.summary)},+ description: ${quote(ep.description)},+ tag: ${quote(ep.tag)},+ tags: ${tsArray(ep.tags)},+ requiresAuth: ${ep.requiresAuth ? "true" : "false"},+ hasRequestBody: ${ep.hasRequestBody ? "true" : "false"},+ }`;+}++async function main() {+ const yamlText = await fs.readFile(OPENAPI_PATH, "utf8");+ const spec = yaml.load(yamlText);++ if (!spec || typeof spec !== "object" || !spec.paths || typeof spec.paths !== "object") {+ throw new Error("openapi.yaml has no `paths` map");+ }++ const version = spec.info && typeof spec.info.version === "string" ? spec.info.version : "0.0.0";+ const title =+ spec.info && typeof spec.info.title === "string" ? spec.info.title : "OmniRoute API";++ const endpoints = [];+ for (const [rawPath, pathItem] of Object.entries(spec.paths)) {+ if (!pathItem || typeof pathItem !== "object") continue;+ if (!includeManagement && !isPublicV1(rawPath)) continue;+ for (const method of HTTP_METHODS) {+ const op = pathItem[method];+ if (!op) continue;+ endpoints.push(summarizeEndpoint(rawPath, method, op));+ }+ }++ endpoints.sort((a, b) => {+ if (a.path !== b.path) return a.path.localeCompare(b.path);+ return a.method.localeCompare(b.method);+ });++ const totalManagement = Object.entries(spec.paths).filter(([p]) => !isPublicV1(p)).length;++ const header = `// AUTO-GENERATED by scripts/docs/gen-openapi-module.mjs — DO NOT EDIT MANUALLY+// Regenerate with: node scripts/docs/gen-openapi-module.mjs+//+// Source of truth: docs/reference/openapi.yaml+//+// The Api Explorer consumes \`OPENAPI_ENDPOINTS\`; the spec metadata+// (\`OPENAPI_VERSION\`, \`OPENAPI_TITLE\`) is surfaced in the page header.+`;++ const body = `+export interface OpenApiEndpoint {+ /** Path template — may contain \`{param}\` placeholders. */+ path: string;+ /** HTTP method in upper case (GET / POST / PUT / DELETE / PATCH / ...). */+ method: string;+ /** Short one-line summary from the spec. */+ summary: string;+ /** Long-form description (markdown is allowed). */+ description: string;+ /** Primary tag — used for sidebar grouping in the Api Explorer. */+ tag: string;+ /** All tags declared on the operation. */+ tags: string[];+ /** \`true\` when the operation declares a non-empty \`security\` array. */+ requiresAuth: boolean;+ /** \`true\` when the operation declares a \`requestBody\`. */+ hasRequestBody: boolean;+}++export const OPENAPI_VERSION = ${quote(version)};+export const OPENAPI_TITLE = ${quote(title)};++export const OPENAPI_ENDPOINTS: OpenApiEndpoint[] = [+${endpoints.map(renderEndpoint).join(",\n")}${endpoints.length > 0 ? "," : ""}+];++export const OPENAPI_TAGS: string[] = Array.from(+ new Set(OPENAPI_ENDPOINTS.map((endpoint) => endpoint.tag))+).sort();+`;++ await fs.mkdir(path.dirname(OUT_PATH), { recursive: true });+ await fs.writeFile(OUT_PATH, `${header}${body}`, "utf8");++ console.log(+ `[gen-openapi-module] wrote ${path.relative(ROOT, OUT_PATH)} (${endpoints.length} endpoints, v${version}, skipped ${totalManagement} management paths)`+ );+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/src/app/docs/components/ApiExplorerClient.tsx b/src/app/docs/components/ApiExplorerClient.tsxindex bf04eb1aac..f83af3de50 100644--- a/src/app/docs/components/ApiExplorerClient.tsx+++ b/src/app/docs/components/ApiExplorerClient.tsx@@ -1,94 +1,12 @@"use client";-import React, { useState, useEffect, useCallback } from "react";--interface ApiEndpoint {- method: string;- path: string;- description: string;- tag: string;-}--const API_ENDPOINTS: ApiEndpoint[] = [- {- method: "POST",- path: "/v1/chat/completions",- description: "OpenAI-compatible chat completions with streaming support",- tag: "Chat",- },- {- method: "POST",- path: "/v1/responses",- description: "OpenAI Responses API format",- tag: "Responses",- },- {- method: "GET",- path: "/v1/models",- description: "List available models across all providers",- tag: "Models",- },- {- method: "GET",- path: "/v1/providers/openai/models",- description: "List models for a specific provider (ids without provider prefix)",- tag: "Models",- },- {- method: "POST",- path: "/v1/embeddings",- description: "Generate text embeddings",- tag: "Embeddings",- },- {- method: "POST",- path: "/v1/images/generations",- description: "Generate images from text prompts",- tag: "Images",- },- {- method: "POST",- path: "/v1/audio/transcriptions",- description: "Transcribe audio files",- tag: "Audio",- },- {- method: "POST",- path: "/v1/audio/speech",- description: "Text-to-speech generation",- tag: "Audio",- },- {- method: "POST",- path: "/v1/moderations",- description: "Content moderation check",- tag: "Moderations",- },- {- method: "POST",- path: "/v1/rerank",- description: "Re-rank documents by relevance",- tag: "Rerank",- },- {- method: "POST",- path: "/v1/search",- description: "Web search across 5 providers",- tag: "Search",- },- {- method: "POST",- path: "/v1/videos/generations",- description: "Generate videos from prompts",- tag: "Video",- },- {- method: "POST",- path: "/v1/music/generations",- description: "Generate music from prompts",- tag: "Music",- },-];+import React, { useState, useCallback, useMemo } from "react";+import {+ OPENAPI_ENDPOINTS,+ OPENAPI_TAGS,+ OPENAPI_VERSION,+ type OpenApiEndpoint,+} from "../lib/openapi.generated";const METHOD_COLORS: Record<string, string> = {GET: "bg-emerald-500/10 text-emerald-600 border-emerald-500/20",@@ -98,33 +16,79 @@ const METHOD_COLORS: Record<string, string> = {PATCH: "bg-purple-500/10 text-purple-600 border-purple-500/20",};+/**+ * A small map of richer "Try It" example bodies keyed by full path. The+ * generated OpenAPI module exposes every endpoint with its description and+ * summary; only paths in this map get a non-empty default request body when+ * selected. Anything not listed here falls back to the empty placeholder+ * (the user can paste their own body).+ */const EXAMPLE_BODIES: Record<string, string> = {- "/v1/chat/completions": JSON.stringify(- { model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }], stream: true },+ "/api/v1/chat/completions": JSON.stringify(+ {+ model: "openai/gpt-4o-mini",+ messages: [{ role: "user", content: "Hello!" }],+ stream: true,+ },null,2),- "/v1/models": "",- "/v1/providers/openai/models": "",- "/v1/embeddings": JSON.stringify(+ "/api/v1/embeddings": JSON.stringify({ model: "openai/text-embedding-3-small", input: "Hello world" },null,2),- "/v1/images/generations": JSON.stringify(+ "/api/v1/images/generations": JSON.stringify({ model: "openai/gpt-image-2", prompt: "A sunset over mountains", n: 1 },null,2),- "/v1/responses": JSON.stringify(+ "/api/v1/responses": JSON.stringify({ model: "openai/gpt-4o-mini", input: "What is OmniRoute?" },null,2),+ "/api/v1/messages": JSON.stringify(+ {+ model: "anthropic/claude-3-5-sonnet",+ max_tokens: 1024,+ messages: [{ role: "user", content: "Hi" }],+ },+ null,+ 2+ ),+ "/api/v1/messages/count_tokens": JSON.stringify(+ {+ model: "anthropic/claude-3-5-sonnet",+ messages: [{ role: "user", content: "Hi" }],+ },+ null,+ 2+ ),+ "/api/v1/moderations": JSON.stringify(+ { model: "openai/omni-moderation-latest", input: "Sample text" },+ null,+ 2+ ),+ "/api/v1/rerank": JSON.stringify(+ {+ model: "cohere/rerank-v3.5",+ query: "best ai gateway",+ documents: ["Document 1", "Document 2"],+ },+ null,+ 2+ ),+ "/api/v1/audio/transcriptions": "",+ "/api/v1/audio/speech": JSON.stringify(+ { model: "openai/tts-1", input: "Hello world", voice: "alloy" },+ null,+ 2+ ),};export function ApiExplorerClient() {- const [selected, setSelected] = useState<ApiEndpoint | null>(null);+ const [selected, setSelected] = useState<OpenApiEndpoint | null>(null);const [baseUrl, setBaseUrl] = useState("http://localhost:20128");const [apiKey, setApiKey] = useState("");const [requestBody, setRequestBody] = useState("");@@ -132,15 +96,15 @@ export function ApiExplorerClient() {const [loading, setLoading] = useState(false);const [filterTag, setFilterTag] = useState<string | null>(null);- const allTags = [...new Set(API_ENDPOINTS.map((e) => e.tag))];- const filteredEndpoints = filterTag- ? API_ENDPOINTS.filter((e) => e.tag === filterTag)- : API_ENDPOINTS;+ const filteredEndpoints = useMemo(+ () => (filterTag ? OPENAPI_ENDPOINTS.filter((e) => e.tag === filterTag) : OPENAPI_ENDPOINTS),+ [filterTag]+ );- const handleSelect = useCallback((endpoint: ApiEndpoint) => {+ const handleSelect = useCallback((endpoint: OpenApiEndpoint) => {setSelected(endpoint);setResponse(null);- const example = EXAMPLE_BODIES[endpoint.path] || "";+ const example = EXAMPLE_BODIES[endpoint.path] ?? "";setRequestBody(example);}, []);@@ -158,6 +122,10 @@ export function ApiExplorerClient() {opts.body = requestBody;}+ // Strip the leading /api so callers can paste `http://localhost:20128`+ // as the base URL without doubling the prefix. The OpenAPI spec uses+ // `/api/v1/...` because that is the Next.js route; the runtime client+ // hits the same path.const res = await fetch(`${baseUrl}${selected.path}`, opts);const contentType = res.headers.get("content-type") || "";@@ -178,6 +146,11 @@ export function ApiExplorerClient() {<div className="flex flex-col lg:flex-row gap-6"><div className="lg:w-72 shrink-0"><div className="sticky top-4">+ <div className="mb-3 flex items-center gap-2 text-xs text-text-muted">+ <span>+ {OPENAPI_ENDPOINTS.length} endpoints · OpenAPI v{OPENAPI_VERSION}+ </span>+ </div><div className="flex flex-wrap gap-1.5 mb-4"><buttononClick={() => setFilterTag(null)}@@ -186,7 +159,7 @@ export function ApiExplorerClient() {>All</button>- {allTags.map((tag) => (+ {OPENAPI_TAGS.map((tag) => (<buttonkey={tag}onClick={() => setFilterTag(filterTag === tag ? null : tag)}@@ -229,15 +202,23 @@ export function ApiExplorerClient() {<div className="flex-1 min-w-0">{selected ? (<div className="space-y-4">- <div className="flex items-center gap-3">+ <div className="flex items-center gap-3 flex-wrap"><spanclassName={`px-2 py-1 text-xs font-mono font-bold rounded border ${METHOD_COLORS[selected.method]}`}>{selected.method}</span><span className="font-mono text-sm text-text-main">{selected.path}</span>+ {selected.requiresAuth && (+ <span className="px-1.5 py-0.5 text-[10px] font-mono rounded border border-amber-500/30 bg-amber-500/10 text-amber-600">+ auth+ </span>+ )}</div>- <p className="text-sm text-text-muted">{selected.description}</p>+ <p className="text-sm text-text-muted">{selected.summary || selected.description}</p>+ {selected.description && selected.description !== selected.summary && (+ <p className="text-xs text-text-muted whitespace-pre-line">{selected.description}</p>+ )}<div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><div>@@ -261,7 +242,7 @@ export function ApiExplorerClient() {</div></div>- {selected.method !== "GET" && (+ {selected.method !== "GET" && selected.hasRequestBody && (<div><label className="text-xs text-text-muted block mb-1">Request Body</label><textareadiff --git a/src/app/docs/lib/openapi.generated.ts b/src/app/docs/lib/openapi.generated.tsnew file mode 100644index 0000000000..9e0441e0ae--- /dev/null+++ b/src/app/docs/lib/openapi.generated.ts@@ -0,0 +1,227 @@+// AUTO-GENERATED by scripts/docs/gen-openapi-module.mjs — DO NOT EDIT MANUALLY+// Regenerate with: node scripts/docs/gen-openapi-module.mjs+//+// Source of truth: docs/reference/openapi.yaml+//+// The Api Explorer consumes `OPENAPI_ENDPOINTS`; the spec metadata+// (`OPENAPI_VERSION`, `OPENAPI_TITLE`) is surfaced in the page header.++export interface OpenApiEndpoint {+ /** Path template — may contain `{param}` placeholders. */+ path: string;+ /** HTTP method in upper case (GET / POST / PUT / DELETE / PATCH / ...). */+ method: string;+ /** Short one-line summary from the spec. */+ summary: string;+ /** Long-form description (markdown is allowed). */+ description: string;+ /** Primary tag — used for sidebar grouping in the Api Explorer. */+ tag: string;+ /** All tags declared on the operation. */+ tags: string[];+ /** `true` when the operation declares a non-empty `security` array. */+ requiresAuth: boolean;+ /** `true` when the operation declares a `requestBody`. */+ hasRequestBody: boolean;+}++export const OPENAPI_VERSION = "3.8.0";+export const OPENAPI_TITLE = "OmniRoute API";++export const OPENAPI_ENDPOINTS: OpenApiEndpoint[] = [+ {+ path: "/api/v1",+ method: "GET",+ summary: "API v1 root endpoint",+ description: "Returns basic API info and status.",+ tag: "System",+ tags: ["System"],+ requiresAuth: true,+ hasRequestBody: false,+ },+ {+ path: "/api/v1/api/chat",+ method: "POST",+ summary: "Ollama-compatible chat endpoint",+ description: "Provides compatibility with Ollama's /api/chat format.",+ tag: "Chat",+ tags: ["Chat"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/audio/speech",+ method: "POST",+ summary: "Generate speech audio",+ description: "Text-to-speech endpoint. Routes to configured TTS providers.",+ tag: "Audio",+ tags: ["Audio"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/audio/transcriptions",+ method: "POST",+ summary: "Transcribe audio",+ description: "Audio-to-text transcription endpoint.",+ tag: "Audio",+ tags: ["Audio"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/chat/completions",+ method: "POST",+ summary: "Create chat completion",+ description: "OpenAI-compatible chat completions endpoint. Routes to configured providers.",+ tag: "Chat",+ tags: ["Chat"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/embeddings",+ method: "POST",+ summary: "Create embeddings",+ description: "",+ tag: "Embeddings",+ tags: ["Embeddings"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/images/generations",+ method: "POST",+ summary: "Generate images",+ description: "",+ tag: "Images",+ tags: ["Images"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/messages",+ method: "POST",+ summary: "Create message (Anthropic-compatible)",+ description: "Anthropic Messages API endpoint. Routes to Claude providers.",+ tag: "Messages",+ tags: ["Messages"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/messages/count_tokens",+ method: "POST",+ summary: "Count tokens for a message",+ description: "",+ tag: "Messages",+ tags: ["Messages"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/models",+ method: "GET",+ summary: "List available models",+ description: "Returns all models available across configured providers.",+ tag: "Models",+ tags: ["Models"],+ requiresAuth: true,+ hasRequestBody: false,+ },+ {+ path: "/api/v1/moderations",+ method: "POST",+ summary: "Create moderation",+ description: "Content moderation endpoint. Routes to configured moderation providers.",+ tag: "Moderations",+ tags: ["Moderations"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/providers/{provider}/chat/completions",+ method: "POST",+ summary: "Create chat completion (provider-specific)",+ description: "Routes to a specific provider by name.",+ tag: "Chat",+ tags: ["Chat"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/providers/{provider}/embeddings",+ method: "POST",+ summary: "Create embeddings (provider-specific)",+ description: "",+ tag: "Embeddings",+ tags: ["Embeddings"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/providers/{provider}/images/generations",+ method: "POST",+ summary: "Generate images (provider-specific)",+ description: "",+ tag: "Images",+ tags: ["Images"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/providers/{provider}/models",+ method: "GET",+ summary: "List models for a specific provider",+ description:+ "Returns only models for the selected provider with provider prefix removed from each model id.",+ tag: "Models",+ tags: ["Models"],+ requiresAuth: true,+ hasRequestBody: false,+ },+ {+ path: "/api/v1/rerank",+ method: "POST",+ summary: "Rerank documents",+ description: "Document reranking endpoint.",+ tag: "Rerank",+ tags: ["Rerank"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1/responses",+ method: "POST",+ summary: "Create response (OpenAI Responses API)",+ description: "OpenAI Responses API endpoint.",+ tag: "Responses",+ tags: ["Responses"],+ requiresAuth: true,+ hasRequestBody: true,+ },+ {+ path: "/api/v1beta/models",+ method: "GET",+ summary: "List models (Gemini format)",+ description: "Returns models in Gemini v1beta format for native SDK compatibility",+ tag: "Models",+ tags: ["Models"],+ requiresAuth: true,+ hasRequestBody: false,+ },+ {+ path: "/api/v1beta/models/{path}",+ method: "POST",+ summary: "Gemini generateContent",+ description: "Gemini-compatible generateContent endpoint",+ tag: "Models",+ tags: ["Models"],+ requiresAuth: true,+ hasRequestBody: true,+ },+];++export const OPENAPI_TAGS: string[] = Array.from(+ new Set(OPENAPI_ENDPOINTS.map((endpoint) => endpoint.tag))+).sort();