The Open Standard for Generative UI
Add Vercel AI SDK + OpenUI Renderer chat example (#346)
subham10779974ebab
diff --git a/docs/app/api/chat/route.ts b/docs/app/api/chat/route.tsindex 58d49e738..ff42bac34 100644--- a/docs/app/api/chat/route.ts+++ b/docs/app/api/chat/route.ts@@ -6,6 +6,39 @@ import { join } from "path";const systemPrompt = readFileSync(join(process.cwd(), "generated/chat-system-prompt.txt"), "utf-8");+const conversationLog: Array<{ role: string; content: string }> = [];++/* eslint-disable @typescript-eslint/no-explicit-any */+function extractText(msg: any): string {+ const content = msg?.content;+ if (typeof content === "string") {+ try {+ const parsed = JSON.parse(content);+ if (parsed?.parts)+ return parsed.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ } catch {+ /* plain string */+ }+ return content;+ }+ if (Array.isArray(content))+ return content+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (Array.isArray(msg?.parts))+ return msg.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (typeof msg?.text === "string") return msg.text;+ return JSON.stringify(msg);+}+/* eslint-enable @typescript-eslint/no-explicit-any */+// ── Tool implementations ──function getWeather({ location }: { location: string }): Promise<string> {@@ -243,6 +276,10 @@ function sseToolCallArgs(export async function POST(req: NextRequest) {const { messages } = await req.json();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const lastUserMsg = (messages as any[]).filter((m: any) => m.role === "user").pop();+ if (lastUserMsg) conversationLog.push({ role: "user", content: extractText(lastUserMsg) });+const client = new OpenAI({apiKey: process.env.OPENROUTER_API_KEY,baseURL: "https://openrouter.ai/api/v1",@@ -288,6 +325,7 @@ export async function POST(req: NextRequest) {}};+ let fullResponse = "";const pendingCalls: Array<{ id: string; name: string; arguments: string }> = [];let callIdx = 0;let resultIdx = 0;@@ -329,6 +367,7 @@ export async function POST(req: NextRequest) {const delta = choice?.delta;if (!delta) return;if (delta.content) {+ fullResponse += delta.content;enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));}if (choice?.finish_reason === "stop") {@@ -337,6 +376,15 @@ export async function POST(req: NextRequest) {});runner.on("end", () => {+ conversationLog.push({ role: "assistant", content: fullResponse });+ console.info(+ "[OpenUI Lang] Conversation:\n",+ JSON.stringify(+ conversationLog.map((m) => ({ ...m, content: m.content.replace(/\n/g, " ") })),+ null,+ 2,+ ),+ );enqueue(encoder.encode("data: [DONE]\n\n"));close();});diff --git a/docs/app/api/playground/stream/route.ts b/docs/app/api/playground/stream/route.tsindex 3af686b88..59d8b31c5 100644--- a/docs/app/api/playground/stream/route.ts+++ b/docs/app/api/playground/stream/route.ts@@ -8,9 +8,13 @@ const systemPrompt = readFileSync("utf-8",);+const conversationLog: Array<{ role: string; content: string }> = [];+export async function POST(req: NextRequest) {const { model, prompt } = await req.json();+ conversationLog.push({ role: "user", content: prompt });+const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {method: "POST",headers: {@@ -42,7 +46,43 @@ export async function POST(req: NextRequest) {);}- return new Response(res.body, {+ const [streamForClient, streamForLog] = res.body!.tee();++ const reader = streamForLog.getReader();+ const decoder = new TextDecoder();+ let fullResponse = "";+ (async () => {+ let done = false;+ while (!done) {+ const result = await reader.read();+ done = result.done;+ if (result.value) {+ const text = decoder.decode(result.value, { stream: true });+ for (const line of text.split("\n")) {+ if (line.startsWith("data: ") && line !== "data: [DONE]") {+ try {+ const json = JSON.parse(line.slice(6));+ const content = json.choices?.[0]?.delta?.content;+ if (content) fullResponse += content;+ } catch {+ /* skip non-JSON lines */+ }+ }+ }+ }+ }+ conversationLog.push({ role: "assistant", content: fullResponse });+ console.info(+ "[OpenUI Lang] Conversation:\n",+ JSON.stringify(+ conversationLog.map((m) => ({ ...m, content: m.content.replace(/\n/g, " ") })),+ null,+ 2,+ ),+ );+ })();++ return new Response(streamForClient, {headers: {"Content-Type": "text/event-stream","Cache-Control": "no-cache",diff --git a/docs/content/docs/openui-lang/examples/react-native.mdx b/docs/content/docs/openui-lang/examples/react-native.mdxindex a642379e7..71c9d6270 100644--- a/docs/content/docs/openui-lang/examples/react-native.mdx+++ b/docs/content/docs/openui-lang/examples/react-native.mdx@@ -5,7 +5,7 @@ description: stream LLM-generated UI to an Expo app that renders real native comOpenUI 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)+[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/openui-react-native)<div className="bg-[rgba(0,0,0,0.05)] dark:bg-gray-900 rounded-2xl p-2"><videodiff --git a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx b/docs/content/docs/openui-lang/examples/shadcn-chat.mdxindex e15fa8c6c..b4b63f9a0 100644--- a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx+++ b/docs/content/docs/openui-lang/examples/shadcn-chat.mdx@@ -5,7 +5,7 @@ description: An example of connecting OpenUI Lang to a custom component library,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)+[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/shadcn-chat)<div className="bg-[rgba(0,0,0,0.05)] dark:bg-gray-900 rounded-2xl h-[500px] flex p-2"><videodiff --git a/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdx b/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdxnew file mode 100644index 000000000..54bd8506e--- /dev/null+++ b/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdx@@ -0,0 +1,121 @@+---+title: Vercel AI Chat+description: A full-featured chatbot using the Vercel AI SDK for streaming and tool execution, with OpenUI Renderer for generative UI.+---++OpenUI's `<Renderer />` is transport-agnostic — it takes a string of OpenUI Lang markup and renders it as interactive React components, regardless of how that string arrived. This example uses the Vercel AI SDK (`ai`, `@ai-sdk/react`, `@ai-sdk/openai`) as the transport layer, paired with the built-in `openuiChatLibrary` of `OpenUI` as the presentation layer. It includes multi-step tool calling, conversation threading with localStorage persistence, and automatic light/dark theme support.++[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/vercel-ai-chat)++<div className="bg-[rgba(0,0,0,0.05)] dark:bg-gray-900 rounded-2xl h-[500px] flex p-2">+ <video+ src="/videos/vercel-ai-chat.mp4"+ noControls+ playsInline+ muted+ preload="metadata"+ className="w-full rounded-lg m-auto"+ autoPlay+ loop+ />+</div>++## How OpenUI plugs into any chat framework++The backend API route reads a pre-generated system prompt from `src/generated/system-prompt.txt` and calls the LLM with `streamText`. Tool definitions use the AI SDK's `tool()` helper with Zod schemas:++```tsx+import { streamText, convertToModelMessages, stepCountIs } from "ai";+import { openai } from "@ai-sdk/openai";+import { tools } from "@/lib/tools";++export async function POST(req: Request) {+ const { messages } = await req.json();+ const modelMessages = await convertToModelMessages(messages);++ const result = streamText({+ model: openai("gpt-5.4"),+ system: systemPrompt,+ messages: modelMessages,+ tools,+ stopWhen: stepCountIs(5),+ });++ return result.toUIMessageStreamResponse();+}+```++On the client, `useChat` from `@ai-sdk/react` manages conversation state and streaming. Each assistant message passes its accumulated text to `<Renderer />`:++```tsx+import { useChat } from "@ai-sdk/react";+import { Renderer } from "@openuidev/react-lang";+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";++const { messages, sendMessage, status, stop } = useChat({+ id: activeThreadId,+ messages: activeThread?.messages,+});++// In the assistant message component:+<Renderer+ response={textContent}+ library={openuiChatLibrary}+ isStreaming={isStreaming}+ onAction={handleAction}+/>+```++- `response` — the accumulated text the LLM has streamed so far; `<Renderer />` parses it progressively as tokens arrive+- `library` — maps OpenUI Lang nodes to the built-in component set (cards, tables, charts, forms, etc.)+- `isStreaming` — tells the renderer to keep expecting more tokens+- `onAction` — captures interactive events like button clicks and feeds them back into the conversation++Swap out `useChat` and the API route for any other transport — raw `fetch`, LangChain, LlamaIndex — and the `<Renderer />` call stays unchanged.++## Architecture++```+Browser (useChat) -- POST /api/chat --> Next.js route --> LLM+ <-- streaming text -- (OpenUI Lang markup)+```++The API route calls the LLM with `streamText`, the system prompt, and tool definitions. When the LLM invokes a tool (weather, stock price, calculator, or web search), the AI SDK executes it server-side and feeds the result back — up to 5 steps. The response streams back as OpenUI Lang markup.++On the client, `<Renderer />` and `openuiChatLibrary` progressively render each token into interactive UI components as the response arrives.++## Project layout++```+examples/vercel-ai-chat/+|- src/app/ # Next.js app (layout, page, API route)+|- src/components/ # Chat UI components (messages, input, sidebar)+|- src/hooks/ # Theme detection, thread management+|- src/lib/ # Tool definitions, localStorage thread store+|- src/generated/ # Generated system prompt+```++## Run the example++Run these commands from `examples/vercel-ai-chat`.++1. Install dependencies:++```bash+cd examples/vercel-ai-chat+pnpm install+```++2. Create a `.env.local` file with your API key:++```bash+OPENAI_API_KEY=sk-...+```++3. Start the dev server:++```bash+pnpm dev+```++This generates the system prompt from the OpenUI component library and starts the Next.js dev server.diff --git a/docs/content/docs/openui-lang/meta.json b/docs/content/docs/openui-lang/meta.jsonindex 1371143ea..648c604c0 100644--- a/docs/content/docs/openui-lang/meta.json+++ b/docs/content/docs/openui-lang/meta.json@@ -14,7 +14,8 @@"specification","benchmarks","---Examples---",+ "examples/shadcn-chat","examples/react-native",- "examples/shadcn-chat"+ "examples/vercel-ai-chat"]}diff --git a/docs/public/videos/vercel-ai-chat.mp4 b/docs/public/videos/vercel-ai-chat.mp4new file mode 100644index 000000000..217276b0dBinary files /dev/null and b/docs/public/videos/vercel-ai-chat.mp4 differdiff --git a/examples/openui-react-native/backend/src/app/api/chat/route.ts b/examples/openui-react-native/backend/src/app/api/chat/route.tsindex e81588404..3a5c893dc 100644--- a/examples/openui-react-native/backend/src/app/api/chat/route.ts+++ b/examples/openui-react-native/backend/src/app/api/chat/route.ts@@ -6,10 +6,48 @@ import { join } from "path";const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY ?? "" });const SYSTEM_PROMPT = readFileSync(join(process.cwd(), "src", "system-prompt.txt"), "utf-8");+console.info("[OpenUI Lang] System prompt loaded:\n", SYSTEM_PROMPT);++const conversationLog: Array<{ role: string; content: string }> = [];++/* eslint-disable @typescript-eslint/no-explicit-any */+function extractText(msg: any): string {+ const content = msg?.content;+ if (typeof content === "string") {+ try {+ const parsed = JSON.parse(content);+ if (parsed?.parts)+ return parsed.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ } catch {+ /* plain string */+ }+ return content;+ }+ if (Array.isArray(content))+ return content+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (Array.isArray(msg?.parts))+ return msg.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (typeof msg?.text === "string") return msg.text;+ return JSON.stringify(msg);+}+/* eslint-enable @typescript-eslint/no-explicit-any */export async function POST(req: NextRequest) {const { messages } = await req.json();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const lastUserMsg = (messages as any[]).filter((m: any) => m.role === "user").pop();+ if (lastUserMsg) conversationLog.push({ role: "user", content: extractText(lastUserMsg) });+const completion = await openai.chat.completions.create({model: "gpt-4o",stream: true,@@ -19,12 +57,23 @@ export async function POST(req: NextRequest) {// Stream raw text chunks — simpler for React Native to consume than SSEconst readable = new ReadableStream({async start(controller) {+ let fullResponse = "";for await (const chunk of completion) {const text = chunk.choices[0]?.delta?.content ?? "";if (text) {+ fullResponse += text;controller.enqueue(new TextEncoder().encode(text));}}+ conversationLog.push({ role: "assistant", content: fullResponse });+ console.info(+ "[OpenUI Lang] Conversation:\n",+ JSON.stringify(+ conversationLog.map((m) => ({ ...m, content: m.content.replace(/\n/g, " ") })),+ null,+ 2,+ ),+ );controller.close();},});diff --git a/examples/shadcn-chat/README.md b/examples/shadcn-chat/README.mdnew file mode 100644index 000000000..6f2250d1f--- /dev/null+++ b/examples/shadcn-chat/README.md@@ -0,0 +1,278 @@+# Shadcn Chat Example++A full-stack generative UI chatbot that demonstrates wiring [OpenUI Lang](https://www.openui.com/docs/openui-lang/overview) to a custom component library built on [shadcn/ui](https://ui.shadcn.com/). Instead of replying with plain text or markdown, the LLM generates structured UI markup that the client renders as shadcn/ui components — cards, tables, charts, forms, dialogs, and more — in real time as tokens stream in.++Features: 45+ custom shadcn/ui components, multi-step tool calling, Server-Sent Events (SSE) streaming, and automatic light/dark theme support.++<video src="../../docs/public/videos/shadcn-demo-chat.mp4"+ noControls+ playsInline+ muted+ preload="metadata"+ className="w-full rounded-lg m-auto"+ autoPlay+ loop+/>++[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/shadcn-chat)++---++## How It Works++The LLM is prompted with a system prompt that describes every available shadcn/ui component — its name, props, and when to use it. Instead of writing prose, the model responds in **OpenUI Lang**: a declarative markup syntax that maps directly to React components. For example:++```+Card([+ CardHeader(title="Q1 Sales Report"),+ Table(columns=["Product", "Revenue"], rows=[...]),+ BarChart(data=[...], title="Monthly Trend")+])+```++On the client, the `<FullScreen />` component from `@openuidev/react-ui` handles everything — conversation state, streaming, input, and rendering. It parses the incoming SSE stream with `openAIAdapter()` and renders each OpenUI Lang node using `shadcnChatLibrary` — the custom 45-component library defined in `src/lib/shadcn-genui/`.++---++## Architecture++```+┌────────────────────────────────────┐ ┌────────────────────────────────────┐+│ Browser │ HTTP │ Next.js API Route │+│ │ ──────►│ │+│ • <FullScreen /> manages UI │ │ • Loads system-prompt.txt │+│ • openAIAdapter() parses SSE │◄────── │ • Calls LLM with runTools │+│ • shadcnChatLibrary renders nodes │ SSE │ • Executes tools server-side │+│ • Conversation starters included │ │ • Streams response as SSE events │+└────────────────────────────────────┘ └────────────────────────────────────┘+```++### Request / Response Flow++1. User types a message. `<FullScreen />` calls `processMessage`, which sends `POST /api/chat` with the conversation history formatted via `openAIMessageFormat.toApi()`.+2. The API route reads `system-prompt.txt`, instantiates an OpenAI client, and calls `runTools` — the OpenAI SDK's built-in multi-step tool execution loop.+3. If the LLM calls a tool, `runTools` executes it server-side and feeds the result back into the model automatically, emitting SSE events for the tool call and result.+4. The LLM generates a final OpenUI Lang response. Text deltas are streamed as SSE `chunk` events. The stream ends with `data: [DONE]`.+5. On the client, `openAIAdapter()` parses the SSE events and hands the accumulated text to `<FullScreen />`'s internal renderer.+6. The renderer passes the text to `<Renderer response={text} library={shadcnChatLibrary} />`, which parses the OpenUI Lang markup and renders each node as a shadcn/ui component in real time.++---++## Project Structure++```+shadcn-chat/+├── src/+│ ├── app/+│ │ ├── api/chat/route.ts # Streaming chat endpoint (OpenAI SDK + SSE)+│ │ ├── page.tsx # Single page — mounts <FullScreen />+│ │ └── layout.tsx # Root layout with ThemeProvider+│ ├── components/ui/ # Base shadcn/ui primitives (accordion, card, table, etc.)+│ ├── hooks/+│ │ └── use-system-theme.tsx # Detects and provides system light/dark preference+│ ├── lib/+│ │ └── shadcn-genui/ # Custom OpenUI component library+│ │ ├── index.tsx # Library export — createLibrary() call+│ │ ├── action.ts # Button action Zod schemas+│ │ ├── helpers.ts # Chart data builder utilities+│ │ ├── rules.ts # Form validation rule schemas+│ │ ├── unions.ts # Zod union types for component children+│ │ └── components/ # One file per component (45+ total)+│ └── generated/+│ └── system-prompt.txt # Auto-generated — do not edit manually+└── package.json+```++---++## Getting Started++### Prerequisites++- Node.js 18++- pnpm+- An OpenAI API key++### 1. Install dependencies++```bash+cd examples/shadcn-chat+pnpm install+```++### 2. Configure environment++Create a `.env.local` file in the `examples/shadcn-chat/` directory:++```+OPENAI_API_KEY=sk-...+```++### 3. Start the dev server++```bash+pnpm dev+```++This runs `generate:prompt` first (compiles the component library → `src/generated/system-prompt.txt`) then starts the Next.js dev server at `http://localhost:3000`.++---++## What's in This Example++### System Prompt Generation++The `src/lib/shadcn-genui/index.tsx` file defines the entire component library using `createLibrary()`. At dev time, the OpenUI CLI reads this library and generates `src/generated/system-prompt.txt` — a text file containing every component's name, prop schema, description, and usage examples. This is what the LLM receives as its system prompt.++Re-run generation any time you change component definitions:++```bash+pnpm generate:prompt+```++### `src/app/api/chat/route.ts` — Backend++The route uses `client.chat.completions.runTools()` from the OpenAI SDK, which handles the full agentic loop: if the LLM calls a tool, the SDK executes it and feeds the result back automatically until the model produces a final text response.++The response is streamed as **Server-Sent Events (SSE)**. Three types of SSE events are emitted:++| Event type | When emitted | What it carries |+| ---------- | ------------ | --------------- |+| Tool call start | LLM invokes a tool | Tool name and ID |+| Tool call result | Tool execution completes | Enriched JSON with `_request` and `_response` |+| Text chunk | LLM generates text tokens | The OpenUI Lang markup delta |++Messages are cleaned before sending to the API: `tool` role messages are stripped, and `tool_calls` are removed from assistant messages (since `runTools` reruns the agentic loop server-side on each request).++### `src/app/page.tsx` — Frontend++The entire chat interface is the `<FullScreen />` component from `@openuidev/react-ui`. You configure it with three things:++| Prop | Value | Purpose |+| ---- | ----- | ------- |+| `processMessage` | `fetch("/api/chat", ...)` | How to call your backend |+| `streamProtocol` | `openAIAdapter()` | How to parse the SSE stream |+| `componentLibrary` | `shadcnChatLibrary` | Which components to render OpenUI Lang nodes with |++`openAIAdapter()` is imported from `@openuidev/react-headless`. It knows how to parse the OpenAI-style SSE format emitted by this route. `openAIMessageFormat.toApi()` converts the internal message objects into the format the OpenAI API expects.++The page also includes 7 built-in conversation starters to showcase the component library:++| Starter | What it demonstrates |+| ------- | -------------------- |+| Startup dashboard | Tabs, BarChart, LineChart, PieChart, Table, Progress, Tags |+| Travel planner | CalendarBlock, Accordion, Tags, Form (Select, Slider, Checkboxes) |+| Market watch | Tool calling (get_stock_price), Table, Alert, DrawerBlock, BarChart |+| Event RSVP | Form (Input, Select, RadioGroup, DatePicker, Slider, Checkboxes, Switches) |+| Team standup | Progress, Table, Alert, Accordion, DialogBlock, PieChart |+| Recipe card | Tabs, Accordion, PieChart, Button, DialogBlock |+| Chart showcase | All 6 chart types: Bar, Line, Area, Pie, Radar, Scatter + RadialChart |++### `src/lib/shadcn-genui/` — Custom Component Library++Each component is defined with `defineComponent()` from `@openuidev/react-lang`, which takes:++- `name` — the OpenUI Lang node name the LLM will emit+- `props` — a Zod schema that validates and types the node's props as they stream in+- `description` — included in the system prompt so the LLM knows when and how to use the component+- `component` — the React render function; `renderNode()` recursively renders child nodes++The full library (`shadcnChatLibrary`) is assembled with `createLibrary({ root: "Card", components: [...] })`.++#### Component Groups++| Group | Components |+| ----- | ---------- |+| **Content** | `Card`, `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`, `SelectItem`, `DatePicker`, `Slider`, `CheckBoxGroup`, `CheckBoxItem`, `RadioGroup`, `RadioItem`, `SwitchGroup`, `SwitchItem` |+| **Buttons** | `Button`, `Buttons` |+| **Follow-ups** | `FollowUpBlock`, `FollowUpItem` |+| **Layout** | `Tabs`, `TabItem`, `Accordion`, `AccordionItemDef`, `Carousel` |+| **Data Display** | `TagBlock`, `Tag` |+| **Typography** | `Heading`, `Blockquote`, `InlineCode` |+| **Navigation** | `PaginationBlock` |+| **Overlays** | `DialogBlock`, `AlertDialogBlock`, `DrawerBlock` |+| **Calendar** | `CalendarBlock` |++### Mock Tools++All four tools are mock implementations with simulated network delays. They return realistic-looking data so the LLM can generate rich UI responses.++#### `get_weather`++Returns current conditions and a two-day forecast for a city.++- **Input**: `location` (string) — city name+- **Simulated delay**: 800ms+- **Returns**:++| Field | Example |+| ----- | ------- |+| `temperature_celsius` | `22` |+| `temperature_fahrenheit` | `72` |+| `condition` | `"Sunny"` |+| `humidity_percent` | `65` |+| `wind_speed_kmh` | `12` |+| `forecast` | 2-day array with `high`, `low`, `condition` |++Hardcoded temperatures for: Tokyo (22°C), San Francisco (18°C), London (14°C), New York (25°C), Paris (19°C), Sydney (27°C), Mumbai (33°C), Berlin (16°C). Other cities get a random value.++#### `get_stock_price`++Returns current price data for a stock ticker.++- **Input**: `symbol` (string) — e.g. `AAPL`+- **Simulated delay**: 600ms+- **Returns**:++| Field | Example |+| ----- | ------- |+| `price` | `190.12` |+| `change` | `+0.28` |+| `change_percent` | `+0.15%` |+| `volume` | `"42.3M"` |+| `day_high` | `191.50` |+| `day_low` | `188.90` |++Hardcoded prices for: AAPL ($189.84), GOOGL ($141.80), TSLA ($248.42), MSFT ($378.91), AMZN ($178.25), NVDA ($875.28), META ($485.58). Other tickers get a random price.++#### `calculate`++Evaluates a math expression safely.++- **Input**: `expression` (string) — e.g. `"2 * (3 + 4)"` or `"Math.sqrt(144)"`+- **Simulated delay**: 300ms+- **Supports**: `+`, `-`, `*`, `/`, `()`, `%`, `Math.sqrt`, `pow`, `abs`, `ceil`, `floor`, `round`+- **Returns**: `{ expression, result }` or `{ expression, error }` on invalid input++#### `search_web`++Returns mock search results for any query.++- **Input**: `query` (string) — the search term+- **Simulated delay**: 1000ms+- **Returns**: an array of 3 results, each with `title` and `snippet` templated from the query string++---++## Scripts++| Script | Description |+| ------ | ----------- |+| `pnpm dev` | Generate system prompt, then start the Next.js dev server |+| `pnpm generate:prompt` | Recompile `shadcn-genui` → `src/generated/system-prompt.txt` |+| `pnpm build` | Build for production |+| `pnpm start` | Start the production server |++---++## Learn More++- [OpenUI Lang overview](https://www.openui.com/docs/openui-lang/overview) — Library, Prompt Generator, Parser, Renderer+- [Defining Components](https://www.openui.com/docs/openui-lang/defining-components) — `defineComponent` and `createLibrary` API+- [shadcn/ui](https://ui.shadcn.com/) — the underlying component system+- [`@openuidev/react-lang` package](../../packages/react-lang)diff --git a/examples/shadcn-chat/src/app/api/chat/route.ts b/examples/shadcn-chat/src/app/api/chat/route.tsindex 1ec51349e..339f4a401 100644--- a/examples/shadcn-chat/src/app/api/chat/route.ts+++ b/examples/shadcn-chat/src/app/api/chat/route.ts@@ -6,6 +6,39 @@ import { join } from "path";const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");+const conversationLog: Array<{ role: string; content: string }> = [];++/* eslint-disable @typescript-eslint/no-explicit-any */+function extractText(msg: any): string {+ const content = msg?.content;+ if (typeof content === "string") {+ try {+ const parsed = JSON.parse(content);+ if (parsed?.parts)+ return parsed.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ } catch {+ /* plain string */+ }+ return content;+ }+ if (Array.isArray(content))+ return content+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (Array.isArray(msg?.parts))+ return msg.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (typeof msg?.text === "string") return msg.text;+ return JSON.stringify(msg);+}+/* eslint-enable @typescript-eslint/no-explicit-any */+// ── Tool implementations ──function getWeather({ location }: { location: string }): Promise<string> {@@ -244,6 +277,10 @@ function sseToolCallArgs(export async function POST(req: NextRequest) {const { messages } = await req.json();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const lastUserMsg = (messages as any[]).filter((m: any) => m.role === "user").pop();+ if (lastUserMsg) conversationLog.push({ role: "user", content: extractText(lastUserMsg) });+const client = new OpenAI({apiKey: process.env.OPENAI_API_KEY,});@@ -290,6 +327,7 @@ export async function POST(req: NextRequest) {}};+ let fullResponse = "";const pendingCalls: Array<{ id: string; name: string; arguments: string }> = [];let callIdx = 0;let resultIdx = 0;@@ -331,6 +369,7 @@ export async function POST(req: NextRequest) {const delta = choice?.delta;if (!delta) return;if (delta.content) {+ fullResponse += delta.content;enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));}if (choice?.finish_reason === "stop") {@@ -339,6 +378,15 @@ export async function POST(req: NextRequest) {});runner.on("end", () => {+ conversationLog.push({ role: "assistant", content: fullResponse });+ console.info(+ "[OpenUI Lang] Conversation:\n",+ JSON.stringify(+ conversationLog.map((m) => ({ ...m, content: m.content.replace(/\n/g, " ") })),+ null,+ 2,+ ),+ );enqueue(encoder.encode("data: [DONE]\n\n"));close();});diff --git a/examples/vercel-ai-chat/.gitignore b/examples/vercel-ai-chat/.gitignorenew file mode 100644index 000000000..63271800a--- /dev/null+++ b/examples/vercel-ai-chat/.gitignore@@ -0,0 +1,39 @@+# dependencies+/node_modules+/.pnp+.pnp.*+.yarn/*+!.yarn/patches+!.yarn/plugins+!.yarn/releases+!.yarn/versions++# testing+/coverage++# next.js+/.next/+/out/++# production+/build++# misc+.DS_Store+*.pem++# debug+npm-debug.log*+yarn-debug.log*+yarn-error.log*+.pnpm-debug.log*++# env files (can opt-in for committing if needed)+.env*++# vercel+.vercel++# typescript+*.tsbuildinfo+next-env.d.tsdiff --git a/examples/vercel-ai-chat/README.md b/examples/vercel-ai-chat/README.mdnew file mode 100644index 000000000..a624ba15f--- /dev/null+++ b/examples/vercel-ai-chat/README.md@@ -0,0 +1,270 @@+# Vercel AI Chat Example++A full-stack generative UI chatbot built with the [Vercel AI SDK](https://ai-sdk.dev/) and [OpenUI Lang](https://www.openui.com/docs/openui-lang/overview). Instead of replying with plain text or markdown, the LLM generates structured UI markup that the client renders as interactive React components — cards, tables, charts, forms, and more — in real time as tokens stream in.++Features: multi-step tool calling, persistent conversation threads (localStorage), collapsible sidebar, and automatic light/dark theme support.++<video src="../../docs/public/videos/vercel-ai-chat.mp4"+ noControls+ playsInline+ muted+ preload="metadata"+ className="w-full rounded-lg m-auto"+ autoPlay+ loop+/>++[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/vercel-ai-chat)++---++## How It Works++The LLM is prompted with a system prompt that describes a set of UI components — their names, props, and when to use them. Instead of writing prose, the model responds in **OpenUI Lang**: a declarative markup syntax that maps directly to React components. For example:++```+Card([+ CardHeader(title="Weather in Tokyo"),+ BarChart(data=[...], title="Temperature this week")+])+```++On the client, `<Renderer />` from `@openuidev/react-lang` parses this markup token-by-token as it streams in and renders it as real React components. The user sees UI building up live — not a wall of text.++The Vercel AI SDK handles the streaming transport on both ends:+- **Backend**: `streamText` calls the LLM, executes tools, and streams the response.+- **Frontend**: `useChat` manages message state, accumulates the streamed text, and triggers re-renders.++---++## Architecture++```+┌────────────────────────────────────┐ ┌────────────────────────────────────┐+│ Browser │ HTTP │ Next.js API Route │+│ │ ──────►│ │+│ • useChat manages message state │ │ • Loads system-prompt.txt │+│ • <Renderer /> parses OpenUI Lang │◄────── │ • Calls LLM with streamText │+│ • openuiChatLibrary renders UI │ stream │ • Executes tools server-side │+│ • Sidebar with thread history │ │ • Returns toUIMessageStreamResponse│+└────────────────────────────────────┘ └────────────────────────────────────┘+```++### Request / Response Flow++1. User types a message. `useChat` sends `POST /api/chat` with the full conversation history.+2. The API route reads `system-prompt.txt`, calls `streamText` with the model, system prompt, messages, and tool definitions.+3. If the LLM calls a tool, the Vercel AI SDK executes it server-side and feeds the result back into the model. This loop runs up to 5 steps (`stopWhen: stepCountIs(5)`).+4. The LLM generates a final OpenUI Lang response and it streams back via `toUIMessageStreamResponse()`.+5. `useChat` accumulates the streaming text and passes it to `<AssistantMessage />`.+6. `<AssistantMessage />` feeds the accumulated text into `<Renderer response={text} library={openuiChatLibrary} isStreaming={isStreaming} />`.+7. `<Renderer />` parses the markup progressively and renders live React components as each token arrives.+8. When the stream ends, `isStreaming` is set to `false`. The message is saved to localStorage via `useThreads`.++---++## Project Structure++```+vercel-ai-chat/+├── src/+│ ├── app/+│ │ ├── api/chat/route.ts # Streaming chat endpoint (Vercel AI SDK)+│ │ ├── page.tsx # Main chat page — wires useChat + components+│ │ └── layout.tsx # Root layout with ThemeProvider+│ ├── components/+│ │ ├── assistant-message.tsx # Renders <Renderer /> for each AI reply+│ │ ├── user-message.tsx # Renders user messages+│ │ ├── chat-input.tsx # Textarea input with send / stop buttons+│ │ ├── chat-header.tsx # Top bar with sidebar toggle+│ │ ├── sidebar.tsx # Thread list with new/switch/delete+│ │ ├── sidebar-toggle.tsx # Mobile sidebar toggle button+│ │ ├── conversation-starters.tsx # Suggested prompts on empty chat+│ │ ├── thinking-indicator.tsx # Animated dots while model is thinking+│ │ └── tool-call-indicator.tsx # Shows which tool is running+│ ├── hooks/+│ │ ├── use-system-theme.tsx # Detects system light/dark preference+│ │ └── use-threads.ts # Thread CRUD + localStorage persistence+│ ├── lib/+│ │ ├── tools.ts # Four mock tool definitions (Vercel AI SDK format)+│ │ └── thread-store.ts # Read/write threads to localStorage+│ ├── library.ts # OpenUI library export for prompt generation+│ └── generated/+│ └── system-prompt.txt # Auto-generated — do not edit manually+└── package.json+```++---++## Getting Started++### Prerequisites++- Node.js 18++- pnpm+- An OpenAI API key++### 1. Install dependencies++```bash+cd examples/vercel-ai-chat+pnpm install+```++### 2. Configure environment++```bash+cp .env.example .env.local+```++Add your key to `.env.local`:++```+OPENAI_API_KEY=sk-...+```++### 3. Start the dev server++```bash+pnpm dev+```++This runs `generate:prompt` first (compiles `src/library.ts` → `src/generated/system-prompt.txt`) then starts the Next.js dev server at `http://localhost:3000`.++---++## What's in This Example++### System Prompt Generation++`src/library.ts` re-exports `openuiChatLibrary` (as `library`) and `openuiChatPromptOptions` (as `promptOptions`) from `@openuidev/react-ui/genui-lib`. At dev time, the OpenUI CLI reads this file and generates `src/generated/system-prompt.txt` — a text file containing every component's name, prop schema, description, and usage examples. This is what the LLM receives as the system prompt, teaching it which components exist and how to use them.++Re-run generation any time you change component definitions:++```bash+pnpm generate:prompt+```++### `src/app/api/chat/route.ts` — Backend++The API route uses the Vercel AI SDK's `streamText` with five arguments:++| Argument | Value | Purpose |+| -------- | ----- | ------- |+| `model` | `openai("gpt-5.4")` | The LLM to call |+| `system` | contents of `system-prompt.txt` | Teaches the model OpenUI Lang and the available components |+| `messages` | conversation history from client | The full thread so far |+| `tools` | four tool definitions | Functions the LLM can call mid-generation |+| `stopWhen` | `stepCountIs(5)` | Stops the tool-call loop after 5 steps maximum |++`convertToModelMessages` bridges the Vercel AI SDK's `UIMessage` client format to the `ModelMessage` server format. `toUIMessageStreamResponse()` serializes the stream in the format `useChat` on the client expects.++### `src/components/assistant-message.tsx` — Frontend Renderer++Each assistant message is rendered by `<AssistantMessage />`, which:++1. Finds all `text` parts in the message (filtering out tool-call parts).+2. Concatenates them into `textContent`.+3. Passes it to `<Renderer />`:++```tsx+<Renderer+ response={textContent}+ library={openuiChatLibrary}+ isStreaming={isStreaming}+ onAction={handleAction}+/>+```++The `onAction` handler listens for `BuiltinActionType.ContinueConversation` events — fired when the user clicks a follow-up button inside a rendered card — and calls `onSend(event.humanFriendlyMessage)` to feed it back into the conversation.++### `src/hooks/use-threads.ts` — Thread Management++Conversations are organized into threads. Each thread has an `id`, `title` (derived from the first user message), `messages`, and timestamps. Threads are stored in localStorage under the key `vercel-ai-chat-threads`.++The hook exposes:++| Function | Description |+| -------- | ----------- |+| `createThread()` | Creates a new empty thread and makes it active |+| `switchThread(id)` | Loads a previous thread's messages into `useChat` |+| `deleteThread(id)` | Removes a thread; switches to a new one if it was active |+| `persistMessages(messages)` | Saves the current `useChat` messages to localStorage |++### `src/lib/tools.ts` — Mock Tools++All four tools are mock implementations with simulated network delays. They return realistic-looking data so the LLM can generate rich UI responses.++#### `get_weather`++Returns current conditions and a two-day forecast for a city.++- **Input**: `location` (string) — city name+- **Simulated delay**: 800ms+- **Returns**:++| Field | Example |+| ----- | ------- |+| `temperature_celsius` | `22` |+| `temperature_fahrenheit` | `72` |+| `condition` | `"Sunny"` |+| `humidity_percent` | `65` |+| `wind_speed_kmh` | `12` |+| `forecast` | `[{ day, high, low, condition }, ...]` (2 days) |++Hardcoded temperatures for: Tokyo (22°C), San Francisco (18°C), London (14°C), New York (25°C), Paris (19°C), Sydney (27°C), Mumbai (33°C), Berlin (16°C). Any other city gets a random temperature between 5–35°C.++#### `get_stock_price`++Returns current price data for a stock ticker.++- **Input**: `symbol` (string) — e.g. `AAPL`+- **Simulated delay**: 600ms+- **Returns**:++| Field | Example |+| ----- | ------- |+| `price` | `190.12` |+| `change` | `+0.28` |+| `change_percent` | `+0.15%` |+| `volume` | `"42.3M"` |+| `day_high` | `191.50` |+| `day_low` | `188.90` |++Hardcoded prices for: AAPL ($189.84), GOOGL ($141.80), TSLA ($248.42), MSFT ($378.91), AMZN ($178.25), NVDA ($875.28), META ($485.58). Other tickers get a random price.++#### `calculate`++Evaluates a math expression safely.++- **Input**: `expression` (string) — e.g. `"2 * (3 + 4)"` or `"Math.sqrt(144)"`+- **Simulated delay**: 300ms+- **Supports**: `+`, `-`, `*`, `/`, `()`, `%`, `Math.sqrt`, `pow`, `abs`, `ceil`, `floor`, `round`+- **Returns**: `{ expression, result }` or `{ expression, error }` on invalid input++#### `search_web`++Returns mock search results for any query.++- **Input**: `query` (string) — the search term+- **Simulated delay**: 1000ms+- **Returns**: an array of 3 results, each with `title` and `snippet` templated from the query string++---++## Scripts++| Script | Description |+| ------ | ----------- |+| `pnpm dev` | Generate system prompt, then start the Next.js dev server |+| `pnpm generate:prompt` | Recompile `src/library.ts` → `src/generated/system-prompt.txt` |+| `pnpm build` | Build for production |+| `pnpm start` | Start the production server |++---++## Learn More++- [OpenUI Lang overview](https://www.openui.com/docs/openui-lang/overview) — Library, Prompt Generator, Parser, Renderer+- [Vercel AI SDK docs](https://ai-sdk.dev/) — `streamText`, `useChat`, `tool()`+- [`@openuidev/react-lang` package](../../packages/react-lang)diff --git a/examples/vercel-ai-chat/eslint.config.mjs b/examples/vercel-ai-chat/eslint.config.mjsnew file mode 100644index 000000000..199c0ecf8--- /dev/null+++ b/examples/vercel-ai-chat/eslint.config.mjs@@ -0,0 +1,16 @@+import { defineConfig, globalIgnores } from "eslint/config";+import nextVitals from "eslint-config-next/core-web-vitals";+import nextTs from "eslint-config-next/typescript";++const eslintConfig = defineConfig([+ ...nextVitals,+ ...nextTs,+ globalIgnores([+ ".next/**",+ "out/**",+ "build/**",+ "next-env.d.ts",+ ]),+]);++export default eslintConfig;diff --git a/examples/vercel-ai-chat/next.config.ts b/examples/vercel-ai-chat/next.config.tsnew file mode 100644index 000000000..cd052058f--- /dev/null+++ b/examples/vercel-ai-chat/next.config.ts@@ -0,0 +1,8 @@+import type { NextConfig } from "next";++const nextConfig: NextConfig = {+ turbopack: {},+ transpilePackages: ["@openuidev/react-ui", "@openuidev/react-lang"],+};++export default nextConfig;diff --git a/examples/vercel-ai-chat/package.json b/examples/vercel-ai-chat/package.jsonnew file mode 100644index 000000000..05302798d--- /dev/null+++ b/examples/vercel-ai-chat/package.json@@ -0,0 +1,35 @@+{+ "name": "vercel-ai-chat",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "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": {+ "@ai-sdk/openai": "^3.0.41",+ "@ai-sdk/react": "^3.0.118",+ "@openuidev/cli": "workspace:*",+ "@openuidev/react-lang": "workspace:*",+ "@openuidev/react-ui": "workspace:*",+ "ai": "^6.0.116",+ "lucide-react": "^0.575.0",+ "next": "16.1.6",+ "react": "19.2.3",+ "react-dom": "19.2.3",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4",+ "@types/node": "^20",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "16.1.6",+ "tailwindcss": "^4",+ "typescript": "^5"+ }+}diff --git a/examples/vercel-ai-chat/postcss.config.mjs b/examples/vercel-ai-chat/postcss.config.mjsnew file mode 100644index 000000000..61e36849c--- /dev/null+++ b/examples/vercel-ai-chat/postcss.config.mjs@@ -0,0 +1,7 @@+const config = {+ plugins: {+ "@tailwindcss/postcss": {},+ },+};++export default config;diff --git a/examples/vercel-ai-chat/src/app/api/chat/route.ts b/examples/vercel-ai-chat/src/app/api/chat/route.tsnew file mode 100644index 000000000..56b773c6b--- /dev/null+++ b/examples/vercel-ai-chat/src/app/api/chat/route.ts@@ -0,0 +1,72 @@+import { tools } from "@/lib/tools";+import { openai } from "@ai-sdk/openai";+import { convertToModelMessages, stepCountIs, streamText } from "ai";+import { readFileSync } from "fs";+import { join } from "path";++const systemPrompt = readFileSync(join(process.cwd(), "src/generated/system-prompt.txt"), "utf-8");++const conversationLog: Array<{ role: string; content: string }> = [];++/* eslint-disable @typescript-eslint/no-explicit-any */+function extractText(msg: any): string {+ const content = msg?.content;+ if (typeof content === "string") {+ try {+ const parsed = JSON.parse(content);+ if (parsed?.parts)+ return parsed.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ } catch {+ /* plain string */+ }+ return content;+ }+ if (Array.isArray(content))+ return content+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (Array.isArray(msg?.parts))+ return msg.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("");+ if (typeof msg?.text === "string") return msg.text;+ return JSON.stringify(msg);+}+/* eslint-enable @typescript-eslint/no-explicit-any */++export async function POST(req: Request) {+ const { messages } = await req.json();++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const lastUserMsg = (messages as any[]).filter((m: any) => m.role === "user").pop();+ if (lastUserMsg) conversationLog.push({ role: "user", content: extractText(lastUserMsg) });++ const modelMessages = await convertToModelMessages(messages);++ const result = streamText({+ model: openai("gpt-5.4"),+ system: systemPrompt,+ messages: modelMessages,+ tools,+ stopWhen: stepCountIs(5),+ });++ result.text.then((text) => {+ conversationLog.push({ role: "assistant", content: text });+ console.info(+ "[OpenUI Lang] Conversation:\n",+ JSON.stringify(+ conversationLog.map((m) => ({ ...m, content: m.content.replace(/\n/g, " ") })),+ null,+ 2,+ ),+ );+ });++ return result.toUIMessageStreamResponse();+}diff --git a/examples/vercel-ai-chat/src/app/globals.css b/examples/vercel-ai-chat/src/app/globals.cssnew file mode 100644index 000000000..e4ac5af9b--- /dev/null+++ b/examples/vercel-ai-chat/src/app/globals.css@@ -0,0 +1,2 @@+@import "tailwindcss";+@import "@openuidev/react-ui/components.css";diff --git a/examples/vercel-ai-chat/src/app/layout.tsx b/examples/vercel-ai-chat/src/app/layout.tsxnew file mode 100644index 000000000..b4a6e9b58--- /dev/null+++ b/examples/vercel-ai-chat/src/app/layout.tsx@@ -0,0 +1,22 @@+import type { Metadata } from "next";+import { ThemeProvider } from "@/hooks/use-system-theme";+import "./globals.css";++export const metadata: Metadata = {+ title: "Vercel AI Chat",+ description: "Generative UI Chat with Vercel AI SDK + OpenUI Renderer",+};++export default function RootLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <html lang="en">+ <body>+ <ThemeProvider>{children}</ThemeProvider>+ </body>+ </html>+ );+}diff --git a/examples/vercel-ai-chat/src/app/page.tsx b/examples/vercel-ai-chat/src/app/page.tsxnew file mode 100644index 000000000..b08b0a679--- /dev/null+++ b/examples/vercel-ai-chat/src/app/page.tsx@@ -0,0 +1,123 @@+"use client";++import "@openuidev/react-ui/components.css";++import { useChat } from "@ai-sdk/react";+import { useRef, useEffect, useState } from "react";+import { useTheme } from "@/hooks/use-system-theme";+import { useThreads } from "@/hooks/use-threads";+import { ChatHeader } from "@/components/chat-header";+import { ChatInput } from "@/components/chat-input";+import { ConversationStarters } from "@/components/conversation-starters";+import { AssistantMessage } from "@/components/assistant-message";+import { UserMessage } from "@/components/user-message";+import { ThinkingIndicator } from "@/components/thinking-indicator";+import { Sidebar } from "@/components/sidebar";++export default function Page() {+ useTheme();+ const scrollRef = useRef<HTMLDivElement>(null);+ const [input, setInput] = useState("");++ const {+ threads,+ activeThreadId,+ activeThread,+ sidebarOpen,+ setSidebarOpen,+ persistMessages,+ createThread,+ switchThread,+ deleteThread,+ } = useThreads();++ const { messages, sendMessage, status, stop } = useChat({+ id: activeThreadId,+ messages: activeThread?.messages,+ });++ const isLoading = status === "submitted" || status === "streaming";++ // Auto-save messages to localStorage+ useEffect(() => {+ if (messages.length > 0) {+ persistMessages(messages);+ }+ }, [messages, persistMessages]);++ useEffect(() => {+ if (scrollRef.current) {+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;+ }+ }, [messages]);++ const handleSend = (text: string) => {+ const trimmed = text.trim();+ if (!trimmed || isLoading) return;+ setInput("");+ sendMessage({ text: trimmed });+ };++ const isEmpty = messages.length === 0;+ const lastIsUser = messages[messages.length - 1]?.role === "user";++ return (+ <div className="h-screen bg-white dark:bg-zinc-950">+ <Sidebar+ threads={threads}+ activeThreadId={activeThreadId}+ isOpen={sidebarOpen}+ onNewChat={createThread}+ onSelectThread={switchThread}+ onDeleteThread={deleteThread}+ onClose={() => setSidebarOpen(false)}+ />++ <div+ className={`flex flex-col h-full transition-[margin] duration-200 ease-in-out ${+ sidebarOpen ? "md:ml-[280px]" : "ml-0"+ }`}+ >+ <ChatHeader+ isSidebarOpen={sidebarOpen}+ onToggleSidebar={() => setSidebarOpen((o) => !o)}+ />++ <div ref={scrollRef} className="flex-1 overflow-y-auto">+ {isEmpty ? (+ <ConversationStarters onSelect={handleSend} />+ ) : (+ <div className="max-w-3xl mx-auto px-4 py-6 space-y-6">+ {messages.map((m, i) => {+ const isLast = i === messages.length - 1;+ if (m.role === "assistant") {+ return (+ <AssistantMessage+ key={m.id}+ message={m}+ isStreaming={isLoading && isLast}+ onSend={handleSend}+ />+ );+ }+ if (m.role === "user") {+ return <UserMessage key={m.id} message={m} />;+ }+ return null;+ })}+ {isLoading && lastIsUser && <ThinkingIndicator />}+ </div>+ )}+ </div>++ <ChatInput+ input={input}+ isLoading={isLoading}+ onInputChange={setInput}+ onSend={handleSend}+ onStop={stop}+ />+ </div>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/components/assistant-message.tsx b/examples/vercel-ai-chat/src/components/assistant-message.tsxnew file mode 100644index 000000000..84c0c9815--- /dev/null+++ b/examples/vercel-ai-chat/src/components/assistant-message.tsx@@ -0,0 +1,69 @@+import type { ActionEvent } from "@openuidev/react-lang";+import { BuiltinActionType, Renderer } from "@openuidev/react-lang";+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";+import type { UIMessage } from "ai";+import { Bot } from "lucide-react";+import { ToolCallIndicator } from "./tool-call-indicator";++interface AssistantMessageProps {+ message: UIMessage;+ isStreaming: boolean;+ onSend: (text: string) => void;+}++function isToolPart(+ part: UIMessage["parts"][number],+): part is UIMessage["parts"][number] & { toolCallId: string; state: string } {+ return part.type.startsWith("tool-") || part.type === "dynamic-tool";+}++function getToolName(part: UIMessage["parts"][number]): string {+ if (part.type === "dynamic-tool" && "toolName" in part) {+ return (part as { toolName: string }).toolName;+ }+ return part.type.replace(/^tool-/, "");+}++export function AssistantMessage({ message, isStreaming, onSend }: AssistantMessageProps) {+ const textContent = message.parts+ .filter((p): p is { type: "text"; text: string } => p.type === "text")+ .map((p) => p.text)+ .join("");++ const toolParts = message.parts.filter(isToolPart);++ const handleAction = (event: ActionEvent) => {+ if (event.type === BuiltinActionType.ContinueConversation && event.humanFriendlyMessage) {+ onSend(event.humanFriendlyMessage);+ }+ };++ const isToolDone = (state: string) => state === "output-available";++ return (+ <div className="flex gap-3 max-w-3xl">+ <div className="shrink-0 w-7 h-7 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center">+ <Bot size={14} className="text-white" />+ </div>+ <div className="flex-1 min-w-0 space-y-2">+ {toolParts.map((tp) => (+ <ToolCallIndicator+ key={(tp as { toolCallId: string }).toolCallId}+ name={getToolName(tp)}+ isDone={isToolDone((tp as { state: string }).state)}+ />+ ))}+ {textContent && (+ <div className="prose-container">+ <Renderer+ response={textContent}+ library={openuiChatLibrary}+ isStreaming={isStreaming}+ onAction={handleAction}+ />+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/components/chat-header.tsx b/examples/vercel-ai-chat/src/components/chat-header.tsxnew file mode 100644index 000000000..33e910bbc--- /dev/null+++ b/examples/vercel-ai-chat/src/components/chat-header.tsx@@ -0,0 +1,26 @@+import { Sparkles } from "lucide-react";+import { SidebarToggle } from "./sidebar-toggle";++interface ChatHeaderProps {+ isSidebarOpen: boolean;+ onToggleSidebar: () => void;+}++export function ChatHeader({ isSidebarOpen, onToggleSidebar }: ChatHeaderProps) {+ return (+ <header className="shrink-0 border-b border-zinc-200 dark:border-zinc-800 px-4 py-3">+ <div className="flex items-center gap-2">+ <SidebarToggle isOpen={isSidebarOpen} onToggle={onToggleSidebar} />+ <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center">+ <Sparkles size={14} className="text-white" />+ </div>+ <div className="flex flex-col items-start">+ <h1 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">Vercel AI Chat</h1>+ <span className="text-xs text-zinc-400 dark:text-zinc-500">+ Vercel AI SDK + OpenUI Renderer+ </span>+ </div>+ </div>+ </header>+ );+}diff --git a/examples/vercel-ai-chat/src/components/chat-input.tsx b/examples/vercel-ai-chat/src/components/chat-input.tsxnew file mode 100644index 000000000..7f74245df--- /dev/null+++ b/examples/vercel-ai-chat/src/components/chat-input.tsx@@ -0,0 +1,70 @@+import { SendHorizonal, Square } from "lucide-react";+import { useRef, useState } from "react";++interface ChatInputProps {+ input: string;+ isLoading: boolean;+ onInputChange: (value: string) => void;+ onSend: (text: string) => void;+ onStop: () => void;+}++export function ChatInput({ input, isLoading, onInputChange, onSend, onStop }: ChatInputProps) {+ const inputRef = useRef<HTMLTextAreaElement>(null);+ const [composing, setComposing] = useState(false);++ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (e.key === "Enter" && !e.shiftKey && !composing) {+ e.preventDefault();+ onSend(input);+ }+ };++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ onSend(input);+ };++ return (+ <div className="shrink-0 border-t border-zinc-200 dark:border-zinc-800 px-4 py-3">+ <form onSubmit={handleSubmit} className="max-w-3xl mx-auto flex items-start gap-2">+ <div className="flex-1 flex relative items-center">+ <textarea+ ref={inputRef}+ value={input}+ onChange={(e) => onInputChange(e.target.value)}+ onKeyDown={handleKeyDown}+ onCompositionStart={() => setComposing(true)}+ onCompositionEnd={() => setComposing(false)}+ placeholder="Send a message…"+ rows={1}+ className="w-full resize-none rounded-xl border border-zinc-300 dark:border-zinc-700 bg-white dark:bg-zinc-900 px-4 py-2.5 text-sm text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-violet-500/40 focus:border-violet-500 transition-shadow"+ style={{ maxHeight: 160 }}+ onInput={(e) => {+ const el = e.currentTarget;+ el.style.height = "auto";+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;+ }}+ />+ </div>+ {isLoading ? (+ <button+ type="button"+ onClick={onStop}+ className="shrink-0 w-10 h-10 rounded-xl bg-zinc-200 dark:bg-zinc-800 flex items-center justify-center text-zinc-600 dark:text-zinc-400 hover:bg-zinc-300 dark:hover:bg-zinc-700 transition-colors"+ >+ <Square size={16} />+ </button>+ ) : (+ <button+ type="submit"+ disabled={!input.trim()}+ className="shrink-0 w-10 h-10 rounded-xl bg-zinc-900 dark:bg-zinc-100 flex items-center justify-center text-white dark:text-zinc-900 hover:bg-zinc-800 dark:hover:bg-zinc-200 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ >+ <SendHorizonal size={16} />+ </button>+ )}+ </form>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/components/conversation-starters.tsx b/examples/vercel-ai-chat/src/components/conversation-starters.tsxnew file mode 100644index 000000000..bfb82eb90--- /dev/null+++ b/examples/vercel-ai-chat/src/components/conversation-starters.tsx@@ -0,0 +1,42 @@+import { Sparkles } from "lucide-react";++const STARTERS = [+ { 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.",+ },+];++export function ConversationStarters({ onSelect }: { onSelect: (prompt: string) => void }) {+ return (+ <div className="flex flex-col items-center justify-center h-full px-4">+ <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center mb-4">+ <Sparkles size={22} className="text-white" />+ </div>+ <h2 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100 mb-1">+ What can I help you with?+ </h2>+ <p className="text-sm text-zinc-500 dark:text-zinc-400 mb-6 text-center max-w-md">+ Ask me anything — I can check weather, look up stocks, do math, search the web, and build+ interactive UI.+ </p>+ <div className="grid grid-cols-2 gap-2 w-full max-w-md">+ {STARTERS.map((s) => (+ <button+ key={s.prompt}+ onClick={() => onSelect(s.prompt)}+ className="text-left text-sm px-3 py-2.5 rounded-xl border border-zinc-200 dark:border-zinc-800 text-zinc-700 dark:text-zinc-300 hover:bg-zinc-50 dark:hover:bg-zinc-900 transition-colors"+ >+ {s.displayText}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/components/sidebar-toggle.tsx b/examples/vercel-ai-chat/src/components/sidebar-toggle.tsxnew file mode 100644index 000000000..99dd30eb0--- /dev/null+++ b/examples/vercel-ai-chat/src/components/sidebar-toggle.tsx@@ -0,0 +1,18 @@+import { PanelLeft, X } from "lucide-react";++interface SidebarToggleProps {+ isOpen: boolean;+ onToggle: () => void;+}++export function SidebarToggle({ isOpen, onToggle }: SidebarToggleProps) {+ return (+ <button+ onClick={onToggle}+ className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-500 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"+ aria-label={isOpen ? "Close sidebar" : "Open sidebar"}+ >+ {isOpen ? <X size={18} /> : <PanelLeft size={18} />}+ </button>+ );+}diff --git a/examples/vercel-ai-chat/src/components/sidebar.tsx b/examples/vercel-ai-chat/src/components/sidebar.tsxnew file mode 100644index 000000000..c513a567c--- /dev/null+++ b/examples/vercel-ai-chat/src/components/sidebar.tsx@@ -0,0 +1,153 @@+"use client";++import type { Thread } from "@/lib/thread-store";+import { Plus, Trash2, MessageSquare } from "lucide-react";++interface SidebarProps {+ threads: Thread[];+ activeThreadId: string;+ isOpen: boolean;+ onNewChat: () => void;+ onSelectThread: (id: string) => void;+ onDeleteThread: (id: string) => void;+ onClose: () => void;+}++function relativeTime(timestamp: number): string {+ const diff = Date.now() - timestamp;+ const mins = Math.floor(diff / 60000);+ if (mins < 1) return "Just now";+ if (mins < 60) return `${mins}m ago`;+ const hours = Math.floor(mins / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.floor(hours / 24);+ if (days < 7) return `${days}d ago`;+ return new Date(timestamp).toLocaleDateString();+}++function groupByDate(threads: Thread[]): { label: string; threads: Thread[] }[] {+ const now = new Date();+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();+ const startOfYesterday = startOfToday - 86400000;+ const startOfLastWeek = startOfToday - 7 * 86400000;++ const today: Thread[] = [];+ const yesterday: Thread[] = [];+ const lastWeek: Thread[] = [];+ const older: Thread[] = [];++ for (const t of threads) {+ if (t.updatedAt >= startOfToday) today.push(t);+ else if (t.updatedAt >= startOfYesterday) yesterday.push(t);+ else if (t.updatedAt >= startOfLastWeek) lastWeek.push(t);+ else older.push(t);+ }++ const groups: { label: string; threads: Thread[] }[] = [];+ if (today.length) groups.push({ label: "Today", threads: today });+ if (yesterday.length) groups.push({ label: "Yesterday", threads: yesterday });+ if (lastWeek.length) groups.push({ label: "Last 7 days", threads: lastWeek });+ if (older.length) groups.push({ label: "Older", threads: older });+ return groups;+}++export function Sidebar({+ threads,+ activeThreadId,+ isOpen,+ onNewChat,+ onSelectThread,+ onDeleteThread,+ onClose,+}: SidebarProps) {+ const groups = groupByDate(threads);++ return (+ <>+ {/* Backdrop for mobile */}+ {isOpen && (+ <div+ className="fixed inset-0 z-40 bg-black/30 md:hidden"+ onClick={onClose}+ />+ )}++ <aside+ className={`+ fixed z-50 top-0 left-0 h-full+ w-[280px] shrink-0+ bg-zinc-50 dark:bg-zinc-900 border-r border-zinc-200 dark:border-zinc-800+ flex flex-col+ transition-transform duration-200 ease-in-out+ ${isOpen ? "translate-x-0" : "-translate-x-full"}+ `}+ >+ {/* Sidebar header */}+ <div className="p-3 border-b border-zinc-200 dark:border-zinc-800">+ <button+ onClick={() => {+ onNewChat();+ onClose();+ }}+ className="w-full flex items-center gap-2 px-3 py-[7px] rounded-lg text-sm font-medium text-zinc-700 dark:text-zinc-200 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors"+ >+ <Plus size={16} />+ New Chat+ </button>+ </div>++ {/* Thread list */}+ <div className="flex-1 overflow-y-auto py-2">+ {groups.length === 0 ? (+ <p className="px-4 py-8 text-center text-xs text-zinc-400 dark:text-zinc-500">+ No conversations yet+ </p>+ ) : (+ groups.map((group) => (+ <div key={group.label} className="flex flex-col gap-1">+ <h3 className="px-4 py-1 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">+ {group.label}+ </h3>+ {group.threads.map((thread) => {+ const isActive = thread.id === activeThreadId;+ return (+ <div+ key={thread.id}+ className={`group flex items-start gap-2 mx-2 px-2 py-1.5 rounded-lg cursor-pointer transition-colors ${+ isActive+ ? "bg-zinc-200 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100"+ : "text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800/60"+ }`}+ onClick={() => {+ onSelectThread(thread.id);+ onClose();+ }}+ >+ <MessageSquare size={14} className="shrink-0 opacity-50 mt-1" />+ <div className="flex-1 min-w-0">+ <p className="text-sm truncate">{thread.title}</p>+ <p className="text-[11px] text-zinc-400 dark:text-zinc-500">+ {relativeTime(thread.updatedAt)}+ </p>+ </div>+ <button+ onClick={(e) => {+ e.stopPropagation();+ onDeleteThread(thread.id);+ }}+ className="shrink-0 p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-zinc-300 dark:hover:bg-zinc-700 transition-opacity text-zinc-400 hover:text-red-500"+ aria-label="Delete thread"+ >+ <Trash2 size={14} />+ </button>+ </div>+ );+ })}+ </div>+ ))+ )}+ </div>+ </aside>+ </>+ );+}diff --git a/examples/vercel-ai-chat/src/components/thinking-indicator.tsx b/examples/vercel-ai-chat/src/components/thinking-indicator.tsxnew file mode 100644index 000000000..321bd732c--- /dev/null+++ b/examples/vercel-ai-chat/src/components/thinking-indicator.tsx@@ -0,0 +1,15 @@+import { Bot, Loader2 } from "lucide-react";++export function ThinkingIndicator() {+ return (+ <div className="flex gap-3 max-w-3xl">+ <div className="shrink-0 w-7 h-7 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center">+ <Bot size={14} className="text-white" />+ </div>+ <div className="flex items-center gap-2 text-sm text-zinc-400">+ <Loader2 size={14} className="animate-spin" />+ Thinking…+ </div>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/components/tool-call-indicator.tsx b/examples/vercel-ai-chat/src/components/tool-call-indicator.tsxnew file mode 100644index 000000000..f5e4f7576--- /dev/null+++ b/examples/vercel-ai-chat/src/components/tool-call-indicator.tsx@@ -0,0 +1,17 @@+import { CheckCircle2, Loader2, Wrench } from "lucide-react";++export function ToolCallIndicator({ name, isDone }: { name: string; isDone: boolean }) {+ const label = name.replace(/_/g, " ");++ return (+ <div className="flex items-center gap-2 px-3 py-1.5 text-xs rounded-lg bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 w-fit">+ {isDone ? (+ <CheckCircle2 size={14} className="text-emerald-500" />+ ) : (+ <Loader2 size={14} className="animate-spin" />+ )}+ <Wrench size={12} />+ <span className="capitalize">{label}</span>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/components/user-message.tsx b/examples/vercel-ai-chat/src/components/user-message.tsxnew file mode 100644index 000000000..c5082d10e--- /dev/null+++ b/examples/vercel-ai-chat/src/components/user-message.tsx@@ -0,0 +1,24 @@+import type { UIMessage } from "ai";+import { User } from "lucide-react";++function extractText(message: UIMessage): string {+ return message.parts+ .filter((p): p is { type: "text"; text: string } => p.type === "text")+ .map((p) => p.text)+ .join("");+}++export function UserMessage({ message }: { message: UIMessage }) {+ const text = extractText(message);++ return (+ <div className="flex gap-3 max-w-3xl justify-end ml-auto">+ <div className="px-4 py-2.5 rounded-2xl bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 text-sm leading-relaxed max-w-[80%]">+ {text}+ </div>+ <div className="shrink-0 w-7 h-7 rounded-full bg-zinc-300 dark:bg-zinc-700 flex items-center justify-center">+ <User size={14} className="text-zinc-600 dark:text-zinc-300" />+ </div>+ </div>+ );+}diff --git a/examples/vercel-ai-chat/src/generated/system-prompt.txt b/examples/vercel-ai-chat/src/generated/system-prompt.txtnew file mode 100644index 000000000..b655c131e--- /dev/null+++ b/examples/vercel-ai-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/vercel-ai-chat/src/hooks/use-system-theme.tsx b/examples/vercel-ai-chat/src/hooks/use-system-theme.tsxnew file mode 100644index 000000000..f001d61fe--- /dev/null+++ b/examples/vercel-ai-chat/src/hooks/use-system-theme.tsx@@ -0,0 +1,46 @@+"use client";++import { createContext, useContext, useEffect, useState } from "react";+import { ThemeProvider as OpenUIThemeProvider } from "@openuidev/react-ui";++type ThemeMode = "light" | "dark";++interface ThemeContextType {+ mode: ThemeMode;+}++const ThemeContext = createContext<ThemeContextType | undefined>(undefined);++function getSystemMode(): ThemeMode {+ if (typeof window === "undefined") return "light";+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";+}++export function ThemeProvider({ children }: { children: React.ReactNode }) {+ const [mode, setMode] = useState<ThemeMode>(getSystemMode);++ useEffect(() => {+ const mq = window.matchMedia("(prefers-color-scheme: dark)");+ const handler = (e: MediaQueryListEvent) => setMode(e.matches ? "dark" : "light");+ mq.addEventListener("change", handler);+ return () => mq.removeEventListener("change", handler);+ }, []);++ useEffect(() => {+ document.documentElement.classList.toggle("dark", mode === "dark");+ }, [mode]);++ return (+ <ThemeContext.Provider value={{ mode }}>+ <OpenUIThemeProvider mode={mode}>{children}</OpenUIThemeProvider>+ </ThemeContext.Provider>+ );+}++export function useTheme(): ThemeMode {+ const ctx = useContext(ThemeContext);+ if (!ctx) {+ throw new Error("useTheme must be used within a ThemeProvider");+ }+ return ctx.mode;+}diff --git a/examples/vercel-ai-chat/src/hooks/use-threads.ts b/examples/vercel-ai-chat/src/hooks/use-threads.tsnew file mode 100644index 000000000..4fb76aa60--- /dev/null+++ b/examples/vercel-ai-chat/src/hooks/use-threads.ts@@ -0,0 +1,73 @@+"use client";++import { useState, useCallback } from "react";+import type { UIMessage } from "ai";+import {+ getThreads,+ getThread,+ saveThread,+ deleteThread as removeThread,+ generateId,+ titleFromMessages,+ type Thread,+} from "@/lib/thread-store";++export function useThreads() {+ const [threads, setThreads] = useState<Thread[]>(() => getThreads());+ const [activeThreadId, setActiveThreadId] = useState<string>(() => generateId());+ const [sidebarOpen, setSidebarOpen] = useState(false);++ const refreshThreads = useCallback(() => {+ setThreads(getThreads());+ }, []);++ const persistMessages = useCallback(+ (messages: UIMessage[]) => {+ if (messages.length === 0) return;+ const existing = getThread(activeThreadId);+ const now = Date.now();+ saveThread({+ id: activeThreadId,+ title: titleFromMessages(messages),+ messages,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ });+ refreshThreads();+ },+ [activeThreadId, refreshThreads],+ );++ const createThread = useCallback(() => {+ setActiveThreadId(generateId());+ }, []);++ const switchThread = useCallback((id: string) => {+ setActiveThreadId(id);+ }, []);++ const deleteThread = useCallback(+ (id: string) => {+ removeThread(id);+ refreshThreads();+ if (id === activeThreadId) {+ setActiveThreadId(generateId());+ }+ },+ [activeThreadId, refreshThreads],+ );++ const activeThread = getThread(activeThreadId);++ return {+ threads,+ activeThreadId,+ activeThread,+ sidebarOpen,+ setSidebarOpen,+ persistMessages,+ createThread,+ switchThread,+ deleteThread,+ };+}diff --git a/examples/vercel-ai-chat/src/lib/thread-store.ts b/examples/vercel-ai-chat/src/lib/thread-store.tsnew file mode 100644index 000000000..8da5c3317--- /dev/null+++ b/examples/vercel-ai-chat/src/lib/thread-store.ts@@ -0,0 +1,62 @@+import type { UIMessage } from "ai";++export interface Thread {+ id: string;+ title: string;+ messages: UIMessage[];+ createdAt: number;+ updatedAt: number;+}++const STORAGE_KEY = "vercel-ai-chat-threads";++function readAll(): Thread[] {+ if (typeof window === "undefined") return [];+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ return raw ? JSON.parse(raw) : [];+ } catch {+ return [];+ }+}++function writeAll(threads: Thread[]) {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(threads));+}++export function getThreads(): Thread[] {+ return readAll().sort((a, b) => b.updatedAt - a.updatedAt);+}++export function getThread(id: string): Thread | null {+ return readAll().find((t) => t.id === id) ?? null;+}++export function saveThread(thread: Thread) {+ const threads = readAll();+ const idx = threads.findIndex((t) => t.id === thread.id);+ if (idx >= 0) {+ threads[idx] = thread;+ } else {+ threads.push(thread);+ }+ writeAll(threads);+}++export function deleteThread(id: string) {+ writeAll(readAll().filter((t) => t.id !== id));+}++export function generateId(): string {+ return crypto.randomUUID();+}++export function titleFromMessages(messages: UIMessage[]): string {+ const first = messages.find((m) => m.role === "user");+ if (!first) return "New Chat";+ const text = first.parts+ .filter((p): p is { type: "text"; text: string } => p.type === "text")+ .map((p) => p.text)+ .join(" ");+ return text.length > 40 ? text.slice(0, 40) + "..." : text || "New Chat";+}diff --git a/examples/vercel-ai-chat/src/lib/tools.ts b/examples/vercel-ai-chat/src/lib/tools.tsnew file mode 100644index 000000000..105be5fc1--- /dev/null+++ b/examples/vercel-ai-chat/src/lib/tools.ts@@ -0,0 +1,117 @@+import { tool } from "ai";+import { z } from "zod";++export const tools = {+ get_weather: tool({+ description: "Get current weather for a location.",+ inputSchema: z.object({+ location: z.string().describe("City name"),+ }),+ execute: async ({ location }) => {+ await new Promise((r) => setTimeout(r, 800));+ const knownTemps: Record<string, number> = {+ tokyo: 22,+ "san francisco": 18,+ london: 14,+ "new york": 25,+ paris: 19,+ sydney: 27,+ mumbai: 33,+ berlin: 16,+ };+ const conditions = ["Sunny", "Partly Cloudy", "Cloudy", "Light Rain", "Clear Skies"];+ const temp = knownTemps[location.toLowerCase()] ?? Math.floor(Math.random() * 30 + 5);+ const condition = conditions[Math.floor(Math.random() * conditions.length)];+ return {+ 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" },+ ],+ };+ },+ }),++ get_stock_price: tool({+ description: "Get stock price for a ticker symbol.",+ inputSchema: z.object({+ symbol: z.string().describe("Ticker symbol, e.g. AAPL"),+ }),+ execute: async ({ symbol }) => {+ await new Promise((r) => setTimeout(r, 600));+ const s = symbol.toUpperCase();+ const knownPrices: Record<string, number> = {+ AAPL: 189.84,+ GOOGL: 141.8,+ TSLA: 248.42,+ MSFT: 378.91,+ AMZN: 178.25,+ NVDA: 875.28,+ META: 485.58,+ };+ const price = knownPrices[s] ?? Math.floor(Math.random() * 500 + 20);+ const change = parseFloat((Math.random() * 8 - 4).toFixed(2));+ return {+ 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)),+ };+ },+ }),++ calculate: tool({+ description: "Evaluate a math expression.",+ inputSchema: z.object({+ expression: z.string().describe("Math expression to evaluate"),+ }),+ execute: async ({ expression }) => {+ await new Promise((r) => setTimeout(r, 300));+ try {+ const sanitized = expression.replace(+ /[^0-9+\-*/().%\s,Math.sqrtpowabsceilfloorround]/g,+ "",+ );+ const result = new Function(`return (${sanitized})`)();+ return { expression, result: Number(result) };+ } catch {+ return { expression, error: "Invalid expression" };+ }+ },+ }),++ search_web: tool({+ description: "Search the web for information.",+ inputSchema: z.object({+ query: z.string().describe("Search query"),+ }),+ execute: async ({ query }) => {+ await new Promise((r) => setTimeout(r, 1000));+ return {+ 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}.`,+ },+ ],+ };+ },+ }),+};diff --git a/examples/vercel-ai-chat/src/library.ts b/examples/vercel-ai-chat/src/library.tsnew file mode 100644index 000000000..c7ceecfc1--- /dev/null+++ b/examples/vercel-ai-chat/src/library.ts@@ -0,0 +1 @@+export { openuiChatLibrary as library, openuiChatPromptOptions as promptOptions } from "@openuidev/react-ui/genui-lib";diff --git a/examples/vercel-ai-chat/tsconfig.json b/examples/vercel-ai-chat/tsconfig.jsonnew file mode 100644index 000000000..cf9c65d3e--- /dev/null+++ b/examples/vercel-ai-chat/tsconfig.json@@ -0,0 +1,34 @@+{+ "compilerOptions": {+ "target": "ES2017",+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "react-jsx",+ "incremental": true,+ "plugins": [+ {+ "name": "next"+ }+ ],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": [+ "next-env.d.ts",+ "**/*.ts",+ "**/*.tsx",+ ".next/types/**/*.ts",+ ".next/dev/types/**/*.ts",+ "**/*.mts"+ ],+ "exclude": ["node_modules"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 772135c22..60c96deeb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -64,7 +64,7 @@ importers:version: 16.6.5(@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])fumadocs-mdx:specifier: 14.2.8- version: 14.2.8(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 14.2.8(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]))fumadocs-ui:specifier: 16.6.5version: 16.6.5(@takumi-rs/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -421,6 +421,67 @@ importers:specifier: ^5version: 5.9.3+ examples/vercel-ai-chat:+ dependencies:+ '@ai-sdk/openai':+ specifier: ^3.0.41+ version: 3.0.41([email protected])+ '@ai-sdk/react':+ specifier: ^3.0.118+ version: 3.0.118([email protected])([email protected])+ '@openuidev/cli':+ specifier: workspace:*+ version: link:../../packages/openui-cli+ '@openuidev/react-lang':+ specifier: workspace:*+ version: link:../../packages/react-lang+ '@openuidev/react-ui':+ specifier: workspace:*+ version: link:../../packages/react-ui+ ai:+ specifier: ^6.0.116+ version: 6.0.116([email protected])+ lucide-react:+ specifier: ^0.575.0+ version: 0.575.0([email protected])+ next:+ specifier: 16.1.6+ version: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])+ react:+ specifier: 19.2.3+ version: 19.2.3+ react-dom:+ specifier: 19.2.3+ version: 19.2.3([email protected])+ zod:+ specifier: ^4.3.6+ version: 4.3.6+ devDependencies:+ '@tailwindcss/postcss':+ specifier: ^4+ version: 4.2.1+ '@types/node':+ specifier: ^20+ version: 20.19.35+ '@types/react':+ specifier: ^19+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19+ version: 19.2.3(@types/[email protected])+ eslint:+ specifier: ^9+ version: 9.29.0([email protected])+ eslint-config-next:+ specifier: 16.1.6+ version: 16.1.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ tailwindcss:+ specifier: ^4+ version: 4.2.1+ typescript:+ specifier: ^5+ version: 5.9.3+packages/openui-cli:dependencies:'@inquirer/core':@@ -717,6 +778,34 @@ packages:'@ag-ui/[email protected]':resolution: {integrity: sha512-Ccsarxb23TChONOWXDbNBqp1fIbOSMht8g7w6AsSYBTtdOwZ7h7AkjNkr3LSdVv+RbT30JMdSLtieJE0YepNPg==}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-SIQ0YY0iMuv+07HLsZ+bB990zUJ6S4ujORAh+Jv1V2KGNn73qQKnGO0JBk+w+Res8YqOFSycwDoWcFlQrVxS4A==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-IZ42A+FO+vuEQCVNqlnAPYQnnUpUfdJIwn1BEDOBywiEHa23fw7PahxVtlX9zm3/zMvTW4JKPzWyvAgDu+SQ2A==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-3eG55CrSWCu2SXlqq2QCsFjo3+E7+Gmg7i/oRVoSZzIodTuDSfLb3MRje67xE9RFea73Zao7Lm4mADIfUETKGg==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==}+ engines: {node: '>=18'}++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-fBAix8Jftxse6/2YJnOFkwW1/O6EQK4DK68M9DlFmZGAzBmsaHXEPVS77sVIlkaOWCy11bE7434NAVXRY+3OsQ==}+ engines: {node: '>=18'}+ peerDependencies:+ react: ^18 || ~19.0.1 || ~19.1.2 || ^19.2.1+'@alloc/[email protected]':resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}@@ -4643,6 +4732,10 @@ packages:peerDependencies:'@urql/core': ^5.0.0+ '@vercel/[email protected]':+ resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}+ engines: {node: '>= 20'}+'@vitest/[email protected]':resolution: {integrity: sha512-yHZtwuP7JZivj65Gxoi8upUN2OzHTi3zVfjwdpu2WrvCZPLwsJ2Ey5ILIPccoW23dd/zQBlJ4/dhi7DWNyXCpA==}@@ -4780,6 +4873,12 @@ packages:resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==}engines: {node: '>= 8.0.0'}+ resolution: {integrity: sha512-7yM+cTmyRLeNIXwt4Vj+mrrJgVQ9RMIW5WO0ydoLoYkewIvsMcvUmqS4j2RJTUXaF1HphwmSKUMQ/HypNRGOmA==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8+resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}peerDependencies:@@ -5986,6 +6085,10 @@ packages:resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}+ resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}+ engines: {node: '>=18.0.0'}+resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}engines: {node: '>=12.0.0'}@@ -6920,6 +7023,9 @@ packages:resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}+ resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==}+resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}@@ -8837,6 +8943,11 @@ packages:resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-2CC6CiKQtEwaEeNiqWTAw9PGykW8SR5zZX8MZk6TeAvEAnVS7Visz8WzphqgtQ8v2xz/4Q5K+j+SeMaKXeeQIA==}+ peerDependencies:+ react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}@@ -8902,6 +9013,10 @@ packages:resolution: {integrity: sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==}+ resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}@@ -9172,6 +9287,11 @@ packages:peerDependencies:react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}@@ -9579,6 +9699,40 @@ snapshots:rxjs: 7.8.1zod: 3.25.67+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.8+ '@ai-sdk/provider-utils': 4.0.19([email protected])+ '@vercel/oidc': 3.1.0+ zod: 4.3.6++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.8+ '@ai-sdk/provider-utils': 4.0.19([email protected])+ zod: 4.3.6++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.8+ '@standard-schema/spec': 1.1.0+ eventsource-parser: 3.0.6+ zod: 4.3.6++ '@ai-sdk/[email protected]':+ dependencies:+ json-schema: 0.4.0++ dependencies:+ '@ai-sdk/provider-utils': 4.0.19([email protected])+ ai: 6.0.116([email protected])+ react: 19.2.3+ swr: 2.4.1([email protected])+ throttleit: 2.1.0+ transitivePeerDependencies:+ - zod+'@alloc/[email protected]': {}'@ampproject/[email protected]':@@ -14381,6 +14535,8 @@ snapshots:'@urql/core': 5.2.0wonka: 6.3.5+ '@vercel/[email protected]': {}+'@vitest/[email protected]':dependencies:'@vitest/spy': 2.0.5@@ -14566,6 +14722,14 @@ snapshots:dependencies:humanize-ms: 1.2.1+ dependencies:+ '@ai-sdk/gateway': 3.0.66([email protected])+ '@ai-sdk/provider': 3.0.8+ '@ai-sdk/provider-utils': 4.0.19([email protected])+ '@opentelemetry/api': 1.9.0+ zod: 4.3.6+optionalDependencies:ajv: 8.17.1@@ -15704,7 +15868,7 @@ snapshots:eslint: 10.0.2([email protected])eslint-import-resolver-node: 0.3.9- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.0.1([email protected]([email protected]))@@ -15761,7 +15925,7 @@ snapshots:tinyglobby: 0.2.15unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -15780,7 +15944,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:@@ -15791,7 +15955,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:@@ -15802,7 +15966,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9@@ -15813,7 +15977,7 @@ snapshots:doctrine: 2.1.0eslint: 10.0.2([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3@@ -15842,7 +16006,7 @@ snapshots:doctrine: 2.1.0eslint: 9.29.0([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3@@ -16174,6 +16338,8 @@ snapshots:+ [email protected]: {}+[email protected]([email protected](@babel/[email protected])([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected]):@@ -16469,7 +16635,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])):dependencies:'@mdx-js/mdx': 3.1.1'@standard-schema/spec': 1.1.0@@ -17277,6 +17443,8 @@ snapshots:+ [email protected]: {}+@@ -18415,7 +18583,7 @@ snapshots:'@next/env': 16.1.6'@swc/helpers': 0.5.15baseline-browser-mapping: 2.10.0- caniuse-lite: 1.0.30001723+ caniuse-lite: 1.0.30001778postcss: 8.4.31react: 19.2.3react-dom: 19.2.3([email protected])@@ -18442,7 +18610,7 @@ snapshots:'@next/env': 16.1.6'@swc/helpers': 0.5.15baseline-browser-mapping: 2.10.0- caniuse-lite: 1.0.30001723+ caniuse-lite: 1.0.30001778postcss: 8.4.31react: 19.2.4react-dom: 19.2.4([email protected])@@ -20092,6 +20260,12 @@ snapshots:+ dependencies:+ dequal: 2.0.3+ react: 19.2.3+ use-sync-external-store: 1.6.0([email protected])+optional: true@@ -20179,6 +20353,8 @@ snapshots:+ [email protected]: {}+@@ -20502,6 +20678,10 @@ snapshots:dependencies:react: 19.2.4+ dependencies:+ react: 19.2.3+