Skip to content

The Open Standard for Generative UI

3.6 KB
Raw Blame
import {
  createDemoCreditsExhaustedResponse,
  isDemoCreditsExhaustedError,
} from "@/lib/demo-credits";
import { BASE_URL } from "@/lib/source";
import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
import { readFileSync } from "fs";
import { type NextRequest } from "next/server";
import { join } from "path";
import { GITHUB_DEMO_MODEL } from "../../../../demo/github/constants";
import {
  GITHUB_ADDITIONAL_RULES,
  GITHUB_PREAMBLE,
  GITHUB_TOOL_EXAMPLES,
} from "../../../../demo/github/github/prompt-config";
import { GITHUB_TOOL_SPECS } from "../../../../demo/github/github/types";

// ── Library spec from `openui generate --spec` ────────────────────────────

const librarySpec = JSON.parse(
  readFileSync(join(process.cwd(), "generated/playground-library.spec.json"), "utf-8"),
) as LibrarySpec;

// ── GitHub system prompt ──────────────────────────────────────────────────

function buildGitHubPrompt(): string {
  return generateSystemPrompt({
    library: librarySpec,
    promptOptions: {
      tools: GITHUB_TOOL_SPECS,
      toolExamples: GITHUB_TOOL_EXAMPLES,
      additionalRules: GITHUB_ADDITIONAL_RULES,
      preamble: GITHUB_PREAMBLE,
      editMode: true,
      inlineMode: true,
      toolCalls: true,
      bindings: true,
    },
  });
}

let cachedPrompt: string | null = null;
function getPrompt(): string {
  if (!cachedPrompt) cachedPrompt = buildGitHubPrompt();
  return cachedPrompt;
}

// ── Route handler ──────────────────────────────────────────────────────────

export async function POST(req: NextRequest) {
  const { prompt, messages } = await req.json();

  const systemPrompt = getPrompt();

  const chatMessages: Array<{ role: string; content: string }> = [
    { role: "system", content: systemPrompt },
  ];
  if (messages && Array.isArray(messages)) {
    for (const m of messages) {
      chatMessages.push({ role: m.role, content: m.content });
    }
  }
  chatMessages.push({ role: "user", content: prompt });

  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) {
    return Response.json(
      { error: { message: "OPENROUTER_API_KEY not configured" } },
      { status: 500 },
    );
  }

  const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      "HTTP-Referer": `${BASE_URL}/demo/github`,
      "X-Title": "OpenUI GitHub Demo",
    },
    body: JSON.stringify({
      model: GITHUB_DEMO_MODEL,
      stream: true,
      messages: chatMessages,
    }),
    signal: req.signal,
  });

  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    if (isDemoCreditsExhaustedError(err, res.status)) {
      return createDemoCreditsExhaustedResponse();
    }

    return Response.json(
      {
        error: (err as { error?: { message?: string } }).error ?? {
          message: `OpenRouter error ${res.status}`,
        },
      },
      { status: res.status },
    );
  }

  // Keep credit handling to provider 4xx responses. Provider-specific mid-stream
  // error chunks are intentionally passed through because they are harder to
  // maintain across OpenRouter/OpenAI streaming shape changes.
  return new Response(res.body, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
    },
  });
}