diff --git a/README.md b/README.md index 68e97d3..b00d22e 100644 --- a/README.md +++ b/README.md @@ -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", -}); -``` diff --git a/src/app/api/dashboard/api-keys/[keyId]/route.ts b/src/app/api/dashboard/api-keys/[keyId]/route.ts index 942082b..0454423 100644 --- a/src/app/api/dashboard/api-keys/[keyId]/route.ts +++ b/src/app/api/dashboard/api-keys/[keyId]/route.ts @@ -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 }); diff --git a/src/app/api/docs/api-keys/route.ts b/src/app/api/docs/api-keys/route.ts new file mode 100644 index 0000000..4c81591 --- /dev/null +++ b/src/app/api/docs/api-keys/route.ts @@ -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"), + }); +} diff --git a/src/app/api/docs/test/route.ts b/src/app/api/docs/test/route.ts new file mode 100644 index 0000000..71172fd --- /dev/null +++ b/src/app/api/docs/test/route.ts @@ -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; + +function shouldRetryProviderError(error: ApiError): boolean { + return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600); +} + +async function resolveAuth(payload: DocsTestRequest): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + 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, + }); +} diff --git a/src/app/dashboard/api-keys/page.tsx b/src/app/dashboard/api-keys/page.tsx index b718702..26bc6ce 100644 --- a/src/app/dashboard/api-keys/page.tsx +++ b/src/app/dashboard/api-keys/page.tsx @@ -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() { {key.label ?? "-"} - {key.status} + {isDisabled(key.status) ? "DISABLED" : key.status} - {key.dailyRequestLimit ? `${key.dailyRequestLimit} req` : "Default"} - {key.dailyTokenLimit ? ` / ${key.dailyTokenLimit} tok` : ""} + {key.dailyRequestLimit != null ? `${key.dailyRequestLimit} req` : "Default"} + {key.dailyTokenLimit != null ? ` / ${key.dailyTokenLimit} tok` : ""} - {key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never"} + {key.lastUsedAt ? (formatDate(key.lastUsedAt) ?? "-") : "Never"} - {new Date(key.createdAt).toLocaleDateString()} + {formatDate(key.createdAt) ?? "-"} - - + + {isDisabled(key.status) ? ( + <> + + + + ) : ( + + )} ))} diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 90de6bf..bd8e8fe 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -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() {

+ + + + + API Documentation + + + +

Open guides, endpoint reference, and live API testing.

+ +
+
+
{stats.map((stat) => ( diff --git a/src/app/docs/auth/page.tsx b/src/app/docs/auth/page.tsx new file mode 100644 index 0000000..3d69768 --- /dev/null +++ b/src/app/docs/auth/page.tsx @@ -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 ( +
+
+

Authentication

+

+ All `/v1/*` endpoints require your LLM Proxy user API key in Bearer format. +

+
+ + + + Authorization header format + + + + + + + + + How keys are validated + + +

- Key must exist and be active

+

- Key must not be expired

+

- User account must be active

+

- Account must have a valid subscription plan

+
+
+ + + + Common auth error response + + + + + +
+ ); +} diff --git a/src/app/docs/claude-code/page.tsx b/src/app/docs/claude-code/page.tsx new file mode 100644 index 0000000..148a73f --- /dev/null +++ b/src/app/docs/claude-code/page.tsx @@ -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 ( +
+
+

Claude Code Guide

+

+ Point Claude Code to your LLM Proxy `/v1` base URL and use your LLM Proxy API key. +

+
+ + + + One-off command + + + + + + + + + Shell environment setup + + + +

Then run: `claude --model gpt-4.1-mini`

+
+
+ + + + Troubleshooting + + + + + +
+ ); +} diff --git a/src/app/docs/endpoints/[endpoint]/page.tsx b/src/app/docs/endpoints/[endpoint]/page.tsx new file mode 100644 index 0000000..6b546c7 --- /dev/null +++ b/src/app/docs/endpoints/[endpoint]/page.tsx @@ -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 ( +
+
+

{endpoint.title}

+

{endpoint.description}

+
+ + + + + {endpoint.method} + {endpoint.path} + + + +
+

cURL example

+ +
+ + {endpoint.requestExample && ( +
+

Request body example

+ +
+ )} + +
+

Response example

+ +
+
+
+ + +
+ ); +} diff --git a/src/app/docs/endpoints/page.tsx b/src/app/docs/endpoints/page.tsx new file mode 100644 index 0000000..f1547cf --- /dev/null +++ b/src/app/docs/endpoints/page.tsx @@ -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 ( +
+
+

Endpoints

+

Reference docs and live tests for all supported API routes.

+
+ +
+ {endpointDocs.map((endpoint) => ( + + + + + {endpoint.method} + {endpoint.path} + + + {endpoint.description} + + + ))} +
+
+ ); +} diff --git a/src/app/docs/getting-started/page.tsx b/src/app/docs/getting-started/page.tsx new file mode 100644 index 0000000..c725403 --- /dev/null +++ b/src/app/docs/getting-started/page.tsx @@ -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 ( +
+
+

Getting Started

+

Get a key, choose a model, and make your first API request.

+
+ + + + Step 1: Create your user API key + + +

Register and login, then open the API key manager to create a key.

+ + Open API Keys page + +

Copy your key immediately when created. It is only shown once.

+
+
+ + + + Step 2: Make a quick chat request + + + + + + + + + Step 3: Use any OpenAI-compatible SDK + + + + + +
+ ); +} diff --git a/src/app/docs/layout.tsx b/src/app/docs/layout.tsx new file mode 100644 index 0000000..c818561 --- /dev/null +++ b/src/app/docs/layout.tsx @@ -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 ( + +
+
+ + LLM Proxy + +
OpenAI-compatible API docs
+
+ +
+ +
+ + {children} +
+
+
+
+ ); +} diff --git a/src/app/docs/page.tsx b/src/app/docs/page.tsx new file mode 100644 index 0000000..dc0fcda --- /dev/null +++ b/src/app/docs/page.tsx @@ -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 ( +
+
+

LLM Proxy API Documentation

+

+ Use one base URL and one key to access multiple model providers with an OpenAI-compatible API. +

+
+ +
+ {docsNav + .filter((item) => item.href !== "/docs") + .map((item) => ( + + + + {item.title} + {item.description} + + + + ))} +
+ +
+

Supported OpenAI-compatible endpoints

+
+ {endpointDocs.map((endpoint) => ( + + + +
+

{endpoint.title}

+

{endpoint.description}

+
+ + {endpoint.method} {endpoint.path} + +
+
+ + ))} +
+
+
+ ); +} diff --git a/src/app/page.tsx b/src/app/page.tsx index fb89712..a279734 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -109,6 +109,9 @@ export default async function Home() { + diff --git a/src/components/docs/code-snippet.tsx b/src/components/docs/code-snippet.tsx new file mode 100644 index 0000000..5fa4df2 --- /dev/null +++ b/src/components/docs/code-snippet.tsx @@ -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 ( +
+
+ {language ?? "text"} + +
+
+        {code}
+      
+
+ ); +} diff --git a/src/components/docs/docs-auth-context.tsx b/src/components/docs/docs-auth-context.tsx new file mode 100644 index 0000000..e3c7338 --- /dev/null +++ b/src/components/docs/docs-auth-context.tsx @@ -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(null); + +export function DocsAuthProvider({ children }: { children: React.ReactNode }) { + const { data: session, status } = useSession(); + const [loading, setLoading] = useState(true); + const [keys, setKeys] = useState([]); + const [mode, setMode] = useState("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( + () => ({ + loggedIn: Boolean(session?.user), + loading, + mode, + setMode, + keys, + selectedKeyId, + setSelectedKeyId, + manualApiKey, + setManualApiKey, + }), + [keys, loading, manualApiKey, mode, selectedKeyId, session?.user], + ); + + return {children}; +} + +export function useDocsAuth() { + const context = useContext(DocsAuthContext); + if (!context) { + throw new Error("useDocsAuth must be used within DocsAuthProvider"); + } + return context; +} diff --git a/src/components/docs/docs-config.ts b/src/components/docs/docs-config.ts new file mode 100644 index 0000000..79e24a7 --- /dev/null +++ b/src/components/docs/docs-config.ts @@ -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); +} diff --git a/src/components/docs/docs-sidebar.tsx b/src/components/docs/docs-sidebar.tsx new file mode 100644 index 0000000..0698d2c --- /dev/null +++ b/src/components/docs/docs-sidebar.tsx @@ -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 ( + + ); +} diff --git a/src/components/docs/endpoint-tester.tsx b/src/components/docs/endpoint-tester.tsx new file mode 100644 index 0000000..33e428c --- /dev/null +++ b/src/components/docs/endpoint-tester.tsx @@ -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; + 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(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 ( + + + + Try It + {endpoint.method} + {endpoint.path} + + + Run a live request using {mode === "saved" ? "your selected account key" : "a pasted API key"}. + + + + {mode === "saved" && selectedLabel && ( +

Using key: {selectedLabel}

+ )} + + {endpoint.method === "POST" && ( +
+ +