Skip to content

The Open Standard for Generative UI

Update OpenUI docs introduction (#286)

abhithesys405e95ba9d3a
diff --git a/docs/app/(home)/components/Navbar.tsx b/docs/app/(home)/components/Navbar.tsx
index 21db1bce8..9d9f2624c 100644
--- a/docs/app/(home)/components/Navbar.tsx
+++ b/docs/app/(home)/components/Navbar.tsx
@@ -17,11 +17,9 @@ import { BUTTON_SHADOW } from "./shared";
// Constants
// ---------------------------------------------------------------------------
-const NAV_TABS = ["Introduction", "OpenUI Lang", "Chat", "Playground", "API Reference"] as const;
+const NAV_TABS = ["OpenUI Lang", "Playground", "API Reference"] as const;
const TAB_URLS: Record<string, string> = {
- Introduction: "/docs/introduction",
"OpenUI Lang": "/docs/openui-lang",
- Chat: "/docs/chat",
Playground: "/playground",
"API Reference": "/docs/api-reference",
};
diff --git a/docs/app/api/chat/route.ts b/docs/app/api/chat/route.ts
new file mode 100644
index 000000000..4fdd33a0f
--- /dev/null
+++ b/docs/app/api/chat/route.ts
@@ -0,0 +1,297 @@
+import { NextRequest } from "next/server";
+import OpenAI from "openai";
+import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";
+
+// ── Tool implementations ──
+
+function getWeather({ location }: { location: string }): Promise<string> {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ const knownTemps: Record<string, number> = {
+ tokyo: 22, "san francisco": 18, london: 14, "new york": 25,
+ paris: 19, sydney: 27, mumbai: 33, berlin: 16,
+ };
+ const conditions = ["Sunny", "Partly Cloudy", "Cloudy", "Light Rain", "Clear Skies"];
+ const temp = knownTemps[location.toLowerCase()] ?? Math.floor(Math.random() * 30 + 5);
+ const condition = conditions[Math.floor(Math.random() * conditions.length)];
+ resolve(JSON.stringify({
+ location, temperature_celsius: temp,
+ temperature_fahrenheit: Math.round(temp * 1.8 + 32),
+ condition,
+ humidity_percent: Math.floor(Math.random() * 40 + 40),
+ wind_speed_kmh: Math.floor(Math.random() * 25 + 5),
+ forecast: [
+ { day: "Tomorrow", high: temp + 2, low: temp - 4, condition: "Partly Cloudy" },
+ { day: "Day After", high: temp + 1, low: temp - 3, condition: "Sunny" },
+ ],
+ }));
+ }, 800);
+ });
+}
+
+function getStockPrice({ symbol }: { symbol: string }): Promise<string> {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ const s = symbol.toUpperCase();
+ const knownPrices: Record<string, number> = {
+ AAPL: 189.84, GOOGL: 141.8, TSLA: 248.42, MSFT: 378.91,
+ AMZN: 178.25, NVDA: 875.28, META: 485.58,
+ };
+ const price = knownPrices[s] ?? Math.floor(Math.random() * 500 + 20);
+ const change = parseFloat((Math.random() * 8 - 4).toFixed(2));
+ resolve(JSON.stringify({
+ symbol: s,
+ price: parseFloat((price + change).toFixed(2)),
+ change, change_percent: parseFloat(((change / price) * 100).toFixed(2)),
+ volume: `${(Math.random() * 50 + 10).toFixed(1)}M`,
+ day_high: parseFloat((price + Math.abs(change) + 1.5).toFixed(2)),
+ day_low: parseFloat((price - Math.abs(change) - 1.2).toFixed(2)),
+ }));
+ }, 600);
+ });
+}
+
+function calculate({ expression }: { expression: string }): Promise<string> {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ try {
+ const sanitized = expression.replace(/[^0-9+\-*/().%\s,Math.sqrtpowabsceilfloorround]/g, "");
+ const result = new Function(`return (${sanitized})`)();
+ resolve(JSON.stringify({ expression, result: Number(result) }));
+ } catch {
+ resolve(JSON.stringify({ expression, error: "Invalid expression" }));
+ }
+ }, 300);
+ });
+}
+
+function searchWeb({ query }: { query: string }): Promise<string> {
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ resolve(JSON.stringify({
+ query,
+ results: [
+ { title: `Top result for "${query}"`, snippet: `Comprehensive overview of ${query} with the latest information.` },
+ { title: `${query} - Latest News`, snippet: `Recent developments and updates related to ${query}.` },
+ { title: `Understanding ${query}`, snippet: `An in-depth guide explaining everything about ${query}.` },
+ ],
+ }));
+ }, 1000);
+ });
+}
+
+// ── Tool definitions ──
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const tools: any[] = [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get current weather for a location.",
+ parameters: {
+ type: "object",
+ properties: { location: { type: "string", description: "City name" } },
+ required: ["location"],
+ },
+ function: getWeather,
+ parse: JSON.parse,
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "get_stock_price",
+ description: "Get stock price for a ticker symbol.",
+ parameters: {
+ type: "object",
+ properties: { symbol: { type: "string", description: "Ticker symbol, e.g. AAPL" } },
+ required: ["symbol"],
+ },
+ function: getStockPrice,
+ parse: JSON.parse,
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "calculate",
+ description: "Evaluate a math expression.",
+ parameters: {
+ type: "object",
+ properties: { expression: { type: "string", description: "Math expression to evaluate" } },
+ required: ["expression"],
+ },
+ function: calculate,
+ parse: JSON.parse,
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "search_web",
+ description: "Search the web for information.",
+ parameters: {
+ type: "object",
+ properties: { query: { type: "string", description: "Search query" } },
+ required: ["query"],
+ },
+ function: searchWeb,
+ parse: JSON.parse,
+ },
+ },
+];
+
+// ── SSE helpers ──
+
+function sseToolCallStart(
+ encoder: TextEncoder,
+ tc: { id: string; function: { name: string } },
+ index: number,
+) {
+ return encoder.encode(
+ `data: ${JSON.stringify({
+ id: `chatcmpl-tc-${tc.id}`,
+ object: "chat.completion.chunk",
+ choices: [{
+ index: 0,
+ delta: {
+ tool_calls: [{ index, id: tc.id, type: "function", function: { name: tc.function.name, arguments: "" } }],
+ },
+ finish_reason: null,
+ }],
+ })}\n\n`,
+ );
+}
+
+function sseToolCallArgs(
+ encoder: TextEncoder,
+ tc: { id: string; function: { arguments: string } },
+ result: string,
+ index: number,
+) {
+ let enrichedArgs: string;
+ try {
+ enrichedArgs = JSON.stringify({ _request: JSON.parse(tc.function.arguments), _response: JSON.parse(result) });
+ } catch {
+ enrichedArgs = tc.function.arguments;
+ }
+ return encoder.encode(
+ `data: ${JSON.stringify({
+ id: `chatcmpl-tc-${tc.id}-args`,
+ object: "chat.completion.chunk",
+ choices: [{
+ index: 0,
+ delta: { tool_calls: [{ index, function: { arguments: enrichedArgs } }] },
+ finish_reason: null,
+ }],
+ })}\n\n`,
+ );
+}
+
+// ── Route handler ──
+
+export async function POST(req: NextRequest) {
+ const { messages, systemPrompt } = await req.json();
+
+ const client = new OpenAI({
+ apiKey: process.env.OPENROUTER_API_KEY,
+ baseURL: "https://openrouter.ai/api/v1",
+ });
+ const MODEL = "openai/gpt-5.4";
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const cleanMessages = (messages as any[])
+ .filter((m) => m.role !== "tool")
+ .map((m) => {
+ if (m.role === "assistant" && m.tool_calls?.length) {
+ const { tool_calls: _tc, ...rest } = m; // eslint-disable-line @typescript-eslint/no-unused-vars
+ return rest;
+ }
+ return m;
+ });
+
+ const chatMessages: ChatCompletionMessageParam[] = [
+ ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
+ ...cleanMessages,
+ ];
+
+ const encoder = new TextEncoder();
+ let controllerClosed = false;
+
+ const readable = new ReadableStream({
+ start(controller) {
+ const enqueue = (data: Uint8Array) => {
+ if (controllerClosed) return;
+ try { controller.enqueue(data); } catch { /* already closed */ }
+ };
+ const close = () => {
+ if (controllerClosed) return;
+ controllerClosed = true;
+ try { controller.close(); } catch { /* already closed */ }
+ };
+
+ const pendingCalls: Array<{ id: string; name: string; arguments: string }> = [];
+ let callIdx = 0;
+ let resultIdx = 0;
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const runner = (client.chat.completions as any).runTools({
+ model: MODEL,
+ messages: chatMessages,
+ tools,
+ stream: true
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ runner.on("functionToolCall", (fc: any) => {
+ const id = `tc-${callIdx}`;
+ pendingCalls.push({ id, name: fc.name, arguments: fc.arguments });
+ enqueue(sseToolCallStart(encoder, { id, function: { name: fc.name } }, callIdx));
+ callIdx++;
+ });
+
+ runner.on("functionToolCallResult", (result: string) => {
+ const tc = pendingCalls[resultIdx];
+ if (tc) {
+ enqueue(sseToolCallArgs(encoder, { id: tc.id, function: { arguments: tc.arguments } }, result, resultIdx));
+ }
+ resultIdx++;
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ runner.on("chunk", (chunk: any) => {
+ const choice = chunk.choices?.[0];
+ const delta = choice?.delta;
+ if (!delta) return;
+ if (delta.content) {
+ enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
+ }
+ if (choice?.finish_reason === "stop") {
+ enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
+ }
+ });
+
+ runner.on("end", () => {
+ enqueue(encoder.encode("data: [DONE]\n\n"));
+ close();
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ runner.on("error", (err: any) => {
+ const msg = err instanceof Error ? err.message : "Stream error";
+ console.error("Chat route error:", msg);
+ enqueue(encoder.encode(`data: ${JSON.stringify({ error: msg })}\n\n`));
+ close();
+ });
+ },
+ });
+
+ return new Response(readable, {
+ headers: {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ },
+ });
+}
diff --git a/docs/app/docs/[[...slug]]/page.tsx b/docs/app/docs/[[...slug]]/page.tsx
index 356857356..77b887bb9 100644
--- a/docs/app/docs/[[...slug]]/page.tsx
+++ b/docs/app/docs/[[...slug]]/page.tsx
@@ -13,23 +13,18 @@ export default async function Page(props: PageProps<"/docs/[[...slug]]">) {
if (!page) notFound();
const MDX = page.data.body;
- const isIntroduction = page.slugs[0] === "introduction";
return (
<DocsPage toc={page.data.toc} full={page.data.full}>
- {!isIntroduction && (
- <>
- <DocsTitle>{page.data.title}</DocsTitle>
- <DocsDescription className="mb-0">{page.data.description}</DocsDescription>
- <div className="flex flex-row gap-2 items-center border-b pb-6">
- <LLMCopyButton markdownUrl={`${page.url}.mdx`} />
- <ViewOptions
- markdownUrl={`${page.url}.mdx`}
- githubUrl={`https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/content/docs/${page.path}`}
- />
- </div>
- </>
- )}
+ <DocsTitle>{page.data.title}</DocsTitle>
+ <DocsDescription className="mb-0">{page.data.description}</DocsDescription>
+ <div className="flex flex-row gap-2 items-center border-b pb-6">
+ <LLMCopyButton markdownUrl={`${page.url}.mdx`} />
+ <ViewOptions
+ markdownUrl={`${page.url}.mdx`}
+ githubUrl={`https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/content/docs/${page.path}`}
+ />
+ </div>
<DocsBody>
<MDX
components={getMDXComponents({
diff --git a/docs/app/docs/introduction/page.module.css b/docs/app/docs/introduction/page.module.css
deleted file mode 100644
index 9951302e3..000000000
--- a/docs/app/docs/introduction/page.module.css
+++ /dev/null
@@ -1,8 +0,0 @@
-:global(#nd-docs-layout:not(:has(#nd-sidebar))) {
- grid-template-columns: 1fr !important;
- grid-template-areas: "main" !important;
-}
-
-:global(#nd-docs-layout:not(:has(#nd-sidebar))) > * {
- grid-area: main !important;
-}
diff --git a/docs/app/docs/introduction/page.tsx b/docs/app/docs/introduction/page.tsx
deleted file mode 100644
index 630bdcbbf..000000000
--- a/docs/app/docs/introduction/page.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import "@/app/docs/introduction/page.module.css";
-import { OverviewPage } from "@/components/overview-components/overview-page";
-
-export const metadata = {
- title: "Introduction",
- description: "OpenUI is a comprehensive toolkit for building LLM-powered user interfaces.",
-};
-
-export default function IntroductionPage() {
- return <OverviewPage />;
-}
diff --git a/docs/app/docs/openui-lang/page.tsx b/docs/app/docs/openui-lang/page.tsx
deleted file mode 100644
index 0c1cd6abc..000000000
--- a/docs/app/docs/openui-lang/page.tsx
+++ /dev/null
@@ -1,454 +0,0 @@
-"use client";
-
-import { Button } from "@/components/button";
-import { CodeBlock, InlineButton, Separator, SimpleCard } from "@/components/overview-components";
-import {
- ArrowRight,
- BarChart3,
- Code2,
- FileText,
- MessageSquare,
- Shield,
- Waves,
- Zap,
-} from "lucide-react";
-import {
- FeatureCard,
- FeatureCards,
-} from "@/components/overview-components";
-import Link from "next/link";
-import { useState } from "react";
-
-const steps = [
- {
- title: "Define Library",
- description: "Create your component library with Zod schemas and generate the system prompt",
- code: `import { defineComponent, createLibrary } from '@openuidev/react-lang';
-import { z } from 'zod';
-
-const Card = defineComponent({
- name: 'Card',
- description: 'Displays a titled content card.',
- props: z.object({
- title: z.string(),
- }),
- component: ({ props }) => <div>{props.title}</div>,
-});
-
-export const library = createLibrary({
- components: [Card, ...otherComponents],
-});
-
-export const systemPrompt = library.prompt(); // Generated system prompt
-`,
- },
- {
- title: "LLM Generates OpenUI Syntax",
- description: "LLM outputs token-efficient, line-oriented syntax",
- code: `root = Stack([welcomeCard])
-welcomeCard = Card([welcomeHeader, welcomeBody], "card")
-welcomeHeader = CardHeader("Welcome", "Get started with our platform")
-welcomeBody = Stack([signupForm], "column", "m")
-signupForm = Form("signup", [nameField, emailField], actions)
-nameField = FormControl("Name", Input("name", "Your name", "text", ["required", "minLength:2"]))
-emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))
-actions = Buttons([signUpBtn, learnMoreBtn], "row")
-signUpBtn = Button("Sign up", "submit:signup", "primary")
-learnMoreBtn = Button("Learn more", "action:learn_more", "secondary")
-`,
- },
-];
-
-export default function OpenUILangOverview() {
- const [activeStep, setActiveStep] = useState(0);
-
- return (
- <div className="mx-auto max-w-4xl px-3 py-8 font-sans text-slate-900 sm:px-4 sm:py-12 lg:px-8 dark:text-slate-100">
- {/* Introduction */}
- <div className="mb-12 sm:mb-20">
- <div className="mb-4 flex items-start gap-3 sm:mb-6 sm:gap-4">
- <div>
- <h1 className="mb-1 text-3xl font-bold sm:mb-2 sm:text-4xl">OpenUI Lang</h1>
- <p className="text-sm text-slate-500 sm:text-base dark:text-slate-400">
- A line-oriented language designed for streaming, token efficiency, and type safety
- </p>
- </div>
- </div>
-
- <p className="mb-6 text-sm text-slate-600 sm:mb-8 sm:text-base dark:text-slate-400">
- An alternative to{" "}
- <Link
- href="https://json-render.dev"
- target="_blank"
- rel="noopener noreferrer"
- className="underline hover:no-underline"
- >
- Vercel JSON renderer
- </Link>{" "}
- and{" "}
- <Link
- href="https://a2ui.org/"
- target="_blank"
- rel="noopener noreferrer"
- className=" underline hover:no-underline"
- >
- A2UI
- </Link>{" "}
- that uses up to 67.1% fewer tokens than equivalent JSON structures. Define your component library
- with Zod schemas and parse LLM responses into renderable components.
- </p>
-
- <div className="flex flex-col gap-3 sm:flex-row">
- <Button
- href="/docs/openui-lang/quickstart"
- text="Build with OpenUI Library"
- variant="primary"
- />
- <Button
- href="/docs/openui-lang/defining-components"
- text="Define Component Library"
- variant="secondary"
- />
- </div>
- </div>
-
- <Separator className="my-8 sm:my-16" />
-
- {/* Key Features */}
- <div className="mb-12 sm:mb-20">
- <h2 className="mb-6 text-2xl font-bold sm:mb-8 sm:text-3xl">Key Features</h2>
-
- <FeatureCards>
- <FeatureCard
- icon={<Waves />}
- title="Streaming Native"
- description="Line-oriented syntax means the UI renders line-by-line. No waiting for valid JSON closing braces."
- />
- <FeatureCard
- icon={<Zap />}
- title="Token Efficient"
- description="Uses up to 67.1% fewer tokens than equivalent JSON structures, significantly reducing inference cost and latency."
- />
- <FeatureCard
- icon={<Shield />}
- title="Hallucination Resistant"
- description="Strictly typed against your Zod schemas. If the generated code does not match your definition, it does not render."
- />
- </FeatureCards>
- </div>
-
- <Separator className="my-8 sm:my-16" />
-
- {/* Comparison */}
- <div className="mb-12 sm:mb-20">
- <h2 className="mb-3 text-2xl font-bold sm:mb-4 sm:text-3xl">JSON vs OpenUI Lang</h2>
- <p className="mb-6 text-sm text-slate-600 sm:mb-8 sm:text-base dark:text-slate-400">
- Compare the same UI component in both formats
- </p>
-
- <div className="mb-6 grid gap-4 lg:grid-cols-2">
- <div>
- <div className="mb-3 flex items-center justify-between">
- <h3 className="text-base font-semibold sm:text-lg">JSON Format</h3>
- <span className="rounded-full bg-red-50 px-3 py-1 text-xs font-semibold text-red-600 dark:bg-red-900/20 dark:text-red-400">
- ~849 tokens
- </span>
- </div>
- <CodeBlock
- codeBlockClassName="h-100 overflow-y-auto"
- code={`{
- "component": {
- "component": "Stack",
- "props": {
- "children": [
- {
- "component": "TextContent",
- "props": {
- "text": "Contact Us",
- "size": "large-heavy"
- }
- },
- {
- "component": "Form",
- "props": {
- "name": "contact",
- "fields": [
- {
- "component": "FormControl",
- "props": {
- "label": "Name",
- "input": {
- "component": "Input",
- "props": {
- "name": "name",
- "placeholder": "Your full name",
- "type": "text",
- "rules": [
- "required",
- "minLength:2"
- ]
- }
- }
- }
- },
- {
- "component": "FormControl",
- "props": {
- "label": "Email",
- "input": {
- "component": "Input",
- "props": {
- "name": "email",
- "placeholder": "[email protected]",
- "type": "email",
- "rules": [
- "required",
- "email"
- ]
- }
- }
- }
- },
- {
- "component": "FormControl",
- "props": {
- "label": "Phone",
- "input": {
- "component": "Input",
- "props": {
- "name": "phone",
- "placeholder": "e.g., +1 555 123 4567",
- "type": "text",
- "rules": [
- "required",
- "minLength:7",
- "maxLength:20"
- ]
- }
- }
- }
- },
- {
- "component": "FormControl",
- "props": {
- "label": "Subject",
- "input": {
- "component": "Select",
- "props": {
- "name": "subject",
- "items": [
- {
- "component": "SelectItem",
- "props": {
- "value": "general",
- "label": "General inquiry"
- }
- },
- {
- "component": "SelectItem",
- "props": {
- "value": "support",
- "label": "Support"
- }
- },
- {
- "component": "SelectItem",
- "props": {
- "value": "sales",
- "label": "Sales"
- }
- },
- {
- "component": "SelectItem",
- "props": {
- "value": "billing",
- "label": "Billing"
- }
- },
- {
- "component": "SelectItem",
- "props": {
- "value": "feedback",
- "label": "Feedback"
- }
- }
- ],
- "placeholder": "Select a subject...",
- "rules": [
- "required"
- ]
- }
- }
- }
- },
- {
- "component": "FormControl",
- "props": {
- "label": "Message",
- "input": {
- "component": "TextArea",
- "props": {
- "name": "message",
- "placeholder": "How can we help?",
- "rows": 6,
- "rules": [
- "required",
- "minLength:10"
- ]
- }
- }
- }
- }
- ],
- "buttons": {
- "component": "Buttons",
- "props": {
- "buttons": [
- {
- "component": "Button",
- "props": {
- "label": "Submit",
- "action": "submit:contact",
- "variant": "primary"
- }
- },
- {
- "component": "Button",
- "props": {
- "label": "Cancel",
- "action": "action:cancel_contact",
- "variant": "secondary"
- }
- }
- ],
- "direction": "row"
- }
- }
- }
- }
- ],
- "direction": "column",
- "gap": "l"
- }
- },
- "error": null
-}`}
- />
- </div>
-
- <div>
- <div className="mb-3 flex items-center justify-between">
- <h3 className="text-base font-semibold sm:text-lg">OpenUI Lang</h3>
- <span className="rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-600 dark:bg-emerald-900/20 dark:text-emerald-400">
- ~294 tokens
- </span>
- </div>
- <CodeBlock
- codeBlockClassName="h-100 overflow-y-auto"
- code={`root = Stack([title, form], "column", "l")
-title = TextContent("Contact Us", "large-heavy")
-form = Form("contact", [nameField, emailField, phoneField, subjectField, messageField], formButtons)
-nameField = FormControl("Name", Input("name", "Your full name", "text", ["required", "minLength:2"]))
-emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))
-phoneField = FormControl("Phone", Input("phone", "e.g., +1 555 123 4567", "text", ["required", "minLength:7", "maxLength:20"]))
-subjectField = FormControl("Subject", Select("subject", subjectOptions, "Select a subject...", ["required"]))
-messageField = FormControl("Message", TextArea("message", "How can we help?", 6, ["required", "minLength:10"]))
-subjectOptions = [SelectItem("general", "General inquiry"), SelectItem("support", "Support"), SelectItem("sales", "Sales"), SelectItem("billing", "Billing"), SelectItem("feedback", "Feedback")]
-formButtons = Buttons([submitBtn, cancelBtn], "row")
-submitBtn = Button("Submit", "submit:contact", "primary")
-cancelBtn = Button("Cancel", "action:cancel_contact", "secondary")`}
- />
- </div>
- </div>
- </div>
-
- <Separator className="my-8 sm:my-16" />
-
- {/* How It Works */}
- <div className="mb-12 sm:mb-20">
- <h2 className="mb-3 text-2xl font-bold sm:mb-4 sm:text-3xl">How It Works</h2>
- <p className="mb-6 text-sm text-slate-600 sm:mb-8 sm:text-base dark:text-slate-400">
- Click through each step to see the complete workflow
- </p>
-
- <div className="mb-6 flex flex-wrap gap-2">
- {steps.map((step, index) => (
- <button
- key={index}
- onClick={() => setActiveStep(index)}
- className={`rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
- activeStep === index
- ? "bg-slate-900 text-white dark:bg-white dark:text-slate-900"
- : "bg-slate-100 text-slate-500 hover:bg-slate-200 hover:text-slate-700 dark:bg-slate-800 dark:text-slate-400 dark:hover:bg-slate-700 dark:hover:text-slate-200"
- }`}
- >
- {index + 1}. {step.title}
- </button>
- ))}
- </div>
-
- <SimpleCard className="p-4 sm:p-6">
- <div className="mb-4">
- <div className="mb-2 flex items-center gap-3">
- <div className="flex size-8 items-center justify-center rounded-lg bg-fd-muted dark:bg-fd-muted">
- <span className="text-sm font-semibold text-fd-foreground">{activeStep + 1}</span>
- </div>
- <div>
- <h3 className="text-base font-semibold sm:text-lg">{steps[activeStep].title}</h3>
- <p className="text-xs text-slate-500 sm:text-sm dark:text-slate-400">
- {steps[activeStep].description}
- </p>
- </div>
- </div>
- </div>
-
- <CodeBlock code={steps[activeStep].code} />
-
- <div className="mt-4 flex justify-between">
- <InlineButton
- variant="outline"
- onClick={() => setActiveStep(Math.max(0, activeStep - 1))}
- disabled={activeStep === 0}
- >
- Previous
- </InlineButton>
- <InlineButton
- onClick={() => setActiveStep(Math.min(steps.length - 1, activeStep + 1))}
- disabled={activeStep === steps.length - 1}
- >
- Next Step <ArrowRight className="ml-2 size-3" />
- </InlineButton>
- </div>
- </SimpleCard>
- </div>
-
- <Separator className="my-8 sm:my-16" />
-
- {/* Use Cases */}
- <div className="mb-12 sm:mb-20">
- <h2 className="mb-3 text-2xl font-bold sm:mb-4 sm:text-3xl">Use Cases</h2>
- <p className="mb-6 text-sm text-slate-600 sm:mb-8 sm:text-base dark:text-slate-400">
- Real-world applications where OpenUI Lang excels
- </p>
-
- <FeatureCards>
- <FeatureCard
- icon={<BarChart3 />}
- title="Analytics Dashboards"
- description="Generate complex data visualizations and metric cards from natural language queries."
- />
- <FeatureCard
- icon={<MessageSquare />}
- title="AI Chat Interfaces"
- description="Stream UI components in real-time as the LLM generates responses."
- />
- <FeatureCard
- icon={<FileText />}
- title="Dynamic Forms"
- description="Build adaptive forms that change based on user input or context."
- />
- </FeatureCards>
- </div>
- </div>
- );
-}
diff --git a/docs/app/docs/openui-lang/streaming-comparison.tsx b/docs/app/docs/openui-lang/streaming-comparison.tsx
new file mode 100644
index 000000000..e4249be23
--- /dev/null
+++ b/docs/app/docs/openui-lang/streaming-comparison.tsx
@@ -0,0 +1,417 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { RotateCcw, Check } from "lucide-react";
+
+const JSON_CODE = `{
+ "component": {
+ "component": "Stack",
+ "props": {
+ "children": [
+ {
+ "component": "TextContent",
+ "props": {
+ "text": "Contact Us",
+ "size": "large-heavy"
+ }
+ },
+ {
+ "component": "Form",
+ "props": {
+ "name": "contact",
+ "fields": [
+ {
+ "component": "FormControl",
+ "props": {
+ "label": "Name",
+ "input": {
+ "component": "Input",
+ "props": {
+ "name": "name",
+ "placeholder": "Your full name",
+ "type": "text",
+ "rules": [
+ "required",
+ "minLength:2"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "component": "FormControl",
+ "props": {
+ "label": "Email",
+ "input": {
+ "component": "Input",
+ "props": {
+ "name": "email",
+ "placeholder": "[email protected]",
+ "type": "email",
+ "rules": [
+ "required",
+ "email"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "component": "FormControl",
+ "props": {
+ "label": "Phone",
+ "input": {
+ "component": "Input",
+ "props": {
+ "name": "phone",
+ "placeholder": "e.g., +1 555 123 4567",
+ "type": "text",
+ "rules": [
+ "required",
+ "minLength:7",
+ "maxLength:20"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "component": "FormControl",
+ "props": {
+ "label": "Subject",
+ "input": {
+ "component": "Select",
+ "props": {
+ "name": "subject",
+ "items": [
+ {
+ "component": "SelectItem",
+ "props": {
+ "value": "general",
+ "label": "General inquiry"
+ }
+ },
+ {
+ "component": "SelectItem",
+ "props": {
+ "value": "support",
+ "label": "Support"
+ }
+ },
+ {
+ "component": "SelectItem",
+ "props": {
+ "value": "sales",
+ "label": "Sales"
+ }
+ },
+ {
+ "component": "SelectItem",
+ "props": {
+ "value": "billing",
+ "label": "Billing"
+ }
+ },
+ {
+ "component": "SelectItem",
+ "props": {
+ "value": "feedback",
+ "label": "Feedback"
+ }
+ }
+ ],
+ "placeholder": "Select a subject...",
+ "rules": [
+ "required"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "component": "FormControl",
+ "props": {
+ "label": "Message",
+ "input": {
+ "component": "TextArea",
+ "props": {
+ "name": "message",
+ "placeholder": "How can we help?",
+ "rows": 6,
+ "rules": [
+ "required",
+ "minLength:10"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "buttons": {
+ "component": "Buttons",
+ "props": {
+ "buttons": [
+ {
+ "component": "Button",
+ "props": {
+ "label": "Submit",
+ "action": "submit:contact",
+ "variant": "primary"
+ }
+ },
+ {
+ "component": "Button",
+ "props": {
+ "label": "Cancel",
+ "action": "action:cancel_contact",
+ "variant": "secondary"
+ }
+ }
+ ],
+ "direction": "row"
+ }
+ }
+ }
+ }
+ ],
+ "direction": "column",
+ "gap": "l"
+ }
+ },
+ "error": null
+}`;
+
+const OPENUI_CODE = `root = Stack([title, form], "column", "l")
+title = TextContent("Contact Us", "large-heavy")
+form = Form("contact", [nameField, emailField, phoneField, subjectField, messageField], formButtons)
+nameField = FormControl("Name", Input("name", "Your full name", "text", ["required", "minLength:2"]))
+emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))
+phoneField = FormControl("Phone", Input("phone", "e.g., +1 555 123 4567", "text", ["required", "minLength:7", "maxLength:20"]))
+subjectField = FormControl("Subject", Select("subject", subjectOptions, "Select a subject...", ["required"]))
+messageField = FormControl("Message", TextArea("message", "How can we help?", 6, ["required", "minLength:10"]))
+subjectOptions = [SelectItem("general", "General inquiry"), SelectItem("support", "Support"), SelectItem("sales", "Sales"), SelectItem("billing", "Billing"), SelectItem("feedback", "Feedback")]
+formButtons = Buttons([submitBtn, cancelBtn], "row")
+submitBtn = Button("Submit", "submit:contact", "primary")
+cancelBtn = Button("Cancel", "action:cancel_contact", "secondary")`;
+
+// Calculated using openai tokenizer, https://platform.openai.com/tokenizer
+const JSON_TOKENS = 849;
+const OPENUI_TOKENS = 294;
+const TOKEN_RATE = 60; // tokens per second
+
+const JSON_DURATION = JSON_TOKENS / TOKEN_RATE; // ~5.7s
+const OPENUI_DURATION = OPENUI_TOKENS / TOKEN_RATE; // ~2.0s
+
+type StreamState = "idle" | "streaming" | "done";
+
+function StreamingCodeBlock({
+ code,
+ charCount,
+ totalTokens,
+ currentTokens,
+ elapsed,
+ totalDuration,
+ state,
+ label,
+ variant,
+}: {
+ code: string;
+ charCount: number;
+ totalTokens: number;
+ currentTokens: number;
+ elapsed: number;
+ totalDuration: number;
+ state: StreamState;
+ label: string;
+ variant: "red" | "green";
+}) {
+ const preRef = useRef<HTMLPreElement>(null);
+ const displayedCode = code.slice(0, charCount);
+ const isDone = state === "done";
+
+ useEffect(() => {
+ if (preRef.current && state === "streaming") {
+ preRef.current.scrollTop = preRef.current.scrollHeight;
+ }
+ }, [charCount, state]);
+
+ const pillBg = variant === "red"
+ ? "bg-red-50 text-red-600 dark:bg-red-900/20 dark:text-red-400"
+ : "bg-emerald-50 text-emerald-600 dark:bg-emerald-900/20 dark:text-emerald-400";
+
+ const doneBg = variant === "red"
+ ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300"
+ : "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300";
+
+ return (
+ <div>
+ <div className="mb-3 flex items-center justify-between">
+ <h3 className="text-base font-semibold sm:text-lg">{label}</h3>
+ <div className="flex items-center gap-2">
+ <span className={`rounded-full px-3 py-1 text-xs font-semibold ${isDone ? doneBg : pillBg}`}>
+ {state === "streaming"
+ ? `${currentTokens}/${totalTokens} tokens`
+ : `${totalTokens} tokens`}
+ </span>
+ {state === "streaming" && (
+ <span className="font-mono text-xs tabular-nums text-slate-500 dark:text-slate-400">
+ {elapsed.toFixed(1)}s
+ </span>
+ )}
+ {isDone && (
+ <span className="flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-1 text-xs font-semibold text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300">
+ <Check size={12} /> {totalDuration.toFixed(1)}s
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="overflow-hidden rounded-lg border border-slate-200 dark:border-[--color-doc-border]">
+ <pre
+ ref={preRef}
+ className="h-100 overflow-y-auto bg-[--color-doc-code-bg] p-4 text-sm leading-relaxed text-slate-700 dark:text-slate-300"
+ >
+ <code className="border-0! bg-transparent!">
+ {displayedCode}
+ {state === "streaming" && (
+ <span className="inline-block h-4 w-0.5 animate-pulse bg-slate-500 align-text-bottom dark:bg-slate-400" />
+ )}
+ </code>
+ </pre>
+ </div>
+ </div>
+ );
+}
+
+export function StreamingComparison() {
+ const [state, setState] = useState<StreamState>("idle");
+ const [jsonChars, setJsonChars] = useState(0);
+ const [openuiChars, setOpenuiChars] = useState(0);
+ const [jsonTokens, setJsonTokens] = useState(0);
+ const [openuiTokens, setOpenuiTokens] = useState(0);
+ const [elapsed, setElapsed] = useState(0);
+ const [jsonDone, setJsonDone] = useState(false);
+ const [openuiDone, setOpenuiDone] = useState(false);
+ const rafRef = useRef<number>(0);
+ const startRef = useRef(0);
+ const sectionRef = useRef<HTMLDivElement>(null);
+ const hasAutoPlayed = useRef(false);
+
+ const reset = useCallback(() => {
+ cancelAnimationFrame(rafRef.current);
+ setState("idle");
+ setJsonChars(0);
+ setOpenuiChars(0);
+ setJsonTokens(0);
+ setOpenuiTokens(0);
+ setElapsed(0);
+ setJsonDone(false);
+ setOpenuiDone(false);
+ }, []);
+
+ const play = useCallback(() => {
+ reset();
+ setState("streaming");
+ startRef.current = performance.now();
+
+ const tick = (now: number) => {
+ const dt = (now - startRef.current) / 1000;
+ setElapsed(dt);
+
+ const jsonProgress = Math.min(1, dt / JSON_DURATION);
+ const openuiProgress = Math.min(1, dt / OPENUI_DURATION);
+
+ setJsonChars(Math.floor(jsonProgress * JSON_CODE.length));
+ setOpenuiChars(Math.floor(openuiProgress * OPENUI_CODE.length));
+ setJsonTokens(Math.floor(jsonProgress * JSON_TOKENS));
+ setOpenuiTokens(Math.floor(openuiProgress * OPENUI_TOKENS));
+
+ if (openuiProgress >= 1) setOpenuiDone(true);
+ if (jsonProgress >= 1) setJsonDone(true);
+
+ if (jsonProgress < 1) {
+ rafRef.current = requestAnimationFrame(tick);
+ } else {
+ setState("done");
+ }
+ };
+
+ rafRef.current = requestAnimationFrame(tick);
+ }, [reset]);
+
+ // Auto-play when section scrolls into view
+ useEffect(() => {
+ const el = sectionRef.current;
+ if (!el) return;
+
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting && !hasAutoPlayed.current) {
+ hasAutoPlayed.current = true;
+ play();
+ }
+ },
+ { threshold: 0.3 },
+ );
+
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [play]);
+
+ useEffect(() => {
+ return () => cancelAnimationFrame(rafRef.current);
+ }, []);
+
+ return (
+ <div ref={sectionRef} className="mb-12 sm:mb-20">
+ <p className="mb-6 text-sm text-slate-600 sm:mb-8 sm:text-base dark:text-slate-400">
+ Same UI component, both streaming at {TOKEN_RATE} tokens/sec. OpenUI Lang finishes in{" "}
+ <strong>{OPENUI_DURATION.toFixed(1)}s</strong> vs JSON&apos;s{" "}
+ <strong>{JSON_DURATION.toFixed(1)}s</strong> &mdash;{" "}
+ <strong>{Math.round((1 - OPENUI_TOKENS / JSON_TOKENS) * 100)}% fewer tokens</strong>.
+ </p>
+
+ <div className="mb-6 grid gap-4 lg:grid-cols-2">
+ <StreamingCodeBlock
+ code={JSON_CODE}
+ charCount={jsonChars}
+ totalTokens={JSON_TOKENS}
+ currentTokens={jsonTokens}
+ elapsed={elapsed}
+ totalDuration={JSON_DURATION}
+ state={jsonDone ? "done" : state}
+ label="JSON Format"
+ variant="red"
+ />
+ <StreamingCodeBlock
+ code={OPENUI_CODE}
+ charCount={openuiChars}
+ totalTokens={OPENUI_TOKENS}
+ currentTokens={openuiTokens}
+ elapsed={openuiDone ? OPENUI_DURATION : elapsed}
+ totalDuration={OPENUI_DURATION}
+ state={openuiDone ? "done" : state}
+ label="OpenUI Lang"
+ variant="green"
+ />
+ </div>
+
+ {state === "done" && (
+ <div className="flex items-center justify-between rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 dark:border-emerald-800 dark:bg-emerald-900/20">
+ <p className="text-sm font-medium text-emerald-800 dark:text-emerald-200">
+ OpenUI Lang completed in <strong>{OPENUI_DURATION.toFixed(1)}s</strong> vs JSON&apos;s{" "}
+ <strong>{JSON_DURATION.toFixed(1)}s</strong> &mdash;{" "}
+ <strong>{(JSON_DURATION / OPENUI_DURATION).toFixed(1)}x faster</strong> with{" "}
+ <strong>{JSON_TOKENS - OPENUI_TOKENS} fewer tokens</strong>.
+ </p>
+ <button
+ onClick={() => { hasAutoPlayed.current = true; play(); }}
+ className="ml-3 flex shrink-0 items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-100 dark:text-emerald-300 dark:hover:bg-emerald-900/40"
+ title="Replay streaming demo"
+ >
+ <RotateCcw size={12} /> Replay
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/docs/components/docs-navbar.tsx b/docs/components/docs-navbar.tsx
index 61f41a8cf..2ac73f14b 100644
--- a/docs/components/docs-navbar.tsx
+++ b/docs/components/docs-navbar.tsx
@@ -11,7 +11,6 @@ import { OpenUILogo, ThesysLogo } from "./brand-logo";
import { ThemeToggle } from "./theme-toggle";
const tabs = [
- { title: "Introduction", url: "/docs/introduction" },
{ title: "OpenUI Lang", url: "/docs/openui-lang" },
{ title: "Chat", url: "/docs/chat" },
{ title: "API Reference", url: "/docs/api-reference" },
@@ -77,7 +76,7 @@ export function DocsNavbar({ showSidebarToggle = false }: { showSidebarToggle?:
return (
<header className="fixed top-0 inset-x-0 z-40 w-full border-b border-fd-border bg-fd-background/80 backdrop-blur-xl">
{/* Top row: logo left, actions right */}
- <div className="flex items-center h-16 max-w-[97rem] mx-auto px-3 md:px-8">
+ <div className="flex items-center h-16 max-w-388 mx-auto px-3 md:px-8">
{showSidebarToggle && (
<SidebarTrigger className="docs-nav-sidebar-toggle flex items-center justify-center size-9 rounded-lg text-fd-muted-foreground bg-transparent border-none cursor-pointer mr-3">
<svg
@@ -151,11 +150,10 @@ export function DocsNavbar({ showSidebarToggle = false }: { showSidebarToggle?:
<Link
key={tab.url}
href={tab.url}
- className={`flex items-center px-4 py-2.5 text-sm font-medium whitespace-nowrap no-underline transition-colors duration-150 border-b-2 -mb-px ${
- isActive
+ className={`flex items-center px-4 py-2.5 text-sm font-medium whitespace-nowrap no-underline transition-colors duration-150 border-b-2 -mb-px ${isActive
? "text-fd-foreground border-fd-primary"
: "text-fd-muted-foreground border-transparent hover:text-fd-foreground"
- }`}
+ }`}
>
{tab.title}
</Link>
diff --git a/docs/components/docs-route-layout.tsx b/docs/components/docs-route-layout.tsx
index d74316766..c77e22740 100644
--- a/docs/components/docs-route-layout.tsx
+++ b/docs/components/docs-route-layout.tsx
@@ -4,7 +4,6 @@ import { DocsNavbar } from "@/components/docs-navbar";
import { baseOptions, siteConfig } from "@/lib/layout.shared";
import { DocsLayout } from "fumadocs-ui/layouts/docs";
import Link from "next/link";
-import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
function SidebarBannerLink({
@@ -39,18 +38,14 @@ type DocsRouteLayoutProps = {
};
export function DocsRouteLayout({ tree, children }: DocsRouteLayoutProps) {
- const pathname = usePathname();
- const isIntroductionRoute =
- pathname === "/docs/introduction" || pathname.startsWith("/docs/introduction/");
-
return (
<DocsLayout
tree={tree}
{...baseOptions()}
- nav={{ component: <DocsNavbar showSidebarToggle={!isIntroductionRoute} /> }}
+ nav={{ component: <DocsNavbar showSidebarToggle /> }}
sidebar={{
tabs: false,
- enabled: !isIntroductionRoute,
+ enabled: true,
collapsible: false,
banner: (
<div className="flex flex-col mb-2">
diff --git a/docs/components/overview-components/chat-modal.css b/docs/components/overview-components/chat-modal.css
new file mode 100644
index 000000000..c8f3df9e2
--- /dev/null
+++ b/docs/components/overview-components/chat-modal.css
@@ -0,0 +1,91 @@
+.chat-modal-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 200;
+ background: rgba(0, 0, 0, 0.5);
+ backdrop-filter: blur(4px);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px;
+ animation: chat-modal-overlay-in 0.15s ease;
+}
+
+@keyframes chat-modal-overlay-in {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
+.chat-modal-container {
+ position: relative;
+ width: min(1400px, 95vw);
+ height: 90vh;
+ border-radius: 16px;
+ overflow: hidden;
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
+ animation: chat-modal-in 0.2s ease;
+}
+
+@keyframes chat-modal-in {
+ from { opacity: 0; transform: translateY(12px) scale(0.98); }
+ to { opacity: 1; transform: translateY(0) scale(1); }
+}
+
+.chat-modal-close {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ z-index: 210;
+ background: rgba(128, 128, 128, 0.2);
+ backdrop-filter: blur(8px);
+ border: none;
+ border-radius: 50%;
+ width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ color: inherit;
+ transition: background 0.15s;
+}
+
+.chat-modal-close:hover {
+ background: rgba(128, 128, 128, 0.4);
+}
+
+.chat-modal-body {
+ width: 100%;
+ height: 100%;
+}
+
+/* Override Shell container sizing to fit within the modal */
+.chat-modal-body .openui-shell-container {
+ height: 100% !important;
+ width: 100% !important;
+}
+
+/* Hide the sidebar in the modal */
+.chat-modal-body .openui-shell-sidebar-container {
+ display: none !important;
+}
+
+/* ─── Mobile ─────────────────────────────────────────────────────────────────── */
+@media (max-width: 768px) {
+ .chat-modal-overlay {
+ padding: 0;
+ align-items: flex-end;
+ }
+
+ .chat-modal-container {
+ width: 100vw;
+ height: 95dvh;
+ border-radius: 16px 16px 0 0;
+ animation: chat-modal-mobile-in 0.35s cubic-bezier(0.22, 1, 0.36, 1);
+ }
+}
+
+@keyframes chat-modal-mobile-in {
+ from { transform: translateY(100%); }
+ to { transform: translateY(0); }
+}
diff --git a/docs/components/overview-components/chat-modal.tsx b/docs/components/overview-components/chat-modal.tsx
new file mode 100644
index 000000000..a6003a8d5
--- /dev/null
+++ b/docs/components/overview-components/chat-modal.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import "@openuidev/react-ui/components.css";
+import "./chat-modal.css";
+
+import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
+import { FullScreen } from "@openuidev/react-ui";
+import { openuiChatLibrary, openuiChatPromptOptions } from "@openuidev/react-ui/genui-lib";
+import { X } from "lucide-react";
+import { useTheme } from "next-themes";
+import { useCallback, useEffect } from "react";
+import { createPortal } from "react-dom";
+
+const systemPrompt = openuiChatLibrary.prompt(openuiChatPromptOptions);
+
+interface ChatModalProps {
+ onClose: () => void;
+}
+
+export function ChatModal({ onClose }: ChatModalProps) {
+ const { resolvedTheme } = useTheme();
+
+ const handleKey = useCallback(
+ (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose();
+ },
+ [onClose],
+ );
+
+ useEffect(() => {
+ document.addEventListener("keydown", handleKey);
+ document.body.style.overflow = "hidden";
+ return () => {
+ document.removeEventListener("keydown", handleKey);
+ document.body.style.overflow = "";
+ };
+ }, [handleKey]);
+
+ return createPortal(
+ <div className="chat-modal-overlay" onClick={onClose}>
+ <div className="chat-modal-container" onClick={(e) => e.stopPropagation()}>
+ <button className="chat-modal-close" onClick={onClose} aria-label="Close chat">
+ <X size={20} />
+ </button>
+ <div className="chat-modal-body">
+ <FullScreen
+ welcomeMessage={{ title: "Hello, how can I help you today?" }}
+ processMessage={async ({ messages, abortController }) => {
+ return fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: openAIMessageFormat.toApi(messages),
+ systemPrompt,
+ }),
+ signal: abortController.signal,
+ });
+ }}
+ streamProtocol={openAIAdapter()}
+ componentLibrary={openuiChatLibrary}
+ agentName="OpenUI Chat"
+ theme={{ mode: (resolvedTheme as "light" | "dark") ?? "light" }}
+ conversationStarters={{
+ variant: "short",
+ options: [
+ { displayText: "Weather in Tokyo", prompt: "What's the weather like in Tokyo right now?" },
+ { displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
+ { displayText: "Contact form", prompt: "Build me a contact form with name, email, topic, and message fields." },
+ { displayText: "Data table", prompt: "Show me a table of the top 5 programming languages by popularity with year created." },
+ ],
+ }}
+ />
+ </div>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/docs/components/overview-components/code-block.tsx b/docs/components/overview-components/code-block.tsx
index f1f082a93..852a55b45 100644
--- a/docs/components/overview-components/code-block.tsx
+++ b/docs/components/overview-components/code-block.tsx
@@ -40,7 +40,7 @@ export function CodeBlock({
</div>
)}
<pre className={`grow-1 overflow-x-auto bg-[var(--color-doc-code-bg)] p-4 text-sm leading-relaxed text-slate-700 dark:text-slate-300 ${codeBlockClassName}`}>
- <code>{code}</code>
+ <code className="border-0! bg-transparent!">{code}</code>
</pre>
</div>
);
diff --git a/docs/components/overview-components/overview-page.tsx b/docs/components/overview-components/overview-page.tsx
index 5ff7e79af..713977178 100644
--- a/docs/components/overview-components/overview-page.tsx
+++ b/docs/components/overview-components/overview-page.tsx
@@ -12,10 +12,14 @@ import {
FeatureCard,
FeatureCards,
} from "@/components/overview-components";
-import { Code2, MessageSquare, Package } from "lucide-react";
+import { ArrowUpRight, Code2, MessageSquare, Package } from "lucide-react";
+import { useState } from "react";
+import { ChatModal } from "./chat-modal";
import { genuiOutput } from "./genui";
export function OverviewPage() {
+ const [isChatModalOpen, setIsChatModalOpen] = useState(false);
+
return (
<div className="mx-auto max-w-4xl px-3 py-8 font-sans text-slate-900 sm:px-4 sm:py-12 lg:px-8 dark:text-slate-100">
{/* Introduction */}
@@ -217,6 +221,35 @@ export function AssistantMessage({ content, isStreaming }) {
/>
</FeatureCards>
+ {/* Interactive Demo */}
+ <div
+ className="group mb-6 cursor-pointer overflow-hidden rounded-xl border-2 border-slate-200 transition-all hover:border-blue-400 hover:shadow-lg dark:border-slate-700 dark:hover:border-blue-500"
+ onClick={() => setIsChatModalOpen(true)}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => e.key === "Enter" && setIsChatModalOpen(true)}
+ >
+ <div className="relative">
+ <img
+ src="/images/openui-lang/compare.png"
+ alt="OpenUI Chat Demo - Click to try it live"
+ className="w-full"
+ />
+ <div className="absolute inset-0 bg-black/0 transition-all group-hover:bg-black/5" />
+ </div>
+ <div className="flex items-start justify-between border-t border-slate-200 px-5 py-4 dark:border-slate-700">
+ <div>
+ <h3 className="text-lg font-semibold">Try it out live</h3>
+ <p className="text-sm text-slate-500 dark:text-slate-400">
+ Live interactive demo of OpenUI Chat in action
+ </p>
+ </div>
+ <ArrowUpRight className="mt-1 size-5 shrink-0 text-slate-400 transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5 dark:text-slate-500" />
+ </div>
+ </div>
+
+ {isChatModalOpen && <ChatModal onClose={() => setIsChatModalOpen(false)} />}
+
<div className="mb-6">
<CodeBlock
title="Quick example"
diff --git a/docs/content/docs/introduction/index.mdx b/docs/content/docs/introduction/index.mdx
deleted file mode 100644
index 93e7f556b..000000000
--- a/docs/content/docs/introduction/index.mdx
+++ /dev/null
@@ -1,4 +0,0 @@
----
-title: Introduction
-description: OpenUI is a comprehensive toolkit for building LLM-powered user interfaces.
----
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json
index 52ad1d81d..ddc80b45a 100644
--- a/docs/content/docs/meta.json
+++ b/docs/content/docs/meta.json
@@ -1,4 +1,4 @@
{
"title": "OpenUI",
- "pages": ["introduction", "openui-lang", "components", "chat", "api-reference"]
+ "pages": ["openui-lang", "components", "chat", "api-reference"]
}
diff --git a/docs/content/docs/openui-lang/components/how-it-works.tsx b/docs/content/docs/openui-lang/components/how-it-works.tsx
new file mode 100644
index 000000000..9a689698b
--- /dev/null
+++ b/docs/content/docs/openui-lang/components/how-it-works.tsx
@@ -0,0 +1,107 @@
+"use client";
+import { SimpleCard } from "@/components/overview-components/simple-card";
+import { useState } from "react";
+import { CodeBlock } from "@/components/overview-components/code-block";
+import { InlineButton } from "@/components/overview-components/inline-button";
+import { ArrowRight } from "lucide-react";
+
+const steps = [
+ {
+ title: "Define Library",
+ description: "Create your component library with Zod schemas and generate the system prompt",
+ code: `import { defineComponent, createLibrary } from '@openuidev/react-lang';
+import { z } from 'zod';
+
+const Card = defineComponent({
+ name: 'Card',
+ description: 'Displays a titled content card.',
+ props: z.object({
+ title: z.string(),
+ }),
+ component: ({ props }) => <div>{props.title}</div>,
+});
+
+export const library = createLibrary({
+ components: [Card, ...otherComponents],
+});
+
+export const systemPrompt = library.prompt(); // Generated system prompt
+`,
+ },
+ {
+ title: "LLM Generates OpenUI Syntax",
+ description: "LLM outputs token-efficient, line-oriented syntax",
+ code: `root = Stack([welcomeCard])
+welcomeCard = Card([welcomeHeader, welcomeBody], "card")
+welcomeHeader = CardHeader("Welcome", "Get started with our platform")
+welcomeBody = Stack([signupForm], "column", "m")
+signupForm = Form("signup", [nameField, emailField], actions)
+nameField = FormControl("Name", Input("name", "Your name", "text", ["required", "minLength:2"]))
+emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))
+actions = Buttons([signUpBtn, learnMoreBtn], "row")
+signUpBtn = Button("Sign up", "submit:signup", "primary")
+learnMoreBtn = Button("Learn more", "action:learn_more", "secondary")
+`,
+ },
+];
+
+
+export const HowItWorks = () => {
+ const [activeStep, setActiveStep] = useState(0);
+ return (
+ <div className="mb-12 sm:mb-20">
+ <p className="mb-6 text-sm text-slate-600 sm:mb-8 sm:text-base dark:text-slate-400">
+ Click through each step to see the complete workflow
+ </p>
+
+ <div className="mb-6 flex flex-wrap gap-2">
+ {steps.map((step, index) => (
+ <button
+ key={index}
+ onClick={() => setActiveStep(index)}
+ className={`rounded-lg px-3 py-2 text-sm font-medium transition-colors ${activeStep === index
+ ? "bg-slate-900 text-white dark:bg-white dark:text-slate-900"
+ : "bg-slate-100 text-slate-500 hover:bg-slate-200 hover:text-slate-700 dark:bg-slate-800 dark:text-slate-400 dark:hover:bg-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ {index + 1}. {step.title}
+ </button>
+ ))}
+ </div>
+
+ <SimpleCard className="p-4 sm:p-6">
+ <div className="mb-4">
+ <div className="mb-2 flex items-center gap-3">
+ <div className="flex size-8 items-center justify-center rounded-lg bg-fd-muted dark:bg-fd-muted">
+ <span className="text-sm font-semibold text-fd-foreground">{activeStep + 1}</span>
+ </div>
+ <div>
+ <h3 className="text-base font-semibold sm:text-lg">{steps[activeStep].title}</h3>
+ <p className="text-xs text-slate-500 sm:text-sm dark:text-slate-400">
+ {steps[activeStep].description}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <CodeBlock code={steps[activeStep].code} />
+
+ <div className="mt-4 flex justify-between">
+ <InlineButton
+ variant="outline"
+ onClick={() => setActiveStep(Math.max(0, activeStep - 1))}
+ disabled={activeStep === 0}
+ >
+ Previous
+ </InlineButton>
+ <InlineButton
+ onClick={() => setActiveStep(Math.min(steps.length - 1, activeStep + 1))}
+ disabled={activeStep === steps.length - 1}
+ >
+ Next Step <ArrowRight className="ml-2 size-3" />
+ </InlineButton>
+ </div>
+ </SimpleCard>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/docs/content/docs/openui-lang/components/lang-example.tsx b/docs/content/docs/openui-lang/components/lang-example.tsx
new file mode 100644
index 000000000..97c21a067
--- /dev/null
+++ b/docs/content/docs/openui-lang/components/lang-example.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+import {
+ CodeBlock,
+ SimpleCard,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/components/overview-components";
+import { genuiOutput } from "@/components/overview-components/genui";
+import { openuiLibrary } from "@openuidev/react-ui";
+import { Renderer } from "@openuidev/react-lang";
+
+const renderableOutput = `root = Stack([welcomeCard])
+welcomeCard = Card([welcomeHeader, welcomeBody])
+welcomeHeader = CardHeader("Welcome", "Get started with our platform")
+welcomeBody = Stack([signupForm], "column", "m")
+signupForm = Form("signup", actions, [nameField, emailField])
+nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))
+emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))
+actions = Buttons([signUpBtn, learnMoreBtn], "row")
+signUpBtn = Button("Sign up", { type: "continue_conversation", context: "signup" }, "primary")
+learnMoreBtn = Button("Learn more", { type: "continue_conversation", context: "learn_more" }, "secondary")
+`;
+
+export const LangExample = () => {
+ return (
+ <div className="grid gap-4 lg:grid-cols-2">
+ {/* Left: Code Tabs */}
+ <Tabs defaultValue="llm-output" className="flex w-full flex-col">
+ <TabsList className="grid w-full grid-cols-2 text-xs sm:text-sm">
+ <TabsTrigger value="define-library" className="px-1 sm:px-2">
+ Define Lib
+ </TabsTrigger>
+ <TabsTrigger value="render-code" className="px-1 sm:px-2">
+ Render Code
+ </TabsTrigger>
+ <TabsTrigger value="system-prompt" className="px-1 sm:px-2">
+ System Prompt
+ </TabsTrigger>
+ <TabsTrigger value="llm-output" className="px-1 sm:px-2">
+ LLM Output
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="define-library" className="mt-3 flex-1">
+ <CodeBlock
+ className="h-full"
+ title="Component Library Definition"
+ code={`import { defineComponent, createLibrary } from '@openuidev/react-lang';
+import { z } from 'zod';
+
+const MyCard = defineComponent({
+ name: 'MyCard',
+ description: 'Display a card with multiple children',
+ props: z.object({
+ children: z.array(z.any()),
+ }),
+ component: ({ props, renderNode }) => <div>{renderNode(props.children)}</div>,
+ ...
+});
+
+export const myLibrary = createLibrary({
+ components: [MyCard, ...otherComponents],
+});`}
+ />
+ </TabsContent>
+
+ <TabsContent value="render-code" className="mt-3 flex-1">
+ <CodeBlock
+ title="Rendering Code"
+ code={`import { Renderer } from '@openuidev/react-lang';
+import { myLibrary } from './library';
+
+// Inside your Chat Message component
+export function AssistantMessage({ content, isStreaming }) {
+ return (
+ <div className="prose dark:prose-invert max-w-none">
+ <Renderer
+ library={myLibrary}
+ response={content}
+ isStreaming={isStreaming}
+ />
+ </div>
+ );
+}`}
+ />
+ </TabsContent>
+ <TabsContent value="system-prompt" className="mt-3 flex-1">
+ <div className="mb-3 text-sm font-medium">Generate System Prompt with CLI</div>
+ <CodeBlock
+ title=""
+ code={`@openuidev/cli generate path/to/library.ts -o system-prompt.txt`}
+ />
+ <div className="my-3 text-sm font-medium">Send system prompt to the LLM</div>
+ <CodeBlock
+ title=""
+ code={`import fs from "fs";
+const openuiSystemPrompt = fs.readFileSync("system-prompt.txt", "utf8");
+const completion = await client.chat.completions.create({
+ model: "gpt-5.2",
+ stream: true,
+ messages: [{ role: "system", content: systemPrompt }, ...messages]
+})`}
+ />
+ </TabsContent>
+
+ <TabsContent value="llm-output" className="mt-3 flex-1">
+ <CodeBlock title="OpenUI Lang (Token Efficient)" code={genuiOutput} />
+ </TabsContent>
+ </Tabs>
+ <SimpleCard className="flex h-full flex-col border-2">
+ <div className="border-b border-slate-200 bg-slate-50 px-4 py-3 dark:border-slate-800 dark:bg-slate-900/50">
+ <span className="text-sm font-medium">Output Preview</span>
+ </div>
+ <div className="p-6">
+ <Renderer library={openuiLibrary} response={renderableOutput} isStreaming={false} />
+ </div>
+ </SimpleCard>
+ </div>
+ )
+}
diff --git a/docs/content/docs/openui-lang/components/try-it-out.tsx b/docs/content/docs/openui-lang/components/try-it-out.tsx
new file mode 100644
index 000000000..e4b7178b2
--- /dev/null
+++ b/docs/content/docs/openui-lang/components/try-it-out.tsx
@@ -0,0 +1,39 @@
+"use client";
+import { useState } from "react";
+import { ArrowUpRight } from "lucide-react";
+import Image from "next/image";
+import { ChatModal } from "@/components/overview-components/chat-modal";
+
+export const TryItOut = () => {
+ const [isChatModalOpen, setIsChatModalOpen] = useState(false);
+
+ return (<div
+ className="group mb-6 cursor-pointer overflow-hidden rounded-xl border-2 border-slate-200 transition-all hover:border-blue-400 hover:shadow-lg dark:border-slate-700 dark:hover:border-blue-500"
+ onClick={() => setIsChatModalOpen(true)}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => e.key === "Enter" && setIsChatModalOpen(true)}
+ >
+ <div className="relative">
+ <Image
+ src="/images/openui-lang/compare.png"
+ alt="OpenUI Chat Demo - Click to try it live"
+ width={1200}
+ height={675}
+ className="w-full m-0!"
+ />
+ <div className="absolute inset-0 bg-black/0 transition-all group-hover:bg-black/5" />
+ </div>
+ <div className="flex items-start justify-between border-t border-slate-200 px-5 py-4 dark:border-slate-700">
+ <div>
+ <h3 className="text-lg font-semibold m-0!">Try it out live</h3>
+ <p className="text-sm text-slate-500 dark:text-slate-400">
+ Live interactive demo of OpenUI Chat in action
+ </p>
+ </div>
+ <ArrowUpRight className="mt-1 size-5 shrink-0 text-slate-400 transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5 dark:text-slate-500" />
+ </div>
+ {isChatModalOpen && <ChatModal onClose={() => setIsChatModalOpen(false)} />}
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/docs/content/docs/openui-lang/index.mdx b/docs/content/docs/openui-lang/index.mdx
index 625c83b9b..8d678f368 100644
--- a/docs/content/docs/openui-lang/index.mdx
+++ b/docs/content/docs/openui-lang/index.mdx
@@ -1,75 +1,58 @@
---
-title: OpenUI Lang
-description: Streaming-first UI language for typed component rendering.
+title: Introduction
---
-OpenUI Lang is a compact, line-oriented language for LLM-generated UI.
-
-It is designed for:
-
-- Streaming output (`identifier = Expression` per line)
-- Token efficiency vs verbose JSON payloads
-- Safe rendering against your registered component library
-
-## How it works
-
-1. Define components with `defineComponent(...)` and group them with `createLibrary(...)`.
-2. Generate instructions with `library.prompt(...)` and send them as your system message.
-3. LLM returns OpenUI Lang text.
-4. `<Renderer />` parses and renders React components from that output.
-
-## Why OpenUI Lang
-
-- Renders progressively while text streams.
-- Uses positional arguments derived from your Zod object key order.
-- Drops invalid nodes with missing required props instead of rendering broken UI.
-
-<Callout type="info">
- The parser currently validates required field presence/nullability from schema metadata. It does
- not perform full runtime Zod type validation of every prop value.
-</Callout>
-
-## Minimal example
-
-```tsx
-import "@openuidev/react-ui/components.css";
-import { Renderer } from "@openuidev/react-lang";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
-
-<Renderer library={openuiLibrary} response={openuiLangText} isStreaming={isStreaming} />;
-```
-
-Example OpenUI Lang output:
-
-```text
-root = Stack([title, form])
-title = TextContent("Contact", "large-heavy")
-form = Form("contact", [nameField, emailField], actions)
-nameField = FormControl("Name", Input("name", "Your name", "text", ["required"]))
-emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))
-actions = Buttons([submitBtn, cancelBtn], "row")
-submitBtn = Button("Submit", "submit:contact", "primary")
-cancelBtn = Button("Cancel", "action:cancel_contact", "secondary")
-```
-
-## Next Steps
-
-<Cards>
- <Card title="Quick Start" href="/docs/openui-lang/quickstart">
- Start with the OpenUI library and render immediately.
- </Card>
- <Card title="Defining Components" href="/docs/openui-lang/defining-components">
- Build custom component contracts with Zod.
- </Card>
- <Card title="System Prompts" href="/docs/openui-lang/system-prompts">
- Generate and customize model instructions.
- </Card>
- <Card title="Renderer" href="/docs/openui-lang/renderer">
- Parse, stream, and handle actions.
- </Card>
- <Card title="Language Specification" href="/docs/openui-lang/specification">
- Formal grammar and parser behavior.
- </Card>
-</Cards>
+import { StreamingComparison } from "@/app/docs/openui-lang/streaming-comparison";
+import { TryItOut } from "./components/try-it-out";
+import { LangExample } from "./components/lang-example";
+
+OpenUI is a framework for building Generative UI with a compact, streaming-first language that is up to **[67% more token-efficient](/docs/openui-lang/benchmarks)** than JSON, resulting in faster AI-generated interfaces.
+
+## What is Generative UI?
+
+
+Most AI applications are limited to returning text (as markdown) or rendering pre-built UI responses. Markdown isn't interactive, and pre-built responses are rigid (they don't adapt to the context of the conversation).
+
+
+Generative UI fundamentally changes this relationship. Instead of merely providing content, the AI composes the interface itself. It dynamically selects, configures, and composes components from a predefined library to create a purpose-built interface tailored to the user's immediate request, be it an interactive chart, a complex form, or a multi-tab dashboard.
+
+<TryItOut />
+## OpenUI Lang
+
+OpenUI Lang is a compact, line-oriented language designed specifically for Large Language Models (LLMs) to generate user interfaces. It serves as a more efficient, predictable, and stream-friendly alternative to verbose formats like JSON.
+
+### Why a New Language?
+
+While JSON is a common data interchange format, it has significant drawbacks when streamed directly from an LLM for UI generation. And there are mutliple implementations around it, like Vercel [JSON-Render](https://json-render.dev/) and [A2UI](https://a2ui.org/).
+
+OpenUI Lang was created to solve these core issues:
+
+- **Token Efficiency:** JSON is extremely verbose. Keys like `"component"`, `"props"`, and `"children"` are repeated for every single element, consuming a large number of tokens. This directly increases API costs and latency. OpenUI Lang uses a concise, positional syntax that drastically reduces the token count. Benchmarks show it is up to **[67% more token-efficient](/docs/openui-lang/benchmarks)** than JSON.
+
+- **Streaming-First Design:** The language is line-oriented (`identifier = Expression`), making it trivial to parse and render progressively. As each line arrives from the model, a new piece of the UI can be rendered immediately. This provides a superior user experience with much better perceived performance compared to waiting for a complete JSON object to download and parse.
+
+- **Robustness:** The LLMs are unpredictable. They can hallucinate component names, produce invalid structures. OpenUI Lang is designed to be robust against this by validating the output and drops the invalid portion of response from rendering.
+
+<StreamingComparison />
+
+## How It Works
+
+<img src="/images/openui-lang/openui-chart-flow.png" alt="Architecture diagram"/>
+
+Here is a breakdown of Generative UI workflow:
+
+1. **User Query:** The process begins when a user interacts with your application. In this example, they ask, "What did I spend on last month?".
+
+2. **Backend Processing:** The user's query is sent to your backend. Backend applies its own business logic (e.g., authenticating the user, fetching spending data from a database) and prepares a request for an LLM provider.
+
+3. **System Prompt to LLM:** Backend sends its system prompt to the request along with OpenUI Lang spec prompt.
+
+4. **LLM Generates OpenUI Lang:** The LLM provider (like OpenAI, Anthropic, etc.) processes the prompt. Instead of returning plain text or JSON, it generates a response in **OpenUI Lang**, a token-efficient syntax designed for this purpose (e.g., `root = Stack([chart])`).
+
+5. **Rendering:** On the client side, the `@openuidev/lang-react` library's `<Renderer />` component receives and parses the OpenUI Lang stream in real-time. As each line arrives, it safely maps the code to the corresponding React components you defined in your library and renders them.
+
+The final result is a rich, native UI—like the "Total expenses" card and interactive pie chart—that was dynamically generated by the AI, streamed efficiently, and rendered safely on the client's device.
+
+## Usage Example
+
+<LangExample />
\ No newline at end of file
diff --git a/docs/content/docs/openui-lang/meta.json b/docs/content/docs/openui-lang/meta.json
index 2b2c934ed..129b06186 100644
--- a/docs/content/docs/openui-lang/meta.json
+++ b/docs/content/docs/openui-lang/meta.json
@@ -1,8 +1,7 @@
{
- "title": "OpenUI Lang",
+ "title": "OpenUI",
"root": true,
"pages": [
- "---Getting Started---",
"index",
"quickstart",
"---Core Concepts---",
diff --git a/docs/content/docs/openui-lang/quickstart.mdx b/docs/content/docs/openui-lang/quickstart.mdx
index 347f8c1a9..4fd33290b 100644
--- a/docs/content/docs/openui-lang/quickstart.mdx
+++ b/docs/content/docs/openui-lang/quickstart.mdx
@@ -3,74 +3,26 @@ title: Quick Start
description: Use the OpenUI library to render OpenUI Lang immediately.
---
-This is the fastest path: use `openuiLibrary` from `@openuidev/react-ui` and render LLM output with `@openuidev/react-lang`.
-## Installation
+#### Bootstrap a GenUI Chat app
```bash
-npm install @openuidev/react-lang @openuidev/react-ui
+npx @openuidev/cli@latest create --name genui-chat-app
+cd genui-chat-app
```
-## Render output
+#### Add your API key
-```tsx
-import "@openuidev/react-ui/components.css";
-import { Renderer } from "@openuidev/react-lang";
-import { openuiLibrary } from "@openuidev/react-ui";
-
-<Renderer library={openuiLibrary} response={streamedText} isStreaming={isStreaming} />;
-```
-
-## Generate prompt
-
-```ts
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+```bash
+echo "OPENAI_API_KEY=sk-your-key-here" > .env
```
-Use `systemPrompt` as your model system message.
-
-## Backend example
+#### Start the dev server
-```ts
-import OpenAI from "openai";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
-
-const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
-
-export async function POST(req: Request) {
- const { messages } = await req.json();
-
- const response = await client.chat.completions.create({
- model: "gpt-5.2",
- stream: true,
- messages: [
- { role: "system", content: openuiLibrary.prompt(openuiPromptOptions) },
- ...messages,
- ],
- });
-
- return new Response("stream here");
-}
+```bash
+npm run dev
```
-## Included component families
-
-- Layout: `Stack`, `Tabs`, `Accordion`, `Steps`, `Carousel`
-- Content: `Card`, `CardHeader`, `TextContent`, `Callout`, `Image`, `CodeBlock`
-- Data: `Table`, `TagBlock`
-- Charts: `BarChart`, `LineChart`, `AreaChart`, `RadarChart`, `HorizontalBarChart`, `PieChart`, `RadialChart`, `SingleStackedBarChart`, `ScatterChart`
-- Forms: `Form`, `FormControl`, `Input`, `Select`, `DatePicker`, `Slider`
-- Actions: `Button`
-
-## Next Steps
+The generated app wires up a predefined component library in `src/app/page.tsx`.
-<Cards>
- <Card title="Defining Components" href="/docs/openui-lang/defining-components">
- Build custom component contracts.
- </Card>
- <Card title="Renderer" href="/docs/openui-lang/renderer">
- Handle streaming and actions.
- </Card>
-</Cards>
+Follow guide: [Define Your Components](/docs/openui-lang/defining-components) to learn how to create your own component library.
diff --git a/docs/next.config.mjs b/docs/next.config.mjs
index 3266b317f..aa47a78e9 100644
--- a/docs/next.config.mjs
+++ b/docs/next.config.mjs
@@ -9,7 +9,7 @@ const withMDX = createMDX();
/** @type {import('next').NextConfig} */
const config = {
serverExternalPackages: ["@takumi-rs/image-response"],
- transpilePackages: ["@openuidev/react-ui", "@openuidev/react-lang"],
+ transpilePackages: ["@openuidev/react-ui", "@openuidev/react-lang", "@openuidev/react-headless"],
turbopack: {
root: dirname(dirname(__dirname)),
},
@@ -19,7 +19,7 @@ const config = {
return [
{
source: "/docs",
- destination: "/docs/introduction",
+ destination: "/docs/openui-lang",
permanent: false,
},
];
diff --git a/docs/package.json b/docs/package.json
index 259dcabd9..7a72c7254 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -16,6 +16,7 @@
"@openuidev/react-lang": "workspace:^",
"@openuidev/react-headless": "workspace:^",
"@openuidev/react-ui": "workspace:^",
+ "openai": "^6.22.0",
"@takumi-rs/image-response": "^0.68.17",
"fumadocs-core": "16.6.5",
"fumadocs-mdx": "14.2.8",
diff --git a/docs/public/images/openui-lang/compare.png b/docs/public/images/openui-lang/compare.png
new file mode 100644
index 000000000..888fc2701
Binary files /dev/null and b/docs/public/images/openui-lang/compare.png differ
diff --git a/docs/public/images/openui-lang/openui-chart-flow.png b/docs/public/images/openui-lang/openui-chart-flow.png
new file mode 100644
index 000000000..22b5cc6a1
Binary files /dev/null and b/docs/public/images/openui-lang/openui-chart-flow.png differ
diff --git a/packages/openui-cli/src/commands/create-chat-app.ts b/packages/openui-cli/src/commands/create-chat-app.ts
index f038f396e..6d9f5237d 100644
--- a/packages/openui-cli/src/commands/create-chat-app.ts
+++ b/packages/openui-cli/src/commands/create-chat-app.ts
@@ -102,5 +102,20 @@ export async function runCreateChatApp(options: CreateChatAppOptions): Promise<v
? "bun"
: "npm";
- console.info(`\nDone! Get started:\n\n cd ${name}\n ${devCmd} run dev\n`);
+ console.info(getStartedMessage(name, devCmd));
}
+
+const getStartedMessage = (name: string, devCmd: string) =>
+ `
+Done!
+Get started:
+
+cd ${name}
+
+touch .env
+
+Add your API key to .env:
+OPENAI_API_KEY=sk-your-key-here
+
+${devCmd} run dev
+`;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 73be71007..4d9ad148e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -80,6 +80,9 @@ importers:
next-themes:
specifier: ^0.4.6
+ openai:
+ specifier: ^6.22.0
posthog-js:
specifier: ^1.358.1
version: 1.358.1