The Open Standard for Generative UI
Make example docs explanatory (#342)
abhithesys2325efea0e84
diff --git a/docs/content/docs/openui-lang/examples/react-native.mdx b/docs/content/docs/openui-lang/examples/react-native.mdxindex 11dcd7362..a642379e7 100644--- a/docs/content/docs/openui-lang/examples/react-native.mdx+++ b/docs/content/docs/openui-lang/examples/react-native.mdx@@ -1,9 +1,9 @@---title: React Native-description: Stream OpenUI Lang to a React Native (Expo) app using a Next.js backend.+description: stream LLM-generated UI to an Expo app that renders real native components.----A full-stack example that streams [OpenUI Lang](/docs/openui-lang/overview) into an Expo app using a Next.js backend, then renders it as native React Native UI with `<Renderer />` from `@openuidev/react-lang`.+OpenUI Lang runs on React Native. This example streams LLM-generated UI to an Expo app, where `<Renderer />` turns it into real native components — not a webview, not markdown, native `Text`, `View`, and SVG charts. The stack is an Expo app paired with a Next.js backend that handles the OpenAI call.[View source on GitHub →](https://github.com/thesysdev/crayon/tree/main/examples/openui-react-native)@@ -19,10 +19,31 @@ A full-stack example that streams [OpenUI Lang](/docs/openui-lang/overview) intoloop/></div>-The example includes two modules:-- `backend`: a Next.js backend that calls OpenAI and streams raw OpenUI Lang-- `chat-app`: an Expo app that progressively parses that stream and renders native components+## What changes on native++Three things differ from a web OpenUI Lang integration:++### 1. Native primitives only++There is no DOM, no HTML, no CSS. Components use `Text`, `View`, `StyleSheet` from `react-native`, and `react-native-svg` for charts:++```tsx+component: ({ props }) => (+ <RNText style={styles.textBody}>{props.content}</RNText>+)+```++### 2. Two mirror libraries++`@openuidev/cli` runs in Node.js to generate the system prompt, but it can't import React Native. This will be fixed in future versions of the CLI. The solution is two files with identical schemas — one with real renderers for the app, one with null renderers for the backend:++| File | Purpose |+| ---- | ------- |+| `chat-app/library.tsx` | Real React Native renderers — what runs on device |+| `backend/src/library.ts` | Null renderers (`() => null`) — used only to generate `system-prompt.txt` |++Keep these in sync: same component names, same prop schemas, same root component.## Architecture@@ -31,9 +52,7 @@ Expo app -- POST /api/chat --> Next.js backend --> OpenAI<-- text/plain stream -- (OpenUI Lang)```-The backend loads a pre-generated `system-prompt.txt`, forwards the conversation to OpenAI with streaming enabled, and returns raw `text/plain` chunks. The mobile app accumulates those chunks and passes the growing string into `<Renderer />`, which progressively parses and renders native UI as the response arrives.--Using plain text keeps the transport simple. React Native does not expose the same browser streaming primitives you would normally use with `fetch()` plus `ReadableStream` or `EventSource`, so this example uses `XMLHttpRequest` and `onprogress` instead.+The backend loads a pre-generated `system-prompt.txt`, forwards the conversation to OpenAI with streaming enabled, and returns raw `text/plain` chunks. The Expo app accumulates those chunks and passes the growing string into `<Renderer />`, which progressively parses and renders native UI as the response arrives.## Project layout@@ -72,7 +91,7 @@ OPENAI_API_KEY=sk-...pnpm generate:prompt```-This generates `backend/src/system-prompt.txt` from `backend/src/library.ts`. Re-run it any time you change the component names, schemas, descriptions, or prompt rules.+This generates `backend/src/system-prompt.txt` from `backend/src/library.ts`. Re-run it any time you change component names, schemas, descriptions, or prompt rules.4. Start the Next.js backend:@@ -89,108 +108,3 @@ pnpm dev:mobileBy default, `chat-app/metro.config.js` auto-detects your local IP address and sets `EXPO_PUBLIC_BACKEND_URL` to `http://<your-ip>:3000/api/chat`. If you need to point the app somewhere else, set `EXPO_PUBLIC_BACKEND_URL` yourself before starting Expo.If you are testing on a physical device, make sure the phone and your development machine are on the same network.--## What to expect--Open the Expo app and try one of the built-in prompt chips such as:--- "Top languages 2025"-- "Revenue trend"-- "Energy mix"--The assistant response should appear progressively. Instead of rendering markdown, the app parses the streamed OpenUI Lang and turns it into native `Text`, `BarChart`, `LineChart`, `PieChart`, and `Card` components.--## Request and render flow--1. The user sends a message from `chat-app/screens/ChatScreen.tsx`.-2. `chat-app/hooks/useStreamingChat.ts` posts the chat history to the backend with `XMLHttpRequest`.-3. `backend/src/app/api/chat/route.ts` forwards that history to OpenAI using the generated `system-prompt.txt`.-4. The backend streams raw OpenUI Lang text back to the phone.-5. `chat-app/store/streamStore.ts` keeps the accumulated response outside the main message list state.-6. `chat-app/components/BotBubble.tsx` subscribes to that stream and renders it with `<Renderer />`.--This separation is important: the message list only stores chat items, while the streamed OpenUI Lang lives in a dedicated store so each bot bubble can update independently.--## Key files--### `chat-app/library.tsx` - React Native renderers--Defines the React Native component library. It includes real renderers for `Text`, `BarChart`, `LineChart`, `PieChart`, and `Card`, using `react-native-svg` for the chart components.--This file must stay in sync with `backend/src/library.ts`: same component names, same prop schemas, same root component.--```tsx-export const library = createLibrary({- components: [- TextComponent,- BarChartComponent,- LineChartComponent,- PieChartComponent,- CardComponent,- ],- root: "Card",-});-```--The mobile version contains the real React Native renderers. It is the code that actually turns parsed OpenUI Lang nodes into UI on screen.--See [Defining Components](/docs/openui-lang/defining-components) for the full `defineComponent` API and [The Renderer](/docs/openui-lang/renderer) for how the library is used at runtime.--### `chat-app/hooks/useStreamingChat.ts` - progressive streaming via XHR--React Native's `fetch()` does not expose `response.body` as a `ReadableStream`, so the hook uses `XMLHttpRequest` instead. `onprogress` fires repeatedly as chunks arrive:--```ts-xhr.onprogress = () => {- const newData = xhr.responseText.slice(lastLength);- lastLength = xhr.responseText.length;- accumulated += newData;- onChunk(accumulated, false);-};-```--Each callback receives the full accumulated OpenUI Lang string so far, which makes it easy to hand the entire in-progress document to `<Renderer />`. This is the main React Native-specific detail in the example.--### `chat-app/components/BotBubble.tsx` - rendering the in-progress response--Each bot message reads from its own entry in `streamStore` and passes the accumulated OpenUI Lang into `<Renderer />`:--```tsx-const content = useStreamContent(messageId);-const openui = content?.openui ?? "";-const isStreaming = content?.isStreaming ?? true;--<Renderer response={openui} library={library} isStreaming={isStreaming} />-```--Keeping streamed content in a separate store means each bubble can update independently instead of forcing the entire message list to re-render on every chunk.--See [The Renderer](/docs/openui-lang/renderer) for the full `<Renderer />` API.--### `backend/src/library.ts` - Node-compatible prompt source--This file mirrors the mobile library, but every `component` returns `null`. That lets the OpenUI CLI inspect the component definitions in a Node environment and generate `system-prompt.txt` without importing React Native.--Run `pnpm generate:prompt` any time you change:--- component names-- prop schemas-- descriptions-- prompt rules or examples--See [System Prompts](/docs/openui-lang/system-prompts) for how prompt generation works.--### `backend/src/app/api/chat/route.ts` - raw text streaming endpoint--The backend route reads `system-prompt.txt`, calls OpenAI with `stream: true`, and writes each `delta.content` chunk into a `ReadableStream` response:--```ts-for await (const chunk of completion) {- const text = chunk.choices[0]?.delta?.content ?? "";- if (text) {- controller.enqueue(new TextEncoder().encode(text));- }-}-```--The response uses `Content-Type: text/plain; charset=utf-8` and permissive CORS headers so the Expo app can call it during development.diff --git a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx b/docs/content/docs/openui-lang/examples/shadcn-chat.mdxindex 9d54a6705..e15fa8c6c 100644--- a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx+++ b/docs/content/docs/openui-lang/examples/shadcn-chat.mdx@@ -1,9 +1,9 @@---title: Shadcn Chat-description: A generative UI chat app that streams OpenUI Lang and renders it as shadcn/ui components.+description: An example of connecting OpenUI Lang to a custom component library, using shadcn/ui as the design system.----A full-stack example that streams [OpenUI Lang](/docs/openui-lang/overview) into a Next.js chat interface using `@openuidev/react-ui`'s [FullScreen](/docs/chat/fullscreen) layout, then renders every response as rich [shadcn/ui](https://ui.shadcn.com/) components via a custom `shadcnChatLibrary`.+OpenUI Lang is not tied to any component library. The LLM generates abstract UI structure; your library definition decides how that structure renders. This example wires OpenUI Lang to [shadcn/ui](https://ui.shadcn.com/) — swapping in a custom `shadcnChatLibrary` in place of the built-in libraries — to show that any design system can sit behind the same protocol.[View source on GitHub →](https://github.com/thesysdev/crayon/tree/main/examples/shadcn-chat)@@ -20,11 +20,47 @@ A full-stack example that streams [OpenUI Lang](/docs/openui-lang/overview) into/></div>-The example includes:+## Bringing your own component library++The bridge between OpenUI Lang and shadcn/ui is built with two primitives: `defineComponent` and `createLibrary` from `@openuidev/react-lang`.++`defineComponent` maps a single OpenUI Lang node to a React component. Here's the root `Card` component from `shadcn-genui/index.tsx`:++```tsx+const ChatCard = defineComponent({+ name: "Card",+ props: z.object({+ children: z.array(ChatCardChildUnion),+ }),+ description:+ "Vertical container for all content in a chat response. Children stack top to bottom automatically.",+ component: ({ props, renderNode }) => (+ <Card>+ <CardContent className="p-0 space-y-3">{renderNode(props.children)}</CardContent>+ </Card>+ ),+});+```++- `name` — the OpenUI Lang node name the LLM will emit+- `props` — a Zod schema that validates the node's props as they stream in+- `description` — included in the generated system prompt so the LLM knows when and how to use the component+- `component` — the React component that renders it; `renderNode` recursively renders children++Once you've defined your components, `createLibrary` assembles them into a library you pass to the renderer:++```tsx+export const shadcnChatLibrary = createLibrary({+ root: "Card",+ componentGroups: shadcnComponentGroups,+ components: [ChatCard, CardHeader, TextContent, Alert /* ... */],+});+```++Swap `shadcnChatLibrary` for a library built on any other design system — Material UI, Radix, your own primitives — and the rest of the stack stays the same.++See [Defining Components](/docs/openui-lang/defining-components) for the full `defineComponent` API.-- A **Next.js frontend** with a FullScreen chat layout that adapts to the system light/dark theme-- A **Next.js API route** that calls OpenAI with streaming and server-side tool execution-- A **shadcn-genui component library** with 40+ components covering content, charts, forms, tables, buttons, layout, overlays, and more## Architecture@@ -33,7 +69,9 @@ Browser (FullScreen) -- POST /api/chat --> Next.js route --> OpenAI<-- SSE stream -- (OpenUI Lang + tool calls)```-The client sends a conversation to `/api/chat`. The API route loads a generated `system-prompt.txt`, forwards the messages to the LLM with streaming and tool definitions, and returns SSE events. On the client side, `openAIAdapter()` parses the SSE stream, and `shadcnChatLibrary` maps each OpenUI Lang node to a shadcn/ui component that renders progressively as tokens arrive.+The client sends a conversation to `/api/chat`. The API route loads a generated `system-prompt.txt`, forwards the messages to the LLM with streaming and tool definitions, and returns SSE events. On the client, `openAIAdapter()` parses the SSE stream and `shadcnChatLibrary` maps each OpenUI Lang node to a shadcn/ui component that renders progressively as tokens arrive.++The key decoupling: the server streams OpenUI Lang — an abstract description of UI structure. The client's `shadcnChatLibrary` decides how each node renders. That's where shadcn/ui enters, and that's also where you'd plug in any other design system.The API route also supports **server-side tool execution**. When the model invokes a tool (weather, stock price, calculator, or web search), the route runs it and feeds the result back into the completion loop before streaming the final UI response.@@ -70,162 +108,3 @@ OPENAI_API_KEY=sk-...```bashpnpm dev```--This automatically generates the system prompt from the library definition before starting Next.js.--## What to expect--Open the app and try one of the built-in conversation starters:--- "Startup dashboard" — analytics dashboard with charts, tables, and progress bars-- "Travel planner" — calendar, accordion destinations, and a preferences form-- "Market watch" — fetches live stock prices and renders a comparison table with charts-- "Event RSVP" — a rich form with every input type-- "Chart showcase" — six chart types (Bar, Line, Area, Pie, Radar, Scatter) in tabbed view--Instead of rendering plain markdown, the assistant response appears progressively as shadcn/ui components — cards, charts, forms, tables, badges, and more — all styled with the shadcn/ui design system and responsive to your system theme.--## Key files--### `src/hooks/use-system-theme.tsx` — theme detection--A `ThemeProvider` wraps the app at the root layout. It detects the system color scheme via `prefers-color-scheme`, sets a `data-theme` attribute on `<body>`, and exposes the resolved `"light"` or `"dark"` mode through a `useTheme()` hook. CSS variables in `globals.css` switch via the `[data-theme="dark"]` selector, and Tailwind's dark variant is configured to match.--### `src/app/page.tsx` — FullScreen chat setup--The page calls `useTheme()` to get the current mode and passes it to the `FullScreen` layout:--```tsx-<FullScreen- processMessage={async ({ messages, abortController }) => {- return fetch("/api/chat", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: openAIMessageFormat.toApi(messages),- }),- signal: abortController.signal,- });- }}- streamProtocol={openAIAdapter()}- componentLibrary={shadcnChatLibrary}- agentName="shadcn/ui Chat"- theme={{ mode }}- conversationStarters={{- variant: "short",- options: [- { displayText: "Startup dashboard", prompt: "Build a startup analytics dashboard ..." },- { displayText: "Market watch", prompt: "Fetch stock prices for AAPL, NVDA ..." },- // ...- ],- }}-/>-```--See [Chat FullScreen Layout](/docs/chat/fullscreen) and [Connecting to a Backend](/docs/chat/connecting) for the full API.--### `src/lib/shadcn-genui/index.tsx` — component library--Defines the complete generative UI library using `createLibrary()` from `@openuidev/react-lang`. The library declares a `Card` root component, 13 component groups, 12 prompt examples, and additional rules that guide the LLM:--```tsx-export const shadcnChatLibrary = createLibrary({- root: "Card",- componentGroups: shadcnComponentGroups,- components: [- ChatCard,- CardHeader,- TextContent,- MarkDownRenderer,- Alert /* ... */,- Table,- Col,- BarChartCondensed,- LineChartCondensed /* ... */,- Form,- FormControl,- Input,- Select /* ... */,- Button,- Buttons,- Tabs,- Accordion,- Carousel,- // ... 40+ components total- ],-});-```--The component groups organize components by category and include notes that become part of the generated system prompt:--| Group | Components |-| ---------------- | ------------------------------------------------------------------------------------------------------------- |-| Content | CardHeader, TextContent, MarkDownRenderer, Alert, Badge, Avatar, CodeBlock, Image, Progress, Separator |-| Tables | Table, Col |-| Charts (2D) | BarChart, LineChart, AreaChart, RadarChart, Series |-| Charts (1D) | PieChart, RadialChart, Slice |-| Charts (Scatter) | ScatterChart, ScatterSeries, Point |-| Forms | Form, FormControl, Label, Input, TextArea, Select, DatePicker, Slider, CheckBoxGroup, RadioGroup, SwitchGroup |-| Buttons | Button, Buttons |-| Follow-ups | FollowUpBlock, FollowUpItem |-| Layout | Tabs, Accordion, Carousel |-| Data Display | TagBlock, Tag |-| Typography | Heading, Blockquote, InlineCode |-| Calendar | CalendarBlock |-| Navigation | PaginationBlock |-| Overlays | DialogBlock, AlertDialogBlock, DrawerBlock |--See [Defining Components](/docs/openui-lang/defining-components) for the full `defineComponent` API.--### `src/app/api/chat/route.ts` — SSE streaming with tool execution--The API route reads the generated system prompt, calls the LLM with `runTools()` for server-side tool execution, and streams the response as SSE:--```ts-const client = new OpenAI({- apiKey: process.env.OPENAI_API_KEY,-});-const MODEL = "gpt-5.4";--const runner = client.chat.completions.runTools({- model: MODEL,- messages: chatMessages,- tools,- stream: true,-});--runner.on("chunk", (chunk) => {- const delta = chunk.choices?.[0]?.delta;- if (delta?.content) {- enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));- }-});-```--When the model calls a tool, the route executes it and enriches the response with both the request and result before continuing. This keeps the tool loop entirely server-side — the client only sees the final streamed UI.--## Tools--The API route defines four server-side tools that the LLM can invoke during a conversation:--| Tool | Description |-| ----------------- | -------------------------------------------------------------------------------------- |-| `get_weather` | Returns temperature, conditions, humidity, wind, and a 2-day forecast for a given city |-| `get_stock_price` | Returns price, change, volume, and day range for a ticker symbol |-| `calculate` | Evaluates a math expression and returns the result |-| `search_web` | Returns mock search results for a query |--These are demo implementations with simulated data. In a production app, you would replace them with real API calls.--### `src/lib/shadcn-genui/helpers.ts` — chart data builders--Utility functions that normalize chart data from OpenUI Lang element nodes into the format expected by Recharts:--- `buildChartData(labels, series)` — transforms labels and series nodes into row-based chart data for 2D charts (bar, line, area, radar)-- `buildSliceData(slices)` — transforms slice nodes into data for 1D charts (pie, radial)--## System prompt generation--The `pnpm generate:prompt` script inspects the library definition in `src/lib/shadcn-genui/index.tsx` and generates `src/generated/system-prompt.txt`. This prompt tells the LLM about every available component, its props, and the OpenUI Lang syntax. Re-run it whenever you change component definitions, prop schemas, descriptions, or prompt rules.--See [System Prompts](/docs/openui-lang/system-prompts) for how prompt generation works.