Skip to content

The Open Standard for Generative UI

Update @openuidev/cli documentation (#287)

Aditya-thesys73c794940ed2
diff --git a/README.md b/README.md
index 3bd2c2507..306ab3f34 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# OpenUI
-[Docs](https://www.openui.com) · [Example App](./examples/openui-chat) · [Contributing](./CONTRIBUTING.md) · [License](./LICENSE)
+[Docs](https://openui.com) · [Example App](./examples/openui-chat) · [Discord](https://discord.com/invite/Pbv5PsqUSv) · [Contributing](./CONTRIBUTING.md) · [License](./LICENSE)
Build **LLM-powered user interfaces** with OpenUI Lang, streaming rendering, and generative UI.
@@ -19,20 +19,22 @@ At the center of OpenUI is **OpenUI Lang**: a compact, streaming-first language
**Core capabilities:**
-- **OpenUI Lang** - A compact language for structured UI generation that is designed for streaming output.
-- **Prompt generation from your component library** - Generate model instructions directly from the components you allow.
-- **Streaming renderer** - Parse and render model output progressively in React as tokens arrive.
-- **Generative UI** - Turn model output into real UI components instead of plain text responses.
+- **OpenUI Lang** — A compact language for structured UI generation designed for streaming output.
+- **Built-in component libraries** — Charts, forms, tables, layouts, and more — ready to use or extend.
+- **Prompt generation from your component library** — Generate model instructions directly from the components you allow.
+- **Streaming renderer** — Parse and render model output progressively in React as tokens arrive.
- **Chat and app surfaces** - Use the same foundation for assistants, copilots, and broader interactive product flows.
+
<!-- Product overview video placeholder -->
<!-- https://openui.com/assets/readme/overview-demo.mp4 -->
## Quick Start
```bash
-npx @openuidev/cli@latest create
+npx @openuidev/cli@latest create --name genui-chat-app
cd genui-chat-app
+echo "OPENAI_API_KEY=sk-your-key-here" > .env
npm run dev
```
@@ -65,54 +67,41 @@ This creates a direct path from model output to UI without relying on brittle te
<!-- Architecture diagram placeholder -->
<!-- ![OpenUI Architecture](./docs/static/readme/architecture.png) -->
-## Why OpenUI Lang
-
-OpenUI Lang is designed for model-generated UI that needs to be both structured and streamable.
-
-It is built for:
+## Packages
-- **Streaming output** - Emit UI incrementally as tokens arrive.
-- **Token efficiency** - Use a compact representation instead of verbose JSON payloads.
-- **Controlled rendering** - Restrict output to the components you define and register.
-- **Typed component contracts** - Define component props and structure up front.
+| Package | Description |
+| :--- | :--- |
+| [`@openuidev/react-lang`](./packages/react-lang) | Core runtime — component definitions, parser, renderer, prompt generation |
+| [`@openuidev/react-headless`](./packages/react-headless) | Headless chat state, streaming adapters, message format converters |
+| [`@openuidev/react-ui`](./packages/react-ui) | Prebuilt chat layouts and two built-in component libraries |
+| [`@openuidev/cli`](./packages/openui-cli) | CLI for scaffolding apps and generating system prompts |
-## Built for real product surfaces
-
-OpenUI is intended for more than demo chat windows.
-
-Use it to build:
+```bash
+npm install @openuidev/react-lang @openuidev/react-ui
+```
-- structured AI interfaces
-- assistants that render forms, charts, tables, and actions
-- embedded copilots inside existing products
-- full-page AI workflows
-- custom applications backed by your own model APIs
+## Why OpenUI Lang
-## Chat is one application layer
+OpenUI Lang is designed for model-generated UI that needs to be both structured and streamable.
-OpenUI also includes ready-made chat surfaces and integration patterns, but chat is only one way to use the platform.
+- **Streaming output** — Emit UI incrementally as tokens arrive.
+- **Token efficiency** — Up to 67% fewer tokens than equivalent JSON.
+- **Controlled rendering** — Restrict output to the components you define and register.
+- **Typed component contracts** — Define component props and structure up front with Zod schemas.
-If you want a complete starting point with backend wiring, streaming, and a built-in UI, use:
+## Built for real product surfaces
-```bash
-npx @openuidev/cli@latest create
-```
+OpenUI is intended for more than demo chat windows. Use it to build:
-From there, you can keep the built-in experience or move toward more custom OpenUI Lang-driven interfaces.
+- Assistants that render forms, charts, tables, and actions
+- Embedded copilots inside existing products
+- Full-page AI workflows
+- Custom applications backed by your own model APIs
## Documentation
Detailed documentation is available at [openui.com](https://openui.com).
-The docs cover:
-
-- OpenUI Lang quick start
-- component definitions and library design
-- prompt generation and customization
-- renderer behavior and streaming semantics
-- end-to-end app setup
-- backend connection patterns and API contracts
-
## Explore the repo
This repository contains the OpenUI monorepo, including the implementation, example app, and documentation source.
diff --git a/docs/.gitignore b/docs/.gitignore
index 9e429e498..8a11fd9b8 100644
--- a/docs/.gitignore
+++ b/docs/.gitignore
@@ -23,4 +23,4 @@ yarn-error.log*
# others
.env*.local
.vercel
-next-env.d.ts
\ No newline at end of file
+next-env.d.ts
diff --git a/docs/app/(home)/components/BuildChatSection.tsx b/docs/app/(home)/components/BuildChatSection.tsx
index 74f2d74dd..80280a6c1 100644
--- a/docs/app/(home)/components/BuildChatSection.tsx
+++ b/docs/app/(home)/components/BuildChatSection.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useEffect, useRef, useState } from "react";
-import Image from "next/image";
import dashboardImg from "@/public/images/home/d67b5e94653944c1d0d4998c6b169c37f98060ad.png";
+import Image from "next/image";
+import { useEffect, useRef, useState } from "react";
import { CopyIcon } from "./shared";
// ---------------------------------------------------------------------------
diff --git a/docs/app/(home)/components/Footer.tsx b/docs/app/(home)/components/Footer.tsx
index 0b10bb40a..5e830d6b5 100644
--- a/docs/app/(home)/components/Footer.tsx
+++ b/docs/app/(home)/components/Footer.tsx
@@ -31,7 +31,6 @@ const SOCIAL_LINKS: SocialLink[] = [
href: "https://discord.com/invite/Pbv5PsqUSv",
viewBox: "0 0 21.9611 17",
path: svgPaths.p3885cd00,
-
},
{
label: "YouTube",
@@ -76,7 +75,13 @@ function SocialIcon({ link }: { link: SocialLink }) {
);
return (
- <a href={link.href} target="_blank" rel="noopener noreferrer" className="size-6 relative" aria-label={link.label}>
+ <a
+ href={link.href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="size-6 relative"
+ aria-label={link.label}
+ >
{link.wrapperClass ? (
<div className={`absolute ${link.wrapperClass}`}>{svgContent}</div>
) : (
diff --git a/docs/app/(home)/components/StepsSection.tsx b/docs/app/(home)/components/StepsSection.tsx
index 259ba6cac..99144c131 100644
--- a/docs/app/(home)/components/StepsSection.tsx
+++ b/docs/app/(home)/components/StepsSection.tsx
@@ -30,7 +30,7 @@ const STEPS: Step[] = [
number: 2,
title: "OpenUI generates system prompt",
description:
- "Generate a system prompt from your library with OpenUI SDK and send it to the LLM.",
+ "Generate a system prompt from your library with the OpenUI CLI or library.prompt() and send it to the LLM.",
details: [],
},
{
diff --git a/docs/app/api/chat/route.ts b/docs/app/api/chat/route.ts
index 4fdd33a0f..58d49e738 100644
--- a/docs/app/api/chat/route.ts
+++ b/docs/app/api/chat/route.ts
@@ -1,6 +1,10 @@
+import { readFileSync } from "fs";
import { NextRequest } from "next/server";
import OpenAI from "openai";
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";
+import { join } from "path";
+
+const systemPrompt = readFileSync(join(process.cwd(), "generated/chat-system-prompt.txt"), "utf-8");
// ── Tool implementations ──
@@ -8,23 +12,32 @@ 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,
+ 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" },
- ],
- }));
+ 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);
});
}
@@ -34,19 +47,27 @@ function getStockPrice({ symbol }: { symbol: string }): Promise<string> {
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,
+ 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)),
- }));
+ 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);
});
}
@@ -55,7 +76,10 @@ function calculate({ expression }: { expression: string }): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
try {
- const sanitized = expression.replace(/[^0-9+\-*/().%\s,Math.sqrtpowabsceilfloorround]/g, "");
+ const sanitized = expression.replace(
+ /[^0-9+\-*/().%\s,Math.sqrtpowabsceilfloorround]/g,
+ "",
+ );
const result = new Function(`return (${sanitized})`)();
resolve(JSON.stringify({ expression, result: Number(result) }));
} catch {
@@ -68,14 +92,25 @@ function calculate({ expression }: { expression: string }): Promise<string> {
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}.` },
- ],
- }));
+ 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);
});
}
@@ -153,13 +188,22 @@ function sseToolCallStart(
`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: "" } }],
+ choices: [
+ {
+ index: 0,
+ delta: {
+ tool_calls: [
+ {
+ index,
+ id: tc.id,
+ type: "function",
+ function: { name: tc.function.name, arguments: "" },
+ },
+ ],
+ },
+ finish_reason: null,
},
- finish_reason: null,
- }],
+ ],
})}\n\n`,
);
}
@@ -172,7 +216,10 @@ function sseToolCallArgs(
) {
let enrichedArgs: string;
try {
- enrichedArgs = JSON.stringify({ _request: JSON.parse(tc.function.arguments), _response: JSON.parse(result) });
+ enrichedArgs = JSON.stringify({
+ _request: JSON.parse(tc.function.arguments),
+ _response: JSON.parse(result),
+ });
} catch {
enrichedArgs = tc.function.arguments;
}
@@ -180,11 +227,13 @@ function sseToolCallArgs(
`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,
- }],
+ choices: [
+ {
+ index: 0,
+ delta: { tool_calls: [{ index, function: { arguments: enrichedArgs } }] },
+ finish_reason: null,
+ },
+ ],
})}\n\n`,
);
}
@@ -192,7 +241,7 @@ function sseToolCallArgs(
// ── Route handler ──
export async function POST(req: NextRequest) {
- const { messages, systemPrompt } = await req.json();
+ const { messages } = await req.json();
const client = new OpenAI({
apiKey: process.env.OPENROUTER_API_KEY,
@@ -212,7 +261,7 @@ export async function POST(req: NextRequest) {
});
const chatMessages: ChatCompletionMessageParam[] = [
- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
+ { role: "system" as const, content: systemPrompt },
...cleanMessages,
];
@@ -223,12 +272,20 @@ export async function POST(req: NextRequest) {
start(controller) {
const enqueue = (data: Uint8Array) => {
if (controllerClosed) return;
- try { controller.enqueue(data); } catch { /* already closed */ }
+ try {
+ controller.enqueue(data);
+ } catch {
+ /* already closed */
+ }
};
const close = () => {
if (controllerClosed) return;
controllerClosed = true;
- try { controller.close(); } catch { /* already closed */ }
+ try {
+ controller.close();
+ } catch {
+ /* already closed */
+ }
};
const pendingCalls: Array<{ id: string; name: string; arguments: string }> = [];
@@ -240,7 +297,7 @@ export async function POST(req: NextRequest) {
model: MODEL,
messages: chatMessages,
tools,
- stream: true
+ stream: true,
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -254,7 +311,14 @@ export async function POST(req: NextRequest) {
runner.on("functionToolCallResult", (result: string) => {
const tc = pendingCalls[resultIdx];
if (tc) {
- enqueue(sseToolCallArgs(encoder, { id: tc.id, function: { arguments: tc.arguments } }, result, resultIdx));
+ enqueue(
+ sseToolCallArgs(
+ encoder,
+ { id: tc.id, function: { arguments: tc.arguments } },
+ result,
+ resultIdx,
+ ),
+ );
}
resultIdx++;
});
diff --git a/docs/app/api/playground/stream/route.ts b/docs/app/api/playground/stream/route.ts
index 633cc3622..3af686b88 100644
--- a/docs/app/api/playground/stream/route.ts
+++ b/docs/app/api/playground/stream/route.ts
@@ -1,8 +1,15 @@
-import { type NextRequest } from "next/server";
import { BASE_URL } from "@/lib/source";
+import { readFileSync } from "fs";
+import { type NextRequest } from "next/server";
+import { join } from "path";
+
+const systemPrompt = readFileSync(
+ join(process.cwd(), "generated/playground-system-prompt.txt"),
+ "utf-8",
+);
export async function POST(req: NextRequest) {
- const { model, prompt, systemPrompt } = await req.json();
+ const { model, prompt } = await req.json();
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
diff --git a/docs/app/docs/chat/page.tsx b/docs/app/docs/chat/page.tsx
index 85f08d501..274a931a7 100644
--- a/docs/app/docs/chat/page.tsx
+++ b/docs/app/docs/chat/page.tsx
@@ -1,7 +1,6 @@
import { Button } from "@/components/button";
import { HeroBadge } from "@/components/hero-badge";
-import { FeatureCard, FeatureCards } from "@/components/overview-components";
-import { CodeBlock } from "@/components/overview-components";
+import { CodeBlock, FeatureCard, FeatureCards } from "@/components/overview-components";
import {
Code2,
Database,
@@ -73,9 +72,24 @@ export default function ChatOverviewPage() {
</div>
<FeatureCards>
- <FeatureCard icon={<PanelRightOpen />} title="Copilot" description="A sidebar assistant that lives alongside your main application content." href="/docs/chat/copilot" />
- <FeatureCard icon={<Maximize2 />} title="Full Screen" description="A standalone, immersive chat page similar to ChatGPT or Claude." href="/docs/chat/fullscreen" />
- <FeatureCard icon={<MessageCircle />} title="Bottom Tray" description="A floating support-style widget that expands from the bottom corner." href="/docs/chat/bottom-tray" />
+ <FeatureCard
+ icon={<PanelRightOpen />}
+ title="Copilot"
+ description="A sidebar assistant that lives alongside your main application content."
+ href="/docs/chat/copilot"
+ />
+ <FeatureCard
+ icon={<Maximize2 />}
+ title="Full Screen"
+ description="A standalone, immersive chat page similar to ChatGPT or Claude."
+ href="/docs/chat/fullscreen"
+ />
+ <FeatureCard
+ icon={<MessageCircle />}
+ title="Bottom Tray"
+ description="A floating support-style widget that expands from the bottom corner."
+ href="/docs/chat/bottom-tray"
+ />
</FeatureCards>
</section>
@@ -89,9 +103,24 @@ export default function ChatOverviewPage() {
</div>
<FeatureCards direction="horizontal">
- <FeatureCard direction="horizontal" icon={<MessageSquare />} title="Streaming Native" description="Handles text deltas, optimistic updates, and loading states automatically." />
- <FeatureCard direction="horizontal" icon={<Database />} title="Thread Persistence" description="Built-in support for saving and loading conversation history via simple API contracts." />
- <FeatureCard direction="horizontal" icon={<Palette />} title="Theming" description="Customize every color, radius, and font using CSS variables or Tailwind." />
+ <FeatureCard
+ direction="horizontal"
+ icon={<MessageSquare />}
+ title="Streaming Native"
+ description="Handles text deltas, optimistic updates, and loading states automatically."
+ />
+ <FeatureCard
+ direction="horizontal"
+ icon={<Database />}
+ title="Thread Persistence"
+ description="Built-in support for saving and loading conversation history via simple API contracts."
+ />
+ <FeatureCard
+ direction="horizontal"
+ icon={<Palette />}
+ title="Theming"
+ description="Customize every color, radius, and font using CSS variables or Tailwind."
+ />
</FeatureCards>
</div>
diff --git a/docs/app/docs/openui-lang/streaming-comparison.tsx b/docs/app/docs/openui-lang/streaming-comparison.tsx
index e4249be23..bca4e1cc1 100644
--- a/docs/app/docs/openui-lang/streaming-comparison.tsx
+++ b/docs/app/docs/openui-lang/streaming-comparison.tsx
@@ -1,7 +1,7 @@
"use client";
+import { Check, RotateCcw } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
-import { RotateCcw, Check } from "lucide-react";
const JSON_CODE = `{
"component": {
@@ -194,7 +194,7 @@ 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
+// Calculated using openai tokenizer, https://platform.openai.com/tokenizer
const JSON_TOKENS = 849;
const OPENUI_TOKENS = 294;
const TOKEN_RATE = 60; // tokens per second
@@ -235,20 +235,24 @@ function StreamingCodeBlock({
}
}, [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 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";
+ 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}`}>
+ <span
+ className={`rounded-full px-3 py-1 text-xs font-semibold ${isDone ? doneBg : pillBg}`}
+ >
{state === "streaming"
? `${currentTokens}/${totalTokens} tokens`
: `${totalTokens} tokens`}
@@ -404,7 +408,10 @@ export function StreamingComparison() {
<strong>{JSON_TOKENS - OPENUI_TOKENS} fewer tokens</strong>.
</p>
<button
- onClick={() => { hasAutoPlayed.current = true; play(); }}
+ 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"
>
diff --git a/docs/app/global.css b/docs/app/global.css
index 8e47f0566..cdc7169d9 100644
--- a/docs/app/global.css
+++ b/docs/app/global.css
@@ -47,7 +47,6 @@
--fd-toc-width: 0px !important;
}
-
#nd-sidebar {
background-color: transparent !important;
}
diff --git a/docs/app/layout.tsx b/docs/app/layout.tsx
index e37795068..9df1866ea 100644
--- a/docs/app/layout.tsx
+++ b/docs/app/layout.tsx
@@ -2,9 +2,9 @@ import { RootProvider } from "fumadocs-ui/provider/next";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import Script from "next/script";
+import { BASE_URL } from "../lib/source";
import "./global.css";
import { PHProvider } from "./providers";
-import { BASE_URL } from "../lib/source";
const inter = Inter({
subsets: ["latin"],
diff --git a/docs/app/playground/page.tsx b/docs/app/playground/page.tsx
index 43c68bb73..73825d071 100644
--- a/docs/app/playground/page.tsx
+++ b/docs/app/playground/page.tsx
@@ -1,16 +1,12 @@
"use client";
-import { openuiExamples, openuiLibrary } from "@openuidev/react-ui";
import { Send, Square } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
-import { CatalogPanel } from "./components/CatalogPanel/CatalogPanel";
import { CodePanel } from "./components/CodePanel/CodePanel";
import { Header } from "./components/Header/Header";
import { PreviewPanel } from "./components/PreviewPanel/PreviewPanel";
import { MODELS, STARTER_PROMPTS, type Model, type Status, type Theme } from "./constants";
-const SYSTEM_PROMPT = openuiLibrary.prompt({ examples: openuiExamples });
-
export default function PlaygroundPage() {
const [theme, setTheme] = useState<Theme>("system");
const [prompt, setPrompt] = useState("");
@@ -63,7 +59,7 @@ export default function PlaygroundPage() {
const res = await fetch("/api/playground/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ model, prompt: prompt.trim(), systemPrompt: SYSTEM_PROMPT }),
+ body: JSON.stringify({ model, prompt: prompt.trim() }),
signal: controller.signal,
});
@@ -131,7 +127,6 @@ export default function PlaygroundPage() {
<Header theme={theme} onThemeToggle={cycleTheme} hasApiKey={false} onChangeKey={() => {}} />
<div className="app-body">
- <CatalogPanel />
<div className="content-wrapper">
<div className="prompt-section">
<h1 className="prompt-heading">What do you want to build?</h1>
diff --git a/docs/components/docs-navbar.tsx b/docs/components/docs-navbar.tsx
index 2ac73f14b..96cde91ef 100644
--- a/docs/components/docs-navbar.tsx
+++ b/docs/components/docs-navbar.tsx
@@ -3,15 +3,15 @@
import { siteConfig } from "@/lib/layout.shared";
import { SidebarTrigger } from "fumadocs-ui/components/sidebar/base";
import { useSearchContext } from "fumadocs-ui/contexts/search";
+import { useTheme } from "next-themes";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
-import { useTheme } from "next-themes";
import { OpenUILogo, ThesysLogo } from "./brand-logo";
import { ThemeToggle } from "./theme-toggle";
const tabs = [
- { title: "OpenUI Lang", url: "/docs/openui-lang" },
+ { title: "OpenUI", url: "/docs/openui-lang" },
{ title: "Chat", url: "/docs/chat" },
{ title: "API Reference", url: "/docs/api-reference" },
];
@@ -150,10 +150,11 @@ 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 c77e22740..4c86eae35 100644
--- a/docs/components/docs-route-layout.tsx
+++ b/docs/components/docs-route-layout.tsx
@@ -66,23 +66,6 @@ export function DocsRouteLayout({ tree, children }: DocsRouteLayoutProps) {
</svg>
}
/>
- <SidebarBannerLink
- href="/docs/mcp"
- label="Docs MCP Server"
- icon={
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <rect x="2" y="3" width="20" height="14" rx="2" />
- <path d="M8 21h8M12 17v4" />
- </svg>
- }
- />
<SidebarBannerLink
href={siteConfig.discordUrl}
label="Discord"
diff --git a/docs/components/overview-components/chat-modal.css b/docs/components/overview-components/chat-modal.css
index c8f3df9e2..c98c21cfd 100644
--- a/docs/components/overview-components/chat-modal.css
+++ b/docs/components/overview-components/chat-modal.css
@@ -12,8 +12,12 @@
}
@keyframes chat-modal-overlay-in {
- from { opacity: 0; }
- to { opacity: 1; }
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
}
.chat-modal-container {
@@ -27,8 +31,14 @@
}
@keyframes chat-modal-in {
- from { opacity: 0; transform: translateY(12px) scale(0.98); }
- to { opacity: 1; transform: translateY(0) scale(1); }
+ from {
+ opacity: 0;
+ transform: translateY(12px) scale(0.98);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0) scale(1);
+ }
}
.chat-modal-close {
@@ -86,6 +96,10 @@
}
@keyframes chat-modal-mobile-in {
- from { transform: translateY(100%); }
- to { transform: translateY(0); }
+ 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
index a6003a8d5..5c382f65a 100644
--- a/docs/components/overview-components/chat-modal.tsx
+++ b/docs/components/overview-components/chat-modal.tsx
@@ -5,14 +5,12 @@ 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 { openuiChatLibrary } 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;
}
@@ -51,7 +49,6 @@ export function ChatModal({ onClose }: ChatModalProps) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: openAIMessageFormat.toApi(messages),
- systemPrompt,
}),
signal: abortController.signal,
});
@@ -63,10 +60,26 @@ export function ChatModal({ onClose }: ChatModalProps) {
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." },
+ {
+ displayText: "Revenue dashboard",
+ prompt:
+ "Build a revenue dashboard with a bar chart showing monthly revenue for Q4, key metrics, and a summary table.",
+ },
+ {
+ displayText: "Signup form",
+ prompt:
+ "Create a user registration form with name, email, password, and country fields with validation.",
+ },
+ {
+ displayText: "Compare React vs Vue",
+ prompt:
+ "Show me a comparison of React and Vue frameworks using tabs with pros, cons, and a feature comparison table.",
+ },
+ {
+ displayText: "Travel destinations",
+ prompt:
+ "Show me a carousel of 3 popular travel destinations with images, descriptions, and best time to visit.",
+ },
],
}}
/>
diff --git a/docs/components/overview-components/code-block.tsx b/docs/components/overview-components/code-block.tsx
index 852a55b45..d3e359b93 100644
--- a/docs/components/overview-components/code-block.tsx
+++ b/docs/components/overview-components/code-block.tsx
@@ -25,12 +25,12 @@ export function CodeBlock({
};
return (
- <div className={`overflow-hidden rounded-lg border border-slate-200 dark:border-[var(--color-doc-border)] flex flex-col ${className}`}>
+ <div
+ className={`overflow-hidden rounded-lg border border-slate-200 dark:border-[var(--color-doc-border)] flex flex-col ${className}`}
+ >
{title && (
<div className="flex items-center justify-between border-b border-slate-200 bg-slate-50 px-4 py-2.5 dark:border-[var(--color-doc-border)] dark:bg-[var(--color-doc-surface)]">
- <span className="text-xs font-medium text-slate-600 dark:text-slate-400">
- {title}
- </span>
+ <span className="text-xs font-medium text-slate-600 dark:text-slate-400">{title}</span>
<button
onClick={handleCopy}
className="text-xs text-slate-500 transition-colors hover:text-slate-700 dark:hover:text-slate-300"
@@ -39,7 +39,9 @@ export function CodeBlock({
</button>
</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}`}>
+ <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 className="border-0! bg-transparent!">{code}</code>
</pre>
</div>
diff --git a/docs/components/overview-components/feature-card.tsx b/docs/components/overview-components/feature-card.tsx
index 37ef408b5..e22c5bd35 100644
--- a/docs/components/overview-components/feature-card.tsx
+++ b/docs/components/overview-components/feature-card.tsx
@@ -9,7 +9,13 @@ interface FeatureCardProps {
direction?: "vertical" | "horizontal";
}
-export function FeatureCard({ icon, title, description, href, direction = "vertical" }: FeatureCardProps) {
+export function FeatureCard({
+ icon,
+ title,
+ description,
+ href,
+ direction = "vertical",
+}: FeatureCardProps) {
let content;
if (direction === "horizontal") {
@@ -18,7 +24,9 @@ export function FeatureCard({ icon, title, description, href, direction = "verti
<div className="flex items-start gap-4">
{icon && (
<div className="flex shrink-0 size-9 items-center justify-center rounded-lg bg-fd-muted">
- <div className="flex size-4 items-center justify-center text-fd-foreground">{icon}</div>
+ <div className="flex size-4 items-center justify-center text-fd-foreground">
+ {icon}
+ </div>
</div>
)}
<div>
@@ -67,7 +75,12 @@ const colsMap: Record<number, string> = {
4: "sm:grid-cols-4",
};
-export function FeatureCards({ children, direction = "vertical", cols, className }: FeatureCardsProps) {
+export function FeatureCards({
+ children,
+ direction = "vertical",
+ cols,
+ className,
+}: FeatureCardsProps) {
let gridClass: string;
if (direction === "horizontal") {
@@ -77,9 +90,5 @@ export function FeatureCards({ children, direction = "vertical", cols, className
gridClass = "grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 items-stretch";
}
- return (
- <div className={`${gridClass} ${className ?? ""}`}>
- {children}
- </div>
- );
+ return <div className={`${gridClass} ${className ?? ""}`}>{children}</div>;
}
diff --git a/docs/components/overview-components/overview-page.tsx b/docs/components/overview-components/overview-page.tsx
index 713977178..3303366e6 100644
--- a/docs/components/overview-components/overview-page.tsx
+++ b/docs/components/overview-components/overview-page.tsx
@@ -3,14 +3,14 @@
import { Button } from "@/components/button";
import {
CodeBlock,
+ FeatureCard,
+ FeatureCards,
Separator,
SimpleCard,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
- FeatureCard,
- FeatureCards,
} from "@/components/overview-components";
import { ArrowUpRight, Code2, MessageSquare, Package } from "lucide-react";
import { useState } from "react";
@@ -87,8 +87,8 @@ export function OverviewPage() {
>
A2UI
</a>{" "}
- that reduces token usage by up to 67.1%. Define your component library with Zod schemas, get
- automatic system prompts, and parse LLM responses into renderable components.
+ that reduces token usage by up to 67.1%. Define your component library with Zod schemas,
+ get automatic system prompts, and parse LLM responses into renderable components.
</p>
<SimpleCard className="mb-4 border-blue-200 p-3 sm:p-4">
@@ -324,10 +324,10 @@ import { FullScreen, openuiLibrary } from "@openuidev/react-ui";
<CodeBlock
title="Quick example"
code={`import { createLibrary, defineComponent } from '@openuidev/react-lang';
-import { openuiLibrary, openuiPromptOptions } from '@openuidev/react-ui';
+import { openuiLibrary } from '@openuidev/react-ui';
import { z } from 'zod';
-const prompt = openuiLibrary.prompt(openuiPromptOptions);
+// Generate prompt with CLI: openui generate ./src/library.ts
const CustomWidget = defineComponent({
name: 'CustomWidget',
diff --git a/docs/components/overview-components/separator.tsx b/docs/components/overview-components/separator.tsx
index 852d370ca..27c5c423f 100644
--- a/docs/components/overview-components/separator.tsx
+++ b/docs/components/overview-components/separator.tsx
@@ -4,8 +4,6 @@ interface SeparatorProps {
export function Separator({ className }: SeparatorProps) {
return (
- <hr
- className={`border-slate-200 dark:border-[var(--color-doc-border)] ${className ?? ""}`}
- />
+ <hr className={`border-slate-200 dark:border-[var(--color-doc-border)] ${className ?? ""}`} />
);
}
diff --git a/docs/components/theme-toggle.tsx b/docs/components/theme-toggle.tsx
index 4b21998f1..c60581c90 100644
--- a/docs/components/theme-toggle.tsx
+++ b/docs/components/theme-toggle.tsx
@@ -1,9 +1,9 @@
-'use client';
+"use client";
-import { useEffect, useState } from 'react';
-import { Moon, Sun } from 'lucide-react';
-import { useTheme } from 'next-themes';
-import { cn } from '@/lib/cn';
+import { cn } from "@/lib/cn";
+import { Moon, Sun } from "lucide-react";
+import { useTheme } from "next-themes";
+import { useEffect, useState } from "react";
export function ThemeToggle({ className }: { className?: string }) {
const { setTheme, resolvedTheme } = useTheme();
@@ -18,24 +18,24 @@ export function ThemeToggle({ className }: { className?: string }) {
return (
<button
className={cn(
- 'inline-flex items-center rounded-full border p-0.5 *:rounded-full cursor-pointer',
+ "inline-flex items-center rounded-full border p-0.5 *:rounded-full cursor-pointer",
className,
)}
aria-label="Toggle Theme"
- onClick={() => setTheme(value === 'light' ? 'dark' : 'light')}
+ onClick={() => setTheme(value === "light" ? "dark" : "light")}
data-theme-toggle=""
>
- {(['light', 'dark'] as const).map((key) => {
- const Icon = key === 'light' ? Sun : Moon;
+ {(["light", "dark"] as const).map((key) => {
+ const Icon = key === "light" ? Sun : Moon;
return (
<Icon
key={key}
fill="currentColor"
className={cn(
- 'size-5 p-1',
+ "size-5 p-1",
value === key
- ? 'bg-fd-accent text-fd-accent-foreground rounded-full'
- : 'text-fd-muted-foreground',
+ ? "bg-fd-accent text-fd-accent-foreground rounded-full"
+ : "text-fd-muted-foreground",
)}
/>
);
diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdx
index 0f68a6900..849fea678 100644
--- a/docs/content/docs/api-reference/index.mdx
+++ b/docs/content/docs/api-reference/index.mdx
@@ -3,16 +3,27 @@ title: OpenUI SDK
description: API reference for the documented surfaces of @openuidev/react-lang, @openuidev/react-headless, and @openuidev/react-ui.
---
+The OpenUI SDK is split into three packages that build on each other:
+
+- **`@openuidev/react-lang`** — Core runtime. Define component libraries with Zod schemas, generate system prompts, parse OpenUI Lang, and render streamed output to React. This is the foundation — you need it for any OpenUI integration.
+
+- **`@openuidev/react-headless`** — Headless chat state management. Provides `ChatProvider`, thread/message hooks, streaming protocol adapters (OpenAI, AG-UI), and message format converters. Use this when you want full control over your chat UI.
+
+- **`@openuidev/react-ui`** — Prebuilt chat layouts (`Copilot`, `FullScreen`, `BottomTray`) and two ready-to-use component libraries (general-purpose and chat-optimized). Depends on both packages above. Use this for the fastest path to a working chat interface.
+
## Packages
<Cards>
<Card title="@openuidev/react-lang" href="/docs/api-reference/react-lang">
- createLibrary, Renderer, parser APIs, action types, and renderer/form hooks.
+ defineComponent, createLibrary, Renderer, parser APIs, action types, context hooks, and form
+ validation.
</Card>
<Card title="@openuidev/react-headless" href="/docs/api-reference/react-headless">
- ChatProvider, useThread/useThreadList, stream adapters, and message formats.
+ ChatProvider, useThread/useThreadList, stream protocol adapters (OpenAI, AG-UI), and message
+ format converters.
</Card>
<Card title="@openuidev/react-ui" href="/docs/api-reference/react-ui">
- Copilot, FullScreen, BottomTray, and default component library exports.
+ Copilot, FullScreen, BottomTray chat layouts, and two built-in component libraries
+ (general-purpose and chat-optimized).
</Card>
</Cards>
diff --git a/docs/content/docs/api-reference/react-headless.mdx b/docs/content/docs/api-reference/react-headless.mdx
index 0f9ad7564..22b2906bf 100644
--- a/docs/content/docs/api-reference/react-headless.mdx
+++ b/docs/content/docs/api-reference/react-headless.mdx
@@ -22,6 +22,7 @@ import {
processStreamedMessage,
MessageProvider,
useMessage,
+ EventType,
} from "@openuidev/react-headless";
```
diff --git a/docs/content/docs/api-reference/react-lang.mdx b/docs/content/docs/api-reference/react-lang.mdx
index 95c4be860..29eae24b8 100644
--- a/docs/content/docs/api-reference/react-lang.mdx
+++ b/docs/content/docs/api-reference/react-lang.mdx
@@ -211,12 +211,20 @@ interface FormValidationContextValue {
}
function useFormValidation(): FormValidationContextValue | null;
+function useCreateFormValidation(): FormValidationContextValue;
function validate(
value: unknown,
rules: ParsedRule[],
customValidators?: Record<string, ValidatorFn>,
): string | undefined;
function parseRules(rules: unknown): ParsedRule[];
+function parseStructuredRules(rules: unknown): ParsedRule[];
const builtInValidators: Record<string, ValidatorFn>;
```
+Context providers for advanced usage:
+
+```ts
+const FormValidationContext: React.Context<FormValidationContextValue | null>;
+const FormNameContext: React.Context<string | undefined>;
+```
diff --git a/docs/content/docs/api-reference/react-ui.mdx b/docs/content/docs/api-reference/react-ui.mdx
index 27e35b9e9..4c6f7063b 100644
--- a/docs/content/docs/api-reference/react-ui.mdx
+++ b/docs/content/docs/api-reference/react-ui.mdx
@@ -104,6 +104,9 @@ import {
// Chat-optimised (root = Card, includes FollowUpBlock, ListBlock, SectionBlock)
openuiChatLibrary,
openuiChatPromptOptions,
+ openuiChatExamples,
+ openuiChatAdditionalRules,
+ openuiChatComponentGroups,
// General-purpose (root = Stack, full component suite)
openuiLibrary,
@@ -114,14 +117,20 @@ import {
} from "@openuidev/react-ui/genui-lib";
```
-Use `openuiChatLibrary` with `FullScreen` / `BottomTray` chat interfaces. Use `openuiLibrary` with the standalone `Renderer` or any non-chat layout.
+**`openuiChatLibrary`** — Root is `Card` (vertical, no layout params). Includes chat-specific components: `FollowUpBlock`, `ListBlock`, `SectionBlock`. Does not include `Stack`. Use with `FullScreen` / `BottomTray` / `Copilot` chat interfaces.
+
+**`openuiLibrary`** — Root is `Stack`. Full layout suite with `Stack`, `Tabs`, `Carousel`, `Accordion`, etc. Use with the standalone `Renderer` or any non-chat layout (e.g., playground, embedded widgets).
+
+Generate the system prompt at build time with the CLI:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts --out src/generated/system-prompt.txt
+```
```tsx
-// Chat interface
-const systemPrompt = openuiChatLibrary.prompt(openuiChatPromptOptions);
+// Chat interface — system prompt stays on the server
<FullScreen componentLibrary={openuiChatLibrary} ... />
// Standalone renderer
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
<Renderer response={message} library={openuiLibrary} />
```
diff --git a/docs/content/docs/chat/api-contract.mdx b/docs/content/docs/chat/api-contract.mdx
index 5cda44d8d..bcb4ff8eb 100644
--- a/docs/content/docs/chat/api-contract.mdx
+++ b/docs/content/docs/chat/api-contract.mdx
@@ -14,9 +14,7 @@ When you pass `apiUrl`, OpenUI sends a `POST` request with this shape:
```json
{
"threadId": "thread_123",
- "messages": [
- { "id": "msg_1", "role": "user", "content": "Hello" }
- ]
+ "messages": [{ "id": "msg_1", "role": "user", "content": "Hello" }]
}
```
@@ -33,24 +31,24 @@ If your backend already accepts the default AG-UI message shape, each message ca
Your response stream must match one of these cases:
-| Backend response shape | Frontend config |
-| :--- | :--- |
-| OpenUI Protocol | No `streamProtocol` needed |
-| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |
+| Backend response shape | Frontend config |
+| :--------------------------------------- | :----------------------------------------------- |
+| OpenUI Protocol | No `streamProtocol` needed |
+| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |
| OpenAI SDK `toReadableStream()` / NDJSON | `streamProtocol={openAIReadableStreamAdapter()}` |
-| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |
+| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |
## Default thread API contract
When using `threadApiUrl="/api/threads"`, OpenUI expects the base URL plus these default path segments:
-| Action | Method | URL | Request body | Response |
-| :--- | :--- | :--- | :--- | :--- |
-| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |
-| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |
-| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |
-| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |
-| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |
+| Action | Method | URL | Request body | Response |
+| :------------ | :------- | :------------------------ | :------------- | :---------------------------------------- |
+| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |
+| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |
+| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |
+| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |
+| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |
`messages` in the create request is the first user message, already converted through `messageFormat.toApi([firstMessage])`.
@@ -73,11 +71,11 @@ type Thread = {
OpenUI ships with these built-in message converters:
-| Converter | Use when your backend expects or returns... |
-| :--- | :--- |
-| Default | AG-UI message objects |
-| `openAIMessageFormat` | OpenAI chat completion messages |
-| `openAIConversationMessageFormat` | OpenAI Responses conversation items |
+| Converter | Use when your backend expects or returns... |
+| :-------------------------------- | :------------------------------------------ |
+| Default | AG-UI message objects |
+| `openAIMessageFormat` | OpenAI chat completion messages |
+| `openAIConversationMessageFormat` | OpenAI Responses conversation items |
Every persisted message should include a unique `id`. Without stable message IDs, history hydration and message updates become unreliable.
diff --git a/docs/content/docs/chat/connecting.mdx b/docs/content/docs/chat/connecting.mdx
index a33b064eb..25eb95f35 100644
--- a/docs/content/docs/chat/connecting.mdx
+++ b/docs/content/docs/chat/connecting.mdx
@@ -29,15 +29,13 @@ With `apiUrl`, OpenUI sends the message history to your endpoint for you. If you
- add auth headers
- build a dynamic URL
-- include extra request fields like `systemPrompt`
+- include extra request fields
- convert `messages` before sending them
```tsx
import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
<FullScreen
processMessage={async ({ messages, abortController }) => {
@@ -49,7 +47,6 @@ const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
},
body: JSON.stringify({
messages: openAIMessageFormat.toApi(messages),
- systemPrompt,
}),
signal: abortController.signal,
});
@@ -66,12 +63,12 @@ const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
`streamProtocol` tells OpenUI how to parse the response stream. By default, OpenUI expects the OpenUI Protocol, so only set this when your backend streams a different format.
-| Backend output | Frontend config |
-| :--- | :--- |
-| OpenUI Protocol | No adapter required |
-| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |
+| Backend output | Frontend config |
+| :--------------------------------------- | :----------------------------------------------- |
+| OpenUI Protocol | No adapter required |
+| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |
| OpenAI SDK `toReadableStream()` / NDJSON | `streamProtocol={openAIReadableStreamAdapter()}` |
-| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |
+| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |
```tsx
import { openAIReadableStreamAdapter } from "@openuidev/react-headless";
@@ -87,10 +84,10 @@ import { openAIReadableStreamAdapter } from "@openuidev/react-headless";
`messageFormat` controls the shape of the `messages` array sent to your backend and the shape expected when loading thread history.
-| Backend message shape | Frontend config |
-| :--- | :--- |
-| AG-UI message shape | No converter required |
-| OpenAI chat completions messages | `messageFormat={openAIMessageFormat}` |
+| Backend message shape | Frontend config |
+| :---------------------------------- | :------------------------------------------------ |
+| AG-UI message shape | No converter required |
+| OpenAI chat completions messages | `messageFormat={openAIMessageFormat}` |
| OpenAI Responses conversation items | `messageFormat={openAIConversationMessageFormat}` |
```tsx
diff --git a/docs/content/docs/chat/custom-ui-guide.mdx b/docs/content/docs/chat/custom-ui-guide.mdx
index ecfd3658b..2932964f3 100644
--- a/docs/content/docs/chat/custom-ui-guide.mdx
+++ b/docs/content/docs/chat/custom-ui-guide.mdx
@@ -22,13 +22,8 @@ import {
} from "@openuidev/react-headless";
function ThreadSidebar() {
- const {
- threads,
- selectedThreadId,
- isLoadingThreads,
- selectThread,
- switchToNewThread,
- } = useThreadList();
+ const { threads, selectedThreadId, isLoadingThreads, selectThread, switchToNewThread } =
+ useThreadList();
return (
<aside>
@@ -111,7 +106,7 @@ export default function App() {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- messages,
+ messages: openAIMessageFormat.toApi(messages),
}),
signal: abortController.signal,
});
@@ -128,10 +123,10 @@ export default function App() {
This example uses the same backend assumptions as the built-in layouts:
-- `messageFormat={openAIMessageFormat}` converts outgoing chat messages and loaded thread history to the backend format
+- `openAIMessageFormat.toApi(messages)` is called explicitly in `processMessage` to convert messages to OpenAI format — the `messageFormat` prop does not transform messages for `processMessage`
+- `messageFormat={openAIMessageFormat}` is still needed here because `threadApiUrl` is set — it tells the UI how to convert messages when loading saved thread history
- `openAIReadableStreamAdapter()` matches `response.toReadableStream()`
- `threadApiUrl` enables saved thread history
-- `processMessage` keeps the request body explicit while still letting `messageFormat` handle message conversion
If you want Generative UI in a headless build, you also need to render structured assistant content yourself instead of relying on the built-in `componentLibrary` behavior from the layout components.
diff --git a/docs/content/docs/chat/from-scratch.mdx b/docs/content/docs/chat/from-scratch.mdx
index 68c2b9e64..dfb520fde 100644
--- a/docs/content/docs/chat/from-scratch.mdx
+++ b/docs/content/docs/chat/from-scratch.mdx
@@ -20,16 +20,33 @@ This path covers:
Complete [Installation](/docs/chat/installation) first, then return here to wire the chat flow.
-## 1. Generate the component-library prompt
+## 1. Generate the system prompt
-If you want Generative UI, generate a system prompt from the component library and send it with each request.
+If you want Generative UI, generate a system prompt from the component library. The backend loads this prompt and sends it to the model with each request.
-If you only want plain text chat, you can skip this step and omit `componentLibrary` and `systemPrompt` in the next examples.
+If you only want plain text chat, you can skip this step and omit `componentLibrary` in the next examples.
-```tsx
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
+```bash
+npx @openuidev/cli generate ./src/library.ts --out src/generated/system-prompt.txt
+```
+
+Where `src/library.ts` exports your library:
+
+```ts
+export {
+ openuiLibrary as library,
+ openuiPromptOptions as promptOptions,
+} from "@openuidev/react-ui/genui-lib";
+```
+
+Add this as a prebuild step in `package.json`:
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+```json
+"scripts": {
+ "generate:prompt": "openui generate src/library.ts --out src/generated/system-prompt.txt",
+ "dev": "pnpm generate:prompt && next dev",
+ "build": "pnpm generate:prompt && next build"
+}
```
This prompt tells the model which UI components it is allowed to emit.
@@ -39,23 +56,21 @@ This prompt tells the model which UI components it is allowed to emit.
Create `app/api/chat/route.ts`:
```ts
+import { readFileSync } from "fs";
+import { join } from "path";
import { NextRequest } from "next/server";
import OpenAI from "openai";
const client = new OpenAI();
+const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");
export async function POST(req: NextRequest) {
try {
- const { messages, systemPrompt } = await req.json();
-
- const chatMessages: OpenAI.ChatCompletionMessageParam[] = [
- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
- ...messages,
- ];
+ const { messages } = await req.json();
const response = await client.chat.completions.create({
model: "gpt-5.2",
- messages: chatMessages,
+ messages: [{ role: "system", content: systemPrompt }, ...messages],
stream: true,
});
@@ -77,20 +92,18 @@ export async function POST(req: NextRequest) {
}
```
-This route expects OpenAI chat-completion messages and returns the OpenAI SDK readable stream.
+The system prompt is loaded from the file generated by the CLI. The route only receives messages from the frontend — the prompt never leaves the server.
## 3. Render a layout and connect it to the route
`FullScreen` is a good baseline because it includes both the thread list and the main chat surface.
-This guide uses `processMessage` instead of `apiUrl` so the request body stays explicit and you can pass `systemPrompt`.
+This guide uses `processMessage` instead of `apiUrl` so the request body stays explicit.
```tsx
import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
export default function Page() {
return (
@@ -101,13 +114,11 @@ export default function Page() {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- messages,
- systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
}),
signal: abortController.signal,
});
}}
- messageFormat={openAIMessageFormat}
streamProtocol={openAIReadableStreamAdapter()}
componentLibrary={openuiLibrary}
agentName="Assistant"
@@ -120,7 +131,7 @@ export default function Page() {
Why this setup matters:
- `processMessage` gives you control over the request body
-- `messageFormat={openAIMessageFormat}` converts the messages before they reach your route
+- `openAIMessageFormat.toApi(messages)` converts messages to OpenAI format before sending
- `openAIReadableStreamAdapter()` matches `response.toReadableStream()`
- `componentLibrary={openuiLibrary}` lets the UI render structured responses
@@ -145,8 +156,7 @@ If you want the UI to load saved threads and previous messages, add `threadApiUr
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- messages,
- systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
}),
signal: abortController.signal,
});
@@ -159,7 +169,7 @@ If you want the UI to load saved threads and previous messages, add `threadApiUr
/>
```
-Add `messageFormat={openAIMessageFormat}` if your thread endpoints also store and return OpenAI-style messages. That keeps both chat requests and thread-history loading aligned without manually calling `openAIMessageFormat.toApi(messages)` in `processMessage`.
+When using `processMessage`, you must call `openAIMessageFormat.toApi(messages)` explicitly in the request body — the `messageFormat` prop does not transform messages for `processMessage`. The `messageFormat={openAIMessageFormat}` prop here is for `threadApiUrl`: it tells the UI how to convert messages when loading saved thread history from the backend.
## 5. Switch layouts or go headless (optional)
diff --git a/docs/content/docs/chat/genui.mdx b/docs/content/docs/chat/genui.mdx
index 0e4c8289f..f5eb57caa 100644
--- a/docs/content/docs/chat/genui.mdx
+++ b/docs/content/docs/chat/genui.mdx
@@ -6,17 +6,25 @@ description: Use Generative UI with Chat components.
GenUI lets assistant messages render structured UI instead of plain text. To make it work, you need both sides of the setup:
- `componentLibrary` on the frontend so OpenUI knows how to render components
-- a generated `systemPrompt` in the request so the model knows what it is allowed to emit
+- a generated system prompt on the backend so the model knows what it is allowed to emit
Passing `componentLibrary` alone is not enough.
The frontend and backend have different jobs here:
- the frontend renders structured responses through `componentLibrary`
-- the backend sends the generated `systemPrompt` to the model with each request
+- the backend loads the generated system prompt and sends it to the model with each request
If either side is missing, the model falls back to plain text or emits components the UI cannot render.
+Generate the system prompt with the CLI:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts --out src/generated/system-prompt.txt
+```
+
+The CLI auto-detects exported `PromptOptions` alongside your library, so examples and rules are included automatically. See [System Prompts](/docs/openui-lang/system-prompts) for details.
+
## Use the chat library
`openuiChatLibrary` is optimised for conversational chat: every response is wrapped in a `Card`, and it includes chat-specific components like `FollowUpBlock`, `ListBlock`, and `SectionBlock`.
@@ -24,9 +32,7 @@ If either side is missing, the model falls back to plain text or emits component
```tsx
import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiChatLibrary, openuiChatPromptOptions } from "@openuidev/react-ui/genui-lib";
-
-const systemPrompt = openuiChatLibrary.prompt(openuiChatPromptOptions);
+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
export default function Page() {
return (
@@ -37,7 +43,6 @@ export default function Page() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: openAIMessageFormat.toApi(messages),
- systemPrompt,
}),
signal: abortController.signal,
});
@@ -52,8 +57,7 @@ export default function Page() {
In this setup:
-- `openuiChatLibrary.prompt(openuiChatPromptOptions)` creates the system prompt
-- `systemPrompt` is sent with every request
+- The system prompt is generated at build time via the CLI and loaded by the backend
- `openAIMessageFormat.toApi(messages)` converts messages before sending
- `componentLibrary={openuiChatLibrary}` tells the UI how to render the model output
- `openAIAdapter()` parses raw SSE chunks from the backend
@@ -66,12 +70,18 @@ This is the minimal complete pattern for GenUI in a chat interface. For a non-ch
If you need domain-specific components, keep the same request flow and swap in your own library definition:
+First, generate the system prompt from your custom library:
+
+```bash
+npx @openuidev/cli generate ./src/lib/my-library.ts --out src/generated/system-prompt.txt
+```
+
+Then wire up the frontend — it only needs the component library for rendering:
+
```tsx
import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { myLibrary, myPromptOptions } from "@/lib/my-library";
-
-const systemPrompt = myLibrary.prompt(myPromptOptions);
+import { myLibrary } from "@/lib/my-library";
<FullScreen
processMessage={async ({ messages, abortController }) => {
@@ -79,25 +89,23 @@ const systemPrompt = myLibrary.prompt(myPromptOptions);
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- messages,
- systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
}),
signal: abortController.signal,
});
}}
- messageFormat={openAIMessageFormat}
streamProtocol={openAIReadableStreamAdapter()}
componentLibrary={myLibrary}
agentName="Assistant"
/>;
```
-This example assumes `myLibrary` is already defined elsewhere in your app. The key rule is that your custom library still has to provide two things:
+Your custom library needs two things:
-- a prompt generator, so the backend can tell the model what components it may emit
-- component definitions, so the frontend can render those emitted components
+- a `createLibrary()` result, so the CLI can generate the system prompt and the frontend can render components
+- optional `PromptOptions` export for examples and rules (auto-detected by the CLI)
-Your backend does not need a special GenUI endpoint. It only needs to receive the generated `systemPrompt` and pass it to the model alongside the message history.
+Your backend loads the generated prompt file and sends it to the model alongside the message history.
## Related guides
diff --git a/docs/content/docs/chat/headless-intro.mdx b/docs/content/docs/chat/headless-intro.mdx
index c3d23075d..e1a54506a 100644
--- a/docs/content/docs/chat/headless-intro.mdx
+++ b/docs/content/docs/chat/headless-intro.mdx
@@ -8,6 +8,7 @@ This page introduces headless mode and the role of `ChatProvider` in a custom ch
The trade-off is simple: you get full control over rendering, but you become responsible for composing the sidebar, message list, and composer yourself.
At the center is `ChatProvider`, which manages:
+
- streaming state
- thread list and selection
- message sending/cancelation
diff --git a/docs/content/docs/chat/installation.mdx b/docs/content/docs/chat/installation.mdx
index 7f9fe9234..3fa87a661 100644
--- a/docs/content/docs/chat/installation.mdx
+++ b/docs/content/docs/chat/installation.mdx
@@ -6,9 +6,8 @@ description: Add OpenUI Chat to an existing Next.js App Router application.
This page covers package installation, style imports, and a basic render check for an existing Next.js App Router app.
<Callout type="info">
- **Starting a new project?**
- Skip this guide and use our scaffold command instead:
- `npx @openuidev/cli@latest create --name my-app`
+ **Starting a new project?** Skip this guide and use our scaffold command instead: `npx
+ @openuidev/cli@latest create --name my-app`
</Callout>
## Prerequisites
@@ -25,24 +24,16 @@ Install the UI package, the headless core, and the icons package used by the bui
<Tabs items={["npm", "pnpm", "yarn", "bun"]}>
<Tab value="npm">
- ```bash
- npm install @openuidev/react-ui @openuidev/react-headless lucide-react
- ```
+ ```bash npm install @openuidev/react-ui @openuidev/react-headless lucide-react ```
</Tab>
<Tab value="pnpm">
- ```bash
- pnpm add @openuidev/react-ui @openuidev/react-headless lucide-react
- ```
+ ```bash pnpm add @openuidev/react-ui @openuidev/react-headless lucide-react ```
</Tab>
<Tab value="yarn">
- ```bash
- yarn add @openuidev/react-ui @openuidev/react-headless lucide-react
- ```
+ ```bash yarn add @openuidev/react-ui @openuidev/react-headless lucide-react ```
</Tab>
<Tab value="bun">
- ```bash
- bun add @openuidev/react-ui @openuidev/react-headless lucide-react
- ```
+ ```bash bun add @openuidev/react-ui @openuidev/react-headless lucide-react ```
</Tab>
</Tabs>
@@ -55,11 +46,7 @@ import "@openuidev/react-ui/components.css";
import "@openuidev/react-ui/styles/index.css";
import "./globals.css";
-export default function RootLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
diff --git a/docs/content/docs/chat/nextjs.mdx b/docs/content/docs/chat/nextjs.mdx
index f3f2bfe31..75384eee2 100644
--- a/docs/content/docs/chat/nextjs.mdx
+++ b/docs/content/docs/chat/nextjs.mdx
@@ -9,32 +9,37 @@ If you want the full install-and-render walkthrough, use the [End-to-End Guide](
This page focuses on one specific backend pattern:
-- `processMessage` on the frontend so you can add `systemPrompt`
+- `processMessage` on the frontend to send messages
- `openAIMessageFormat` to send OpenAI chat messages
- `openAIReadableStreamAdapter()` because `response.toReadableStream()` emits NDJSON, not raw SSE
+- the system prompt stays on the server, generated at build time by the CLI
## Route handler
+Generate the system prompt at build time:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts --out src/generated/system-prompt.txt
+```
+
Create `app/api/chat/route.ts`:
```ts
+import { readFileSync } from "fs";
+import { join } from "path";
import { NextRequest } from "next/server";
import OpenAI from "openai";
const client = new OpenAI();
+const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");
export async function POST(req: NextRequest) {
try {
- const { messages, systemPrompt } = await req.json();
-
- const chatMessages: OpenAI.ChatCompletionMessageParam[] = [
- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
- ...messages,
- ];
+ const { messages } = await req.json();
const response = await client.chat.completions.create({
model: "gpt-5.2",
- messages: chatMessages,
+ messages: [{ role: "system", content: systemPrompt }, ...messages],
stream: true,
});
@@ -56,20 +61,18 @@ export async function POST(req: NextRequest) {
}
```
-This route expects `messages` to already be in OpenAI chat format and optionally prepends a `systemPrompt`.
+The system prompt is loaded from the file generated by the CLI. It never leaves the server.
## Matching frontend configuration
Because `toReadableStream()` produces newline-delimited JSON, pair it with `openAIReadableStreamAdapter()` on the frontend.
-Use `processMessage` here because the client needs to send both `messages` and `systemPrompt` explicitly. `messageFormat={openAIMessageFormat}` handles the message conversion before the request is sent.
+When using `processMessage`, you must convert messages yourself with `openAIMessageFormat.toApi(messages)` before sending. The `messageFormat` prop only applies automatically for the `apiUrl` flow.
```tsx
import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
<FullScreen
processMessage={async ({ messages, abortController }) => {
@@ -77,13 +80,11 @@ const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- messages,
- systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
}),
signal: abortController.signal,
});
}}
- messageFormat={openAIMessageFormat}
streamProtocol={openAIReadableStreamAdapter()}
componentLibrary={openuiLibrary}
agentName="Assistant"
diff --git a/docs/content/docs/chat/persistence.mdx b/docs/content/docs/chat/persistence.mdx
index 03e36ab0e..4135d7459 100644
--- a/docs/content/docs/chat/persistence.mdx
+++ b/docs/content/docs/chat/persistence.mdx
@@ -16,13 +16,13 @@ This config only affects thread history. Your live chat request still comes from
When you pass `threadApiUrl="/api/threads"`, OpenUI appends its own path segments. The default requests look like this:
-| Action | Method | URL | Request body | Expected response |
-| :--- | :--- | :--- | :--- | :--- |
-| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |
-| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |
-| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |
-| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |
-| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |
+| Action | Method | URL | Request body | Expected response |
+| :------------ | :------- | :------------------------ | :------------- | :---------------------------------------- |
+| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |
+| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |
+| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |
+| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |
+| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |
```tsx
import { FullScreen } from "@openuidev/react-ui";
@@ -99,7 +99,7 @@ then provide the individual thread functions instead of relying on the default `
return res.json();
}}
agentName="Assistant"
-/>;
+/>
```
{/* add visual: flow-chart showing how threadApiUrl maps to list, create, update, delete, and load requests, and where messageFormat affects create/load payloads */}
diff --git a/docs/content/docs/chat/providers.mdx b/docs/content/docs/chat/providers.mdx
index 07d17164b..49423112a 100644
--- a/docs/content/docs/chat/providers.mdx
+++ b/docs/content/docs/chat/providers.mdx
@@ -11,12 +11,12 @@ For the core connection concepts, see [Connecting to LLM](/docs/chat/connecting)
## Common mappings
-| Backend pattern | `streamProtocol` | `messageFormat` | Use this when... |
-| :--- | :--- | :--- | :--- |
-| OpenUI Protocol | none | none | Your backend already emits the default OpenUI stream and accepts OpenUI messages |
-| Raw OpenAI Chat Completions SSE | `openAIAdapter()` | `openAIMessageFormat` when needed | You forward raw `data:` SSE chunks from Chat Completions |
-| OpenAI SDK `toReadableStream()` / NDJSON | `openAIReadableStreamAdapter()` | `openAIMessageFormat` when needed | You return `response.toReadableStream()` from the OpenAI SDK |
-| OpenAI Responses API | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` when needed | Your backend uses `openai.responses.create()` |
+| Backend pattern | `streamProtocol` | `messageFormat` | Use this when... |
+| :--------------------------------------- | :------------------------------ | :-------------------------------------------- | :------------------------------------------------------------------------------- |
+| OpenUI Protocol | none | none | Your backend already emits the default OpenUI stream and accepts OpenUI messages |
+| Raw OpenAI Chat Completions SSE | `openAIAdapter()` | `openAIMessageFormat` when needed | You forward raw `data:` SSE chunks from Chat Completions |
+| OpenAI SDK `toReadableStream()` / NDJSON | `openAIReadableStreamAdapter()` | `openAIMessageFormat` when needed | You return `response.toReadableStream()` from the OpenAI SDK |
+| OpenAI Responses API | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` when needed | Your backend uses `openai.responses.create()` |
Start with the backend output format. Then add `messageFormat` only if the request or stored-history message shape also differs from the OpenUI default.
@@ -63,10 +63,7 @@ Use `openAIResponsesAdapter()` for the Responses API event stream.
Add `openAIConversationMessageFormat` only if your backend also expects or stores Responses conversation items instead of the default AG-UI message shape.
```tsx
-import {
- openAIConversationMessageFormat,
- openAIResponsesAdapter,
-} from "@openuidev/react-headless";
+import { openAIConversationMessageFormat, openAIResponsesAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
<FullScreen
diff --git a/docs/content/docs/chat/quick-start.mdx b/docs/content/docs/chat/quick-start.mdx
index 1552515e5..41ba1a8e7 100644
--- a/docs/content/docs/chat/quick-start.mdx
+++ b/docs/content/docs/chat/quick-start.mdx
@@ -11,31 +11,11 @@ If you already have an existing Next.js app, use [Installation](/docs/chat/insta
Run the create command. This scaffolds a Next.js app with OpenUI Chat already wired to an OpenAI-backed route.
-<Tabs groupId="pkg" items={['npx', 'pnpm', 'yarn', 'bun']} persist>
- <Tab value="npx">
- ```bash
- npx @openuidev/cli@latest create
- cd genui-chat-app
- ```
- </Tab>
- <Tab value="pnpm">
- ```bash
- pnpm dlx @openuidev/cli@latest create
- cd genui-chat-app
- ```
- </Tab>
- <Tab value="yarn">
- ```bash
- yarn dlx @openuidev/cli@latest create
- cd genui-chat-app
- ```
- </Tab>
- <Tab value="bun">
- ```bash
- bunx @openuidev/cli@latest create
- cd genui-chat-app
- ```
- </Tab>
+<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>
+ <Tab value="npx">```bash npx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
+ <Tab value="pnpm">```bash pnpm dlx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
+ <Tab value="yarn">```bash yarn dlx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
+ <Tab value="bun">```bash bunx @openuidev/cli@latest create cd genui-chat-app ```</Tab>
</Tabs>
## 2. Add your API key
@@ -48,27 +28,11 @@ OPENAI_API_KEY=sk-your-key-here
## 3. Start the dev server
-<Tabs groupId="pkg" items={['npx', 'pnpm', 'yarn', 'bun']} persist>
- <Tab value="npx">
- ```bash
- npm run dev
- ```
- </Tab>
- <Tab value="pnpm">
- ```bash
- pnpm dev
- ```
- </Tab>
- <Tab value="yarn">
- ```bash
- yarn dev
- ```
- </Tab>
- <Tab value="bun">
- ```bash
- bun dev
- ```
- </Tab>
+<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>
+ <Tab value="npx">```bash npm run dev ```</Tab>
+ <Tab value="pnpm">```bash pnpm dev ```</Tab>
+ <Tab value="yarn">```bash yarn dev ```</Tab>
+ <Tab value="bun">```bash bun dev ```</Tab>
</Tabs>
Open [http://localhost:3000](http://localhost:3000) in your browser. You should see the default **FullScreen** chat. Try sending a message.
@@ -85,14 +49,12 @@ You do not need to recreate these files during quick start. This section is here
### The Frontend (`app/page.tsx`)
-The frontend renders `FullScreen`, sends requests with `processMessage`, relies on `messageFormat` for OpenAI message conversion, and parses the OpenAI SDK readable stream correctly.
+**The** frontend renders `FullScreen`, sends requests with `processMessage`, converts messages explicitly with `openAIMessageFormat.toApi(messages)`, and parses the OpenAI SDK readable stream correctly.
```tsx
import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
export default function Page() {
return (
@@ -102,13 +64,11 @@ export default function Page() {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- messages,
- systemPrompt,
+ messages: openAIMessageFormat.toApi(messages),
}),
signal: abortController.signal,
});
}}
- messageFormat={openAIMessageFormat}
streamProtocol={openAIReadableStreamAdapter()}
componentLibrary={openuiLibrary}
agentName="OpenUI Chat"
@@ -123,17 +83,13 @@ The scaffold also creates a Next.js route handler at `app/api/chat/route.ts`.
That route:
+- loads the system prompt generated by the CLI at build time
- receives OpenAI-format messages
-- optionally prepends `systemPrompt`
+- prepends the system prompt
- calls OpenAI Chat Completions with streaming enabled
- returns `response.toReadableStream()`
-That is why the frontend uses:
-
-- `processMessage` instead of a plain `apiUrl`
-- `messageFormat={openAIMessageFormat}` for request conversion
-- `openAIReadableStreamAdapter()` for stream parsing
-- `openuiLibrary` plus `systemPrompt` for GenUI rendering
+The scaffold includes a prebuild step (`openui generate`) that creates the system prompt from your component library. This keeps the prompt on the server — it is never sent from the frontend.
## Next steps
diff --git a/docs/content/docs/chat/theming.mdx b/docs/content/docs/chat/theming.mdx
index 59b35ea52..b490885ea 100644
--- a/docs/content/docs/chat/theming.mdx
+++ b/docs/content/docs/chat/theming.mdx
@@ -15,11 +15,7 @@ There are two common theming paths:
```tsx
import { FullScreen } from "@openuidev/react-ui";
-<FullScreen
- apiUrl="/api/chat"
- theme={{ mode: "dark" }}
- agentName="Assistant"
-/>;
+<FullScreen apiUrl="/api/chat" theme={{ mode: "dark" }} agentName="Assistant" />;
```
## Override theme tokens
@@ -53,11 +49,7 @@ If your app already wraps the page in `ThemeProvider`, disable the built-in wrap
```tsx
import { FullScreen } from "@openuidev/react-ui";
-<FullScreen
- apiUrl="/api/chat"
- disableThemeProvider
- agentName="Assistant"
-/>;
+<FullScreen apiUrl="/api/chat" disableThemeProvider agentName="Assistant" />;
```
`disableThemeProvider` only skips the wrapper. It does not remove any chat functionality.
diff --git a/docs/content/docs/chat/welcome.mdx b/docs/content/docs/chat/welcome.mdx
index 8e765ca8d..280bd3556 100644
--- a/docs/content/docs/chat/welcome.mdx
+++ b/docs/content/docs/chat/welcome.mdx
@@ -70,7 +70,7 @@ Use `variant="short"` for compact pill buttons or `variant="long"` for more desc
],
}}
agentName="Assistant"
-/>;
+/>
```
{/* add visual: image showing the empty state with a welcome message and both short and long conversation starter variants */}
diff --git a/docs/content/docs/openui-lang/components/how-it-works.tsx b/docs/content/docs/openui-lang/components/how-it-works.tsx
index 9a689698b..f15722386 100644
--- a/docs/content/docs/openui-lang/components/how-it-works.tsx
+++ b/docs/content/docs/openui-lang/components/how-it-works.tsx
@@ -1,9 +1,9 @@
"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 { SimpleCard } from "@/components/overview-components/simple-card";
import { ArrowRight } from "lucide-react";
+import { useState } from "react";
const steps = [
{
@@ -45,7 +45,6 @@ learnMoreBtn = Button("Learn more", "action:learn_more", "secondary")
},
];
-
export const HowItWorks = () => {
const [activeStep, setActiveStep] = useState(0);
return (
@@ -59,10 +58,11 @@ export const HowItWorks = () => {
<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"
- }`}
+ 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>
@@ -104,4 +104,4 @@ export const HowItWorks = () => {
</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
index 97c21a067..7ab270a76 100644
--- a/docs/content/docs/openui-lang/components/lang-example.tsx
+++ b/docs/content/docs/openui-lang/components/lang-example.tsx
@@ -9,8 +9,8 @@ import {
TabsTrigger,
} from "@/components/overview-components";
import { genuiOutput } from "@/components/overview-components/genui";
-import { openuiLibrary } from "@openuidev/react-ui";
import { Renderer } from "@openuidev/react-lang";
+import { openuiLibrary } from "@openuidev/react-ui";
const renderableOutput = `root = Stack([welcomeCard])
welcomeCard = Card([welcomeHeader, welcomeBody])
@@ -119,5 +119,5 @@ const completion = await client.chat.completions.create({
</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
index e4b7178b2..545fc3aff 100644
--- a/docs/content/docs/openui-lang/components/try-it-out.tsx
+++ b/docs/content/docs/openui-lang/components/try-it-out.tsx
@@ -1,39 +1,40 @@
"use client";
-import { useState } from "react";
+import { ChatModal } from "@/components/overview-components/chat-modal";
import { ArrowUpRight } from "lucide-react";
import Image from "next/image";
-import { ChatModal } from "@/components/overview-components/chat-modal";
+import { useState } from "react";
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>
+ 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>
- <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" />
+ {isChatModalOpen && <ChatModal onClose={() => setIsChatModalOpen(false)} />}
</div>
- {isChatModalOpen && <ChatModal onClose={() => setIsChatModalOpen(false)} />}
- </div>
);
-}
\ No newline at end of file
+};
diff --git a/docs/content/docs/openui-lang/defining-components.mdx b/docs/content/docs/openui-lang/defining-components.mdx
index c4a70b18d..f0e1075cb 100644
--- a/docs/content/docs/openui-lang/defining-components.mdx
+++ b/docs/content/docs/openui-lang/defining-components.mdx
@@ -84,6 +84,26 @@ const TabItemSchema = z.object({
});
```
+## The `root` field
+
+The `root` option in `createLibrary` specifies which component the LLM must use as the entry point. The generated system prompt instructs the model to always start with `root = <RootName>(...)`.
+
+```ts
+const library = createLibrary({
+ root: "Stack", // → prompt tells LLM: "every program must define root = Stack(...)"
+ components: [Stack, Card, TextContent],
+});
+```
+
+This serves two purposes:
+
+1. **Constrains the LLM** — the model always wraps its output in a known top-level component, making output predictable.
+2. **Enables streaming** — because the root statement comes first, the UI shell renders immediately while child components stream in.
+
+The `root` must match the `name` of one of the components in your library. If omitted, the prompt uses "Root" as a placeholder.
+
+For the built-in libraries: `openuiLibrary` uses `Stack` (flexible layout container), while `openuiChatLibrary` uses `Card` (vertical container optimized for chat responses).
+
## Notes on schema metadata
- Positional mapping is driven by Zod object key order.
@@ -103,6 +123,67 @@ const library = createLibrary({
});
```
+### Why group components?
+
+`componentGroups` organize the generated system prompt into named sections (e.g., Layout, Forms, Charts). This helps the LLM locate relevant components quickly instead of scanning a flat list. Without groups, all component signatures appear under a single "Ungrouped" heading.
+
+Groups also let you co-locate related components so the LLM understands which components work together (e.g., `Form` with `FormControl`, `Input`, `Select`).
+
+### Adding group notes
+
+Each group can include a `notes` array — these strings are appended directly after the group's component signatures in the generated prompt. Use notes to give the LLM usage hints and constraints:
+
+```ts
+componentGroups: [
+ {
+ name: "Forms",
+ components: ["Form", "FormControl", "Input", "TextArea", "Select"],
+ notes: [
+ "- Define EACH FormControl as its own reference for progressive streaming.",
+ "- NEVER nest Form inside Form.",
+ "- Form requires explicit buttons: Form(name, buttons, fields).",
+ ],
+ },
+ {
+ name: "Layout",
+ components: ["Stack", "Tabs", "TabItem", "Accordion", "AccordionItem"],
+ notes: [
+ '- For grid-like layouts, use Stack with direction "row" and wrap=true.',
+ ],
+ },
+],
+```
+
+Notes appear in the prompt output like this:
+
+```
+### Forms
+Form(id: string, buttons: Buttons, controls: FormControl[]) — Form container
+FormControl(label: string, field: Input | TextArea | Select) — Single field
+...
+- Define EACH FormControl as its own reference for progressive streaming.
+- NEVER nest Form inside Form.
+- Form requires explicit buttons: Form(name, buttons, fields).
+```
+
+### Prompt options
+
+When generating the system prompt, you can pass `PromptOptions` to customize the output further:
+
+```ts
+import type { PromptOptions } from "@openuidev/react-lang";
+
+const options: PromptOptions = {
+ preamble: "You are an assistant that outputs only OpenUI Lang.",
+ additionalRules: ["Always use Card as the root for chat responses."],
+ examples: [`root = Stack([title])\ntitle = TextContent("Hello", "large-heavy")`],
+};
+
+const prompt = library.prompt(options);
+```
+
+See [System Prompts](/docs/openui-lang/system-prompts) for full details on prompt generation.
+
## Next Steps
<Cards>
diff --git a/docs/content/docs/openui-lang/index.mdx b/docs/content/docs/openui-lang/index.mdx
index 8d678f368..8d90e47d4 100644
--- a/docs/content/docs/openui-lang/index.mdx
+++ b/docs/content/docs/openui-lang/index.mdx
@@ -4,22 +4,19 @@ title: Introduction
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.
+OpenUI is a full-stack Generative UI framework — a compact streaming-first language, a React runtime with built-in component libraries, and ready-to-use chat interfaces — that is up to **[67% more token-efficient](/docs/openui-lang/benchmarks)** than JSON.
## 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.
+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. For the complete syntax reference, see the [Language Specification](/docs/openui-lang/specification).
### Why a New Language?
@@ -37,22 +34,14 @@ OpenUI Lang was created to solve these core issues:
## 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.
+<img src="/images/openui-lang/openui-chart-flow.png" alt="Architecture diagram" />
-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])`).
+The key difference from a standard chat app is what happens at the LLM and rendering layers:
-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.
+1. **System prompt includes OpenUI Lang spec** — Your backend appends the generated component library prompt alongside your system prompt, instructing the LLM to respond in OpenUI Lang instead of plain text or JSON.
-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.
+2. **LLM generates OpenUI Lang** — Instead of returning markdown, the model outputs a compact, line-oriented syntax (e.g., `root = Stack([chart])`) constrained to your component library.
-## Usage Example
+3. **Streaming render** — On the client, the `<Renderer />` component parses each line as it arrives and maps it to your React components in real-time — structure first, then data fills in progressively.
-<LangExample />
\ No newline at end of file
+The result is a native UI — like the "Total expenses" card and interactive pie chart above — dynamically composed by the AI, streamed efficiently, and rendered safely from your own components.
diff --git a/docs/content/docs/openui-lang/interactivity.mdx b/docs/content/docs/openui-lang/interactivity.mdx
index dd2324cea..795781a48 100644
--- a/docs/content/docs/openui-lang/interactivity.mdx
+++ b/docs/content/docs/openui-lang/interactivity.mdx
@@ -25,13 +25,13 @@ When a user clicks a button or follow-up, the component calls `triggerAction`. T
### `ActionEvent`
-| Field | Type | Description |
-| :--------------------- | :------------------------------ | :--------------------------------------------- |
-| `type` | `string` | Action type (see built-in types below). |
-| `params` | `Record<string, any>` | Extra parameters from the component. |
-| `humanFriendlyMessage` | `string` | Display label for the action. |
-| `formState` | `Record<string, any> \| undefined` | Raw field state at time of action. |
-| `formName` | `string \| undefined` | Form that scoped the action, if any. |
+| Field | Type | Description |
+| :--------------------- | :--------------------------------- | :-------------------------------------- |
+| `type` | `string` | Action type (see built-in types below). |
+| `params` | `Record<string, any>` | Extra parameters from the component. |
+| `humanFriendlyMessage` | `string` | Display label for the action. |
+| `formState` | `Record<string, any> \| undefined` | Raw field state at time of action. |
+| `formName` | `string \| undefined` | Form that scoped the action, if any. |
### Built-in action types
@@ -91,12 +91,12 @@ Use `onStateUpdate` to persist field state (e.g. to a message in your thread sto
Use these inside `defineComponent` renderers:
-| Hook | Signature | Description |
-| :------------------ | :------------------------------------------------------------------------------------------------- | :--------------------------------- |
-| `useGetFieldValue` | `(formName: string \| undefined, name: string) => any` | Read a field's current value. |
-| `useSetFieldValue` | `(formName: string \| undefined, componentType: string \| undefined, name: string, value: any, shouldTriggerSaveCallback?: boolean) => void` | Write a field value. |
-| `useFormName` | `() => string \| undefined` | Get the enclosing form's name. |
-| `useSetDefaultValue`| `(options: { formName?, componentType, name, existingValue, defaultValue, shouldTriggerSaveCallback? }) => void` | Set a default if no value exists. |
+| Hook | Signature | Description |
+| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------- |
+| `useGetFieldValue` | `(formName: string \| undefined, name: string) => any` | Read a field's current value. |
+| `useSetFieldValue` | `(formName: string \| undefined, componentType: string \| undefined, name: string, value: any, shouldTriggerSaveCallback?: boolean) => void` | Write a field value. |
+| `useFormName` | `() => string \| undefined` | Get the enclosing form's name. |
+| `useSetDefaultValue` | `(options: { formName?, componentType, name, existingValue, defaultValue, shouldTriggerSaveCallback? }) => void` | Set a default if no value exists. |
---
diff --git a/docs/content/docs/openui-lang/meta.json b/docs/content/docs/openui-lang/meta.json
index 129b06186..11bc1aede 100644
--- a/docs/content/docs/openui-lang/meta.json
+++ b/docs/content/docs/openui-lang/meta.json
@@ -5,6 +5,7 @@
"index",
"quickstart",
"---Core Concepts---",
+ "overview",
"defining-components",
"system-prompts",
"renderer",
diff --git a/docs/content/docs/openui-lang/overview.mdx b/docs/content/docs/openui-lang/overview.mdx
new file mode 100644
index 000000000..98a32c6fe
--- /dev/null
+++ b/docs/content/docs/openui-lang/overview.mdx
@@ -0,0 +1,98 @@
+---
+title: Overview
+description: Key building blocks of the OpenUI framework and the built-in component libraries.
+---
+
+import { LangExample } from "./components/lang-example";
+
+OpenUI is built around four core building blocks that work together to turn LLM output into rendered UI:
+
+- **Library** — A collection of components defined with Zod schemas and React renderers. The library is the contract between your app and the AI — it defines what components the LLM can use and how they render.
+
+- **Prompt Generator** — Converts your library into a system prompt that instructs the LLM to output valid OpenUI Lang. Includes syntax rules, component signatures, streaming guidelines, and your custom examples/rules.
+
+- **Parser** — Parses OpenUI Lang text (line-by-line, streaming-compatible) into a typed element tree. Validates against your library's JSON Schema and gracefully handles partial/invalid output.
+
+- **Renderer** — The `<Renderer />` React component takes parsed output and maps each element to your library's React components, rendering the UI progressively as the stream arrives.
+
+## Built-in Component Libraries
+
+OpenUI ships with two ready-to-use libraries via `@openuidev/react-ui`. Both include layouts, content blocks, charts, forms, tables, and more.
+
+### General-purpose library (`openuiLibrary`)
+
+Root component is `Stack`. Includes the full component suite with flexible layout primitives. Use this for standalone rendering, playgrounds, and non-chat interfaces.
+
+```ts
+import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
+import { Renderer } from "@openuidev/react-lang";
+
+// Generate system prompt
+const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+
+// Render streamed output
+<Renderer library={openuiLibrary} response={streamedText} isStreaming={isStreaming} />
+```
+
+### Chat-optimized library (`openuiChatLibrary`)
+
+Root component is `Card` (vertical container, no layout params). Adds chat-specific components like `FollowUpBlock`, `ListBlock`, and `SectionBlock`. Does not include `Stack` — responses are always single-card, vertically stacked.
+
+```ts
+import { openuiChatLibrary, openuiChatPromptOptions } from "@openuidev/react-ui/genui-lib";
+import { FullScreen } from "@openuidev/react-ui";
+
+// Use with a chat layout
+<FullScreen
+ componentLibrary={openuiChatLibrary}
+ processMessage={...}
+ streamProtocol={openAIAdapter()}
+/>
+```
+
+Both libraries expose a `.prompt()` method to generate the system prompt your LLM needs. See [System Prompts](/docs/openui-lang/system-prompts) for CLI and programmatic generation options.
+
+### Extend a built-in library
+
+```ts
+import { createLibrary, defineComponent } from "@openuidev/react-lang";
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
+import { z } from "zod";
+
+const ProductCard = defineComponent({
+ name: "ProductCard",
+ description: "Product tile",
+ props: z.object({
+ name: z.string(),
+ price: z.number(),
+ }),
+ component: ({ props }) => <div>{props.name}: ${props.price}</div>,
+});
+
+const myLibrary = createLibrary({
+ root: openuiLibrary.root ?? "Stack",
+ componentGroups: openuiLibrary.componentGroups,
+ components: [...Object.values(openuiLibrary.components), ProductCard],
+});
+```
+
+## Usage Example
+
+<LangExample />
+
+## Next Steps
+
+<Cards>
+ <Card title="Defining Components" href="/docs/openui-lang/defining-components">
+ Create custom components with Zod schemas and React renderers.
+ </Card>
+ <Card title="System Prompts" href="/docs/openui-lang/system-prompts">
+ Generate and customize LLM instructions from your library.
+ </Card>
+ <Card title="The Renderer" href="/docs/openui-lang/renderer">
+ Parse and render streamed OpenUI Lang in React.
+ </Card>
+ <Card title="Chat Integration" href="/docs/chat">
+ Build AI chat interfaces with prebuilt layouts.
+ </Card>
+</Cards>
diff --git a/docs/content/docs/openui-lang/quickstart.mdx b/docs/content/docs/openui-lang/quickstart.mdx
index 4fd33290b..fc19f1c02 100644
--- a/docs/content/docs/openui-lang/quickstart.mdx
+++ b/docs/content/docs/openui-lang/quickstart.mdx
@@ -1,28 +1,65 @@
---
title: Quick Start
-description: Use the OpenUI library to render OpenUI Lang immediately.
+description: Bootstrap a Generative UI chat app in under a minute.
---
-
-#### Bootstrap a GenUI Chat app
+## Bootstrap a GenUI Chat app
```bash
npx @openuidev/cli@latest create --name genui-chat-app
cd genui-chat-app
```
-#### Add your API key
+## Add your API key
+
+The generated app uses OpenAI by default, but works with any OpenAI-compatible provider (e.g., OpenRouter, Azure OpenAI, Anthropic via proxy).
```bash
echo "OPENAI_API_KEY=sk-your-key-here" > .env
```
-#### Start the dev server
+## Start the dev server
```bash
npm run dev
```
-The generated app wires up a predefined component library in `src/app/page.tsx`.
+## What's included
+
+The CLI generates a Next.js app with everything wired up:
+
+```
+src/
+ app/
+ page.tsx # FullScreen chat layout with the built-in component library
+ api/chat/
+ route.ts # Backend route with OpenAI streaming + example tools
+ library.ts # Re-exports openuiChatLibrary and openuiChatPromptOptions
+ generated/
+ system-prompt.txt # Auto-generated at build time via `openui generate`
+```
+
+- **`page.tsx`** — Renders the `FullScreen` chat layout with `openuiChatLibrary` for Generative UI rendering and `openAIAdapter()` for streaming.
+- **`route.ts`** — A backend API route that sends the system prompt to the LLM and streams the response back.
+- **`library.ts`** — Your component library entrypoint. The `openui generate` CLI reads this file to produce the system prompt.
+
+The `dev` and `build` scripts automatically regenerate the system prompt before starting:
+
+```json
+"generate:prompt": "openui generate src/library.ts --out src/generated/system-prompt.txt",
+"dev": "pnpm generate:prompt && next dev"
+```
+
+## Next Steps
-Follow guide: [Define Your Components](/docs/openui-lang/defining-components) to learn how to create your own component library.
+<Cards>
+ <Card title="Overview" href="/docs/openui-lang/overview">
+ Understand the key building blocks and built-in component libraries.
+ </Card>
+ <Card title="Defining Components" href="/docs/openui-lang/defining-components">
+ Create your own custom component library.
+ </Card>
+ <Card title="Chat Quick Start" href="/docs/chat/quick-start">
+ Explore chat-specific layouts and configurations.
+ </Card>
+</Cards>
diff --git a/docs/content/docs/openui-lang/renderer.mdx b/docs/content/docs/openui-lang/renderer.mdx
index 9e528362e..58adcadba 100644
--- a/docs/content/docs/openui-lang/renderer.mdx
+++ b/docs/content/docs/openui-lang/renderer.mdx
@@ -24,15 +24,15 @@ export function AssistantMessage({
## Props
-| Prop | Type | Description |
-| :--------------- | :-------------------------------------- | :------------------------------------------------------------- |
-| `response` | `string \| null` | Raw OpenUI Lang response text. |
-| `library` | `Library` | Library created by `createLibrary(...)`. |
-| `isStreaming` | `boolean` | Indicates stream is in progress. |
-| `onAction` | `(event: ActionEvent) => void` | Receives structured action events from interactive components. |
-| `onStateUpdate` | `(state: Record<string, any>) => void` | Called on form field changes with the raw field state map. |
-| `initialState` | `Record<string, any>` | Hydrates form state on load (e.g. from persisted message). |
-| `onParseResult` | `(result: ParseResult \| null) => void` | Debug/inspect latest parse result. |
+| Prop | Type | Description |
+| :-------------- | :-------------------------------------- | :------------------------------------------------------------- |
+| `response` | `string \| null` | Raw OpenUI Lang response text. |
+| `library` | `Library` | Library created by `createLibrary(...)`. |
+| `isStreaming` | `boolean` | Indicates stream is in progress. |
+| `onAction` | `(event: ActionEvent) => void` | Receives structured action events from interactive components. |
+| `onStateUpdate` | `(state: Record<string, any>) => void` | Called on form field changes with the raw field state map. |
+| `initialState` | `Record<string, any>` | Hydrates form state on load (e.g. from persisted message). |
+| `onParseResult` | `(result: ParseResult \| null) => void` | Debug/inspect latest parse result. |
## Streaming behavior
diff --git a/docs/content/docs/openui-lang/standard-library.mdx b/docs/content/docs/openui-lang/standard-library.mdx
index 0c71f9f74..dd754fa5d 100644
--- a/docs/content/docs/openui-lang/standard-library.mdx
+++ b/docs/content/docs/openui-lang/standard-library.mdx
@@ -23,6 +23,14 @@ import { openuiLibrary } from "@openuidev/react-ui";
## Generate prompt
+Use the CLI to generate the system prompt at build time:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts --out src/generated/system-prompt.txt
+```
+
+Or generate programmatically:
+
```ts
import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
diff --git a/docs/content/docs/openui-lang/system-prompts.mdx b/docs/content/docs/openui-lang/system-prompts.mdx
index 8072cd4bd..fc522a348 100644
--- a/docs/content/docs/openui-lang/system-prompts.mdx
+++ b/docs/content/docs/openui-lang/system-prompts.mdx
@@ -3,9 +3,31 @@ title: System Prompts
description: Generate and customize prompt instructions from your OpenUI library.
---
-`library.prompt(...)` generates the instruction text your model needs to output valid OpenUI Lang.
+`library.prompt(...)` generates the instruction text your model needs to output valid OpenUI Lang. You can generate it programmatically or with the CLI.
-## Generate prompt
+## Generate with the CLI
+
+The fastest way to generate a system prompt — works with any backend language:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts
+```
+
+Write to a file:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts --out system-prompt.txt
+```
+
+Generate JSON Schema instead:
+
+```bash
+npx @openuidev/cli generate ./src/library.ts --json-schema
+```
+
+The CLI auto-detects exported `PromptOptions` (examples, rules) alongside your library. Use `--prompt-options <name>` to pick a specific export.
+
+## Generate programmatically
```ts
import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
@@ -46,7 +68,7 @@ The generated prompt includes:
```ts
import OpenAI from "openai";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
+import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
@@ -56,13 +78,12 @@ export async function POST(req: Request) {
const completion = await client.chat.completions.create({
model: "gpt-5.2",
stream: true,
- messages: [
- { role: "system", content: openuiLibrary.prompt(openuiPromptOptions) },
- ...messages,
- ],
+ messages: [{ role: "system", content: openuiLibrary.prompt(openuiPromptOptions) }, ...messages],
});
- return new Response("stream here");
+ return new Response(completion.toReadableStream(), {
+ headers: { "Content-Type": "text/event-stream" },
+ });
}
```
diff --git a/docs/generated/chat-system-prompt.txt b/docs/generated/chat-system-prompt.txt
new file mode 100644
index 000000000..b655c131e
--- /dev/null
+++ b/docs/generated/chat-system-prompt.txt
@@ -0,0 +1,202 @@
+You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.
+
+## Syntax Rules
+
+1. Each statement is on its own line: `identifier = Expression`
+2. `root` is the entry point — every program must define `root = Card(...)`
+3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)
+4. Use references for readability: define `name = ...` on one line, then use `name` later
+5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.
+6. Arguments are POSITIONAL (order matters, not names)
+7. Optional arguments can be omitted from the end
+8. No operators, no logic, no variables — only declarations
+9. Strings use double quotes with backslash escaping
+
+## Component Signatures
+
+Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.
+The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).
+
+### Content
+CardHeader(title?: string, subtitle?: string) — Header with optional title and subtitle
+TextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".
+MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant
+Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Callout banner with variant, title, and description
+TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and description
+Image(alt: string, src?: string) — Image with alt text and optional URL
+ImageBlock(src: string, alt?: string) — Image block with loading state
+ImageGallery(images: {src: string, alt?: string, details?: string}[]) — Gallery grid of images with modal preview
+CodeBlock(language: string, codeString: string) — Syntax-highlighted code block
+Separator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections
+
+### Tables
+Table(columns: Col[], rows: (string | number | boolean)[][]) — Data table
+Col(label: string, type?: "string" | "number" | "action") — Column definition
+
+### Charts (2D)
+BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series
+LineChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Lines over categories; use for trends and continuous data over time
+AreaChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Filled area under lines; use for cumulative totals or volume trends over time
+RadarChart(labels: string[], series: Series[]) — Spider/web chart; use for comparing multiple variables across one or more entities
+HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Horizontal bars; prefer when category labels are long or for ranked lists
+Series(category: string, values: number[]) — One data series
+
+### Charts (1D)
+PieChart(slices: Slice[], variant?: "pie" | "donut") — Circular slices showing part-to-whole proportions; supports pie and donut variants
+RadialChart(slices: Slice[]) — Radial bars showing proportional distribution across named segments
+SingleStackedBarChart(slices: Slice[]) — Single horizontal stacked bar; use for showing part-to-whole proportions in one row
+Slice(category: string, value: number) — One slice with label and numeric value
+
+### Charts (Scatter)
+ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string) — X/Y scatter plot; use for correlations, distributions, and clustering
+ScatterSeries(name: string, points: Point[]) — Named dataset
+Point(x: number, y: number, z?: number) — Data point with numeric coordinates
+
+### Forms
+Form(name: string, buttons: Buttons, fields) — Form container with fields and explicit action buttons
+FormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint text
+Label(text: string) — Text label
+Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+SelectItem(value: string, label: string) — Option for Select
+DatePicker(name: string, mode: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}) — Numeric slider input; supports continuous and discrete (stepped) variants
+CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)
+RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+RadioItem(label: string, description: string, value: string)
+SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk") — Group of switch toggles
+SwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle
+- Define EACH FormControl as its own reference — do NOT inline all controls in one array.
+- NEVER nest Form inside Form.
+- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.
+- rules is an optional object: { required: true, email: true, min: 8, maxLength: 100 }
+- The renderer shows error messages automatically — do NOT generate error text in the UI
+
+### Buttons
+Button(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button
+Buttons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".
+
+### Lists & Follow-ups
+ListBlock(items: ListItem[], variant?: "number" | "image") — A list of items with number or image indicators. Each item can optionally have an action.
+ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.
+FollowUpBlock(items: FollowUpItem[]) — List of clickable follow-up suggestions placed at the end of a response
+FollowUpItem(text: string) — Clickable follow-up suggestion — when clicked, sends text as user message
+- Use ListBlock with ListItem references for numbered, clickable lists.
+- Use FollowUpBlock with FollowUpItem references at the end of a response to suggest next actions.
+- Clicking a ListItem or FollowUpItem sends its text to the LLM as a user message.
+- Example: list = ListBlock([item1, item2]) item1 = ListItem("Option A", "Details about A")
+
+### Sections
+SectionBlock(sections: SectionItem[], isFoldable?: boolean) — Collapsible accordion sections. Auto-opens sections as they stream in. Use SectionItem for each section.
+SectionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock)[]) — Section with a label and collapsible content — used inside SectionBlock
+- SectionBlock renders collapsible accordion sections that auto-open as they stream.
+- Each section needs a unique `value` id, a `trigger` label, and a `content` array.
+- Example: sections = SectionBlock([s1, s2]) s1 = SectionItem("intro", "Introduction", [content1])
+- Set isFoldable=false to render sections as flat headers instead of accordion.
+
+### Layout
+Tabs(items: TabItem[]) — Tabbed container
+TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is tab label, content is array of components
+Accordion(items: AccordionItem[]) — Collapsible sections
+AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is section title
+Steps(items: StepsItem[]) — Step-by-step guide
+StepsItem(title: string, details: string) — title and details text for one step
+Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: "card" | "sunk") — Horizontal scrollable carousel
+- Use Tabs to present alternative views — each TabItem has a value id, trigger label, and content array.
+- Carousel takes an array of slides, where each slide is an array of content: carousel = Carousel([[t1, img1], [t2, img2]])
+- IMPORTANT: Every slide in a Carousel must have the same structure — same component types in the same order.
+- For image carousels use: [[title, image, description, tags], ...] — every slide must follow this exact pattern.
+- Use real, publicly accessible image URLs (e.g. https://picsum.photos/seed/KEYWORD/800/500). Never hallucinate image URLs.
+
+### Data Display
+TagBlock(tags: string[]) — tags is an array of strings
+Tag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant
+
+### Ungrouped
+Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock | SectionBlock | Tabs | Carousel)[]) — Vertical container for all content in a chat response. Children stack top to bottom automatically.
+
+## Hoisting & Streaming (CRITICAL)
+
+openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.
+
+During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.
+
+**Recommended statement order for optimal streaming:**
+1. `root = Card(...)` — UI shell appears immediately
+2. Component definitions — fill in as they stream
+3. Data values — leaf content last
+
+Always write the root = Card(...) statement first so the UI shell appears immediately, even before child data has streamed in.
+
+## Examples
+
+Example 1 — Table with follow-ups:
+root = Card([title, tbl, followUps])
+title = TextContent("Top Languages", "large-heavy")
+tbl = Table(cols, rows)
+cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]
+rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995]]
+followUps = FollowUpBlock([fu1, fu2])
+fu1 = FollowUpItem("Tell me more about Python")
+fu2 = FollowUpItem("Show me a JavaScript comparison")
+
+Example 2 — Clickable list:
+root = Card([title, list])
+title = TextContent("Choose a topic", "large-heavy")
+list = ListBlock([item1, item2, item3])
+item1 = ListItem("Getting started", "New to the platform? Start here.")
+item2 = ListItem("Advanced features", "Deep dives into powerful capabilities.")
+item3 = ListItem("Troubleshooting", "Common issues and how to fix them.")
+
+Example 3 — Image carousel with consistent slides + follow-ups:
+root = Card([header, carousel, followups])
+header = CardHeader("Featured Destinations", "Discover highlights and best time to visit")
+carousel = Carousel([[t1, img1, d1, tags1], [t2, img2, d2, tags2], [t3, img3, d3, tags3]], "card")
+t1 = TextContent("Paris, France", "large-heavy")
+img1 = ImageBlock("https://picsum.photos/seed/paris/800/500", "Eiffel Tower at night")
+d1 = TextContent("City of light — best Apr–Jun and Sep–Oct.", "default")
+tags1 = TagBlock(["Landmark", "City Break", "Culture"])
+t2 = TextContent("Kyoto, Japan", "large-heavy")
+img2 = ImageBlock("https://picsum.photos/seed/kyoto/800/500", "Bamboo grove in Arashiyama")
+d2 = TextContent("Temples and bamboo groves — best Mar–Apr and Nov.", "default")
+tags2 = TagBlock(["Temples", "Autumn", "Culture"])
+t3 = TextContent("Machu Picchu, Peru", "large-heavy")
+img3 = ImageBlock("https://picsum.photos/seed/machupicchu/800/500", "Inca citadel in the clouds")
+d3 = TextContent("High-altitude Inca citadel — best May–Sep.", "default")
+tags3 = TagBlock(["Andes", "Hike", "UNESCO"])
+followups = FollowUpBlock([fu1, fu2])
+fu1 = FollowUpItem("Show me only beach destinations")
+fu2 = FollowUpItem("Turn this into a comparison table")
+
+Example 4 — Form with validation:
+root = Card([title, form])
+title = TextContent("Contact Us", "large-heavy")
+form = Form("contact", btns, [nameField, emailField, msgField])
+nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))
+emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))
+msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))
+btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary")])
+
+## Important Rules
+- ALWAYS start with root = Card(...)
+- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)
+- Each statement on its own line
+- No trailing text or explanations — output ONLY openui-lang code
+- When asked about data, generate realistic/plausible data
+- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)
+- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.
+
+- Every response is a single Card(children) — children stack vertically automatically. No layout params are needed on Card.
+- Card is the only layout container. Do NOT use Stack. Use Tabs to switch between sections, Carousel for horizontal scroll.
+- Use FollowUpBlock at the END of a Card to suggest what the user can do or ask next.
+- Use ListBlock when presenting a set of options or steps the user can click to select.
+- Use SectionBlock to group long responses into collapsible sections — good for reports, FAQs, and structured content.
+- Use SectionItem inside SectionBlock: each item needs a unique value id, a trigger (header label), and a content array.
+- Carousel takes an array of slides, where each slide is an array of content: carousel = Carousel([[t1, img1], [t2, img2]])
+- IMPORTANT: Every slide in a Carousel must use the same component structure in the same order — e.g. all slides: [title, image, description, tags].
+- For image carousels, always use real accessible URLs like https://picsum.photos/seed/KEYWORD/800/500. Never hallucinate or invent image URLs.
+- For forms, define one FormControl reference per field so controls can stream progressively.
+- For forms, always provide the second Form argument with Buttons(...) actions: Form(name, buttons, fields).
+- Never nest Form inside Form.
diff --git a/docs/generated/playground-system-prompt.txt b/docs/generated/playground-system-prompt.txt
new file mode 100644
index 000000000..382a5ecd8
--- /dev/null
+++ b/docs/generated/playground-system-prompt.txt
@@ -0,0 +1,157 @@
+You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.
+
+## Syntax Rules
+
+1. Each statement is on its own line: `identifier = Expression`
+2. `root` is the entry point — every program must define `root = Stack(...)`
+3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)
+4. Use references for readability: define `name = ...` on one line, then use `name` later
+5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.
+6. Arguments are POSITIONAL (order matters, not names)
+7. Optional arguments can be omitted from the end
+8. No operators, no logic, no variables — only declarations
+9. Strings use double quotes with backslash escaping
+
+## Component Signatures
+
+Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.
+The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).
+
+### Layout
+Stack([children], direction?: "row" | "column", gap?: "none" | "xs" | "s" | "m" | "l" | "xl" | "2xl", align?: "start" | "center" | "end" | "stretch" | "baseline", justify?: "start" | "center" | "end" | "between" | "around" | "evenly", wrap?: boolean) — Flex container. direction: "row"|"column" (default "column"). gap: "none"|"xs"|"s"|"m"|"l"|"xl"|"2xl" (default "m"). align: "start"|"center"|"end"|"stretch"|"baseline". justify: "start"|"center"|"end"|"between"|"around"|"evenly".
+Tabs(items: TabItem[]) — Tabbed container
+TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is tab label, content is array of components
+Accordion(items: AccordionItem[]) — Collapsible sections
+AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is section title
+Steps(items: StepsItem[]) — Step-by-step guide
+StepsItem(title: string, details: string) — title and details text for one step
+Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: "card" | "sunk") — Horizontal scrollable carousel
+Separator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections
+- For grid-like layouts, use Stack with direction "row" and wrap set to true.
+- Prefer justify "start" (or omit justify) with wrap=true for stable columns instead of uneven gutters.
+- Use nested Stacks when you need explicit rows/sections.
+
+### Content
+Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | Tabs | Carousel | Stack)[], variant?: "card" | "sunk" | "clear", direction?: "row" | "column", gap?: "none" | "xs" | "s" | "m" | "l" | "xl" | "2xl", align?: "start" | "center" | "end" | "stretch" | "baseline", justify?: "start" | "center" | "end" | "between" | "around" | "evenly", wrap?: boolean) — Styled container. variant: "card" (default, elevated) | "sunk" (recessed) | "clear" (transparent). Always full width. Accepts all Stack flex params (default: direction "column"). Cards flex to share space in row/wrap layouts.
+CardHeader(title?: string, subtitle?: string) — Header with optional title and subtitle
+TextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".
+MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant
+Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Callout banner with variant, title, and description
+TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and description
+Image(alt: string, src?: string) — Image with alt text and optional URL
+ImageBlock(src: string, alt?: string) — Image block with loading state
+ImageGallery(images: {src: string, alt?: string, details?: string}[]) — Gallery grid of images with modal preview
+CodeBlock(language: string, codeString: string) — Syntax-highlighted code block
+
+### Tables
+Table(columns: Col[], rows: (string | number | boolean)[][]) — Data table
+Col(label: string, type?: "string" | "number" | "action") — Column definition
+
+### Charts (2D)
+BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series
+LineChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Lines over categories; use for trends and continuous data over time
+AreaChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Filled area under lines; use for cumulative totals or volume trends over time
+RadarChart(labels: string[], series: Series[]) — Spider/web chart; use for comparing multiple variables across one or more entities
+HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Horizontal bars; prefer when category labels are long or for ranked lists
+Series(category: string, values: number[]) — One data series
+
+### Charts (1D)
+PieChart(slices: Slice[], variant?: "pie" | "donut") — Circular slices showing part-to-whole proportions; supports pie and donut variants
+RadialChart(slices: Slice[]) — Radial bars showing proportional distribution across named segments
+SingleStackedBarChart(slices: Slice[]) — Single horizontal stacked bar; use for showing part-to-whole proportions in one row
+Slice(category: string, value: number) — One slice with label and numeric value
+
+### Charts (Scatter)
+ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string) — X/Y scatter plot; use for correlations, distributions, and clustering
+ScatterSeries(name: string, points: Point[]) — Named dataset
+Point(x: number, y: number, z?: number) — Data point with numeric coordinates
+
+### Forms
+Form(name: string, buttons: Buttons, fields) — Form container with fields and explicit action buttons
+FormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint text
+Label(text: string) — Text label
+Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+SelectItem(value: string, label: string) — Option for Select
+DatePicker(name: string, mode: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}) — Numeric slider input; supports continuous and discrete (stepped) variants
+CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)
+RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+RadioItem(label: string, description: string, value: string)
+SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk") — Group of switch toggles
+SwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle
+- For Form fields, define EACH FormControl as its own reference — do NOT inline all controls in one array. This allows progressive field-by-field streaming.
+- NEVER nest Form inside Form — each Form should be a standalone container.
+- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.
+- rules is an optional array of validation strings: ["required", "email", "min:8", "maxLength:100"]
+- Available rules: required, email, min:N, max:N, minLength:N, maxLength:N, pattern:REGEX, url, numeric
+- The renderer shows error messages automatically — do NOT generate error text in the UI
+
+### Buttons
+Button(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button
+Buttons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".
+
+### Data Display
+TagBlock(tags: string[]) — tags is an array of strings
+Tag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant
+
+## Hoisting & Streaming (CRITICAL)
+
+openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.
+
+During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.
+
+**Recommended statement order for optimal streaming:**
+1. `root = Stack(...)` — UI shell appears immediately
+2. Component definitions — fill in as they stream
+3. Data values — leaf content last
+
+Always write the root = Stack(...) statement first so the UI shell appears immediately, even before child data has streamed in.
+
+## Examples
+
+Example 1 — Table:
+root = Stack([title, tbl])
+title = TextContent("Top Languages", "large-heavy")
+tbl = Table(cols, rows)
+cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]
+rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995], ["TypeScript", 8.5, 2012], ["Go", 5.2, 2009]]
+
+Example 2 — Bar chart:
+root = Stack([title, chart])
+title = TextContent("Q4 Revenue", "large-heavy")
+chart = BarChart(labels, [s1, s2], "grouped")
+labels = ["Oct", "Nov", "Dec"]
+s1 = Series("Product A", [120, 150, 180])
+s2 = Series("Product B", [90, 110, 140])
+
+Example 3 — Form with validation:
+root = Stack([title, form])
+title = TextContent("Contact Us", "large-heavy")
+form = Form("contact", btns, [nameField, emailField, countryField, msgField])
+nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))
+emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))
+countryField = FormControl("Country", Select("country", countryOpts, "Select...", { required: true }))
+msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))
+countryOpts = [SelectItem("us", "United States"), SelectItem("uk", "United Kingdom"), SelectItem("de", "Germany")]
+btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary"), Button("Cancel", { type: "continue_conversation" }, "secondary")])
+
+Example 4 — Tabs with mixed content:
+root = Stack([title, tabs])
+title = TextContent("React vs Vue", "large-heavy")
+tabs = Tabs([tabReact, tabVue])
+tabReact = TabItem("react", "React", reactContent)
+tabVue = TabItem("vue", "Vue", vueContent)
+reactContent = [TextContent("React is a library by Meta for building UIs."), Callout("info", "Note", "React uses JSX syntax.")]
+vueContent = [TextContent("Vue is a progressive framework by Evan You."), Callout("success", "Tip", "Vue has a gentle learning curve.")]
+
+## Important Rules
+- ALWAYS start with root = Stack(...)
+- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)
+- Each statement on its own line
+- No trailing text or explanations — output ONLY openui-lang code
+- When asked about data, generate realistic/plausible data
+- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)
+- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.
diff --git a/docs/imports/OpenUiGeneratesSchema.tsx b/docs/imports/OpenUiGeneratesSchema.tsx
index 2c4a249f1..ab23e8742 100644
--- a/docs/imports/OpenUiGeneratesSchema.tsx
+++ b/docs/imports/OpenUiGeneratesSchema.tsx
@@ -13,10 +13,10 @@ function Group() {
<path d={svgPaths.p1bd62700} fill="var(--fill-0, black)" id="Rectangle 34662625" />
</svg>
</div>
- <p className="absolute font-['Andale_Mono:Regular',sans-serif] h-[262px] leading-none left-[73px] not-italic text-[10px] text-white top-[71px] w-[254px] whitespace-pre-wrap">{`import { library } from "./library"
-
-const systemPrompt = library.prompt()
+ <p className="absolute font-['Andale_Mono:Regular',sans-serif] h-[262px] leading-none left-[73px] not-italic text-[10px] text-white top-[71px] w-[254px] whitespace-pre-wrap">{`# generate system prompt from library
+npx @openuidev/cli generate ./src/library.ts
+# use in your backend
const completion = await client.chat.completions.create({
model: "gpt-5.2",
stream: true,
diff --git a/docs/lib/chat-library.ts b/docs/lib/chat-library.ts
new file mode 100644
index 000000000..316f65a7d
--- /dev/null
+++ b/docs/lib/chat-library.ts
@@ -0,0 +1,4 @@
+export {
+ openuiChatLibrary as library,
+ openuiChatPromptOptions as promptOptions,
+} from "@openuidev/react-ui/genui-lib";
diff --git a/docs/lib/playground-library.ts b/docs/lib/playground-library.ts
new file mode 100644
index 000000000..5150c55c6
--- /dev/null
+++ b/docs/lib/playground-library.ts
@@ -0,0 +1,4 @@
+import { openuiExamples } from "@openuidev/react-ui/genui-lib";
+
+export { openuiLibrary as library } from "@openuidev/react-ui/genui-lib";
+export const promptOptions = { examples: openuiExamples };
diff --git a/docs/package.json b/docs/package.json
index 7a72c7254..676daa44e 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -3,8 +3,9 @@
"version": "0.0.0",
"private": true,
"scripts": {
+ "generate:prompts": "pnpm --filter @openuidev/cli build && pnpm exec openui generate lib/chat-library.ts --out generated/chat-system-prompt.txt && pnpm exec openui generate lib/playground-library.ts --out generated/playground-system-prompt.txt",
"build": "next build",
- "dev": "next dev",
+ "dev": "pnpm generate:prompts && next dev",
"start": "next start",
"types:check": "fumadocs-mdx && next typegen && tsc --noEmit",
"postinstall": "fumadocs-mdx",
@@ -13,6 +14,7 @@
"format:check": "prettier --check ."
},
"dependencies": {
+ "@openuidev/cli": "workspace:*",
"@openuidev/react-lang": "workspace:^",
"@openuidev/react-headless": "workspace:^",
"@openuidev/react-ui": "workspace:^",
diff --git a/examples/openui-chat/package.json b/examples/openui-chat/package.json
index 28bd6860c..0e46d9c90 100644
--- a/examples/openui-chat/package.json
+++ b/examples/openui-chat/package.json
@@ -3,12 +3,14 @@
"version": "0.1.0",
"private": true,
"scripts": {
- "dev": "next dev",
+ "generate:prompt": "pnpm --filter @openuidev/cli build && pnpm exec openui generate src/library.ts --out src/generated/system-prompt.txt",
+ "dev": "pnpm generate:prompt && next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
+ "@openuidev/cli": "workspace:*",
"@openuidev/react-ui": "workspace:*",
"@openuidev/react-headless": "workspace:*",
"@openuidev/react-lang": "workspace:*",
diff --git a/examples/openui-chat/src/app/api/chat/route.ts b/examples/openui-chat/src/app/api/chat/route.ts
index ec81a0adb..e7cf3b06f 100644
--- a/examples/openui-chat/src/app/api/chat/route.ts
+++ b/examples/openui-chat/src/app/api/chat/route.ts
@@ -1,6 +1,10 @@
+import { readFileSync } from "fs";
import { NextRequest } from "next/server";
import OpenAI from "openai";
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";
+import { join } from "path";
+
+const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");
// ── Tool implementations ──
@@ -193,7 +197,7 @@ function sseToolCallArgs(
// ── Route handler ──
export async function POST(req: NextRequest) {
- const { messages, systemPrompt } = await req.json();
+ const { messages } = await req.json();
const client = new OpenAI({
apiKey: process.env.OPENROUTER_API_KEY,
@@ -215,7 +219,7 @@ export async function POST(req: NextRequest) {
});
const chatMessages: ChatCompletionMessageParam[] = [
- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
+ { role: "system", content: systemPrompt },
...cleanMessages,
];
diff --git a/examples/openui-chat/src/app/page.tsx b/examples/openui-chat/src/app/page.tsx
index 1814f45d6..b45c90326 100644
--- a/examples/openui-chat/src/app/page.tsx
+++ b/examples/openui-chat/src/app/page.tsx
@@ -3,11 +3,9 @@ import "@openuidev/react-ui/components.css";
import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiChatLibrary, openuiChatPromptOptions } from "@openuidev/react-ui/genui-lib";
+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
import { useState } from "react";
-const systemPrompt = openuiChatLibrary.prompt(openuiChatPromptOptions);
-
export default function Page() {
const [mode, setMode] = useState<"light" | "dark">("light");
return (
@@ -46,7 +44,6 @@ export default function Page() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: openAIMessageFormat.toApi(messages),
- systemPrompt,
}),
signal: abortController.signal,
});
diff --git a/examples/openui-chat/src/generated/system-prompt.txt b/examples/openui-chat/src/generated/system-prompt.txt
new file mode 100644
index 000000000..b655c131e
--- /dev/null
+++ b/examples/openui-chat/src/generated/system-prompt.txt
@@ -0,0 +1,202 @@
+You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.
+
+## Syntax Rules
+
+1. Each statement is on its own line: `identifier = Expression`
+2. `root` is the entry point — every program must define `root = Card(...)`
+3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)
+4. Use references for readability: define `name = ...` on one line, then use `name` later
+5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.
+6. Arguments are POSITIONAL (order matters, not names)
+7. Optional arguments can be omitted from the end
+8. No operators, no logic, no variables — only declarations
+9. Strings use double quotes with backslash escaping
+
+## Component Signatures
+
+Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.
+The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).
+
+### Content
+CardHeader(title?: string, subtitle?: string) — Header with optional title and subtitle
+TextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".
+MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant
+Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Callout banner with variant, title, and description
+TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and description
+Image(alt: string, src?: string) — Image with alt text and optional URL
+ImageBlock(src: string, alt?: string) — Image block with loading state
+ImageGallery(images: {src: string, alt?: string, details?: string}[]) — Gallery grid of images with modal preview
+CodeBlock(language: string, codeString: string) — Syntax-highlighted code block
+Separator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections
+
+### Tables
+Table(columns: Col[], rows: (string | number | boolean)[][]) — Data table
+Col(label: string, type?: "string" | "number" | "action") — Column definition
+
+### Charts (2D)
+BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series
+LineChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Lines over categories; use for trends and continuous data over time
+AreaChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Filled area under lines; use for cumulative totals or volume trends over time
+RadarChart(labels: string[], series: Series[]) — Spider/web chart; use for comparing multiple variables across one or more entities
+HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Horizontal bars; prefer when category labels are long or for ranked lists
+Series(category: string, values: number[]) — One data series
+
+### Charts (1D)
+PieChart(slices: Slice[], variant?: "pie" | "donut") — Circular slices showing part-to-whole proportions; supports pie and donut variants
+RadialChart(slices: Slice[]) — Radial bars showing proportional distribution across named segments
+SingleStackedBarChart(slices: Slice[]) — Single horizontal stacked bar; use for showing part-to-whole proportions in one row
+Slice(category: string, value: number) — One slice with label and numeric value
+
+### Charts (Scatter)
+ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string) — X/Y scatter plot; use for correlations, distributions, and clustering
+ScatterSeries(name: string, points: Point[]) — Named dataset
+Point(x: number, y: number, z?: number) — Data point with numeric coordinates
+
+### Forms
+Form(name: string, buttons: Buttons, fields) — Form container with fields and explicit action buttons
+FormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint text
+Label(text: string) — Text label
+Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+SelectItem(value: string, label: string) — Option for Select
+DatePicker(name: string, mode: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}) — Numeric slider input; supports continuous and discrete (stepped) variants
+CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)
+RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})
+RadioItem(label: string, description: string, value: string)
+SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk") — Group of switch toggles
+SwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle
+- Define EACH FormControl as its own reference — do NOT inline all controls in one array.
+- NEVER nest Form inside Form.
+- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.
+- rules is an optional object: { required: true, email: true, min: 8, maxLength: 100 }
+- The renderer shows error messages automatically — do NOT generate error text in the UI
+
+### Buttons
+Button(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button
+Buttons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".
+
+### Lists & Follow-ups
+ListBlock(items: ListItem[], variant?: "number" | "image") — A list of items with number or image indicators. Each item can optionally have an action.
+ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.
+FollowUpBlock(items: FollowUpItem[]) — List of clickable follow-up suggestions placed at the end of a response
+FollowUpItem(text: string) — Clickable follow-up suggestion — when clicked, sends text as user message
+- Use ListBlock with ListItem references for numbered, clickable lists.
+- Use FollowUpBlock with FollowUpItem references at the end of a response to suggest next actions.
+- Clicking a ListItem or FollowUpItem sends its text to the LLM as a user message.
+- Example: list = ListBlock([item1, item2]) item1 = ListItem("Option A", "Details about A")
+
+### Sections
+SectionBlock(sections: SectionItem[], isFoldable?: boolean) — Collapsible accordion sections. Auto-opens sections as they stream in. Use SectionItem for each section.
+SectionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock)[]) — Section with a label and collapsible content — used inside SectionBlock
+- SectionBlock renders collapsible accordion sections that auto-open as they stream.
+- Each section needs a unique `value` id, a `trigger` label, and a `content` array.
+- Example: sections = SectionBlock([s1, s2]) s1 = SectionItem("intro", "Introduction", [content1])
+- Set isFoldable=false to render sections as flat headers instead of accordion.
+
+### Layout
+Tabs(items: TabItem[]) — Tabbed container
+TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is tab label, content is array of components
+Accordion(items: AccordionItem[]) — Collapsible sections
+AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is section title
+Steps(items: StepsItem[]) — Step-by-step guide
+StepsItem(title: string, details: string) — title and details text for one step
+Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: "card" | "sunk") — Horizontal scrollable carousel
+- Use Tabs to present alternative views — each TabItem has a value id, trigger label, and content array.
+- Carousel takes an array of slides, where each slide is an array of content: carousel = Carousel([[t1, img1], [t2, img2]])
+- IMPORTANT: Every slide in a Carousel must have the same structure — same component types in the same order.
+- For image carousels use: [[title, image, description, tags], ...] — every slide must follow this exact pattern.
+- Use real, publicly accessible image URLs (e.g. https://picsum.photos/seed/KEYWORD/800/500). Never hallucinate image URLs.
+
+### Data Display
+TagBlock(tags: string[]) — tags is an array of strings
+Tag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant
+
+### Ungrouped
+Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock | SectionBlock | Tabs | Carousel)[]) — Vertical container for all content in a chat response. Children stack top to bottom automatically.
+
+## Hoisting & Streaming (CRITICAL)
+
+openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.
+
+During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.
+
+**Recommended statement order for optimal streaming:**
+1. `root = Card(...)` — UI shell appears immediately
+2. Component definitions — fill in as they stream
+3. Data values — leaf content last
+
+Always write the root = Card(...) statement first so the UI shell appears immediately, even before child data has streamed in.
+
+## Examples
+
+Example 1 — Table with follow-ups:
+root = Card([title, tbl, followUps])
+title = TextContent("Top Languages", "large-heavy")
+tbl = Table(cols, rows)
+cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]
+rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995]]
+followUps = FollowUpBlock([fu1, fu2])
+fu1 = FollowUpItem("Tell me more about Python")
+fu2 = FollowUpItem("Show me a JavaScript comparison")
+
+Example 2 — Clickable list:
+root = Card([title, list])
+title = TextContent("Choose a topic", "large-heavy")
+list = ListBlock([item1, item2, item3])
+item1 = ListItem("Getting started", "New to the platform? Start here.")
+item2 = ListItem("Advanced features", "Deep dives into powerful capabilities.")
+item3 = ListItem("Troubleshooting", "Common issues and how to fix them.")
+
+Example 3 — Image carousel with consistent slides + follow-ups:
+root = Card([header, carousel, followups])
+header = CardHeader("Featured Destinations", "Discover highlights and best time to visit")
+carousel = Carousel([[t1, img1, d1, tags1], [t2, img2, d2, tags2], [t3, img3, d3, tags3]], "card")
+t1 = TextContent("Paris, France", "large-heavy")
+img1 = ImageBlock("https://picsum.photos/seed/paris/800/500", "Eiffel Tower at night")
+d1 = TextContent("City of light — best Apr–Jun and Sep–Oct.", "default")
+tags1 = TagBlock(["Landmark", "City Break", "Culture"])
+t2 = TextContent("Kyoto, Japan", "large-heavy")
+img2 = ImageBlock("https://picsum.photos/seed/kyoto/800/500", "Bamboo grove in Arashiyama")
+d2 = TextContent("Temples and bamboo groves — best Mar–Apr and Nov.", "default")
+tags2 = TagBlock(["Temples", "Autumn", "Culture"])
+t3 = TextContent("Machu Picchu, Peru", "large-heavy")
+img3 = ImageBlock("https://picsum.photos/seed/machupicchu/800/500", "Inca citadel in the clouds")
+d3 = TextContent("High-altitude Inca citadel — best May–Sep.", "default")
+tags3 = TagBlock(["Andes", "Hike", "UNESCO"])
+followups = FollowUpBlock([fu1, fu2])
+fu1 = FollowUpItem("Show me only beach destinations")
+fu2 = FollowUpItem("Turn this into a comparison table")
+
+Example 4 — Form with validation:
+root = Card([title, form])
+title = TextContent("Contact Us", "large-heavy")
+form = Form("contact", btns, [nameField, emailField, msgField])
+nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))
+emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))
+msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))
+btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary")])
+
+## Important Rules
+- ALWAYS start with root = Card(...)
+- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)
+- Each statement on its own line
+- No trailing text or explanations — output ONLY openui-lang code
+- When asked about data, generate realistic/plausible data
+- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)
+- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.
+
+- Every response is a single Card(children) — children stack vertically automatically. No layout params are needed on Card.
+- Card is the only layout container. Do NOT use Stack. Use Tabs to switch between sections, Carousel for horizontal scroll.
+- Use FollowUpBlock at the END of a Card to suggest what the user can do or ask next.
+- Use ListBlock when presenting a set of options or steps the user can click to select.
+- Use SectionBlock to group long responses into collapsible sections — good for reports, FAQs, and structured content.
+- Use SectionItem inside SectionBlock: each item needs a unique value id, a trigger (header label), and a content array.
+- Carousel takes an array of slides, where each slide is an array of content: carousel = Carousel([[t1, img1], [t2, img2]])
+- IMPORTANT: Every slide in a Carousel must use the same component structure in the same order — e.g. all slides: [title, image, description, tags].
+- For image carousels, always use real accessible URLs like https://picsum.photos/seed/KEYWORD/800/500. Never hallucinate or invent image URLs.
+- For forms, define one FormControl reference per field so controls can stream progressively.
+- For forms, always provide the second Form argument with Buttons(...) actions: Form(name, buttons, fields).
+- Never nest Form inside Form.
diff --git a/examples/openui-chat/src/library.ts b/examples/openui-chat/src/library.ts
new file mode 100644
index 000000000..c7ceecfc1
--- /dev/null
+++ b/examples/openui-chat/src/library.ts
@@ -0,0 +1 @@
+export { openuiChatLibrary as library, openuiChatPromptOptions as promptOptions } from "@openuidev/react-ui/genui-lib";
diff --git a/packages/openui-cli/README.md b/packages/openui-cli/README.md
index d2da4e5fd..88a5271fb 100644
--- a/packages/openui-cli/README.md
+++ b/packages/openui-cli/README.md
@@ -84,6 +84,7 @@ Options:
- `-o, --out <file>`: Write output to a file instead of stdout
- `--json-schema`: Output JSON Schema instead of the system prompt
- `--export <name>`: Use a specific export name instead of auto-detecting the library export
+- `--prompt-options <name>`: Use a specific `PromptOptions` export name (auto-detected by default)
- `--no-interactive`: Fail instead of prompting for a missing `entry`
What it does:
@@ -93,6 +94,7 @@ What it does:
- supports both TypeScript and JavaScript entry files
- stubs common asset imports such as CSS, SVG, images, and fonts during bundling
- auto-detects the exported library by checking `library`, `default`, and then all exports
+- auto-detects a `PromptOptions` export (with `examples`, `additionalRules`, or `preamble`) and passes it to `library.prompt()`
Examples:
@@ -101,6 +103,7 @@ openui generate ./src/library.ts
openui generate ./src/library.ts --json-schema
openui generate ./src/library.ts --export library
openui generate ./src/library.ts --out ./artifacts/system-prompt.txt
+openui generate ./src/library.ts --prompt-options myPromptOptions
openui generate --no-interactive ./src/library.ts
```
@@ -114,6 +117,16 @@ If `--export` is not provided, it looks for exports in this order:
2. `default`
3. any other export that matches the expected library shape
+### PromptOptions auto-detection
+
+If `--prompt-options` is not provided, the CLI looks for a `PromptOptions` export in this order:
+
+1. `promptOptions`
+2. `options`
+3. any export whose name ends with `PromptOptions` (case-insensitive)
+
+A valid `PromptOptions` object has at least one of: `examples` (string array), `additionalRules` (string array), or `preamble` (string).
+
## Local Development
Build the CLI locally:
diff --git a/packages/openui-cli/package.json b/packages/openui-cli/package.json
index be0b5cc19..5f5f84ebe 100644
--- a/packages/openui-cli/package.json
+++ b/packages/openui-cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/cli",
- "version": "0.0.2",
+ "version": "0.0.3",
"description": "CLI for OpenUI",
"bin": {
"openui": "dist/index.js"
diff --git a/packages/openui-cli/src/commands/generate-worker.ts b/packages/openui-cli/src/commands/generate-worker.ts
index 6cee6eaf2..1bf20fefd 100644
--- a/packages/openui-cli/src/commands/generate-worker.ts
+++ b/packages/openui-cli/src/commands/generate-worker.ts
@@ -3,7 +3,7 @@
* prompt or JSON schema. Asset imports are stubbed during bundling so React
* component modules can be evaluated without CSS/image/font loaders.
*
- * argv: [entryPath, exportName?, "--json-schema"?]
+ * argv: [entryPath, exportName?, "--json-schema"?, "--prompt-options", name?]
* stdout: the prompt string or JSON schema
*/
@@ -70,16 +70,61 @@ function findLibrary(mod: Record<string, unknown>, exportName?: string): Library
return undefined;
}
+interface PromptOptions {
+ preamble?: string;
+ additionalRules?: string[];
+ examples?: string[];
+}
+
+function isPromptOptions(value: unknown): value is PromptOptions {
+ if (typeof value !== "object" || value === null) return false;
+ const obj = value as Record<string, unknown>;
+ const hasExamples = Array.isArray(obj["examples"]);
+ const hasRules = Array.isArray(obj["additionalRules"]);
+ const hasPreamble = typeof obj["preamble"] === "string";
+ return hasExamples || hasRules || hasPreamble;
+}
+
+function findPromptOptions(
+ mod: Record<string, unknown>,
+ exportName?: string,
+): PromptOptions | undefined {
+ if (exportName) {
+ const val = mod[exportName];
+ return isPromptOptions(val) ? val : undefined;
+ }
+
+ // Check well-known names first
+ for (const name of ["promptOptions", "options"]) {
+ if (isPromptOptions(mod[name])) return mod[name] as PromptOptions;
+ }
+
+ // Check any export ending with "PromptOptions" or "promptOptions"
+ for (const [key, val] of Object.entries(mod)) {
+ if (/[Pp]rompt[Oo]ptions$/.test(key) && isPromptOptions(val)) return val;
+ }
+
+ return undefined;
+}
+
async function main(): Promise<void> {
const args = process.argv.slice(2);
const entryPath = args[0];
if (!entryPath) {
- console.error("Usage: generate-worker <entryPath> [exportName] [--json-schema]");
+ console.error(
+ "Usage: generate-worker <entryPath> [exportName] [--json-schema] [--prompt-options <name>]",
+ );
process.exit(1);
}
const jsonSchema = args.includes("--json-schema");
- const exportName = args.find((a) => a !== entryPath && a !== "--json-schema");
+ const promptOptionsIdx = args.indexOf("--prompt-options");
+ const promptOptionsName = promptOptionsIdx !== -1 ? args[promptOptionsIdx + 1] : undefined;
+ const reserved = new Set(["--json-schema", "--prompt-options"]);
+ if (promptOptionsName) reserved.add(promptOptionsName);
+ const exportName = args.find(
+ (a, i) => a !== entryPath && !reserved.has(a) && !(i > 0 && args[i - 1] === "--prompt-options"),
+ );
const bundleDir = fs.mkdtempSync(path.join(os.tmpdir(), "openui-generate-"));
const bundlePath = path.join(bundleDir, "entry.cjs");
@@ -125,7 +170,13 @@ async function main(): Promise<void> {
process.exit(1);
}
- const output = jsonSchema ? JSON.stringify(library.toJSONSchema(), null, 2) : library.prompt();
+ let output: string;
+ if (jsonSchema) {
+ output = JSON.stringify(library.toJSONSchema(), null, 2);
+ } else {
+ const promptOptions = findPromptOptions(mod, promptOptionsName);
+ output = library.prompt(promptOptions);
+ }
process.stdout.write(output);
}
diff --git a/packages/openui-cli/src/commands/generate.ts b/packages/openui-cli/src/commands/generate.ts
index e89260441..f6dab897b 100644
--- a/packages/openui-cli/src/commands/generate.ts
+++ b/packages/openui-cli/src/commands/generate.ts
@@ -6,6 +6,7 @@ export interface GenerateOptions {
out?: string;
jsonSchema?: boolean;
export?: string;
+ promptOptions?: string;
}
export async function runGenerate(entry: string, options: GenerateOptions): Promise<void> {
@@ -21,6 +22,7 @@ export async function runGenerate(entry: string, options: GenerateOptions): Prom
const workerArgs = [workerPath, entryPath];
if (options.export) workerArgs.push(options.export);
if (options.jsonSchema) workerArgs.push("--json-schema");
+ if (options.promptOptions) workerArgs.push("--prompt-options", options.promptOptions);
let output: string;
try {
diff --git a/packages/openui-cli/src/index.ts b/packages/openui-cli/src/index.ts
index 36129cb1d..d60f26a53 100644
--- a/packages/openui-cli/src/index.ts
+++ b/packages/openui-cli/src/index.ts
@@ -26,11 +26,21 @@ program
.option("-o, --out <file>", "Write output to a file instead of stdout")
.option("--json-schema", "Output JSON schema instead of the system prompt")
.option("--export <name>", "Name of the export to use (auto-detected by default)")
+ .option(
+ "--prompt-options <name>",
+ "Name of the PromptOptions export to use (auto-detected by default)",
+ )
.option("--no-interactive", "Fail with error if required args are missing")
.action(
async (
entry: string | undefined,
- options: { out?: string; jsonSchema?: boolean; export?: string; interactive: boolean },
+ options: {
+ out?: string;
+ jsonSchema?: boolean;
+ export?: string;
+ promptOptions?: string;
+ interactive: boolean;
+ },
) => {
const args = await resolveArgs(
{
diff --git a/packages/openui-cli/src/templates/openui-chat/.gitignore b/packages/openui-cli/src/templates/openui-chat/.gitignore
index 5ef6a5207..aa8b41dec 100644
--- a/packages/openui-cli/src/templates/openui-chat/.gitignore
+++ b/packages/openui-cli/src/templates/openui-chat/.gitignore
@@ -36,6 +36,9 @@ yarn-error.log*
# vercel
.vercel
+# generated
+/src/generated/
+
# typescript
*.tsbuildinfo
next-env.d.ts
diff --git a/packages/openui-cli/src/templates/openui-chat/package.json b/packages/openui-cli/src/templates/openui-chat/package.json
index d043fd702..87f7d36a9 100644
--- a/packages/openui-cli/src/templates/openui-chat/package.json
+++ b/packages/openui-cli/src/templates/openui-chat/package.json
@@ -3,8 +3,9 @@
"version": "0.1.0",
"private": true,
"scripts": {
- "dev": "next dev",
- "build": "next build",
+ "generate:prompt": "openui generate src/library.ts --out src/generated/system-prompt.txt",
+ "dev": "npm run generate:prompt && next dev",
+ "build": "npm run generate:prompt && next build",
"start": "next start",
"lint": "eslint"
},
@@ -18,6 +19,7 @@
"react-dom": "19.2.3"
},
"devDependencies": {
+ "@openuidev/cli": "latest",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
diff --git a/packages/openui-cli/src/templates/openui-chat/src/app/api/chat/route.ts b/packages/openui-cli/src/templates/openui-chat/src/app/api/chat/route.ts
index 404fd0276..3e6c0c9a3 100644
--- a/packages/openui-cli/src/templates/openui-chat/src/app/api/chat/route.ts
+++ b/packages/openui-cli/src/templates/openui-chat/src/app/api/chat/route.ts
@@ -1,19 +1,21 @@
+import { readFileSync } from "fs";
+import { join } from "path";
import { NextRequest } from "next/server";
import OpenAI from "openai";
+const client = new OpenAI();
+const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");
+
export async function POST(req: NextRequest) {
- const client = new OpenAI();
try {
- const { messages, systemPrompt } = await req.json();
-
- const chatMessages: OpenAI.ChatCompletionMessageParam[] = [
- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
- ...messages,
- ];
+ const { messages } = await req.json();
const response = await client.chat.completions.create({
- model: "gpt-4o",
- messages: chatMessages,
+ model: "gpt-5.2",
+ messages: [
+ { role: "system", content: systemPrompt },
+ ...messages,
+ ],
stream: true,
});
diff --git a/packages/openui-cli/src/templates/openui-chat/src/app/page.tsx b/packages/openui-cli/src/templates/openui-chat/src/app/page.tsx
index b828b1d20..ddfd81526 100644
--- a/packages/openui-cli/src/templates/openui-chat/src/app/page.tsx
+++ b/packages/openui-cli/src/templates/openui-chat/src/app/page.tsx
@@ -4,9 +4,7 @@ import "@openuidev/react-ui/styles/index.css";
import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";
-
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
export default function Home() {
return (
@@ -18,7 +16,6 @@ export default function Home() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: openAIMessageFormat.toApi(messages),
- systemPrompt,
}),
signal: abortController.signal,
});
diff --git a/packages/openui-cli/src/templates/openui-chat/src/library.ts b/packages/openui-cli/src/templates/openui-chat/src/library.ts
new file mode 100644
index 000000000..8a2edfa62
--- /dev/null
+++ b/packages/openui-cli/src/templates/openui-chat/src/library.ts
@@ -0,0 +1 @@
+export { openuiLibrary as library, openuiPromptOptions as promptOptions } from "@openuidev/react-ui/genui-lib";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4d9ad148e..19085f6f6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -44,6 +44,9 @@ importers:
docs:
dependencies:
+ '@openuidev/cli':
+ specifier: workspace:*
+ version: link:../packages/openui-cli
'@openuidev/react-headless':
specifier: workspace:^
version: link:../packages/react-headless
@@ -129,6 +132,9 @@ importers:
examples/openui-chat:
dependencies:
+ '@openuidev/cli':
+ specifier: workspace:*
+ version: link:../../packages/openui-cli
'@openuidev/react-headless':
specifier: workspace:*
version: link:../../packages/react-headless