Documentation

This commit is contained in:
Zebratic committed 2026-02-27 18:19:00 +01:00
1 parent b4396c6c1a
commit 6195553845
21 files changed
+1472 -80

No files matched your search

+22 -66
View File
@@ -30,50 +30,37 @@ npm run dev
App runs at `http://localhost:3000`.
## Getting Your User API Key
## API Documentation
Use the full interactive docs at:
- `http://localhost:3000/docs`
Inside `/docs` you get:
- Multi-page API reference and auth guide
- Endpoint docs for:
- `GET /v1/models`
- `POST /v1/chat/completions`
- `POST /v1/completions`
- `POST /v1/embeddings`
- Live endpoint testing with:
- Account key dropdown when logged in
- Manual API key input when logged out
- Claude Code setup guide and troubleshooting
## API Key Setup
1. Register at `/register`
2. Login and open `/dashboard/api-keys`
3. Create a key and copy it (shown once)
4. Use it as:
4. Use it in requests:
```bash
Authorization: Bearer lp_...
```
## OpenAI-Compatible Endpoints
- `POST /v1/chat/completions`
- `GET /v1/models`
## cURL Examples
### List models
```bash
curl -s http://localhost:3000/v1/models \
-H "Authorization: Bearer $LLM_PROXY_API_KEY"
```
### Chat completion
```bash
curl -s http://localhost:3000/v1/chat/completions \
-H "Authorization: Bearer $LLM_PROXY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4.1-mini",
"messages": [
{ "role": "user", "content": "Say hello from LLM Proxy" }
]
}'
```
## Using With Claude Code
Claude Code can call any OpenAI-compatible endpoint. Point it to this proxy instead of a vendor URL.
### Option A: one-off command
## Claude Code Quick Example
```bash
claude \
@@ -81,34 +68,3 @@ claude \
--openai-api-base http://localhost:3000/v1 \
--openai-api-key "$LLM_PROXY_API_KEY"
```
### Option B: shell profile env vars
```bash
export OPENAI_API_BASE="http://localhost:3000/v1"
export OPENAI_API_KEY="$LLM_PROXY_API_KEY"
```
Then run:
```bash
claude --model gpt-4.1-mini
```
## Using With Other OpenAI-Compatible Tools
Any SDK/client that supports custom base URL works. Set:
- Base URL: `http://localhost:3000/v1`
- API key: your LLM Proxy user key
Example in JS:
```ts
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.LLM_PROXY_API_KEY,
baseURL: "http://localhost:3000/v1",
});
```
@@ -46,9 +46,15 @@ export async function DELETE(_req: Request, { params }: { params: Promise<{ keyI
});
if (!key) return NextResponse.json({ error: "Not found" }, { status: 404 });
await db.userApiKey.update({
if (key.status !== "DISABLED" && key.status !== "REVOKED") {
return NextResponse.json(
{ error: "Key must be disabled before permanent deletion" },
{ status: 400 },
);
}
await db.userApiKey.delete({
where: { id: keyId },
data: { status: "REVOKED" },
});
return NextResponse.json({ success: true });
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
export async function GET() {
const session = await getSession();
if (!session) {
return NextResponse.json({ loggedIn: false, keys: [] });
}
const keys = (await db.userApiKey.findMany({
where: { userId: session.user.id },
select: {
id: true,
keyPrefix: true,
label: true,
status: true,
},
orderBy: { createdAt: "desc" },
})) as Array<{ id: string; keyPrefix: string; label: string | null; status: string }>;
return NextResponse.json({
loggedIn: true,
keys: keys.filter((key) => key.status === "ACTIVE"),
});
}
+390
View File
@@ -0,0 +1,390 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getMongoDb } from "@/lib/mongo";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { ApiError, internalError, invalidApiKey, invalidRequest, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
import { authenticateApiKey, type AuthResult } from "@/server/services/api-key-auth";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { chatCompletionSchema } from "@/lib/validations/chat-completion";
import { completionSchema } from "@/lib/validations/completion";
import { embeddingsSchema } from "@/lib/validations/embeddings";
import type { UnifiedChatRequest, UnifiedCompletionRequest, UnifiedEmbeddingRequest } from "@/types/unified-request";
const docsTestRequestSchema = z
.object({
endpoint: z.enum(["models", "chat-completions", "completions", "embeddings"]),
apiKeyId: z.string().min(1).optional(),
apiKey: z.string().min(1).optional(),
body: z.unknown().optional(),
})
.refine((value) => Boolean(value.apiKeyId || value.apiKey), {
message: "Provide apiKeyId or apiKey.",
path: ["apiKey"],
});
type DocsTestRequest = z.infer<typeof docsTestRequestSchema>;
function shouldRetryProviderError(error: ApiError): boolean {
return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
}
async function resolveAuth(payload: DocsTestRequest): Promise<AuthResult | null> {
if (payload.apiKey?.trim()) {
return authenticateApiKey(`Bearer ${payload.apiKey.trim()}`);
}
if (!payload.apiKeyId) {
return null;
}
const session = await getSession();
if (!session?.user?.id) {
return null;
}
const [apiKey, subscription] = (await Promise.all([
db.userApiKey.findUnique({
where: { id: payload.apiKeyId, userId: session.user.id },
select: {
id: true,
userId: true,
status: true,
expiresAt: true,
dailyRequestLimit: true,
dailyTokenLimit: true,
softCostLimitCents: true,
},
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
])) as [
| {
id: string;
userId: string;
status?: "ACTIVE" | "DISABLED" | "REVOKED" | null;
expiresAt?: Date | null;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
softCostLimitCents?: number | null;
}
| null,
| {
id: string;
userId: string;
status: "ACTIVE" | "PAST_DUE" | "CANCELED" | "TRIALING";
plan?: {
id: string;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
} | null;
}
| null,
];
if (!apiKey) return null;
if (apiKey.status && apiKey.status !== "ACTIVE") return null;
if (apiKey.expiresAt && apiKey.expiresAt < new Date()) return null;
if (!subscription?.plan) return null;
return {
user: {
id: session.user.id,
email: session.user.email ?? "",
name: session.user.name ?? undefined,
role: session.user.role,
status: "ACTIVE",
},
apiKey: {
id: apiKey.id,
userId: apiKey.userId,
dailyRequestLimit: apiKey.dailyRequestLimit ?? null,
dailyTokenLimit: apiKey.dailyTokenLimit ?? null,
softCostLimitCents: apiKey.softCostLimitCents ?? null,
},
subscription: {
id: subscription.id,
userId: subscription.userId,
status: subscription.status,
plan: {
id: subscription.plan.id,
dailyRequestLimit: subscription.plan.dailyRequestLimit ?? null,
dailyTokenLimit: subscription.plan.dailyTokenLimit ?? null,
},
},
};
}
async function runModelsRequest(): Promise<Response> {
const mappings = await getMongoDb()
.collection<{ _id: string }>("model_mappings")
.aggregate([
{ $match: { enabled: true } },
{
$lookup: {
from: "providers",
localField: "providerId",
foreignField: "_id",
as: "provider",
},
},
{ $unwind: "$provider" },
{ $match: { "provider.enabled": true } },
{
$lookup: {
from: "provider_api_keys",
let: { providerId: "$providerId" },
pipeline: [
{
$match: {
$expr: { $eq: ["$providerId", "$$providerId"] },
status: "ACTIVE",
},
},
{ $limit: 1 },
],
as: "activeProviderKeys",
},
},
{ $match: { activeProviderKeys: { $ne: [] } } },
{ $group: { _id: "$logicalModelId" } },
])
.toArray();
return Response.json({
object: "list",
data: mappings.map((m) => ({
id: m._id,
object: "model" as const,
created: Math.floor(Date.now() / 1000),
owned_by: "llm-proxy",
})),
});
}
async function runChatCompletion(body: unknown, auth: AuthResult): Promise<Response> {
const parsed = chatCompletionSchema.safeParse(body);
if (!parsed.success) {
const firstError = parsed.error.errors[0];
return invalidRequest(firstError?.message ?? "Invalid request.", firstError?.path?.join(".")).toResponse();
}
const input = parsed.data;
const limits = {
dailyRequests: auth.apiKey.dailyRequestLimit ?? auth.subscription.plan.dailyRequestLimit,
dailyTokens: auth.apiKey.dailyTokenLimit ?? auth.subscription.plan.dailyTokenLimit,
dailyCostCents: auth.apiKey.softCostLimitCents,
};
const rateLimitResult = await checkRateLimit(auth.apiKey.id, limits);
if (!rateLimitResult.allowed) {
return rateLimitExceeded(rateLimitResult.reason!, rateLimitResult.retryAfter!);
}
const routes = await resolveModelRouteCandidates(input.model);
if (!routes.length) {
return modelNotFound(input.model).toResponse();
}
const unifiedReq: UnifiedChatRequest = {
model: input.model,
messages: input.messages,
stream: false,
temperature: input.temperature,
top_p: input.top_p,
max_tokens: input.max_tokens,
stop: input.stop,
presence_penalty: input.presence_penalty,
frequency_penalty: input.frequency_penalty,
n: input.n,
user: input.user,
tools: input.tools,
tool_choice: input.tool_choice,
};
let lastError: ApiError | null = null;
for (const route of routes) {
try {
const result = await route.adapter.chatCompletion(unifiedReq, route.ctx);
return Response.json(result, { status: 200 });
} catch (error) {
if (error instanceof ApiError) {
lastError = error;
if (shouldRetryProviderError(error)) continue;
return error.toResponse();
}
logger.error(error, "Unhandled docs chat test error");
}
}
return (lastError ?? internalError()).toResponse();
}
async function runCompletion(body: unknown, auth: AuthResult): Promise<Response> {
const parsed = completionSchema.safeParse(body);
if (!parsed.success) {
const firstError = parsed.error.errors[0];
return invalidRequest(firstError?.message ?? "Invalid request.", firstError?.path?.join(".")).toResponse();
}
const input = parsed.data;
const limits = {
dailyRequests: auth.apiKey.dailyRequestLimit ?? auth.subscription.plan.dailyRequestLimit,
dailyTokens: auth.apiKey.dailyTokenLimit ?? auth.subscription.plan.dailyTokenLimit,
dailyCostCents: auth.apiKey.softCostLimitCents,
};
const rateLimitResult = await checkRateLimit(auth.apiKey.id, limits);
if (!rateLimitResult.allowed) {
return rateLimitExceeded(rateLimitResult.reason!, rateLimitResult.retryAfter!);
}
const routes = await resolveModelRouteCandidates(input.model);
if (!routes.length) {
return modelNotFound(input.model).toResponse();
}
const unifiedReq: UnifiedCompletionRequest = {
model: input.model,
prompt: input.prompt,
stream: false,
max_tokens: input.max_tokens,
temperature: input.temperature,
top_p: input.top_p,
stop: input.stop,
n: input.n,
user: input.user,
};
let lastError: ApiError | null = null;
for (const route of routes) {
if (!route.adapter.completion) continue;
try {
const result = await route.adapter.completion(unifiedReq, route.ctx);
return Response.json(result, { status: 200 });
} catch (error) {
if (error instanceof ApiError) {
lastError = error;
if (shouldRetryProviderError(error)) continue;
return error.toResponse();
}
logger.error(error, "Unhandled docs completion test error");
}
}
if (lastError) return lastError.toResponse();
return invalidRequest(`Model '${input.model}' does not support /v1/completions.`).toResponse();
}
async function runEmbeddings(body: unknown, auth: AuthResult): Promise<Response> {
const parsed = embeddingsSchema.safeParse(body);
if (!parsed.success) {
const firstError = parsed.error.errors[0];
return invalidRequest(firstError?.message ?? "Invalid request.", firstError?.path?.join(".")).toResponse();
}
const input = parsed.data;
const limits = {
dailyRequests: auth.apiKey.dailyRequestLimit ?? auth.subscription.plan.dailyRequestLimit,
dailyTokens: auth.apiKey.dailyTokenLimit ?? auth.subscription.plan.dailyTokenLimit,
dailyCostCents: auth.apiKey.softCostLimitCents,
};
const rateLimitResult = await checkRateLimit(auth.apiKey.id, limits);
if (!rateLimitResult.allowed) {
return rateLimitExceeded(rateLimitResult.reason!, rateLimitResult.retryAfter!);
}
const routes = await resolveModelRouteCandidates(input.model);
if (!routes.length) {
return modelNotFound(input.model).toResponse();
}
const unifiedReq: UnifiedEmbeddingRequest = {
model: input.model,
input: input.input,
encoding_format: input.encoding_format,
user: input.user,
};
let lastError: ApiError | null = null;
for (const route of routes) {
if (!route.adapter.embeddings) continue;
try {
const result = await route.adapter.embeddings(unifiedReq, route.ctx);
return Response.json(result, { status: 200 });
} catch (error) {
if (error instanceof ApiError) {
lastError = error;
if (shouldRetryProviderError(error)) continue;
return error.toResponse();
}
logger.error(error, "Unhandled docs embeddings test error");
}
}
if (lastError) return lastError.toResponse();
return invalidRequest(`Model '${input.model}' does not support /v1/embeddings.`).toResponse();
}
async function executeTest(payload: DocsTestRequest, auth: AuthResult): Promise<Response> {
switch (payload.endpoint) {
case "models":
return runModelsRequest();
case "chat-completions":
return runChatCompletion(payload.body, auth);
case "completions":
return runCompletion(payload.body, auth);
case "embeddings":
return runEmbeddings(payload.body, auth);
default:
return invalidRequest("Unsupported endpoint.").toResponse();
}
}
export async function POST(req: Request) {
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
}
const parsed = docsTestRequestSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid request." }, { status: 400 });
}
const auth = await resolveAuth(parsed.data);
if (!auth) {
const response = invalidApiKey().toResponse();
const message = (await response.json().catch(() => ({ error: { message: "Invalid API key provided." } }))) as {
error?: { message?: string };
};
return NextResponse.json({ error: message.error?.message ?? "Invalid API key provided." }, { status: 401 });
}
const startedAt = Date.now();
const response = await executeTest(parsed.data, auth);
const latencyMs = Date.now() - startedAt;
const rawText = await response.text();
let parsedBody: unknown = rawText;
try {
parsedBody = rawText ? JSON.parse(rawText) : null;
} catch {
parsedBody = rawText;
}
return NextResponse.json({
ok: response.ok,
status: response.status,
latencyMs,
headers: {
"content-type": response.headers.get("Content-Type") ?? "",
"retry-after": response.headers.get("Retry-After") ?? "",
},
body: parsedBody,
});
}
+59 -11
View File
@@ -77,12 +77,40 @@ export default function ApiKeysPage() {
}
async function deleteKey(id: string) {
if (!confirm("Are you sure you want to delete this key?")) return;
if (!confirm("This permanently deletes the key. Continue?")) return;
const res = await fetch(`/api/dashboard/api-keys/${id}`, { method: "DELETE" });
if (res.ok) {
fetchKeys();
toast.success("Key deleted");
toast.success("Key permanently deleted");
return;
}
const data = await res.json().catch(() => null);
toast.error(data?.error ?? "Failed to delete key");
}
async function updateKeyStatus(id: string, status: "ACTIVE" | "DISABLED", successMessage: string) {
const res = await fetch(`/api/dashboard/api-keys/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
});
if (res.ok) {
fetchKeys();
toast.success(successMessage);
return;
}
toast.error("Failed to update key status");
}
function isDisabled(status: string) {
return status === "DISABLED" || status === "REVOKED";
}
function formatDate(value: string | null) {
if (!value) return null;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
return date.toLocaleDateString();
}
function copyToClipboard(text: string) {
@@ -210,23 +238,43 @@ export default function ApiKeysPage() {
<TableCell>{key.label ?? "-"}</TableCell>
<TableCell>
<Badge variant={key.status === "ACTIVE" ? "default" : "secondary"}>
{key.status}
{isDisabled(key.status) ? "DISABLED" : key.status}
</Badge>
</TableCell>
<TableCell className="text-sm">
{key.dailyRequestLimit ? `${key.dailyRequestLimit} req` : "Default"}
{key.dailyTokenLimit ? ` / ${key.dailyTokenLimit} tok` : ""}
{key.dailyRequestLimit != null ? `${key.dailyRequestLimit} req` : "Default"}
{key.dailyTokenLimit != null ? ` / ${key.dailyTokenLimit} tok` : ""}
</TableCell>
<TableCell className="text-sm">
{key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never"}
{key.lastUsedAt ? (formatDate(key.lastUsedAt) ?? "-") : "Never"}
</TableCell>
<TableCell className="text-sm">
{new Date(key.createdAt).toLocaleDateString()}
{formatDate(key.createdAt) ?? "-"}
</TableCell>
<TableCell>
<Button size="icon" variant="ghost" onClick={() => deleteKey(key.id)}>
<Trash2 className="h-4 w-4" />
</Button>
<TableCell className="space-x-2">
{isDisabled(key.status) ? (
<>
<Button
size="sm"
variant="outline"
onClick={() => updateKeyStatus(key.id, "ACTIVE", "Key enabled")}
>
Enable
</Button>
<Button size="sm" variant="destructive" onClick={() => deleteKey(key.id)}>
<Trash2 className="h-4 w-4" />
Delete
</Button>
</>
) : (
<Button
size="sm"
variant="secondary"
onClick={() => updateKeyStatus(key.id, "DISABLED", "Key revoked")}
>
Revoke
</Button>
)}
</TableCell>
</TableRow>
))}
+18 -1
View File
@@ -1,8 +1,10 @@
import Link from "next/link";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { DashboardUsageGraphs } from "@/components/dashboard/dashboard-usage-graphs";
import { Key, Activity, Coins, AlertCircle } from "lucide-react";
import { Key, Activity, Coins, AlertCircle, BookOpen } from "lucide-react";
export default async function DashboardOverview() {
const session = await getSession();
@@ -97,6 +99,21 @@ export default async function DashboardOverview() {
</p>
</div>
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<BookOpen className="h-4 w-4" />
API Documentation
</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap items-center gap-3">
<p className="text-sm text-muted-foreground">Open guides, endpoint reference, and live API testing.</p>
<Button asChild size="sm">
<Link href="/docs">Open Docs</Link>
</Button>
</CardContent>
</Card>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => (
<Card key={stat.title}>
+56
View File
@@ -0,0 +1,56 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CodeSnippet } from "@/components/docs/code-snippet";
const authHeaderExample = `Authorization: Bearer lp_your_user_api_key`;
const errorExample = `{
"error": {
"message": "Invalid API key.",
"type": "invalid_request_error",
"code": "invalid_api_key",
"param": null
}
}`;
export default function AuthDocsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Authentication</h1>
<p className="text-muted-foreground">
All `/v1/*` endpoints require your LLM Proxy user API key in Bearer format.
</p>
</div>
<Card>
<CardHeader>
<CardTitle>Authorization header format</CardTitle>
</CardHeader>
<CardContent>
<CodeSnippet language="http" code={authHeaderExample} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>How keys are validated</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p>- Key must exist and be active</p>
<p>- Key must not be expired</p>
<p>- User account must be active</p>
<p>- Account must have a valid subscription plan</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Common auth error response</CardTitle>
</CardHeader>
<CardContent>
<CodeSnippet language="json" code={errorExample} />
</CardContent>
</Card>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CodeSnippet } from "@/components/docs/code-snippet";
const oneOffExample = `claude \\
--model gpt-4.1-mini \\
--openai-api-base http://localhost:3000/v1 \\
--openai-api-key "$LLM_PROXY_API_KEY"`;
const envExample = `export OPENAI_API_BASE="http://localhost:3000/v1"
export OPENAI_API_KEY="$LLM_PROXY_API_KEY"`;
const troubleshooting = `# Invalid key / auth errors
# - verify OPENAI_API_KEY starts with lp_
# - verify key is ACTIVE in /dashboard/api-keys
# Model not found
# - call GET /v1/models and pick an available id
# Rate limit exceeded
# - reduce request volume or increase plan/key limits`;
export default function ClaudeCodePage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Claude Code Guide</h1>
<p className="text-muted-foreground">
Point Claude Code to your LLM Proxy `/v1` base URL and use your LLM Proxy API key.
</p>
</div>
<Card>
<CardHeader>
<CardTitle>One-off command</CardTitle>
</CardHeader>
<CardContent>
<CodeSnippet language="bash" code={oneOffExample} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Shell environment setup</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<CodeSnippet language="bash" code={envExample} />
<p className="text-sm text-muted-foreground">Then run: `claude --model gpt-4.1-mini`</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Troubleshooting</CardTitle>
</CardHeader>
<CardContent>
<CodeSnippet language="bash" code={troubleshooting} />
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,53 @@
import { notFound } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CodeSnippet } from "@/components/docs/code-snippet";
import { EndpointTester } from "@/components/docs/endpoint-tester";
import { endpointDocs, getEndpointDocBySlug } from "@/components/docs/docs-config";
export function generateStaticParams() {
return endpointDocs.map((endpoint) => ({ endpoint: endpoint.slug }));
}
export default async function EndpointDocPage({ params }: { params: Promise<{ endpoint: string }> }) {
const { endpoint: endpointSlug } = await params;
const endpoint = getEndpointDocBySlug(endpointSlug);
if (!endpoint) notFound();
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">{endpoint.title}</h1>
<p className="text-muted-foreground">{endpoint.description}</p>
</div>
<Card>
<CardHeader>
<CardTitle>
<span className="mr-2 font-mono text-xs">{endpoint.method}</span>
{endpoint.path}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<h3 className="mb-2 text-sm font-semibold">cURL example</h3>
<CodeSnippet language="bash" code={endpoint.curlExample} />
</div>
{endpoint.requestExample && (
<div>
<h3 className="mb-2 text-sm font-semibold">Request body example</h3>
<CodeSnippet language="json" code={endpoint.requestExample} />
</div>
)}
<div>
<h3 className="mb-2 text-sm font-semibold">Response example</h3>
<CodeSnippet language="json" code={endpoint.responseExample} />
</div>
</CardContent>
</Card>
<EndpointTester endpoint={endpoint} />
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { endpointDocs } from "@/components/docs/docs-config";
export default function EndpointsIndexPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Endpoints</h1>
<p className="text-muted-foreground">Reference docs and live tests for all supported API routes.</p>
</div>
<div className="grid gap-3">
{endpointDocs.map((endpoint) => (
<Link key={endpoint.slug} href={`/docs/endpoints/${endpoint.slug}`}>
<Card className="transition hover:border-primary/40">
<CardHeader>
<CardTitle className="text-base">
<span className="mr-2 font-mono text-xs">{endpoint.method}</span>
{endpoint.path}
</CardTitle>
</CardHeader>
<CardContent className="pt-0 text-sm text-muted-foreground">{endpoint.description}</CardContent>
</Card>
</Link>
))}
</div>
</div>
);
}
+67
View File
@@ -0,0 +1,67 @@
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CodeSnippet } from "@/components/docs/code-snippet";
const quickStartCurl = `curl -s http://localhost:3000/v1/chat/completions \\
-H "Authorization: Bearer $LLM_PROXY_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"model": "gpt-4.1-mini",
"messages": [{"role":"user","content":"Say hello from LLM Proxy"}]
}'`;
const openAiJsExample = `import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.LLM_PROXY_API_KEY,
baseURL: "http://localhost:3000/v1",
});
const response = await client.chat.completions.create({
model: "gpt-4.1-mini",
messages: [{ role: "user", content: "Give me one deployment checklist item." }],
});
console.log(response.choices[0]?.message?.content);`;
export default function GettingStartedPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Getting Started</h1>
<p className="text-muted-foreground">Get a key, choose a model, and make your first API request.</p>
</div>
<Card>
<CardHeader>
<CardTitle>Step 1: Create your user API key</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm text-muted-foreground">
<p>Register and login, then open the API key manager to create a key.</p>
<Link href="/dashboard/api-keys" className="text-primary underline underline-offset-4">
Open API Keys page
</Link>
<p>Copy your key immediately when created. It is only shown once.</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Step 2: Make a quick chat request</CardTitle>
</CardHeader>
<CardContent>
<CodeSnippet language="bash" code={quickStartCurl} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Step 3: Use any OpenAI-compatible SDK</CardTitle>
</CardHeader>
<CardContent>
<CodeSnippet language="typescript" code={openAiJsExample} />
</CardContent>
</Card>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import Link from "next/link";
import { DocsSidebar } from "@/components/docs/docs-sidebar";
import { DocsAuthProvider } from "@/components/docs/docs-auth-context";
import { KeySelector } from "@/components/docs/key-selector";
export default function DocsLayout({ children }: { children: React.ReactNode }) {
return (
<DocsAuthProvider>
<main className="mx-auto min-h-screen w-full max-w-7xl px-6 py-8">
<div className="mb-6 flex items-center justify-between">
<Link href="/" className="text-sm font-semibold">
LLM Proxy
</Link>
<div className="text-xs text-muted-foreground">OpenAI-compatible API docs</div>
</div>
<div className="grid gap-6 lg:grid-cols-[280px_minmax(0,1fr)]">
<DocsSidebar />
<div className="space-y-6">
<KeySelector />
{children}
</div>
</div>
</main>
</DocsAuthProvider>
);
}
+52
View File
@@ -0,0 +1,52 @@
import Link from "next/link";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { docsNav, endpointDocs } from "@/components/docs/docs-config";
export default function DocsOverviewPage() {
return (
<div className="space-y-6">
<section className="space-y-2">
<h1 className="text-3xl font-bold">LLM Proxy API Documentation</h1>
<p className="text-muted-foreground">
Use one base URL and one key to access multiple model providers with an OpenAI-compatible API.
</p>
</section>
<section className="grid gap-4 md:grid-cols-2">
{docsNav
.filter((item) => item.href !== "/docs")
.map((item) => (
<Link key={item.href} href={item.href}>
<Card className="h-full transition hover:border-primary/40">
<CardHeader>
<CardTitle className="text-lg">{item.title}</CardTitle>
<CardDescription>{item.description}</CardDescription>
</CardHeader>
</Card>
</Link>
))}
</section>
<section className="space-y-3">
<h2 className="text-xl font-semibold">Supported OpenAI-compatible endpoints</h2>
<div className="grid gap-3">
{endpointDocs.map((endpoint) => (
<Link key={endpoint.slug} href={`/docs/endpoints/${endpoint.slug}`}>
<Card className="transition hover:border-primary/40">
<CardContent className="flex items-center justify-between p-4">
<div>
<p className="font-medium">{endpoint.title}</p>
<p className="text-sm text-muted-foreground">{endpoint.description}</p>
</div>
<code className="rounded bg-muted px-2 py-1 text-xs">
{endpoint.method} {endpoint.path}
</code>
</CardContent>
</Card>
</Link>
))}
</div>
</section>
</div>
);
}
+3
View File
@@ -109,6 +109,9 @@ export default async function Home() {
<ArrowRight className="h-4 w-4" />
</Link>
</Button>
<Button asChild size="lg" variant="outline" className="border-white/20 bg-white/5 hover:bg-white/10">
<Link href="/docs">Read API Docs</Link>
</Button>
<Button asChild size="lg" variant="outline" className="border-white/20 bg-white/5 hover:bg-white/10">
<Link href="/v1/models">View Models API</Link>
</Button>
+31
View File
@@ -0,0 +1,31 @@
"use client";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Copy } from "lucide-react";
export function CodeSnippet({ code, language }: { code: string; language?: string }) {
async function copyCode() {
try {
await navigator.clipboard.writeText(code);
toast.success("Code copied");
} catch {
toast.error("Failed to copy");
}
}
return (
<div className="overflow-hidden rounded-xl border">
<div className="flex items-center justify-between border-b bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
<span>{language ?? "text"}</span>
<Button size="sm" variant="ghost" onClick={copyCode}>
<Copy className="h-4 w-4" />
Copy
</Button>
</div>
<pre className="overflow-x-auto bg-muted/20 p-4 text-xs">
<code>{code}</code>
</pre>
</div>
);
}
+101
View File
@@ -0,0 +1,101 @@
"use client";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { useSession } from "next-auth/react";
type DocsApiKey = {
id: string;
keyPrefix: string;
label: string | null;
status: string;
};
type AuthMode = "saved" | "manual";
type DocsAuthContextValue = {
loggedIn: boolean;
loading: boolean;
mode: AuthMode;
setMode: (mode: AuthMode) => void;
keys: DocsApiKey[];
selectedKeyId: string;
setSelectedKeyId: (value: string) => void;
manualApiKey: string;
setManualApiKey: (value: string) => void;
};
const DocsAuthContext = createContext<DocsAuthContextValue | null>(null);
export function DocsAuthProvider({ children }: { children: React.ReactNode }) {
const { data: session, status } = useSession();
const [loading, setLoading] = useState(true);
const [keys, setKeys] = useState<DocsApiKey[]>([]);
const [mode, setMode] = useState<AuthMode>("manual");
const [selectedKeyId, setSelectedKeyId] = useState("");
const [manualApiKey, setManualApiKey] = useState("");
useEffect(() => {
async function loadKeys() {
setLoading(true);
const res = await fetch("/api/docs/api-keys");
if (!res.ok) {
setKeys([]);
setLoading(false);
return;
}
const payload = (await res.json()) as { loggedIn: boolean; keys: DocsApiKey[] };
setKeys(payload.keys ?? []);
setLoading(false);
}
loadKeys().catch(() => {
setLoading(false);
setKeys([]);
});
}, [status]);
useEffect(() => {
if (session?.user) {
setMode("saved");
} else {
setMode("manual");
}
}, [session?.user]);
useEffect(() => {
if (!keys.length) {
setSelectedKeyId("");
return;
}
if (!keys.some((key) => key.id === selectedKeyId)) {
setSelectedKeyId(keys[0].id);
}
}, [keys, selectedKeyId]);
const value = useMemo<DocsAuthContextValue>(
() => ({
loggedIn: Boolean(session?.user),
loading,
mode,
setMode,
keys,
selectedKeyId,
setSelectedKeyId,
manualApiKey,
setManualApiKey,
}),
[keys, loading, manualApiKey, mode, selectedKeyId, session?.user],
);
return <DocsAuthContext.Provider value={value}>{children}</DocsAuthContext.Provider>;
}
export function useDocsAuth() {
const context = useContext(DocsAuthContext);
if (!context) {
throw new Error("useDocsAuth must be used within DocsAuthProvider");
}
return context;
}
+186
View File
@@ -0,0 +1,186 @@
export type DocsNavItem = {
title: string;
href: string;
description: string;
};
export type EndpointDoc = {
slug: "models" | "chat-completions" | "completions" | "embeddings";
title: string;
method: "GET" | "POST";
path: "/v1/models" | "/v1/chat/completions" | "/v1/completions" | "/v1/embeddings";
description: string;
requestExample?: string;
responseExample: string;
curlExample: string;
};
export const docsNav: DocsNavItem[] = [
{
title: "Overview",
href: "/docs",
description: "What this API is and how to use it.",
},
{
title: "Getting Started",
href: "/docs/getting-started",
description: "Create a key and make your first request.",
},
{
title: "Authentication",
href: "/docs/auth",
description: "Bearer auth format and key usage.",
},
{
title: "Endpoints",
href: "/docs/endpoints",
description: "All OpenAI-compatible routes.",
},
{
title: "Claude Code",
href: "/docs/claude-code",
description: "Connect Claude Code to this proxy.",
},
];
export const endpointDocs: EndpointDoc[] = [
{
slug: "models",
title: "List Models",
method: "GET",
path: "/v1/models",
description: "Returns all currently available logical models for your key.",
responseExample: `{
"object": "list",
"data": [
{
"id": "gpt-4.1-mini",
"object": "model",
"created": 1735678910,
"owned_by": "llm-proxy"
}
]
}`,
curlExample: `curl -s http://localhost:3000/v1/models \\
-H "Authorization: Bearer $LLM_PROXY_API_KEY"`,
},
{
slug: "chat-completions",
title: "Chat Completions",
method: "POST",
path: "/v1/chat/completions",
description: "Primary text generation endpoint compatible with OpenAI chat clients.",
requestExample: `{
"model": "gpt-4.1-mini",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Write one short product tagline for an AI proxy." }
],
"temperature": 0.7,
"max_tokens": 120
}`,
responseExample: `{
"id": "chatcmpl_123",
"object": "chat.completion",
"created": 1735678910,
"model": "gpt-4.1-mini",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "One API key, every model, zero integration chaos."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 22,
"completion_tokens": 14,
"total_tokens": 36
}
}`,
curlExample: `curl -s http://localhost:3000/v1/chat/completions \\
-H "Authorization: Bearer $LLM_PROXY_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"model": "gpt-4.1-mini",
"messages": [{"role":"user","content":"Say hello from LLM Proxy"}]
}'`,
},
{
slug: "completions",
title: "Completions",
method: "POST",
path: "/v1/completions",
description: "Legacy text completion endpoint for clients that use prompt-based completions.",
requestExample: `{
"model": "gpt-4.1-mini",
"prompt": "Write a one-line release note for an API gateway.",
"max_tokens": 60,
"temperature": 0.5
}`,
responseExample: `{
"id": "cmpl_123",
"object": "text_completion",
"created": 1735678910,
"model": "gpt-4.1-mini",
"choices": [
{
"text": "New: route one OpenAI-compatible request across multiple providers.",
"index": 0,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 12,
"completion_tokens": 14,
"total_tokens": 26
}
}`,
curlExample: `curl -s http://localhost:3000/v1/completions \\
-H "Authorization: Bearer $LLM_PROXY_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"model": "gpt-4.1-mini",
"prompt": "Summarize this API in one line."
}'`,
},
{
slug: "embeddings",
title: "Embeddings",
method: "POST",
path: "/v1/embeddings",
description: "Generate vector embeddings for semantic search and retrieval.",
requestExample: `{
"model": "text-embedding-3-small",
"input": "LLM Proxy routes one OpenAI-compatible API across providers."
}`,
responseExample: `{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": [0.0123, -0.0191, 0.0442]
}
],
"model": "text-embedding-3-small",
"usage": {
"prompt_tokens": 13,
"total_tokens": 13
}
}`,
curlExample: `curl -s http://localhost:3000/v1/embeddings \\
-H "Authorization: Bearer $LLM_PROXY_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"model": "text-embedding-3-small",
"input": "Hello from LLM Proxy"
}'`,
},
];
export function getEndpointDocBySlug(slug: string) {
return endpointDocs.find((item) => item.slug === slug);
}
+60
View File
@@ -0,0 +1,60 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { docsNav, endpointDocs } from "@/components/docs/docs-config";
import { cn } from "@/lib/utils";
export function DocsSidebar() {
const pathname = usePathname();
return (
<aside className="h-fit space-y-4 rounded-xl border bg-card p-4">
<div>
<h2 className="text-sm font-semibold">Documentation</h2>
<p className="text-xs text-muted-foreground">Guides and API reference</p>
</div>
<nav className="space-y-1">
{docsNav.map((item) => {
const isActive = item.href === "/docs" ? pathname === item.href : pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={cn(
"block rounded-md px-3 py-2 text-sm transition-colors",
isActive ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted",
)}
>
{item.title}
</Link>
);
})}
</nav>
<div className="border-t pt-4">
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">API Endpoints</h3>
<nav className="space-y-1">
{endpointDocs.map((endpoint) => {
const href = `/docs/endpoints/${endpoint.slug}`;
const isActive = pathname === href;
return (
<Link
key={endpoint.slug}
href={href}
className={cn(
"block rounded-md px-3 py-2 text-sm transition-colors",
isActive ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted",
)}
>
<span className="mr-2 font-mono text-xs">{endpoint.method}</span>
{endpoint.path}
</Link>
);
})}
</nav>
</div>
</aside>
);
}
+143
View File
@@ -0,0 +1,143 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useDocsAuth } from "@/components/docs/docs-auth-context";
import type { EndpointDoc } from "@/components/docs/docs-config";
type TestResult = {
status: number;
ok: boolean;
latencyMs: number;
headers: Record<string, string>;
body: unknown;
};
export function EndpointTester({ endpoint }: { endpoint: EndpointDoc }) {
const { mode, selectedKeyId, manualApiKey, keys, loggedIn } = useDocsAuth();
const [requestBody, setRequestBody] = useState(endpoint.requestExample ?? "");
const [testing, setTesting] = useState(false);
const [result, setResult] = useState<TestResult | null>(null);
const canTestWithSaved = mode === "saved" && loggedIn && Boolean(selectedKeyId);
const canTestWithManual = mode === "manual" && manualApiKey.trim().length > 0;
const canTest = canTestWithSaved || canTestWithManual;
async function runTest() {
if (!canTest || testing) return;
let parsedBody: unknown;
if (endpoint.method === "POST") {
try {
parsedBody = JSON.parse(requestBody);
} catch {
toast.error("Request body must be valid JSON");
return;
}
}
setTesting(true);
setResult(null);
const res = await fetch("/api/docs/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
endpoint: endpoint.slug,
apiKeyId: canTestWithSaved ? selectedKeyId : undefined,
apiKey: canTestWithManual ? manualApiKey.trim() : undefined,
body: parsedBody,
}),
});
setTesting(false);
const payload = (await res.json().catch(() => null)) as
| (TestResult & { error?: string | { message?: string } })
| null;
if (!res.ok || !payload) {
const message =
typeof payload?.error === "string"
? payload.error
: payload?.error?.message ?? "Failed to test endpoint.";
toast.error(message);
return;
}
setResult({
status: payload.status,
ok: payload.ok,
latencyMs: payload.latencyMs,
headers: payload.headers,
body: payload.body,
});
}
const selectedLabel =
mode === "saved" && selectedKeyId
? (keys.find((item) => item.id === selectedKeyId)?.label ??
keys.find((item) => item.id === selectedKeyId)?.keyPrefix ??
"Selected key")
: null;
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<span>Try It</span>
<Badge variant="secondary">{endpoint.method}</Badge>
<code className="rounded bg-muted px-2 py-1 text-xs">{endpoint.path}</code>
</CardTitle>
<CardDescription>
Run a live request using {mode === "saved" ? "your selected account key" : "a pasted API key"}.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === "saved" && selectedLabel && (
<p className="text-xs text-muted-foreground">Using key: {selectedLabel}</p>
)}
{endpoint.method === "POST" && (
<div className="space-y-2">
<label className="text-sm font-medium">Request JSON</label>
<textarea
value={requestBody}
onChange={(event) => setRequestBody(event.target.value)}
rows={12}
className="w-full rounded-md border bg-background px-3 py-2 text-xs font-mono outline-none focus:ring-1 focus:ring-ring"
/>
</div>
)}
<Button onClick={runTest} disabled={!canTest || testing}>
{testing ? "Testing..." : "Run test request"}
</Button>
{!canTest && (
<p className="text-xs text-amber-500">
Select an account key or paste a manual key first to test endpoints.
</p>
)}
{result && (
<div className="space-y-2 rounded-xl border p-3">
<div className="flex flex-wrap items-center gap-2 text-xs">
<Badge variant={result.ok ? "default" : "secondary"}>{result.status}</Badge>
<span className="text-muted-foreground">{result.latencyMs} ms</span>
{result.headers["content-type"] && (
<span className="text-muted-foreground">content-type: {result.headers["content-type"]}</span>
)}
</div>
<pre className="overflow-x-auto rounded-lg bg-muted/20 p-3 text-xs">
<code>{JSON.stringify(result.body, null, 2)}</code>
</pre>
</div>
)}
</CardContent>
</Card>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { useDocsAuth } from "@/components/docs/docs-auth-context";
export function KeySelector() {
const { loggedIn, loading, mode, setMode, keys, selectedKeyId, setSelectedKeyId, manualApiKey, setManualApiKey } =
useDocsAuth();
return (
<Card>
<CardHeader className="pb-3">
<CardTitle>Test Authentication</CardTitle>
<CardDescription>
{loggedIn
? "Select one of your account API keys or paste a key manually."
: "Paste a valid LLM Proxy API key to run endpoint tests."}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{loggedIn && (
<div className="flex flex-wrap gap-2">
<Button variant={mode === "saved" ? "default" : "outline"} onClick={() => setMode("saved")}>
Use Account Key
</Button>
<Button variant={mode === "manual" ? "default" : "outline"} onClick={() => setMode("manual")}>
Paste Key Manually
</Button>
</div>
)}
{mode === "saved" && loggedIn ? (
loading ? (
<p className="text-sm text-muted-foreground">Loading your API keys...</p>
) : keys.length === 0 ? (
<div className="space-y-2 text-sm text-muted-foreground">
<p>No active keys found on your account.</p>
<Button asChild size="sm" variant="outline">
<Link href="/dashboard/api-keys">Create API key</Link>
</Button>
</div>
) : (
<div className="space-y-2">
<label className="text-sm font-medium">Account API key</label>
<select
value={selectedKeyId}
onChange={(event) => setSelectedKeyId(event.target.value)}
className="h-10 w-full rounded-md border bg-background px-3 text-sm"
>
{keys.map((key) => (
<option key={key.id} value={key.id}>
{key.label ? `${key.label} (${key.keyPrefix})` : key.keyPrefix}
</option>
))}
</select>
<Badge variant="secondary">Stored key mode (no raw key exposed)</Badge>
</div>
)
) : (
<div className="space-y-2">
<label className="text-sm font-medium">Manual API key</label>
<Input
value={manualApiKey}
onChange={(event) => setManualApiKey(event.target.value)}
placeholder="lp_..."
autoComplete="off"
/>
</div>
)}
</CardContent>
</Card>
);
}
+2
View File
@@ -10,6 +10,7 @@ import {
ScrollText,
BarChart3,
MessageSquare,
BookOpen,
CreditCard,
Users,
Settings,
@@ -29,6 +30,7 @@ interface NavItem {
const dashboardNav: NavItem[] = [
{ label: "Overview", href: "/dashboard", icon: LayoutDashboard },
{ label: "Playground", href: "/dashboard/playground", icon: MessageSquare },
{ label: "Docs", href: "/docs", icon: BookOpen },
{ label: "API Keys", href: "/dashboard/api-keys", icon: Key },
{ label: "Usage", href: "/dashboard/usage", icon: BarChart3 },
{ label: "Logs", href: "/dashboard/logs", icon: ScrollText },