The Open Standard for Generative UI
Chat docs update (#271)
abhithesysa34c03f78e44
diff --git a/README.md b/README.mdindex e69de29bb..58cfc472e 100644--- a/README.md+++ b/README.md@@ -0,0 +1,132 @@+# OpenUI++[Docs](https://openui.com) · [Example App](./examples/openui-chat) · [Contributing](./CONTRIBUTING.md) · [License](./LICENSE)++Build **LLM-powered user interfaces** with OpenUI Lang, streaming rendering, and generative UI.++OpenUI gives you a fast path from model output to structured, streamable UI in React.++<!-- Hero image placeholder -->+<!-- [](https://openui.com) -->++---++## What is OpenUI++OpenUI is an open source toolkit for building AI-native product interfaces in React.++At the center of OpenUI is **OpenUI Lang**: a compact, streaming-first language for model-generated UI. Instead of treating model output as only text, OpenUI lets you define components, generate prompt instructions from that component library, and render structured UI as the model streams.++**Core capabilities:**++- **OpenUI Lang** - A compact language for structured UI generation that is designed for streaming output.+- **Prompt generation from your component library** - Generate model instructions directly from the components you allow.+- **Streaming renderer** - Parse and render model output progressively in React as tokens arrive.+- **Generative UI** - Turn model output into real UI components instead of plain text responses.+- **Chat and app surfaces** - Use the same foundation for assistants, copilots, and broader interactive product flows.++<!-- Product overview video placeholder -->+<!-- https://openui.com/assets/readme/overview-demo.mp4 -->++## Quick Start++```bash+npx create-openui-chat my-chat-app+cd my-chat-app+npm run dev+```++This is the fastest way to start with OpenUI. The scaffolded app gives you an end-to-end starting point with streaming, built-in UI, and OpenUI Lang support.++What this gives you:++- **OpenUI Lang support** - Start with structured UI generation built into the app flow.+- **Library-driven prompts** - Generate instructions from your allowed component set.+- **Streaming support** - Update the UI progressively as output arrives.+- **Working app foundation** - Start from a ready-to-run example instead of wiring everything manually.++[Detailed docs at openui.com ->](https://openui.com)++<!-- Quick start demo placeholder -->+<!--  -->++## How it works++OpenUI turns your component library into a contract the model can target.++1. Define or reuse a component library.+2. Generate a system prompt from that library.+3. Send that prompt to your model.+4. Stream OpenUI Lang output back to the client.+5. Render the structured output progressively with `<Renderer />`.++This creates a direct path from model output to UI without relying on brittle text parsing or ad hoc JSON rendering layers.++<!-- Architecture diagram placeholder -->+<!--  -->++## Why OpenUI Lang++OpenUI Lang is designed for model-generated UI that needs to be both structured and streamable.++It is built for:++- **Streaming output** - Emit UI incrementally as tokens arrive.+- **Token efficiency** - Use a compact representation instead of verbose JSON payloads.+- **Controlled rendering** - Restrict output to the components you define and register.+- **Typed component contracts** - Define component props and structure up front.++## Built for real product surfaces++OpenUI is intended for more than demo chat windows.++Use it to build:++- structured AI interfaces+- assistants that render forms, charts, tables, and actions+- embedded copilots inside existing products+- full-page AI workflows+- custom applications backed by your own model APIs++## Chat is one application layer++OpenUI also includes ready-made chat surfaces and integration patterns, but chat is only one way to use the platform.++If you want a complete starting point with backend wiring, streaming, and a built-in UI, use:++```bash+npx create-openui-chat my-chat-app+```++From there, you can keep the built-in experience or move toward more custom OpenUI Lang-driven interfaces.++## Documentation++Detailed documentation is available at [openui.com](https://openui.com).++The docs cover:++- OpenUI Lang quick start+- component definitions and library design+- prompt generation and customization+- renderer behavior and streaming semantics+- end-to-end app setup+- backend connection patterns and API contracts++## Explore the repo++This repository contains the OpenUI monorepo, including the implementation, example app, and documentation source.++Good places to start:++- [openui.com](https://openui.com) for the full docs+- [`examples/openui-chat`](./examples/openui-chat) for a working app+- [`CONTRIBUTING.md`](./CONTRIBUTING.md) if you want to contribute++## Contributing++Contributions are welcome. See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for contribution guidelines and ways to get involved.++## License++This project is available under the terms described in [`LICENSE`](./LICENSE).diff --git a/docs/content/docs/chat/api-contract.mdx b/docs/content/docs/chat/api-contract.mdxindex f99aef46f..5cda44d8d 100644--- a/docs/content/docs/chat/api-contract.mdx+++ b/docs/content/docs/chat/api-contract.mdx@@ -5,19 +5,56 @@ description: JSON contract for threads, messages, and streaming.OpenUI Chat can work with any backend stack as long as the API contract is respected.-### Thread endpoints+This page is the reference source for request and response shapes. Use [Connecting to LLM](/docs/chat/connecting) for decision guidance and [Connect Thread History](/docs/chat/persistence) for the setup flow.-When using `threadApiUrl="/api/threads"`, OpenUI expects:+## Chat endpoint contract-| Action | Method | URL |-| :------------ | :------- | :-------------------------- |-| List threads | `GET` | `/api/threads` |-| Create thread | `POST` | `/api/threads` |-| Update thread | `PUT` | `/api/threads/:id` |-| Delete thread | `DELETE` | `/api/threads/:id` |-| Load messages | `GET` | `/api/threads/:id/messages` |+When you pass `apiUrl`, OpenUI sends a `POST` request with this shape:-### Thread shape+```json+{+ "threadId": "thread_123",+ "messages": [+ { "id": "msg_1", "role": "user", "content": "Hello" }+ ]+}+```++- `threadId` is the selected thread ID when persistence is enabled, or `"ephemeral"` when no thread storage is configured.+- `messages` is converted through `messageFormat.toApi(messages)` before the request is sent.++If your backend already accepts the default AG-UI message shape, each message can stay in this form:++```json+{ "id": "msg_1", "role": "user", "content": "Hello" }+```++### Stream response++Your response stream must match one of these cases:++| Backend response shape | Frontend config |+| :--- | :--- |+| OpenUI Protocol | No `streamProtocol` needed |+| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |+| OpenAI SDK `toReadableStream()` / NDJSON | `streamProtocol={openAIReadableStreamAdapter()}` |+| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |++## Default thread API contract++When using `threadApiUrl="/api/threads"`, OpenUI expects the base URL plus these default path segments:++| Action | Method | URL | Request body | Response |+| :--- | :--- | :--- | :--- | :--- |+| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |+| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |+| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |+| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |+| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |++`messages` in the create request is the first user message, already converted through `messageFormat.toApi([firstMessage])`.++## Thread shape```tstype Thread = {@@ -27,19 +64,47 @@ type Thread = {};```-### Message formats+## Message format contract++`messageFormat` controls both directions:++- `toApi()` shapes the `messages` array sent to `apiUrl` and `threadApiUrl/create`+- `fromApi()` shapes the array returned from `threadApiUrl/get/:id`-Your backend message shape can vary. Use `messageFormat` to map to/from OpenUI internal shape:+OpenUI ships with these built-in message converters:-- default OpenUI format-- OpenAI Chat Completions format-- OpenAI Responses conversation-item format+| Converter | Use when your backend expects or returns... |+| :--- | :--- |+| Default | AG-UI message objects |+| `openAIMessageFormat` | OpenAI chat completion messages |+| `openAIConversationMessageFormat` | OpenAI Responses conversation items |-### Streaming formats+Every persisted message should include a unique `id`. Without stable message IDs, history hydration and message updates become unreliable.++## Example custom converter++```ts+const myCustomFormat = {+ toApi(messages) {+ return messages.map((message) => ({+ speaker: message.role,+ text: message.content,+ }));+ },+ fromApi(items) {+ return items.map((item) => ({+ id: item.id,+ role: item.speaker,+ content: item.text,+ }));+ },+};+```-Use `streamProtocol` when your backend stream shape is not OpenUI default.+{/* add visual: flow-chart showing how messageFormat.toApi affects outgoing chat and thread-create requests, and how messageFormat.fromApi affects thread loading */}-See:+## Related guides- [Next.js Implementation](/docs/chat/nextjs)+- [Connect Thread History](/docs/chat/persistence)- [Providers](/docs/chat/providers)diff --git a/docs/content/docs/chat/backend/llm-chat-endpoint.mdx b/docs/content/docs/chat/backend/llm-chat-endpoint.mdxdeleted file mode 100644index c9a953dc7..000000000--- a/docs/content/docs/chat/backend/llm-chat-endpoint.mdx+++ /dev/null@@ -1,158 +0,0 @@-----title: LLM Chat Endpoint-description: Build a streaming chat endpoint using OpenAI and Next.js.------Your backend needs a single endpoint that receives the conversation history and streams back a response from an LLM. This guide shows how to build one using the OpenAI SDK and Next.js.--## Next.js Route Handler--Create a route handler at `app/api/chat/route.ts`:--```typescript-import OpenAI from "openai";--const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });--export async function POST(req: Request) {- const { messages } = await req.json();-- const stream = await openai.chat.completions.create({- model: "gpt-4o",- messages,- stream: true,- });-- const encoder = new TextEncoder();- const readable = new ReadableStream({- async start(controller) {- for await (const chunk of stream) {- const text = JSON.stringify(chunk) + "\n";- controller.enqueue(encoder.encode(text));- }- controller.close();- },- });-- return new Response(readable, {- headers: { "Content-Type": "text/event-stream" },- });-}-```--This endpoint:--1. Reads the `messages` array from the request body-2. Calls OpenAI's chat completions API with streaming enabled-3. Forwards each chunk as newline-delimited JSON back to the client--## Connecting the frontend--Since this endpoint returns OpenAI's streaming format (not AG-UI), you need to tell OpenUI how to parse it using `openAIAdapter` and how to convert messages using `openAIMessageFormat`:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray', 'ChatProvider']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="ChatProvider">- ```tsx- import { ChatProvider } from "@openuidev/react-headless";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <ChatProvider- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- >- {/* Your custom UI */}- </ChatProvider>- );- }- ```-- </Tab>-</Tabs>--## What `streamProtocol` and `messageFormat` do--These two props handle the translation between your backend and OpenUI's internal format:--- **`streamProtocol`** — parses the raw streaming response from your endpoint into OpenUI events. Different LLM providers stream in different formats.-- **`messageFormat`** — converts messages between OpenUI's internal format and the format your backend expects in the request body (and returns in loaded threads).--| Backend format | `streamProtocol` | `messageFormat` |-| ----------------------- | -------------------------- | --------------------------------- |-| AG-UI (default) | Not needed | Not needed |-| OpenAI Chat Completions | `openAIAdapter()` | `openAIMessageFormat` |-| OpenAI Responses API | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` |--If your backend uses AG-UI, you don't need to set either prop — they default to AG-UI.--## Request format--When a user sends a message, OpenUI makes a `POST` request to your `apiUrl` with this body:--```json-{- "messages": [- { "role": "user", "content": "Hello!" },- { "role": "assistant", "content": "Hi there! How can I help?" },- { "role": "user", "content": "What's the weather like?" }- ]-}-```--The exact shape of each message depends on your `messageFormat`. With `openAIMessageFormat`, messages use OpenAI's `{ role, content, id}` shape. By default, OpenUI uses [AG-UI](https://docs.ag-ui.com/concepts/messages#message-types) format..diff --git a/docs/content/docs/chat/backend/meta.json b/docs/content/docs/chat/backend/meta.jsondeleted file mode 100644index 41b2aa62d..000000000--- a/docs/content/docs/chat/backend/meta.json+++ /dev/null@@ -1,4 +0,0 @@-{- "title": "Backend",- "pages": ["llm-chat-endpoint", "thread-conversation-api"]-}diff --git a/docs/content/docs/chat/backend/thread-conversation-api.mdx b/docs/content/docs/chat/backend/thread-conversation-api.mdxdeleted file mode 100644index c9123992d..000000000--- a/docs/content/docs/chat/backend/thread-conversation-api.mdx+++ /dev/null@@ -1,252 +0,0 @@-----title: Thread & Conversation API-description: Build the backend API for creating, loading, and managing chat threads and messages.------By default, conversations live in memory and are lost on page reload. To let users save and resume conversations, your chat component needs a backend API for managing threads and messages.--This guide walks you through building that API step by step using Next.js.--## The API contract--OpenUI expects five RESTful endpoints. When you pass `threadApiUrl="/api/threads"` to a chat component, it calls these automatically:--| Action | Method | URL | Request body | Response |-| ------------- | -------- | --------------------------- | ------------------ | ----------------------------------------- |-| List threads | `GET` | `/api/threads` | — | `{ threads: Thread[], nextCursor?: any }` |-| Create thread | `POST` | `/api/threads` | `{ firstMessage }` | `Thread` |-| Delete thread | `DELETE` | `/api/threads/:id` | — | — |-| Update thread | `PUT` | `/api/threads/:id` | `Thread` | `Thread` |-| Load messages | `GET` | `/api/threads/:id/messages` | — | `Message[]` |--Every `Thread` object must have this shape:--```typescript-type Thread = {- id: string;- title: string;- createdAt: string | number;-};-```--## Choosing a message format--<Callout type="warn">**Important:** Every message must have a unique `id` field.</Callout>--Your backend can store messages in any format — OpenAI's `{ id, role, content }` objects, the OpenAI Responses API items list, or your own custom shape. The `messageFormat` prop on the frontend acts as a translator between your backend's format and OpenUI's internal format.--OpenUI ships with built-in converters for common formats:--| Converter | Your backend stores messages as... |-| --------------------------------- | ---------------------------------------------------- |-| Default (AG-UI) | OpenUI's native format: `{ id, role, content, ... }` |-| `openAIMessageFormat` | OpenAI chat completions: `{ id, role, content }` |-| `openAIConversationMessageFormat` | OpenAI Responses API items list with id |--If your backend uses a different shape, you can write a custom converter for Ag-UI:--```typescript-const myCustomFormat: MessageFormat = {- toApi(messages) {- // Convert OpenUI messages → your backend's format (for chat requests)- return messages.map((m) => ({ speaker: m.role, text: m.content }));- },- fromApi(messages) {- // Convert your backend's format → OpenUI messages (when loading threads)- return messages.map((m) => ({ id: m.id, role: m.speaker, content: m.text }));- },-};-```--The examples below use `openAIMessageFormat`, so the message endpoints return and accept OpenAI's `{ role, content, id }` shape.--## Step-by-step implementation (Next.js)--### 1. Thread endpoints — `app/api/threads/route.ts`--This file handles listing and creating threads:--```typescript-import { db } from "@/lib/db";--// GET /api/threads — List all threads-export async function GET() {- const threads = await db.threads.findMany({- orderBy: { createdAt: "desc" },- });-- return Response.json({- threads: threads.map((t) => ({- id: t.id,- title: t.title,- createdAt: t.createdAt,- })),- });-}--// POST /api/threads — Create a new thread-export async function POST(req: Request) {- const { firstMessage } = await req.json();-- const thread = await db.threads.create({- data: {- title: firstMessage.content?.slice(0, 50) || "New conversation",- },- });-- return Response.json({- id: thread.id,- title: thread.title,- createdAt: thread.createdAt,- });-}-```--### 2. Single-thread endpoints — `app/api/threads/[id]/route.ts`--This file handles deleting and updating a specific thread:--```typescript-import { db } from "@/lib/db";--// DELETE /api/threads/:id — Delete a thread-export async function DELETE(req: Request, { params }: { params: { id: string } }) {- await db.threads.delete({ where: { id: params.id } });- return new Response(null, { status: 204 });-}--// PUT /api/threads/:id — Update a thread (e.g. rename)-export async function PUT(req: Request, { params }: { params: { id: string } }) {- const body = await req.json();-- const thread = await db.threads.update({- where: { id: params.id },- data: { title: body.title },- });-- return Response.json({- id: thread.id,- title: thread.title,- createdAt: thread.createdAt,- });-}-```--### 3. Message endpoint — `app/api/threads/[id]/messages/route.ts`--This endpoint returns the message history for a thread. The shape of each message must match the `messageFormat` you set on the frontend.--Since we're using `openAIMessageFormat`, we return messages as `{ role, content, id }` objects:--```typescript-import { db } from "@/lib/db";--// GET /api/threads/:id/messages — Load message history-export async function GET(req: Request, { params }: { params: { id: string } }) {- const messages = await db.messages.findMany({- where: { threadId: params.id },- orderBy: { createdAt: "asc" },- });-- return Response.json(messages);-}-```--## Connecting the frontend--Now that the backend is ready, point your chat component to it using `threadApiUrl`. Set `messageFormat` to match the format your endpoints return — in this case, `openAIMessageFormat`:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray', 'ChatProvider']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- threadApiUrl="/api/threads"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- threadApiUrl="/api/threads"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- threadApiUrl="/api/threads"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="ChatProvider">- ```tsx- import { ChatProvider, openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <ChatProvider- apiUrl="/api/chat"- threadApiUrl="/api/threads"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- >- {/* Your custom UI */}- </ChatProvider>- );- }- ```-- </Tab>-</Tabs>--The two key props:--- **`threadApiUrl`** — points to the REST API you just built-- **`messageFormat`** — tells OpenUI how to translate messages to/from your backend's format--## Next steps--<Cards>- <Card title="Conversation History" href="/docs/chat/chat-ui/conversation-history">- Learn about custom thread functions for non-REST backends.- </Card>- <Card title="Customization" href="/docs/chat/customization/custom-ui">- Build a fully custom chat UI with headless hooks.- </Card>-</Cards>diff --git a/docs/content/docs/chat/bottom-tray.mdx b/docs/content/docs/chat/bottom-tray.mdxindex ab7361426..b096dbc2c 100644--- a/docs/content/docs/chat/bottom-tray.mdx+++ b/docs/content/docs/chat/bottom-tray.mdx@@ -3,7 +3,9 @@ title: BottomTraydescription: A floating support-style chat widget.----`BottomTray` gives you a collapsible chat widget anchored to the bottom corner.+`BottomTray` provides a floating chat widget instead of a full-page chat surface.++This page covers the widget-style layout for support flows, product assistants, and experiences where chat stays collapsed until a user opens it.```tsximport { BottomTray } from "@openuidev/react-ui";@@ -18,19 +20,31 @@ export function App() {}```-### Controlled open state+{/* add visual: gif showing the BottomTray widget in collapsed and expanded states */}++## Controlled open state```tsx<BottomTray apiUrl="/api/chat" isOpen={isOpen} onOpenChange={setIsOpen} />```-### Related guides+Use the same backend configuration props as the other layouts. The only layout-specific props are the open-state controls.++That means you can start with `BottomTray` for the UI and still reuse the same `apiUrl`, `processMessage`, `streamProtocol`, and `threadApiUrl` setup from the other layouts.++## Related guides<Cards><Card title="Connecting to LLM" href="/docs/chat/connecting">Configure endpoint, adapters, and auth headers.</Card>- <Card title="Persistence (Threads)" href="/docs/chat/persistence">- Persist conversations between sessions.+ <Card title="Connect Thread History" href="/docs/chat/persistence">+ Load saved threads and previous messages into the widget.+ </Card>+ <Card title="Welcome & Starters" href="/docs/chat/welcome">+ Configure the empty-state content and starter prompts.+ </Card>+ <Card title="Theming" href="/docs/chat/theming">+ Adjust mode and theme overrides.</Card></Cards>diff --git a/docs/content/docs/chat/chat-ui/bottom-tray.mdx b/docs/content/docs/chat/chat-ui/bottom-tray.mdxdeleted file mode 100644index 1ca39f26a..000000000--- a/docs/content/docs/chat/chat-ui/bottom-tray.mdx+++ /dev/null@@ -1,117 +0,0 @@-----title: Bottom Tray-description: Add a floating chat widget to your application.------The BottomTray component adds a collapsible chat widget that floats at the bottom of your page — similar to the support chat widgets you see on many websites.--{/* TODO: Add screenshot/gif of BottomTray */}--## Basic usage--```tsx-import { BottomTray } from "@openuidev/react-ui";--function App() {- return (- <>- <main>{/* Your app content */}</main>- <BottomTray apiUrl="/api/chat" agentName="Assistant" />- </>- );-}-```--By default, BottomTray starts collapsed. The user clicks to expand it.--## Controlling open state--You can control whether the tray is open or closed from your app:--```tsx-import { BottomTray } from "@openuidev/react-ui";-import { useState } from "react";--function App() {- const [isOpen, setIsOpen] = useState(false);-- return (- <>- <main>- <button onClick={() => setIsOpen(true)}>Chat with us</button>- </main>- <BottomTray- apiUrl="/api/chat"- agentName="Assistant"- isOpen={isOpen}- onOpenChange={setIsOpen}- />- </>- );-}-```--Or set it to open by default:--```tsx-<BottomTray apiUrl="/api/chat" agentName="Assistant" defaultOpen />-```--## Full example--```tsx-import { BottomTray } from "@openuidev/react-ui";--function App() {- return (- <>- <main>{/* App content */}</main>- <BottomTray- apiUrl="/api/chat"- threadApiUrl="/api/threads"- agentName="Support"- logoUrl="/logo.png"- defaultOpen- welcomeMessage={{- heading: "Need help?",- body: "Our AI assistant is here to help.",- }}- conversationStarters={[- { label: "Track order", message: "Where is my order?" },- { label: "Returns", message: "How do I return an item?" },- ]}- />- </>- );-}-```--## Props--BottomTray accepts all shared chat config and UI props, plus these layout-specific props:--### BottomTray-specific props--| Prop | Type | Default | Description |-| -------------- | --------------------------- | ------- | --------------------------------------------- |-| `isOpen` | `boolean` | — | Controlled open state |-| `onOpenChange` | `(isOpen: boolean) => void` | — | Called when the user opens or closes the tray |-| `defaultOpen` | `boolean` | `false` | Whether the tray starts open (uncontrolled) |--### Shared props--See [Overview](/docs/chat/chat-ui) for the full list.--| Prop | Type | Description |-| ---------------------- | ---------------------------- | --------------------------------------------------------------- |-| `apiUrl` | `string` | Endpoint that receives messages and returns a streamed response |-| `threadApiUrl` | `string` | Base URL for thread persistence endpoints |-| `agentName` | `string` | Name shown in the chat header |-| `logoUrl` | `string` | Logo image shown in the chat header |-| `welcomeMessage` | `WelcomeMessageConfig` | Heading and body for the empty-chat screen |-| `conversationStarters` | `ConversationStartersConfig` | Suggested prompts shown on the welcome screen |-| `assistantMessage` | `AssistantMessageComponent` | Custom renderer for assistant messages |-| `userMessage` | `UserMessageComponent` | Custom renderer for user messages |-| `processMessage` | `function` | Custom fetch function (use instead of `apiUrl`) |-| `streamProtocol` | `StreamProtocolAdapter` | Parser for the backend's streaming format |-| `messageFormat` | `MessageFormat` | Converter for the backend's message format |diff --git a/docs/content/docs/chat/chat-ui/connecting-to-llm.mdx b/docs/content/docs/chat/chat-ui/connecting-to-llm.mdxdeleted file mode 100644index e408d5c62..000000000--- a/docs/content/docs/chat/chat-ui/connecting-to-llm.mdx+++ /dev/null@@ -1,153 +0,0 @@-----title: Connecting to LLM-description: Point your chat components to a backend that streams LLM responses.------Every chat component needs to know where to send messages. You have two options: a simple URL (`apiUrl`) for standard use cases, or a custom function (`processMessage`) for full control.--## Using `apiUrl`--The simplest way is to pass the URL of your backend endpoint:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return <Copilot apiUrl="/api/chat" agentName="My Agent" />;- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return <FullScreen apiUrl="/api/chat" agentName="My Agent" />;- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return <BottomTray apiUrl="/api/chat" agentName="My Agent" />;- }- ```-- </Tab>-</Tabs>--When a user sends a message, OpenUI makes a `POST` request to your endpoint with the conversation history. Your endpoint processes the messages through an LLM and streams the response back.--See [Backend Implementation](/docs/chat/backend/nextjs) for how to build this endpoint.--## Using `processMessage`--If you need to customize the request — add **Authorization headers**, change the URL structure (e.g., path parameters), or transform the payload — use `processMessage` instead of `apiUrl`:--<Tabs groupId="layout" items={["Copilot", "FullScreen", "BottomTray"]} persist>- <Tab value="Copilot">- ```tsx- <Copilot- processMessage={async ({ threadId, messages, abortController }) => {- // Example: Fetching with a Bearer token and dynamic URL- return fetch(`/api/threads/${threadId}/chat`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${getToken()}`,- },- body: JSON.stringify({ messages }),- signal: abortController.signal,- });- }}- agentName="My Agent"- />- ```- </Tab>- <Tab value="FullScreen">- ```tsx- <FullScreen- processMessage={async ({ threadId, messages, abortController }) => {- return fetch(`/api/threads/${threadId}/chat`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${getToken()}`,- },- body: JSON.stringify({ messages }),- signal: abortController.signal,- });- }}- agentName="My Agent"- />- ```- </Tab>- <Tab value="BottomTray">- ```tsx- <BottomTray- processMessage={async ({ threadId, messages, abortController }) => {- return fetch(`/api/threads/${threadId}/chat`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${getToken()}`,- },- body: JSON.stringify({ messages }),- signal: abortController.signal,- });- }}- agentName="My Agent"- />- ```- </Tab>-</Tabs>--The function receives:--| Parameter | Type | Description |-| :-------------------- | :---------------- | :--------------------------------------------------------- |-| **`threadId`** | `string` | The current conversation's ID (if persistence is enabled). |-| **`messages`** | `Message[]` | The full message history. |-| **`abortController`** | `AbortController` | Signal to cancel the request if the user clicks "Stop". |--It must return a standard `Response` object (the result of `fetch`).--## Streaming Format--By default, OpenUI uses its own **OpenUI Protocol**. If your backend streams in a different format (like raw OpenAI chunks), pass a `streamProtocol` adapter:--```tsx-import { openAIAdapter } from "@openuidev/react-headless";--<Copilot apiUrl="/api/chat" streamProtocol={openAIAdapter()} agentName="My Agent" />;-```--| Adapter | Use when... |-| :----------------------------- | :----------------------------------------------------------------- |-| **Default** | Backend uses the OpenUI Protocol (Standard). |-| **`openAIAdapter()`** | Backend uses `openai.chat.completions.create` with `stream: true`. |-| **`openAIResponsesAdapter()`** | Backend uses `openai.responses.create` (Realtime API). |--See [Backend & Integrations](/docs/chat/backend/providers) for full setup guides.--## Message Format--By default, OpenUI uses its internal message structure. If your backend expects messages in a different shape (e.g., strictly OpenAI format), pass a `messageFormat` converter:--```tsx-import { openAIMessageFormat } from "@openuidev/react-headless";--<Copilot apiUrl="/api/chat" messageFormat={openAIMessageFormat} agentName="My Agent" />;-```--| Format | Use when... |-| :------------------------------------ | :--------------------------------------------------------- |-| **Default** | Backend expects OpenUI message format. |-| **`openAIMessageFormat`** | Backend expects standard OpenAI `{role, content}` objects. |-| **`openAIConversationMessageFormat`** | Backend expects OpenAI Responses API items. |diff --git a/docs/content/docs/chat/chat-ui/conversation-history.mdx b/docs/content/docs/chat/chat-ui/conversation-history.mdxdeleted file mode 100644index 723252122..000000000--- a/docs/content/docs/chat/chat-ui/conversation-history.mdx+++ /dev/null@@ -1,223 +0,0 @@-----title: Conversation History-description: Persist chat threads so users can return to previous conversations.------By default, conversations live in memory and are lost when the page reloads. To persist them, you can either point to a REST API or provide your own functions.--## Using `threadApiUrl`--The simplest approach — pass a base URL and OpenUI handles the rest:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- threadApiUrl="/api/threads"- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- threadApiUrl="/api/threads"- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- threadApiUrl="/api/threads"- agentName="My Agent"- />- );- }- ```-- </Tab>-</Tabs>--OpenUI expects the following endpoints at your `threadApiUrl`:--| Action | Method | URL | Body | Response |-| ------------- | -------- | --------------------------- | ------------------ | ----------------------------------------- |-| List threads | `GET` | `/api/threads` | — | `{ threads: Thread[], nextCursor?: any }` |-| Create thread | `POST` | `/api/threads` | `{ firstMessage }` | `Thread` |-| Delete thread | `DELETE` | `/api/threads/:id` | — | — |-| Update thread | `PUT` | `/api/threads/:id` | `Thread` | `Thread` |-| Load messages | `GET` | `/api/threads/:id/messages` | — | `Message[]` |--A `Thread` object looks like:--```typescript-type Thread = {- id: string;- title: string;- createdAt: string | number;-};-```--See [Thread API Endpoint](/docs/chat/backend/thread-api-endpoint) for how to build this on the server.--## Custom thread functions--If your API doesn't follow the REST pattern above — for example, you need auth headers, a different URL structure, or want to call a GraphQL API — you can pass individual functions:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- fetchThreadList={async () => {- const res = await fetch("/my-api/conversations", {- headers: { Authorization: `Bearer ${getToken()}` },- });- return res.json(); // { threads, nextCursor? }- }}- createThread={async (firstMessage) => {- const res = await fetch("/my-api/conversations", {- method: "POST",- headers: { Authorization: `Bearer ${getToken()}` },- body: JSON.stringify({ message: firstMessage.content }),- });- return res.json(); // Thread- }}- deleteThread={async (id) => {- await fetch(`/my-api/conversations/${id}`, {- method: "DELETE",- headers: { Authorization: `Bearer ${getToken()}` },- });- }}- loadThread={async (threadId) => {- const res = await fetch(`/my-api/conversations/${threadId}/messages`, {- headers: { Authorization: `Bearer ${getToken()}` },- });- return res.json(); // Message[]- }}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- fetchThreadList={async () => {- const res = await fetch("/my-api/conversations", {- headers: { Authorization: `Bearer ${getToken()}` },- });- return res.json();- }}- createThread={async (firstMessage) => {- const res = await fetch("/my-api/conversations", {- method: "POST",- headers: { Authorization: `Bearer ${getToken()}` },- body: JSON.stringify({ message: firstMessage.content }),- });- return res.json();- }}- deleteThread={async (id) => {- await fetch(`/my-api/conversations/${id}`, {- method: "DELETE",- headers: { Authorization: `Bearer ${getToken()}` },- });- }}- loadThread={async (threadId) => {- const res = await fetch(`/my-api/conversations/${threadId}/messages`, {- headers: { Authorization: `Bearer ${getToken()}` },- });- return res.json();- }}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- fetchThreadList={async () => {- const res = await fetch("/my-api/conversations", {- headers: { Authorization: `Bearer ${getToken()}` },- });- return res.json();- }}- createThread={async (firstMessage) => {- const res = await fetch("/my-api/conversations", {- method: "POST",- headers: { Authorization: `Bearer ${getToken()}` },- body: JSON.stringify({ message: firstMessage.content }),- });- return res.json();- }}- deleteThread={async (id) => {- await fetch(`/my-api/conversations/${id}`, {- method: "DELETE",- headers: { Authorization: `Bearer ${getToken()}` },- });- }}- loadThread={async (threadId) => {- const res = await fetch(`/my-api/conversations/${threadId}/messages`, {- headers: { Authorization: `Bearer ${getToken()}` },- });- return res.json();- }}- agentName="My Agent"- />- );- }- ```-- </Tab>-</Tabs>--### Function reference--| Function | Signature | Purpose |-| ----------------- | ---------------------------------------------------------- | ----------------------------------------------------------------- |-| `fetchThreadList` | `(cursor?) => Promise<{ threads: Thread[]; nextCursor? }>` | Load the list of conversations (supports pagination via cursor) |-| `createThread` | `(firstMessage: UserMessage) => Promise<Thread>` | Create a new conversation when the user sends their first message |-| `deleteThread` | `(id: string) => Promise<void>` | Delete a conversation |-| `updateThread` | `(thread: Thread) => Promise<Thread>` | Update a conversation (e.g. rename) |-| `loadThread` | `(threadId: string) => Promise<Message[]>` | Load all messages for a conversation |diff --git a/docs/content/docs/chat/chat-ui/copilot.mdx b/docs/content/docs/chat/chat-ui/copilot.mdxdeleted file mode 100644index 01c889baf..000000000--- a/docs/content/docs/chat/chat-ui/copilot.mdx+++ /dev/null@@ -1,71 +0,0 @@-----title: Copilot-description: Add a sidebar chat panel alongside your app.------The Copilot component adds a chat panel that sits beside your main application content, like a sidebar assistant.--{/* TODO: Add screenshot/gif of Copilot */}--## Basic usage--```tsx-import { Copilot } from "@openuidev/react-ui";--function App() {- return (- <div style={{ display: "flex", height: "100vh" }}>- <main style={{ flex: 1 }}>{/* Your app content */}</main>- <Copilot apiUrl="/api/chat" agentName="My Agent" logoUrl="/logo.png" />- </div>- );-}-```--The Copilot panel renders alongside your content. It doesn't manage layout of your app — you control where it sits using standard CSS (e.g. flexbox as shown above).--## Full example--```tsx-import { Copilot } from "@openuidev/react-ui";--function App() {- return (- <div style={{ display: "flex", height: "100vh" }}>- <main style={{ flex: 1 }}>{/* App content */}</main>- <Copilot- apiUrl="/api/chat"- threadApiUrl="/api/threads"- agentName="My Agent"- logoUrl="/logo.png"- welcomeMessage={{- heading: "Hi there! 👋",- body: "I can help you with anything in this app.",- }}- conversationStarters={[- { label: "Get started", message: "How do I get started?" },- { label: "Help", message: "What can you help me with?" },- ]}- />- </div>- );-}-```--## Props--Copilot accepts all shared chat config and UI props. See [Overview](/docs/chat/chat-ui) for the full list.--| Prop | Type | Description |-| ---------------------- | ---------------------------- | --------------------------------------------------------------- |-| `apiUrl` | `string` | Endpoint that receives messages and returns a streamed response |-| `threadApiUrl` | `string` | Base URL for thread persistence endpoints |-| `agentName` | `string` | Name shown in the chat header |-| `logoUrl` | `string` | Logo image shown in the chat header |-| `welcomeMessage` | `WelcomeMessageConfig` | Heading and body for the empty-chat screen |-| `conversationStarters` | `ConversationStartersConfig` | Suggested prompts shown on the welcome screen |-| `assistantMessage` | `AssistantMessageComponent` | Custom renderer for assistant messages |-| `userMessage` | `UserMessageComponent` | Custom renderer for user messages |-| `processMessage` | `function` | Custom fetch function (use instead of `apiUrl`) |-| `streamProtocol` | `StreamProtocolAdapter` | Parser for the backend's streaming format |-| `messageFormat` | `MessageFormat` | Converter for the backend's message format |diff --git a/docs/content/docs/chat/chat-ui/custom-rendering.mdx b/docs/content/docs/chat/chat-ui/custom-rendering.mdxdeleted file mode 100644index a49b04596..000000000--- a/docs/content/docs/chat/chat-ui/custom-rendering.mdx+++ /dev/null@@ -1,358 +0,0 @@-----title: Custom Rendering-description: Override how the composer, assistant messages, and user messages are displayed.------## Custom composer--Use the `composer` prop to replace the built-in message input with your own component. OpenUI passes your component everything it needs — send/cancel callbacks and streaming state — so you can focus on the UI:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { useState } from "react";-- function MyComposer({ onSend, onCancel, isRunning }) {- const [text, setText] = useState("");-- return (- <form- onSubmit={(e) => {- e.preventDefault();- if (text.trim() && !isRunning) {- onSend(text);- setText("");- }- }}- >- <input- value={text}- onChange={(e) => setText(e.target.value)}- placeholder="Ask anything..."- disabled={isRunning}- />- {isRunning ? (- <button type="button" onClick={onCancel}>Stop</button>- ) : (- <button type="submit">Send</button>- )}- </form>- );- }-- function App() {- return (- <Copilot- apiUrl="/api/chat"- agentName="My Agent"- composer={MyComposer}- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { useState } from "react";-- function MyComposer({ onSend, onCancel, isRunning }) {- const [text, setText] = useState("");-- return (- <form- onSubmit={(e) => {- e.preventDefault();- if (text.trim() && !isRunning) {- onSend(text);- setText("");- }- }}- >- <input- value={text}- onChange={(e) => setText(e.target.value)}- placeholder="Ask anything..."- disabled={isRunning}- />- {isRunning ? (- <button type="button" onClick={onCancel}>Stop</button>- ) : (- <button type="submit">Send</button>- )}- </form>- );- }-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- agentName="My Agent"- composer={MyComposer}- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { useState } from "react";-- function MyComposer({ onSend, onCancel, isRunning }) {- const [text, setText] = useState("");-- return (- <form- onSubmit={(e) => {- e.preventDefault();- if (text.trim() && !isRunning) {- onSend(text);- setText("");- }- }}- >- <input- value={text}- onChange={(e) => setText(e.target.value)}- placeholder="Ask anything..."- disabled={isRunning}- />- {isRunning ? (- <button type="button" onClick={onCancel}>Stop</button>- ) : (- <button type="submit">Send</button>- )}- </form>- );- }-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- agentName="My Agent"- composer={MyComposer}- />- );- }- ```-- </Tab>-</Tabs>--### `ComposerProps`--OpenUI passes these props to your custom composer component:--| Prop | Type | Description |-| ------------------- | --------------------------- | -------------------------------------------------- |-| `onSend` | `(message: string) => void` | Call this with the user's input to send a message |-| `onCancel` | `() => void` | Cancel the in-progress response |-| `isRunning` | `boolean` | `true` while the assistant is streaming a response |-| `isLoadingMessages` | `boolean` | `true` while conversation history is being loaded |--```typescript-type ComposerProps = {- onSend: (message: string) => void;- onCancel: () => void;- isRunning: boolean;- isLoadingMessages: boolean;-};-```--Your component manages its own input state (the text value). When the user submits, call `onSend(text)` and clear your input. OpenUI handles everything else — adding the message to the thread, calling the backend, and streaming the response.--## Custom assistant messages--By default, OpenUI renders assistant messages as [GenUI](/docs/chat/genui) components. Use the `assistantMessage` prop to replace this with your own component:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- agentName="My Agent"- assistantMessage={({ message }) => (- <div className="my-assistant-bubble">- <strong>Agent:</strong>- <p>{message.content}</p>- </div>- )}- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- agentName="My Agent"- assistantMessage={({ message }) => (- <div className="my-assistant-bubble">- <strong>Agent:</strong>- <p>{message.content}</p>- </div>- )}- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- agentName="My Agent"- assistantMessage={({ message }) => (- <div className="my-assistant-bubble">- <strong>Agent:</strong>- <p>{message.content}</p>- </div>- )}- />- );- }- ```-- </Tab>-</Tabs>--Your component receives the full `AssistantMessage` object:--```typescript-type AssistantMessage = {- id: string;- role: "assistant";- content?: string;- toolCalls?: ToolCall[];- status?: "streaming" | "complete" | "awaiting_input";- context?: JSONValue[];-};-```--You can use the `status` field to show a typing indicator while the response is still streaming:--```tsx-assistantMessage={({ message }) => (- <div className="my-assistant-bubble">- <p>{message.content}</p>- {message.status === "streaming" && <span className="typing-dot">●</span>}- </div>-)}-```--## Custom user messages--By default, OpenUI renders user messages as plain text bubbles. Use the `userMessage` prop to replace this with your own component:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- agentName="My Agent"- userMessage={({ message }) => (- <div className="my-user-bubble">- {typeof message.content === "string"- ? message.content- : message.content.map((part, i) =>- part.type === "text" ? <span key={i}>{part.text}</span> : null- )}- </div>- )}- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- agentName="My Agent"- userMessage={({ message }) => (- <div className="my-user-bubble">- {typeof message.content === "string"- ? message.content- : message.content.map((part, i) =>- part.type === "text" ? <span key={i}>{part.text}</span> : null- )}- </div>- )}- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- agentName="My Agent"- userMessage={({ message }) => (- <div className="my-user-bubble">- {typeof message.content === "string"- ? message.content- : message.content.map((part, i) =>- part.type === "text" ? <span key={i}>{part.text}</span> : null- )}- </div>- )}- />- );- }- ```-- </Tab>-</Tabs>--Your component receives the full `UserMessage` object:--```typescript-type UserMessage = {- id: string;- role: "user";- content: string | InputContent[];- context?: JSONValue[];-};--type InputContent =- | { type: "text"; text: string }- | { type: "binary"; mimeType: string; url?: string; data?: string; filename?: string };-```--User message content can be either a plain string or an array of `InputContent` parts (for multimodal inputs like text + images). Handle both cases in your component.diff --git a/docs/content/docs/chat/chat-ui/full-screen.mdx b/docs/content/docs/chat/chat-ui/full-screen.mdxdeleted file mode 100644index 25818eebb..000000000--- a/docs/content/docs/chat/chat-ui/full-screen.mdx+++ /dev/null@@ -1,63 +0,0 @@-----title: Full Screen-description: Build a full-page standalone chat experience.------The FullScreen component renders a complete chat interface that takes up the entire page — including a sidebar for conversation history, a message area, and a composer.--{/* TODO: Add screenshot/gif of FullScreen */}--## Basic usage--```tsx-import { FullScreen } from "@openuidev/react-ui";--function App() {- return <FullScreen apiUrl="/api/chat" agentName="My Agent" logoUrl="/logo.png" />;-}-```--FullScreen fills its parent container. Make sure the parent has a defined height (e.g. `height: 100vh`).--## Full example--```tsx-import { FullScreen } from "@openuidev/react-ui";--function App() {- return (- <FullScreen- apiUrl="/api/chat"- threadApiUrl="/api/threads"- agentName="My Agent"- logoUrl="/logo.png"- welcomeMessage={{- heading: "Welcome!",- body: "Start a conversation or pick up where you left off.",- }}- conversationStarters={[- { label: "Summarize my data", message: "Can you summarize my latest data?" },- { label: "Create a report", message: "Help me create a report." },- ]}- />- );-}-```--## Props--FullScreen accepts all shared chat config and UI props. See [Overview](/docs/chat/chat-ui) for the full list.--| Prop | Type | Description |-| ---------------------- | ---------------------------- | --------------------------------------------------------------- |-| `apiUrl` | `string` | Endpoint that receives messages and returns a streamed response |-| `threadApiUrl` | `string` | Base URL for thread persistence endpoints |-| `agentName` | `string` | Name shown in the chat header |-| `logoUrl` | `string` | Logo image shown in the chat header |-| `welcomeMessage` | `WelcomeMessageConfig` | Heading and body for the empty-chat screen |-| `conversationStarters` | `ConversationStartersConfig` | Suggested prompts shown on the welcome screen |-| `assistantMessage` | `AssistantMessageComponent` | Custom renderer for assistant messages |-| `userMessage` | `UserMessageComponent` | Custom renderer for user messages |-| `processMessage` | `function` | Custom fetch function (use instead of `apiUrl`) |-| `streamProtocol` | `StreamProtocolAdapter` | Parser for the backend's streaming format |-| `messageFormat` | `MessageFormat` | Converter for the backend's message format |diff --git a/docs/content/docs/chat/chat-ui/index.mdx b/docs/content/docs/chat/chat-ui/index.mdxdeleted file mode 100644index 4d8e21462..000000000--- a/docs/content/docs/chat/chat-ui/index.mdx+++ /dev/null@@ -1,39 +0,0 @@-----title: Overview-description: Everything OpenUI Chat UI offers — layouts, messaging, persistence, and customization.------OpenUI Chat UI gives you a complete chat experience out of the box, with the flexibility to customize every part of it.--## Chat components--Three ready-to-use components for different use cases:--<Cards>- <Card title="Copilot" href="/docs/chat/chat-ui/copilot">- A sidebar chat panel that sits alongside your app.- </Card>- <Card title="FullScreen" href="/docs/chat/chat-ui/full-screen">- A full-page standalone chat experience.- </Card>- <Card title="BottomTray" href="/docs/chat/chat-ui/bottom-tray">- A floating chat widget anchored to the bottom of the page.- </Card>-</Cards>--## Customize them for your use case--<Cards>- <Card title="Connecting to LLM" href="/docs/chat/chat-ui/connecting-to-llm">- Point to your backend, add auth headers, or use a custom streaming protocol.- </Card>- <Card title="Conversation History" href="/docs/chat/chat-ui/conversation-history">- Persist threads so users can pick up where they left off.- </Card>- <Card title="Welcome & Starters" href="/docs/chat/chat-ui/welcome-and-starters">- Show a welcome message and suggested prompts on the empty chat screen.- </Card>- <Card title="Custom Rendering" href="/docs/chat/chat-ui/custom-chat-components">- Replace how assistant and user messages are displayed.- </Card>-</Cards>diff --git a/docs/content/docs/chat/chat-ui/meta.json b/docs/content/docs/chat/chat-ui/meta.jsondeleted file mode 100644index f93dcd952..000000000--- a/docs/content/docs/chat/chat-ui/meta.json+++ /dev/null@@ -1,14 +0,0 @@-{- "title": "Chat UI",- "defaultOpen": true,- "pages": [- "index",- "copilot",- "full-screen",- "bottom-tray",- "connecting-to-llm",- "conversation-history",- "welcome-and-starters",- "custom-rendering"- ]-}diff --git a/docs/content/docs/chat/chat-ui/welcome-and-starters.mdx b/docs/content/docs/chat/chat-ui/welcome-and-starters.mdxdeleted file mode 100644index 8509e2939..000000000--- a/docs/content/docs/chat/chat-ui/welcome-and-starters.mdx+++ /dev/null@@ -1,211 +0,0 @@-----title: Welcome & Starters-description: Configure the welcome experience and conversation starter prompts.------When a user opens your chat with no messages, OpenUI shows a welcome screen. You can customize the welcome message and provide suggested prompts (conversation starters) to help users get started.--## Welcome message--Use the `welcomeMessage` prop to set a heading and body text for the empty-chat screen:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- agentName="My Agent"- welcomeMessage={{- title: "Hi there! 👋",- description: "I'm your AI assistant. Ask me anything about your account, orders, or products.",- }}- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- agentName="My Agent"- welcomeMessage={{- title: "Hi there! 👋",- description: "I'm your AI assistant. Ask me anything about your account, orders, or products.",- }}- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- agentName="My Agent"- welcomeMessage={{- title: "Hi there! 👋",- description: "I'm your AI assistant. Ask me anything about your account, orders, or products.",- }}- />- );- }- ```-- </Tab>-</Tabs>--### `WelcomeMessageConfig`--Can be either a custom React component or a config object:--```typescript-type WelcomeMessageConfig =- | React.ComponentType<any>- | {- title?: string;- description?: string;- image?: { url: string } | ReactNode;- };-```--## Conversation starters--Conversation starters are clickable prompts shown below the welcome message. When a user clicks one, it sends that prompt as a message automatically:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- agentName="My Agent"- welcomeMessage={{- title: "Hi there! 👋",- description: "How can I help you today?",- }}- conversationStarters={{- options: [- {- displayText: "Track my order",- prompt: "Where is my latest order?",- },- {- displayText: "Return an item",- prompt: "How do I return a product?",- },- {- displayText: "Billing help",- prompt: "I have a question about my bill.",- },- ],- }}- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- agentName="My Agent"- welcomeMessage={{- title: "Hi there! 👋",- description: "How can I help you today?",- }}- conversationStarters={{- options: [- {- displayText: "Track my order",- prompt: "Where is my latest order?",- },- {- displayText: "Return an item",- prompt: "How do I return a product?",- },- {- displayText: "Billing help",- prompt: "I have a question about my bill.",- },- ],- }}- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- agentName="My Agent"- welcomeMessage={{- title: "Hi there! 👋",- description: "How can I help you today?",- }}- conversationStarters={{- options: [- {- displayText: "Track my order",- prompt: "Where is my latest order?",- },- {- displayText: "Return an item",- prompt: "How do I return a product?",- },- {- displayText: "Billing help",- prompt: "I have a question about my bill.",- },- ],- }}- />- );- }- ```-- </Tab>-</Tabs>--### `ConversationStartersConfig`--```typescript-interface ConversationStartersConfig {- variant?: "short" | "long"; // "short" for pill buttons (default), "long" for list items- options: Array<{- displayText: string; // Text shown on the button- prompt: string; // Message sent when clicked- icon?: ReactNode; // Optional icon- }>;-}-```--The `displayText` is what the user sees on the button. The `prompt` is what actually gets sent to the chat. This lets you show a short, friendly label while sending a more detailed prompt to the LLM.diff --git a/docs/content/docs/chat/connecting.mdx b/docs/content/docs/chat/connecting.mdxindex f59845f17..d6e9e8418 100644--- a/docs/content/docs/chat/connecting.mdx+++ b/docs/content/docs/chat/connecting.mdx@@ -3,45 +3,131 @@ title: Connecting to LLMdescription: Configure apiUrl, streamProtocol adapters, and authentication.----Every chat layout needs to know where to send messages. Use either:+Every chat layout needs a backend connection, but there are a few separate pieces involved:-- `apiUrl` for standard endpoint usage-- `processMessage` for full control (custom auth, URLs, payload transforms)+- how the frontend sends the request+- how the backend streams the response+- what message shape the backend expects-### Standard setup+This page introduces each one first, then shows how to choose the right combination for your backend.++## `apiUrl`++`apiUrl` is the simplest connection option. Use it when your frontend can call one backend endpoint directly and you do not need custom request logic on the client.```tsx-import { Copilot } from "@openuidev/react-ui";+import { FullScreen } from "@openuidev/react-ui";-<Copilot apiUrl="/api/chat" agentName="Assistant" />;+<FullScreen apiUrl="/api/chat" agentName="Assistant" />;```-### Custom request logic+With `apiUrl`, OpenUI sends the message history to your endpoint for you. If your backend expects a different message format, configure `messageFormat`. If you need custom headers, extra fields, or a different request body, use `processMessage` instead.++## `processMessage`++`processMessage` gives you full control over the request. Use it when you need to:++- add auth headers+- build a dynamic URL+- include extra request fields like `systemPrompt`+- convert `messages` before sending them```tsx-<Copilot- processMessage={async ({ threadId, messages, abortController }) => {- return fetch(`/api/threads/${threadId}/chat`, {+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";+import { defaultLibrary, defaultPromptOptions } from "@openuidev/react-ui/genui-lib";++const systemPrompt = defaultLibrary.prompt(defaultPromptOptions);++<FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {method: "POST",headers: {"Content-Type": "application/json",Authorization: `Bearer ${getToken()}`,},- body: JSON.stringify({ messages }),+ body: JSON.stringify({+ messages: openAIMessageFormat.toApi(messages),+ systemPrompt,+ }),signal: abortController.signal,});}}-/>+ streamProtocol={openAIReadableStreamAdapter()}+ componentLibrary={defaultLibrary}+ agentName="Assistant"+/>;+```++`processMessage` receives `threadId`, `messages`, and `abortController`, and must return a standard `Response` from your backend call.++## `streamProtocol`++`streamProtocol` tells OpenUI how to parse the response stream. By default, OpenUI expects the OpenUI Protocol, so only set this when your backend streams a different format.++| Backend output | Frontend config |+| :--- | :--- |+| OpenUI Protocol | No adapter required |+| Raw OpenAI Chat Completions SSE | `streamProtocol={openAIAdapter()}` |+| OpenAI SDK `toReadableStream()` / NDJSON | `streamProtocol={openAIReadableStreamAdapter()}` |+| OpenAI Responses API | `streamProtocol={openAIResponsesAdapter()}` |++```tsx+import { openAIReadableStreamAdapter } from "@openuidev/react-headless";++<FullScreen+ apiUrl="/api/chat"+ streamProtocol={openAIReadableStreamAdapter()}+ agentName="Assistant"+/>;```-### Stream adapters+## `messageFormat`-Use `streamProtocol` when your backend stream format differs from OpenUI default.+`messageFormat` controls the shape of the `messages` array sent to your backend and the shape expected when loading thread history.++| Backend message shape | Frontend config |+| :--- | :--- |+| AG-UI message shape | No converter required |+| OpenAI chat completions messages | `messageFormat={openAIMessageFormat}` |+| OpenAI Responses conversation items | `messageFormat={openAIConversationMessageFormat}` |```tsx-import { openAIAdapter } from "@openuidev/react-headless";+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";-<Copilot apiUrl="/api/chat" streamProtocol={openAIAdapter()} />;+<FullScreen+ apiUrl="/api/chat"+ streamProtocol={openAIReadableStreamAdapter()}+ messageFormat={openAIMessageFormat}+ agentName="Assistant"+/>;```-See full provider setup in [Providers](/docs/chat/providers).+Use `messageFormat` whenever your backend expects or returns a non-default message shape. This is especially important if you store messages for thread history.++## How to choose++Once you know what each prop does, the decision becomes:++1. Start with `apiUrl`.+2. Switch to `processMessage` only if you need auth, extra fields, dynamic URLs, or request conversion.+3. Add `streamProtocol` only if your backend does not stream the default OpenUI Protocol.+4. Add `messageFormat` only if your backend expects or returns a non-default message shape.++{/* add visual: flow-chart showing the decision between apiUrl and processMessage, then mapping backend stream output to the correct streamProtocol adapter and messageFormat choice */}++## Rules summary++- `apiUrl` is the simplest path when one endpoint can handle the request as-is.+- `processMessage` is the right choice when you need auth, extra fields, or payload conversion.+- `streamProtocol` parses the response stream.+- `messageFormat` converts request messages and loaded thread history.++## Related guides++- [Next.js Implementation](/docs/chat/nextjs)+- [The API Contract](/docs/chat/api-contract)+- [Providers](/docs/chat/providers)+- [Connect Thread History](/docs/chat/persistence)diff --git a/docs/content/docs/chat/copilot.mdx b/docs/content/docs/chat/copilot.mdxindex 70efa6bc6..93688f002 100644--- a/docs/content/docs/chat/copilot.mdx+++ b/docs/content/docs/chat/copilot.mdx@@ -3,7 +3,9 @@ title: Copilotdescription: The sidebar assistant layout for in-app chat experiences.----The `Copilot` component renders a chat sidebar next to your app content.+`Copilot` provides a sidebar assistant layout that stays visible alongside the rest of your application.++This layout keeps the main app screen in view while chat stays available at the side. For a full-page chat surface, see [FullScreen](/docs/chat/fullscreen). For a floating widget, see [BottomTray](/docs/chat/bottom-tray).```tsximport { Copilot } from "@openuidev/react-ui";@@ -18,7 +20,9 @@ export function App() {}```-### Common configuration+{/* add visual: image showing the Copilot sidebar layout next to the main app content */}++## Common configuration```tsx<Copilot@@ -29,14 +33,24 @@ export function App() {/>```-### Related guides+`Copilot` only handles the UI layer. It is a good fit for support panels, assistant sidebars, and workflows where users need to keep the main screen visible while chatting.++Set up your backend connection in [Connecting to LLM](/docs/chat/connecting), connect thread history in [Connect Thread History](/docs/chat/persistence), and customize the empty state in [Welcome & Starters](/docs/chat/welcome).++## Related guides<Cards><Card title="Connecting to LLM" href="/docs/chat/connecting">Configure `apiUrl`, adapters, and auth.</Card>- <Card title="Persistence (Threads)" href="/docs/chat/persistence">- Save and restore conversation history.+ <Card title="Connect Thread History" href="/docs/chat/persistence">+ Load thread lists and previous messages from your backend.+ </Card>+ <Card title="Welcome & Starters" href="/docs/chat/welcome">+ Configure the empty-state experience.+ </Card>+ <Card title="Theming" href="/docs/chat/theming">+ Adjust colors, mode, and theme overrides.</Card><Card title="Custom Chat Components" href="/docs/chat/custom-chat-components">Override assistant, user, and composer UI.diff --git a/docs/content/docs/chat/custom-chat-components.mdx b/docs/content/docs/chat/custom-chat-components.mdxindex 38c605193..91e5638fb 100644--- a/docs/content/docs/chat/custom-chat-components.mdx+++ b/docs/content/docs/chat/custom-chat-components.mdx@@ -9,7 +9,11 @@ You can customize specific UI surfaces without rebuilding the full chat stack:- `assistantMessage`- `userMessage`-### Custom composer+These props replace the built-in UI entirely for that surface. If you override them, your component becomes responsible for rendering the message or composer state correctly.++Use these props when you want to swap a specific surface while keeping the built-in layout and state model. If you need to redesign the whole chat shell, use the headless APIs instead.++## Custom composer```tsxfunction MyComposer({ onSend, onCancel, isRunning }) {@@ -19,7 +23,22 @@ function MyComposer({ onSend, onCancel, isRunning }) {<Copilot apiUrl="/api/chat" composer={MyComposer} />;```-### Custom assistant/user messages+### `ComposerProps`++```ts+type ComposerProps = {+ onSend: (message: string) => void;+ onCancel: () => void;+ isRunning: boolean;+ isLoadingMessages: boolean;+};+```++Call `onSend(text)` when the user submits. Use `onCancel()` to stop a running response.++Even a simple custom composer should still account for both `isRunning` and `isLoadingMessages`, because the composer may need to disable input while streaming or while history is still loading.++## Custom assistant and user messages```tsxfunction AssistantBubble({ message }) {@@ -33,4 +52,20 @@ function UserBubble({ message }) {<Copilot apiUrl="/api/chat" assistantMessage={AssistantBubble} userMessage={UserBubble} />;```-For full control over all layout pieces, move to [Headless Introduction](/docs/chat/headless-intro).+The `message` prop is the full `AssistantMessage` or `UserMessage` object from `@openuidev/react-headless`.++## Important behavior notes++- `assistantMessage` replaces the default assistant wrapper, including the avatar/container UI.+- `userMessage` replaces the default user bubble wrapper.+- If you pass `componentLibrary` and also pass `assistantMessage`, your custom component takes priority. That means you are responsible for rendering any structured assistant content yourself.+- `composer` should handle both `isRunning` and `isLoadingMessages` so the input behaves correctly while streaming or loading history.+- If your custom assistant renderer only handles plain text, document that constraint in your app and avoid assuming `message.content` is always a simple string.++{/* add visual: image showing the default assistant bubble beside a custom assistant bubble implementation */}++## Related guides++- [Headless Intro](/docs/chat/headless-intro)+- [Custom UI Guide](/docs/chat/custom-ui-guide)+- [GenUI](/docs/chat/genui)diff --git a/docs/content/docs/chat/custom-ui-guide.mdx b/docs/content/docs/chat/custom-ui-guide.mdxindex dec23ab0f..ecfd3658b 100644--- a/docs/content/docs/chat/custom-ui-guide.mdx+++ b/docs/content/docs/chat/custom-ui-guide.mdx@@ -1,36 +1,144 @@----title: Building Custom UI+title: Custom UI Guidedescription: Build a chat interface from scratch using headless hooks.----This guide shows the typical headless composition:+This guide shows a complete headless composition with:-1. `ThreadSidebar` from `useThreadList()`-2. `MessageList` from `useThread()`-3. `Composer` using `processMessage()` and `cancelMessage()`+1. `ChatProvider` for backend configuration+2. `useThreadList()` for the sidebar+3. `useThread()` for messages and the composer++The goal is to show how those pieces fit together in one working example, not to prescribe a specific visual design.```tsx-import { ChatProvider, useThread, useThreadList } from "@openuidev/react-headless";+import { useState } from "react";+import {+ ChatProvider,+ openAIMessageFormat,+ openAIReadableStreamAdapter,+ useThread,+ useThreadList,+} from "@openuidev/react-headless";-function CustomChat() {- const { messages, processMessage, isRunning } = useThread();- const { threads, selectThread } = useThreadList();+function ThreadSidebar() {+ const {+ threads,+ selectedThreadId,+ isLoadingThreads,+ selectThread,+ switchToNewThread,+ } = useThreadList();++ return (+ <aside>+ <button onClick={switchToNewThread}>New chat</button>+ {isLoadingThreads ? <p>Loading threads...</p> : null}+ {threads.map((thread) => (+ <button+ key={thread.id}+ onClick={() => selectThread(thread.id)}+ aria-pressed={thread.id === selectedThreadId}+ >+ {thread.title}+ </button>+ ))}+ </aside>+ );+}- // Render your own layout here- return null;+function MessageList() {+ const { messages, isRunning } = useThread();++ return (+ <div>+ {messages.map((message) => (+ <div key={message.id}>+ <strong>{message.role}:</strong> {String(message.content ?? "")}+ </div>+ ))}+ {isRunning ? <p>Thinking...</p> : null}+ </div>+ );+}++function Composer() {+ const { processMessage, cancelMessage, isRunning } = useThread();+ const [input, setInput] = useState("");++ return (+ <form+ onSubmit={(event) => {+ event.preventDefault();+ if (!input.trim() || isRunning) return;+ processMessage({ role: "user", content: input });+ setInput("");+ }}+ >+ <input+ value={input}+ onChange={(event) => setInput(event.target.value)}+ placeholder="Ask anything..."+ />+ {isRunning ? (+ <button type="button" onClick={cancelMessage}>+ Stop+ </button>+ ) : (+ <button type="submit">Send</button>+ )}+ </form>+ );+}++function CustomChat() {+ return (+ <div className="chat-app">+ <ThreadSidebar />+ <main>+ <MessageList />+ <Composer />+ </main>+ </div>+ );}export default function App() {return (- <ChatProvider apiUrl="/api/chat" threadApiUrl="/api/threads">+ <ChatProvider+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ }),+ signal: abortController.signal,+ });+ }}+ threadApiUrl="/api/threads"+ streamProtocol={openAIReadableStreamAdapter()}+ messageFormat={openAIMessageFormat}+ ><CustomChat /></ChatProvider>);}```-Start simple, then layer in:+This example uses the same backend assumptions as the built-in layouts:++- `messageFormat={openAIMessageFormat}` converts outgoing chat messages and loaded thread history to the backend format+- `openAIReadableStreamAdapter()` matches `response.toReadableStream()`+- `threadApiUrl` enables saved thread history+- `processMessage` keeps the request body explicit while still letting `messageFormat` handle message conversion++If you want Generative UI in a headless build, you also need to render structured assistant content yourself instead of relying on the built-in `componentLibrary` behavior from the layout components.++{/* add visual: flow-chart showing ChatProvider feeding ThreadSidebar, MessageList, and Composer through useThreadList and useThread */}++## Related guides-- custom rendering-- optimistic UI-- auth-aware backend calls with `processMessage`+- [Headless Intro](/docs/chat/headless-intro)+- [Hooks & State](/docs/chat/hooks)+- [Connecting to LLM](/docs/chat/connecting)diff --git a/docs/content/docs/chat/customization/custom-ui.mdx b/docs/content/docs/chat/customization/custom-ui.mdxdeleted file mode 100644index 1802803ee..000000000--- a/docs/content/docs/chat/customization/custom-ui.mdx+++ /dev/null@@ -1,167 +0,0 @@-----title: Custom UI (Headless)-description: Build a fully custom chat interface using ChatProvider and hooks.------If the built-in chat components (`Copilot`, `FullScreen`, `BottomTray`) don't fit your needs, you can build your own chat UI from scratch using `ChatProvider` and hooks from `@openuidev/react-headless`. You bring the components — OpenUI handles the state, streaming, and thread management.--## `ChatProvider`--Wrap your UI in `ChatProvider` to set up the chat backend. It accepts the same config props as the built-in chat components — `apiUrl`, `threadApiUrl`, `processMessage`, `streamProtocol`, `messageFormat`, and all the custom thread functions.--```tsx-import { ChatProvider } from "@openuidev/react-headless";--function App() {- return (- <ChatProvider apiUrl="/api/chat" threadApiUrl="/api/threads">- <MyChat />- </ChatProvider>- );-}-```--See [Connecting to LLM](/docs/chat/chat-ui/connecting-to-llm) and [Conversation History](/docs/chat/chat-ui/conversation-history) for details on these props.--## Hooks--All hooks must be used inside a `ChatProvider`. Both support custom selectors for fine-grained re-renders (e.g. `useThread(s => s.messages)`).--### `useThread`--Access the current thread's state and actions:--```typescript-const {- // State- messages, // Message[] — the current conversation- isRunning, // boolean — true while streaming a response- isLoadingMessages, // boolean — true while loading thread history- threadError, // Error | null — last error, if any-- // Actions- processMessage, // (message: CreateMessage) => Promise<void> — send a message- cancelMessage, // () => void — cancel the in-progress response- appendMessages, // (...messages: Message[]) => void — add messages to the thread- updateMessage, // (message: Message) => void — update a specific message- setMessages, // (messages: Message[]) => void — replace all messages- deleteMessage, // (messageId: string) => void — remove a message-} = useThread();-```--### `useThreadList`--Access the thread list state and actions:--```typescript-const {- // State- threads, // Thread[] — all conversations- isLoadingThreads, // boolean — true while fetching the list- threadListError, // Error | null — last error, if any- selectedThreadId, // string | null — currently active thread- hasMoreThreads, // boolean — true if more threads can be loaded (pagination)-- // Actions- loadThreads, // () => void — load the thread list- loadMoreThreads, // () => void — load next page of threads- switchToNewThread, // () => void — start a new conversation- createThread, // (firstMessage: UserMessage) => Promise<Thread>- selectThread, // (threadId: string) => void — switch to a thread- updateThread, // (thread: Thread) => void — rename, etc.- deleteThread, // (threadId: string) => void-} = useThreadList();-```--## Example: full custom chat--A complete custom chat with a message list, input, and thread sidebar — no OpenUI UI components used:--```tsx-import { useState } from "react";-import { ChatProvider, useThread, useThreadList } from "@openuidev/react-headless";--function MessageList() {- const { messages, isRunning } = useThread();-- return (- <div className="messages">- {messages.map((msg) => (- <div key={msg.id} className={`message message-${msg.role}`}>- {msg.content}- </div>- ))}- {isRunning && <div className="typing-indicator">Thinking...</div>}- </div>- );-}--function ChatInput() {- const { isRunning, processMessage, cancelMessage } = useThread();- const [input, setInput] = useState("");-- return (- <form- onSubmit={(e) => {- e.preventDefault();- if (input.trim() && !isRunning) {- processMessage({ role: "user", content: input });- setInput("");- }- }}- >- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Type a message..."- disabled={isRunning}- />- {isRunning ? (- <button type="button" onClick={cancelMessage}>- Stop- </button>- ) : (- <button type="submit">Send</button>- )}- </form>- );-}--function ThreadSidebar() {- const {- threads,- selectedThreadId,- isLoadingThreads,- selectThread,- switchToNewThread,- deleteThread,- } = useThreadList();-- return (- <aside className="sidebar">- <button onClick={switchToNewThread}>+ New Chat</button>- {isLoadingThreads && <div>Loading...</div>}- {threads.map((t) => (- <div key={t.id} className={t.id === selectedThreadId ? "active" : ""}>- <button onClick={() => selectThread(t.id)}>{t.title}</button>- <button onClick={() => deleteThread(t.id)}>×</button>- </div>- ))}- </aside>- );-}--function App() {- return (- <ChatProvider apiUrl="/api/chat" threadApiUrl="/api/threads">- <div className="chat-app">- <ThreadSidebar />- <main>- <MessageList />- <ChatInput />- </main>- </div>- </ChatProvider>- );-}-```diff --git a/docs/content/docs/chat/customization/meta.json b/docs/content/docs/chat/customization/meta.jsondeleted file mode 100644index e54161f4d..000000000--- a/docs/content/docs/chat/customization/meta.json+++ /dev/null@@ -1,4 +0,0 @@-{- "title": "Customization",- "pages": ["custom-ui", "theming"]-}diff --git a/docs/content/docs/chat/customization/theming.mdx b/docs/content/docs/chat/customization/theming.mdxdeleted file mode 100644index b22bbe0d0..000000000--- a/docs/content/docs/chat/customization/theming.mdx+++ /dev/null@@ -1,8 +0,0 @@-----title: Theming-description: Customize the look and feel of OpenUI Chat components.------# Theming--TODO: ThemeProvider, light/dark mode, custom colors, branding.diff --git a/docs/content/docs/chat/from-scratch.mdx b/docs/content/docs/chat/from-scratch.mdxnew file mode 100644index 000000000..6f5c80a35--- /dev/null+++ b/docs/content/docs/chat/from-scratch.mdx@@ -0,0 +1,186 @@+---+title: End-to-End Guide+description: Build a complete OpenUI Chat setup from an existing app.+---++This guide shows a complete OpenUI Chat setup in an existing Next.js App Router project.++This path covers:++- a built-in chat layout+- an OpenAI-backed route handler+- frontend request wiring with `processMessage`+- the correct stream adapter and message format+- optional thread history+- optional headless customization++{/* add visual: flow-chart showing frontend page -> processMessage -> /api/chat route -> OpenAI -> toReadableStream() -> openAIReadableStreamAdapter() -> rendered UI with componentLibrary */}++## Prerequisites++Complete [Installation](/docs/chat/installation) first, then return here to wire the chat flow.++## 1. Generate the component-library prompt++If you want Generative UI, generate a system prompt from the component library and send it with each request.++If you only want plain text chat, you can skip this step and omit `componentLibrary` and `systemPrompt` in the next examples.++```tsx+import { defaultLibrary, defaultPromptOptions } from "@openuidev/react-ui/genui-lib";++const systemPrompt = defaultLibrary.prompt(defaultPromptOptions);+```++This prompt tells the model which UI components it is allowed to emit.++## 2. Create the streaming backend route++Create `app/api/chat/route.ts`:++```ts+import { NextRequest } from "next/server";+import OpenAI from "openai";++const client = new OpenAI();++export async function POST(req: NextRequest) {+ try {+ const { messages, systemPrompt } = await req.json();++ const chatMessages: OpenAI.ChatCompletionMessageParam[] = [+ ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),+ ...messages,+ ];++ const response = await client.chat.completions.create({+ model: "gpt-5.2",+ messages: chatMessages,+ stream: true,+ });++ return new Response(response.toReadableStream(), {+ headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+ },+ });+ } catch (err) {+ console.error(err);+ const message = err instanceof Error ? err.message : "Unknown error";+ return new Response(JSON.stringify({ error: message }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ });+ }+}+```++This route expects OpenAI chat-completion messages and returns the OpenAI SDK readable stream.++## 3. Render a layout and connect it to the route++`FullScreen` is a good baseline because it includes both the thread list and the main chat surface.++This guide uses `processMessage` instead of `apiUrl` so the request body stays explicit and you can pass `systemPrompt`.++```tsx+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";+import { defaultLibrary, defaultPromptOptions } from "@openuidev/react-ui/genui-lib";++const systemPrompt = defaultLibrary.prompt(defaultPromptOptions);++export default function Page() {+ return (+ <div className="h-screen">+ <FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ systemPrompt,+ }),+ signal: abortController.signal,+ });+ }}+ messageFormat={openAIMessageFormat}+ streamProtocol={openAIReadableStreamAdapter()}+ componentLibrary={defaultLibrary}+ agentName="Assistant"+ />+ </div>+ );+}+```++Why this setup matters:++- `processMessage` gives you control over the request body+- `messageFormat={openAIMessageFormat}` converts the messages before they reach your route+- `openAIReadableStreamAdapter()` matches `response.toReadableStream()`+- `componentLibrary={defaultLibrary}` lets the UI render structured responses++### Checkpoint++At this point, you should be able to send a message and receive streamed responses in the UI.++Guides: [Connecting to LLM](/docs/chat/connecting), [Next.js Implementation](/docs/chat/nextjs), [Providers](/docs/chat/providers)++## 4. Connect Thread History (optional)++Stop here if you only need a working streamed chat UI.++Continue with this section only if your app also needs saved threads and message history from the backend.++If you want the UI to load saved threads and previous messages, add `threadApiUrl` and implement the default thread contract described in [Connect Thread History](/docs/chat/persistence).++```tsx+<FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ systemPrompt,+ }),+ signal: abortController.signal,+ });+ }}+ threadApiUrl="/api/threads"+ streamProtocol={openAIReadableStreamAdapter()}+ messageFormat={openAIMessageFormat}+ componentLibrary={defaultLibrary}+ agentName="Assistant"+/>+```++Add `messageFormat={openAIMessageFormat}` if your thread endpoints also store and return OpenAI-style messages. That keeps both chat requests and thread-history loading aligned without manually calling `openAIMessageFormat.toApi(messages)` in `processMessage`.++## 5. Switch layouts or go headless (optional)++This step does not change your backend contract. It only changes the UI layer that sits on top of the same chat and thread wiring.++Once the backend contract is working, you can keep the same chat wiring and swap the UI layer.++- Use [Copilot](/docs/chat/copilot) for a sidebar layout+- Use [BottomTray](/docs/chat/bottom-tray) for a floating widget+- Use [Headless Intro](/docs/chat/headless-intro) and [Custom UI Guide](/docs/chat/custom-ui-guide) for full UI control++## You now have++- a streaming `/api/chat` route+- a connected chat layout+- the correct OpenAI message conversion and stream adapter+- optional GenUI support+- a clear path to thread history and headless customization++## Next steps++- [Connect Thread History](/docs/chat/persistence)+- [GenUI](/docs/chat/genui)+- [Custom UI Guide](/docs/chat/custom-ui-guide)diff --git a/docs/content/docs/chat/fullscreen.mdx b/docs/content/docs/chat/fullscreen.mdxindex d2be1064a..01ba24883 100644--- a/docs/content/docs/chat/fullscreen.mdx+++ b/docs/content/docs/chat/fullscreen.mdx@@ -3,7 +3,9 @@ title: FullScreendescription: The full-page, ChatGPT-style chat layout.----`FullScreen` renders a complete chat experience, including thread list and message area.+`FullScreen` provides a full-page chat layout with the built-in thread list and main conversation area.++This page covers the complete built-in layout. For a sidebar inside an existing app screen, see [Copilot](/docs/chat/copilot). For a floating widget, see [BottomTray](/docs/chat/bottom-tray).```tsximport { FullScreen } from "@openuidev/react-ui";@@ -17,7 +19,9 @@ export function App() {}```-### Common configuration+{/* add visual: image showing the FullScreen layout with sidebar, thread list, and main conversation area */}++## Common configuration```tsx<FullScreen@@ -28,13 +32,24 @@ export function App() {/>```-### Related guides+`FullScreen` is the best starting point for end-to-end setup because it exercises both the message surface and thread UI. See the [End-to-End Guide](/docs/chat/from-scratch) if you want to wire the whole flow manually.++## Related guides<Cards><Card title="Connecting to LLM" href="/docs/chat/connecting">Configure endpoint, streaming adapters, and auth.</Card>- <Card title="Persistence (Threads)" href="/docs/chat/persistence">- Configure thread storage and loading.+ <Card title="Connect Thread History" href="/docs/chat/persistence">+ Load thread lists and message history from your backend.+ </Card>+ <Card title="Welcome & Starters" href="/docs/chat/welcome">+ Customize the empty-state experience.+ </Card>+ <Card title="Theming" href="/docs/chat/theming">+ Control colors, mode, and theme overrides.+ </Card>+ <Card title="Custom Chat Components" href="/docs/chat/custom-chat-components">+ Override the built-in composer and message rendering.</Card></Cards>diff --git a/docs/content/docs/chat/genui.mdx b/docs/content/docs/chat/genui.mdxindex df13c729d..e4b072b39 100644--- a/docs/content/docs/chat/genui.mdx+++ b/docs/content/docs/chat/genui.mdx@@ -3,71 +3,104 @@ title: GenUIdescription: Use Generative UI with Chat components.----OpenUI Chat components support **GenUI** out of the box.+GenUI lets assistant messages render structured UI instead of plain text. To make it work, you need both sides of the setup:-If your backend streams OpenUI Lang responses and provides a component library prompt, chat messages can render rich UI (cards, charts, forms, layouts) directly in the conversation.+- `componentLibrary` on the frontend so OpenUI knows how to render components+- a generated `systemPrompt` in the request so the model knows what it is allowed to emit-## Two ways to enable GenUI+Passing `componentLibrary` alone is not enough.-### 1) Use `defaultLibrary` from `react-ui` (recommended)+The frontend and backend have different jobs here:-This is the fastest path and the one used in the OpenUI Lang quick start.+- the frontend renders structured responses through `componentLibrary`+- the backend sends the generated `systemPrompt` to the model with each request-- Import `defaultLibrary` from `@openuidev/react-ui`-- Pass it to the chat component via `componentLibrary`-- Use the generated system prompt on your backend so the model knows what components it can emit+If either side is missing, the model falls back to plain text or emits components the UI cannot render.-`defaultLibrary` includes 40+ ready-to-use components and examples, so you can ship quickly without defining schemas first.+## Use the default library-```tsx-import { Copilot } from "@openuidev/react-ui";-import { defaultLibrary } from "@openuidev/react-ui";+`defaultLibrary` is the fastest way to enable GenUI because it ships with ready-to-use components and example prompt rules.-export function App() {- return <Copilot apiUrl="/api/chat" componentLibrary={defaultLibrary} />;+```tsx+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";+import { defaultLibrary, defaultPromptOptions } from "@openuidev/react-ui/genui-lib";++const systemPrompt = defaultLibrary.prompt(defaultPromptOptions);++export default function Page() {+ return (+ <FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ systemPrompt,+ }),+ signal: abortController.signal,+ });+ }}+ messageFormat={openAIMessageFormat}+ streamProtocol={openAIReadableStreamAdapter()}+ componentLibrary={defaultLibrary}+ agentName="Assistant"+ />+ );}```-### 2) Create your own custom library+In this setup:-If you need domain-specific components, define your own library and pass it as `componentLibrary`.+- `defaultLibrary.prompt(defaultPromptOptions)` creates the system prompt+- `systemPrompt` is sent with every request+- `messageFormat={openAIMessageFormat}` converts messages to the backend format+- `componentLibrary={defaultLibrary}` tells the UI how to render the model output-See [Define Components](/docs/openui-lang/defining-components) for the full setup.+This is the minimal complete pattern for GenUI with the built-in library.-```tsx-import { Copilot } from "@openuidev/react-ui";-import { myLibrary } from "@/lib/my-library";+{/* add visual: image showing the difference between a plain text assistant response and a GenUI-rendered component response */}-export function App() {- return <Copilot apiUrl="/api/chat" componentLibrary={myLibrary} />;-}+## Use your own library++If you need domain-specific components, keep the same request flow and swap in your own library definition:++```tsx+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";+import { myLibrary, myPromptOptions } from "@/lib/my-library";++const systemPrompt = myLibrary.prompt(myPromptOptions);++<FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ systemPrompt,+ }),+ signal: abortController.signal,+ });+ }}+ messageFormat={openAIMessageFormat}+ streamProtocol={openAIReadableStreamAdapter()}+ componentLibrary={myLibrary}+ agentName="Assistant"+/>;```-## Use the standard library with all chat layouts+This example assumes `myLibrary` is already defined elsewhere in your app. The key rule is that your custom library still has to provide two things:-The same `defaultLibrary` works across all built-in chat UIs:+- a prompt generator, so the backend can tell the model what components it may emit+- component definitions, so the frontend can render those emitted components-```tsx-import { Copilot, FullScreen, BottomTray, defaultLibrary } from "@openuidev/react-ui";+Your backend does not need a special GenUI endpoint. It only needs to receive the generated `systemPrompt` and pass it to the model alongside the message history.-<Copilot apiUrl="/api/chat" componentLibrary={defaultLibrary} />;-<FullScreen apiUrl="/api/chat" componentLibrary={defaultLibrary} />;-<BottomTray apiUrl="/api/chat" componentLibrary={defaultLibrary} />;-```+## Related guides-### Related pages--<Cards>- <Card title="Copilot" href="/docs/chat/copilot">- Sidebar layout with GenUI enabled via `componentLibrary`.- </Card>- <Card title="FullScreen" href="/docs/chat/fullscreen">- Full-page chat layout with the same GenUI setup.- </Card>- <Card title="BottomTray" href="/docs/chat/bottom-tray">- Floating widget layout with standard library support.- </Card>- <Card title="Define Components" href="/docs/openui-lang/defining-components">- Build and use a custom library for domain-specific UI.- </Card>-</Cards>+- [End-to-End Guide](/docs/chat/from-scratch)+- [Connecting to LLM](/docs/chat/connecting)+- [Define Components](/docs/openui-lang/defining-components)diff --git a/docs/content/docs/chat/headless-intro.mdx b/docs/content/docs/chat/headless-intro.mdxindex f60a2f3c3..c3d23075d 100644--- a/docs/content/docs/chat/headless-intro.mdx+++ b/docs/content/docs/chat/headless-intro.mdx@@ -1,16 +1,17 @@----title: Introduction+title: Headless Introductiondescription: Why and when to use headless mode with ChatProvider.----Use headless mode when pre-built layouts are not enough and you need full UI control.+This page introduces headless mode and the role of `ChatProvider` in a custom chat UI.-At the center is `ChatProvider`, which manages:+The trade-off is simple: you get full control over rendering, but you become responsible for composing the sidebar, message list, and composer yourself.+At the center is `ChatProvider`, which manages:- streaming state- thread list and selection- message sending/cancelation-- persistence hooks+- thread-history hooks```tsximport { ChatProvider } from "@openuidev/react-headless";@@ -24,7 +25,26 @@ export function App() {}```-Next:+`ChatProvider` accepts the same backend props as the built-in layouts:++- `apiUrl` or `processMessage`+- `streamProtocol`+- `messageFormat`+- `threadApiUrl` or custom thread functions++Thread history is not automatic. To load and save threads, you still need `threadApiUrl` or the custom thread handlers.++The usual build order is:++1. configure `ChatProvider` with your backend connection+2. read state with `useThread()` and `useThreadList()`+3. render your own sidebar, messages, and composer components++{/* add visual: flow-chart showing ChatProvider at the center with hooks, backend config, and custom UI components around it */}++## Related guides- [Hooks & State](/docs/chat/hooks)-- [Building Custom UI](/docs/chat/custom-ui-guide)+- [Custom UI Guide](/docs/chat/custom-ui-guide)+- [Connecting to LLM](/docs/chat/connecting)+- [Connect Thread History](/docs/chat/persistence)diff --git a/docs/content/docs/chat/hooks.mdx b/docs/content/docs/chat/hooks.mdxindex b1b46a563..4b50fa8c6 100644--- a/docs/content/docs/chat/hooks.mdx+++ b/docs/content/docs/chat/hooks.mdx@@ -5,32 +5,162 @@ description: Deep dive into useThread, useThreadList, and related headless stateAll headless hooks must run inside `ChatProvider`.-### `useThread()`+Use `useThread()` for the active conversation and `useThreadList()` for thread navigation. Most custom UIs need both.-Handles active conversation state:+## Start with `ChatProvider`-- `messages`-- `isRunning`-- `processMessage()`-- `cancelMessage()`-- message mutation helpers+```tsx+import {+ ChatProvider,+ openAIMessageFormat,+ openAIReadableStreamAdapter,+} from "@openuidev/react-headless";++export function App() {+ return (+ <ChatProvider+ apiUrl="/api/chat"+ threadApiUrl="/api/threads"+ streamProtocol={openAIReadableStreamAdapter()}+ messageFormat={openAIMessageFormat}+ >+ <MyCustomChat />+ </ChatProvider>+ );+}+```++That provider owns the shared state. The hooks below read from and write to that state.++## `useThread()`++Use `useThread()` for the currently selected conversation: messages, send state, loading state, and message mutations.++```tsx+const {+ messages,+ isRunning,+ isLoadingMessages,+ threadError,+ processMessage,+ cancelMessage,+ appendMessages,+ updateMessage,+ setMessages,+ deleteMessage,+} = useThread();+```++### Common send flow```tsx-const { messages, isRunning, processMessage, cancelMessage } = useThread();+function Composer() {+ const { processMessage, cancelMessage, isRunning } = useThread();+ const [input, setInput] = useState("");++ return (+ <form+ onSubmit={(event) => {+ event.preventDefault();+ if (!input.trim() || isRunning) return;+ processMessage({ role: "user", content: input });+ setInput("");+ }}+ >+ <input value={input} onChange={(event) => setInput(event.target.value)} />+ {isRunning ? (+ <button type="button" onClick={cancelMessage}>+ Stop+ </button>+ ) : (+ <button type="submit">Send</button>+ )}+ </form>+ );+}```-### `useThreadList()`+Use `isLoadingMessages` to show a loading state when a saved thread is being hydrated, and use `threadError` to render request or load failures near the conversation surface.-Handles thread sidebar state:+## `useThreadList()`-- `threads`-- `selectedThreadId`-- `loadThreads()`-- `selectThread()`-- `createThread()` / `deleteThread()`+Use `useThreadList()` for the sidebar: thread loading, selection, creation, pagination, and thread-level mutations.```tsx-const { threads, selectedThreadId, selectThread, switchToNewThread } = useThreadList();+const {+ threads,+ isLoadingThreads,+ threadListError,+ selectedThreadId,+ hasMoreThreads,+ loadThreads,+ loadMoreThreads,+ switchToNewThread,+ createThread,+ selectThread,+ updateThread,+ deleteThread,+} = useThreadList();```-Use selectors when needed to minimize re-renders, for example `useThread((s) => s.messages)`.+### Common sidebar flow++```tsx+function ThreadSidebar() {+ const {+ threads,+ selectedThreadId,+ hasMoreThreads,+ isLoadingThreads,+ loadMoreThreads,+ switchToNewThread,+ selectThread,+ deleteThread,+ } = useThreadList();++ return (+ <aside>+ <button onClick={switchToNewThread}>New chat</button>++ {threads.map((thread) => (+ <div key={thread.id}>+ <button+ onClick={() => selectThread(thread.id)}+ aria-pressed={thread.id === selectedThreadId}+ >+ {thread.title}+ </button>+ <button onClick={() => deleteThread(thread.id)}>Delete</button>+ </div>+ ))}++ {hasMoreThreads ? (+ <button onClick={() => loadMoreThreads()} disabled={isLoadingThreads}>+ Load more+ </button>+ ) : null}+ </aside>+ );+}+```++`switchToNewThread()` clears the current selection so the next user message starts a new conversation. `updateThread()` is useful when you want to rename or otherwise patch thread metadata after creation.++## Selectors++Use selectors to minimize re-renders when you only need a small part of the store.++```tsx+const messages = useThread((state) => state.messages);+const selectedThreadId = useThreadList((state) => state.selectedThreadId);+```++This is especially useful when your sidebar and message list are separate components and you do not want unrelated state updates to rerender both.++{/* add visual: flow-chart showing how useThread maps to the active conversation and useThreadList maps to the thread sidebar */}++## Related guides++- [Headless Intro](/docs/chat/headless-intro)+- [Custom UI Guide](/docs/chat/custom-ui-guide)+- [Connect Thread History](/docs/chat/persistence)diff --git a/docs/content/docs/chat/installation.mdx b/docs/content/docs/chat/installation.mdxindex 8519d89f9..fe55ffd73 100644--- a/docs/content/docs/chat/installation.mdx+++ b/docs/content/docs/chat/installation.mdx@@ -1,45 +1,65 @@---title: Installation-description: Add OpenUI Chat to your existing React application.+description: Add OpenUI Chat to an existing Next.js App Router application.----Add OpenUI Chat to your existing React application.+This page covers package installation, style imports, and a basic render check for an existing Next.js App Router app.<Callout type="info">- **Starting a new project?** Skip this guide and use our scaffold command instead: `npx- create-openui-chat my-app`+ **Starting a new project?**+ Skip this guide and use our scaffold command instead:+ `npx create-openui-chat my-app`</Callout>-### 1. Install Dependencies+## Prerequisites-Install the UI package and the headless core. We also recommend `lucide-react` for icons if you are not using it already.+This guide assumes:++- Next.js App Router+- React 18 or newer+- a page where you can mount a chat layout++## 1. Install dependencies++Install the UI package, the headless core, and the icons package used by the built-in layouts.<Tabs items={["npm", "pnpm", "yarn", "bun"]}><Tab value="npm">- ```bash npm install @openuidev/react-ui @openuidev/react-headless lucide-react ```+ ```bash+ npm install @openuidev/react-ui @openuidev/react-headless lucide-react+ ```</Tab><Tab value="pnpm">- ```bash pnpm add @openuidev/react-ui @openuidev/react-headless lucide-react ```+ ```bash+ pnpm add @openuidev/react-ui @openuidev/react-headless lucide-react+ ```</Tab><Tab value="yarn">- ```bash yarn add @openuidev/react-ui @openuidev/react-headless lucide-react ```+ ```bash+ yarn add @openuidev/react-ui @openuidev/react-headless lucide-react+ ```</Tab><Tab value="bun">- ```bash bun add @openuidev/react-ui @openuidev/react-headless lucide-react ```+ ```bash+ bun add @openuidev/react-ui @openuidev/react-headless lucide-react+ ```</Tab></Tabs>-### 2. Configure Styles+## 2. Import the styles-OpenUI components come with a default theme. Import the CSS in your root layout file.--**Next.js App Router (`app/layout.tsx`):**+Import the component and theme styles in your root layout.```tsx-import "@openuidev/react-ui/styles.css"; // 👈 Add this line+import "@openuidev/react-ui/components.css";+import "@openuidev/react-ui/styles/index.css";import "./globals.css";-export default function RootLayout({ children }) {+export default function RootLayout({+ children,+}: {+ children: React.ReactNode;+}) {return (<html lang="en"><body>{children}</body>@@ -48,83 +68,39 @@ export default function RootLayout({ children }) {}```-### 3. Render chat component on a page+These imports give you the default chat layout styling and theme tokens.++## 3. Render a layout to verify setup-Render a basic `Copilot` component to ensure everything is working.+Render one of the built-in layouts on a page to confirm the package is installed correctly.```tsx// app/page.tsx-import { Copilot } from "@openuidev/react-ui";+import { FullScreen } from "@openuidev/react-ui";export default function Page() {return (- <div className="h-screen w-full flex">- <main className="flex-1 p-8">- <h1 className="text-2xl font-bold">My App</h1>- </main>-- {/* The Chat Sidebar */}- <Copilot apiUrl="/api/chat" agentName="Assistant" />+ <div className="h-screen">+ <FullScreen apiUrl="/api/chat" agentName="Assistant" /></div>);}```-### 4. Create an LLM endpoint--```ts-// app/api/chat/route.ts--import { NextRequest } from "next/server";-import OpenAI from "openai";--const client = new OpenAI({- apiKey: process.env.OPENAI_API_KEY,-});--export async function POST(req: NextRequest) {- try {- const { messages, systemPrompt } = await req.json();-- const chatMessages: OpenAI.ChatCompletionMessageParam[] = [- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),- ...messages,- ];-- const response = await client.chat.completions.create({- model: "gpt-5.2",- messages: chatMessages,- stream: true,- });-- return new Response(response.toReadableStream(), {- headers: {- "Content-Type": "text/event-stream",- "Cache-Control": "no-cache, no-transform",- Connection: "keep-alive",- },- });- } catch (err) {- console.error(err);- const message = err instanceof Error ? err.message : "Unknown error";- return new Response(JSON.stringify({ error: message }), {- status: 500,- headers: { "Content-Type": "application/json" },- });- }-}-```+At this stage, the page should render the layout shell. It will not send working chat requests until you add a backend.-### Next Steps+{/* add visual: image showing the expected baseline render after styles are imported and a built-in layout is mounted */}-Now that you have the library installed, choose a layout or configure your backend.+## Related guides<Cards>- <Card title="Explore Layouts" href="/docs/chat/copilot">- See the Copilot, FullScreen, and BottomTray components.+ <Card title="End-to-End Guide" href="/docs/chat/from-scratch">+ Add the backend route, message conversion, stream adapter, and optional persistence.</Card>-- <Card title="Connect Backend" href="/docs/chat/connecting">- Set up the API route to handle streaming responses.+ <Card title="Explore Layouts" href="/docs/chat/fullscreen">+ Compare the built-in layouts and choose the one you want to ship.+ </Card>+ <Card title="Quick Start" href="/docs/chat/quick-start">+ Prefer a generated app instead of wiring everything manually.</Card></Cards>diff --git a/docs/content/docs/chat/integrations/langgraph.mdx b/docs/content/docs/chat/integrations/langgraph.mdxdeleted file mode 100644index df9b5b8e6..000000000--- a/docs/content/docs/chat/integrations/langgraph.mdx+++ /dev/null@@ -1,6 +0,0 @@-----title: LangGraph-description: Connect OpenUI to a LangGraph agent backend.------Coming soon.diff --git a/docs/content/docs/chat/integrations/meta.json b/docs/content/docs/chat/integrations/meta.jsondeleted file mode 100644index 7407da849..000000000--- a/docs/content/docs/chat/integrations/meta.json+++ /dev/null@@ -1,4 +0,0 @@-{- "title": "Integrations",- "pages": ["openai-chat-completions", "openai-responses", "langgraph", "vercel-ai-sdk"]-}diff --git a/docs/content/docs/chat/integrations/openai-chat-completions.mdx b/docs/content/docs/chat/integrations/openai-chat-completions.mdxdeleted file mode 100644index 9fb666266..000000000--- a/docs/content/docs/chat/integrations/openai-chat-completions.mdx+++ /dev/null@@ -1,166 +0,0 @@-----title: OpenAI Chat Completions-description: Connect OpenUI to a backend using OpenAI's chat completions streaming format.------Use `openAIAdapter` when your backend streams responses using `openai.chat.completions.create({ stream: true })`.--If your backend also stores and loads messages in OpenAI's `{ role, content }` format, add `openAIMessageFormat` as well.--### Stream only--If you only need to parse the streaming response (messages are stored in OpenUI's default format):--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray', 'ChatProvider']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { openAIAdapter } from "@openuidev/react-headless";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { openAIAdapter } from "@openuidev/react-headless";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { openAIAdapter } from "@openuidev/react-headless";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="ChatProvider">- ```tsx- import { ChatProvider, openAIAdapter } from "@openuidev/react-headless";-- function App() {- return (- <ChatProvider- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- >- {/* Your custom UI */}- </ChatProvider>- );- }- ```-- </Tab>-</Tabs>--### With OpenAI message format--If your backend also stores messages in OpenAI's `{ role, content }` format and your thread endpoints return them in that shape:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray', 'ChatProvider']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="ChatProvider">- ```tsx- import { ChatProvider, openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <ChatProvider- apiUrl="/api/chat"- streamProtocol={openAIAdapter()}- messageFormat={openAIMessageFormat}- >- {/* Your custom UI */}- </ChatProvider>- );- }- ```-- </Tab>-</Tabs>--**`openAIAdapter()`** parses the streaming response from OpenAI's chat completions API. The stream consists of newline-delimited JSON chunks, each containing a `delta` with the next piece of content. The adapter reads these chunks and converts them into OpenUI's internal stream events.--**`openAIMessageFormat`** is only needed if your backend stores and loads messages in OpenAI's `{ role, content }` format. It converts between this format and OpenUI's internal format when sending chat requests and loading saved threads.diff --git a/docs/content/docs/chat/integrations/openai-responses.mdx b/docs/content/docs/chat/integrations/openai-responses.mdxdeleted file mode 100644index 053c2fa64..000000000--- a/docs/content/docs/chat/integrations/openai-responses.mdx+++ /dev/null@@ -1,166 +0,0 @@-----title: OpenAI Responses API-description: Connect OpenUI to a backend using OpenAI's Responses API streaming format.------Use `openAIResponsesAdapter` when your backend streams responses using `openai.responses.create()`.--If your backend also stores and loads messages in the Responses API's conversation items format, add `openAIConversationMessageFormat` as well.--### Stream only--If you only need to parse the streaming response (messages are stored in OpenUI's default format):--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray', 'ChatProvider']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { openAIResponsesAdapter } from "@openuidev/react-headless";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { openAIResponsesAdapter } from "@openuidev/react-headless";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { openAIResponsesAdapter } from "@openuidev/react-headless";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="ChatProvider">- ```tsx- import { ChatProvider, openAIResponsesAdapter } from "@openuidev/react-headless";-- function App() {- return (- <ChatProvider- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- >- {/* Your custom UI */}- </ChatProvider>- );- }- ```-- </Tab>-</Tabs>--### With conversation message format--If your backend also stores messages in the Responses API's items list format and your thread endpoints return them in that shape:--<Tabs groupId="layout" items={['Copilot', 'FullScreen', 'BottomTray', 'ChatProvider']} persist>- <Tab value="Copilot">- ```tsx- import { Copilot } from "@openuidev/react-ui";- import { openAIResponsesAdapter, openAIConversationMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <Copilot- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- messageFormat={openAIConversationMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="FullScreen">- ```tsx- import { FullScreen } from "@openuidev/react-ui";- import { openAIResponsesAdapter, openAIConversationMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <FullScreen- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- messageFormat={openAIConversationMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="BottomTray">- ```tsx- import { BottomTray } from "@openuidev/react-ui";- import { openAIResponsesAdapter, openAIConversationMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <BottomTray- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- messageFormat={openAIConversationMessageFormat}- agentName="My Agent"- />- );- }- ```-- </Tab>- <Tab value="ChatProvider">- ```tsx- import { ChatProvider, openAIResponsesAdapter, openAIConversationMessageFormat } from "@openuidev/react-headless";-- function App() {- return (- <ChatProvider- apiUrl="/api/chat"- streamProtocol={openAIResponsesAdapter()}- messageFormat={openAIConversationMessageFormat}- >- {/* Your custom UI */}- </ChatProvider>- );- }- ```-- </Tab>-</Tabs>--**`openAIResponsesAdapter()`** parses the streaming response from OpenAI's Responses API. This API uses a different event format than chat completions — it streams server-sent events with types like `response.output_item.added` and `response.content_part.delta`. The adapter handles all of these and converts them into OpenUI's internal stream events.--**`openAIConversationMessageFormat`** is only needed if your backend stores and loads messages in the Responses API's items list format (`{ type: "message", role, content: [{ type: "input_text", text }] }`). It converts between this format and OpenUI's internal format when sending chat requests and loading saved threads.diff --git a/docs/content/docs/chat/integrations/vercel-ai-sdk.mdx b/docs/content/docs/chat/integrations/vercel-ai-sdk.mdxdeleted file mode 100644index 4dae8c307..000000000--- a/docs/content/docs/chat/integrations/vercel-ai-sdk.mdx+++ /dev/null@@ -1,6 +0,0 @@-----title: Vercel AI SDK-description: Use OpenUI with Vercel AI SDK on the backend.------Coming soon.diff --git a/docs/content/docs/chat/meta.json b/docs/content/docs/chat/meta.jsonindex 5e169b69e..ff4a9110d 100644--- a/docs/content/docs/chat/meta.json+++ b/docs/content/docs/chat/meta.json@@ -7,6 +7,7 @@"quick-start","installation","genui",+ "from-scratch","---Chat Layouts---","copilot","fullscreen",diff --git a/docs/content/docs/chat/nextjs.mdx b/docs/content/docs/chat/nextjs.mdxindex 663035c31..23b35d1ac 100644--- a/docs/content/docs/chat/nextjs.mdx+++ b/docs/content/docs/chat/nextjs.mdx@@ -3,45 +3,99 @@ title: Next.js Implementationdescription: Build a Route Handler for streaming chat responses.----Create a Route Handler at `app/api/chat/route.ts` and stream model output back to the client.+This page covers the Route Handler pattern and matching frontend configuration for a Next.js App Router setup.++If you want the full install-and-render walkthrough, use the [End-to-End Guide](/docs/chat/from-scratch) instead.++This page focuses on one specific backend pattern:++- `processMessage` on the frontend so you can add `systemPrompt`+- `openAIMessageFormat` to send OpenAI chat messages+- `openAIReadableStreamAdapter()` because `response.toReadableStream()` emits NDJSON, not raw SSE++## Route handler++Create `app/api/chat/route.ts`:```ts+import { NextRequest } from "next/server";import OpenAI from "openai";-const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });--export async function POST(req: Request) {- const { messages } = await req.json();-- const stream = await openai.chat.completions.create({- model: "gpt-4o",- messages,- stream: true,- });-- const encoder = new TextEncoder();- const readable = new ReadableStream({- async start(controller) {- for await (const chunk of stream) {- controller.enqueue(encoder.encode(JSON.stringify(chunk) + "\n"));- }- controller.close();- },- });-- return new Response(readable, {- headers: { "Content-Type": "text/event-stream" },- });+const client = new OpenAI();++export async function POST(req: NextRequest) {+ try {+ const { messages, systemPrompt } = await req.json();++ const chatMessages: OpenAI.ChatCompletionMessageParam[] = [+ ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),+ ...messages,+ ];++ const response = await client.chat.completions.create({+ model: "gpt-5.2",+ messages: chatMessages,+ stream: true,+ });++ return new Response(response.toReadableStream(), {+ headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+ },+ });+ } catch (err) {+ console.error(err);+ const message = err instanceof Error ? err.message : "Unknown error";+ return new Response(JSON.stringify({ error: message }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ });+ }}```-If you stream raw OpenAI chunks, configure frontend adapters:+This route expects `messages` to already be in OpenAI chat format and optionally prepends a `systemPrompt`.++## Matching frontend configuration++Because `toReadableStream()` produces newline-delimited JSON, pair it with `openAIReadableStreamAdapter()` on the frontend.++Use `processMessage` here because the client needs to send both `messages` and `systemPrompt` explicitly. `messageFormat={openAIMessageFormat}` handles the message conversion before the request is sent.```tsx-import { Copilot } from "@openuidev/react-ui";-import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";+import { defaultLibrary, defaultPromptOptions } from "@openuidev/react-ui/genui-lib";-<Copilot apiUrl="/api/chat" streamProtocol={openAIAdapter()} messageFormat={openAIMessageFormat} />;+const systemPrompt = defaultLibrary.prompt(defaultPromptOptions);++<FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ systemPrompt,+ }),+ signal: abortController.signal,+ });+ }}+ messageFormat={openAIMessageFormat}+ streamProtocol={openAIReadableStreamAdapter()}+ componentLibrary={defaultLibrary}+ agentName="Assistant"+/>;```-For provider-specific options, see [Providers](/docs/chat/providers).+Use `openAIAdapter()` only if your backend emits raw SSE chunks instead of the OpenAI SDK readable stream.++{/* add visual: flow-chart showing request from FullScreen -> /api/chat route -> OpenAI chat completions -> toReadableStream() -> openAIReadableStreamAdapter() -> rendered assistant message */}++## Related guides++- [Connecting to LLM](/docs/chat/connecting)+- [Providers](/docs/chat/providers)+- [End-to-End Guide](/docs/chat/from-scratch)diff --git a/docs/content/docs/chat/persistence.mdx b/docs/content/docs/chat/persistence.mdxindex 1048f228b..03e36ab0e 100644--- a/docs/content/docs/chat/persistence.mdx+++ b/docs/content/docs/chat/persistence.mdx@@ -1,36 +1,111 @@----title: Persistence (Threads)-description: Configure threadApiUrl and load/save chat history.+title: Connect Thread History+description: Configure threadApiUrl and load thread lists and message history.----To persist conversations, pass `threadApiUrl` or provide custom thread functions.+This page explains how to connect thread lists and previous messages from a backend.-### REST-style setup+To connect thread history, either:++- pass `threadApiUrl` and implement the default endpoint contract used by OpenUI+- provide custom thread functions if your API shape is different++This config only affects thread history. Your live chat request still comes from `apiUrl` or `processMessage`.++## Default `threadApiUrl` contract++When you pass `threadApiUrl="/api/threads"`, OpenUI appends its own path segments. The default requests look like this:++| Action | Method | URL | Request body | Expected response |+| :--- | :--- | :--- | :--- | :--- |+| List threads | `GET` | `/api/threads/get` | — | `{ threads: Thread[], nextCursor?: any }` |+| Create thread | `POST` | `/api/threads/create` | `{ messages }` | `Thread` |+| Update thread | `PATCH` | `/api/threads/update/:id` | `Thread` | `Thread` |+| Delete thread | `DELETE` | `/api/threads/delete/:id` | — | empty response is fine |+| Load messages | `GET` | `/api/threads/get/:id` | — | message array in your backend format |++```tsx+import { FullScreen } from "@openuidev/react-ui";++<FullScreen apiUrl="/api/chat" threadApiUrl="/api/threads" agentName="Assistant" />;+```++`createThread` sends the first user message as `messages`, already converted through your current `messageFormat`. `loadThread` expects the response body to be something `messageFormat.fromApi()` can read.++## When to add `messageFormat`++If your thread API stores messages in OpenUI's default shape, you do not need any extra config.++If your thread API stores messages in OpenAI chat format, add `messageFormat={openAIMessageFormat}` so both chat requests and thread loading stay aligned.++In other words:++- `apiUrl` or `processMessage` handles sending new chat requests+- `threadApiUrl` handles listing threads and loading saved messages+- `messageFormat` keeps both paths aligned when your backend does not use the default AG-UI message shape```tsx+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";import { FullScreen } from "@openuidev/react-ui";-<FullScreen apiUrl="/api/chat" threadApiUrl="/api/threads" />;+<FullScreen+ apiUrl="/api/chat"+ threadApiUrl="/api/threads"+ streamProtocol={openAIReadableStreamAdapter()}+ messageFormat={openAIMessageFormat}+ agentName="Assistant"+/>;```-Expected endpoints under `/api/threads`:+## Use custom thread functions when your API differs++If your backend already uses a different shape, such as:++- REST routes like `/api/threads/:id/messages`+- GraphQL+- auth-protected endpoints with custom headers+- a different request body for creating threads-| Action | Method | URL |-| :------------ | :------- | :-------------------------- |-| List threads | `GET` | `/api/threads` |-| Create thread | `POST` | `/api/threads` |-| Update thread | `PUT` | `/api/threads/:id` |-| Delete thread | `DELETE` | `/api/threads/:id` |-| Load messages | `GET` | `/api/threads/:id/messages` |+then provide the individual thread functions instead of relying on the default `threadApiUrl` behavior.-### Custom functions+```tsx+<FullScreen+ apiUrl="/api/chat"+ fetchThreadList={async (cursor) => {+ const res = await fetch(`/api/conversations?cursor=${cursor ?? ""}`);+ return res.json();+ }}+ createThread={async (firstMessage) => {+ const res = await fetch("/api/conversations", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ firstMessage }),+ });+ return res.json();+ }}+ updateThread={async (thread) => {+ const res = await fetch(`/api/conversations/${thread.id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(thread),+ });+ return res.json();+ }}+ deleteThread={async (id) => {+ await fetch(`/api/conversations/${id}`, { method: "DELETE" });+ }}+ loadThread={async (threadId) => {+ const res = await fetch(`/api/conversations/${threadId}/messages`);+ return res.json();+ }}+ agentName="Assistant"+/>;+```-If your API is non-REST or needs custom auth, pass:+{/* add visual: flow-chart showing how threadApiUrl maps to list, create, update, delete, and load requests, and where messageFormat affects create/load payloads */}-- `fetchThreadList`-- `createThread`-- `updateThread`-- `deleteThread`-- `loadThread`+## Related guides-For the full payload spec, see [The API Contract](/docs/chat/api-contract).+- [The API Contract](/docs/chat/api-contract)+- [Connecting to LLM](/docs/chat/connecting)+- [End-to-End Guide](/docs/chat/from-scratch)diff --git a/docs/content/docs/chat/providers.mdx b/docs/content/docs/chat/providers.mdxindex eb4d748cc..07d17164b 100644--- a/docs/content/docs/chat/providers.mdx+++ b/docs/content/docs/chat/providers.mdx@@ -3,24 +3,99 @@ title: Providersdescription: Provider-specific setup for OpenAI, Vercel AI SDK, and LangGraph.----Use these adapters and message converters based on your backend provider.+Choose config based on the stream format and message shape your backend emits, not just the provider name.++This page maps common provider and backend patterns to the matching `streamProtocol` and `messageFormat` configuration.++For the core connection concepts, see [Connecting to LLM](/docs/chat/connecting).++## Common mappings++| Backend pattern | `streamProtocol` | `messageFormat` | Use this when... |+| :--- | :--- | :--- | :--- |+| OpenUI Protocol | none | none | Your backend already emits the default OpenUI stream and accepts OpenUI messages |+| Raw OpenAI Chat Completions SSE | `openAIAdapter()` | `openAIMessageFormat` when needed | You forward raw `data:` SSE chunks from Chat Completions |+| OpenAI SDK `toReadableStream()` / NDJSON | `openAIReadableStreamAdapter()` | `openAIMessageFormat` when needed | You return `response.toReadableStream()` from the OpenAI SDK |+| OpenAI Responses API | `openAIResponsesAdapter()` | `openAIConversationMessageFormat` when needed | Your backend uses `openai.responses.create()` |++Start with the backend output format. Then add `messageFormat` only if the request or stored-history message shape also differs from the OpenUI default.## OpenAI Chat Completions-- Stream adapter: `openAIAdapter()`-- Message converter (optional): `openAIMessageFormat`+There are two common OpenAI Chat Completions patterns.++### Raw SSE++Use `openAIAdapter()` if your server forwards raw Chat Completions SSE events.++```tsx+import { openAIAdapter, openAIMessageFormat } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";++<FullScreen+ apiUrl="/api/chat"+ streamProtocol={openAIAdapter()}+ messageFormat={openAIMessageFormat}+ agentName="Assistant"+/>;+```++### OpenAI SDK `toReadableStream()`++Use `openAIReadableStreamAdapter()` if your route returns `response.toReadableStream()`.++```tsx+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";++<FullScreen+ apiUrl="/api/chat"+ streamProtocol={openAIReadableStreamAdapter()}+ messageFormat={openAIMessageFormat}+ agentName="Assistant"+/>;+```## OpenAI Responses API-- Stream adapter: `openAIResponsesAdapter()`-- Message converter (optional): `openAIConversationMessageFormat`+Use `openAIResponsesAdapter()` for the Responses API event stream.++Add `openAIConversationMessageFormat` only if your backend also expects or stores Responses conversation items instead of the default AG-UI message shape.++```tsx+import {+ openAIConversationMessageFormat,+ openAIResponsesAdapter,+} from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";++<FullScreen+ apiUrl="/api/chat"+ streamProtocol={openAIResponsesAdapter()}+ messageFormat={openAIConversationMessageFormat}+ agentName="Assistant"+/>;+```## Vercel AI SDK-Use your Vercel AI SDK backend route as `apiUrl`, then set `streamProtocol` only if your stream shape differs from OpenUI defaults.+Ignore the SDK name at first and inspect what your route actually returns.++- If the route already speaks the OpenUI Protocol, `apiUrl` is usually enough.+- If it returns a different stream format, keep `apiUrl` or switch to `processMessage`, then add the matching `streamProtocol`.+- If the route expects a custom request body, use `processMessage`.## LangGraph-Use your LangGraph endpoint as `apiUrl`. Provide `processMessage` if you need custom auth, routing, or payload transformation.+Use the same decision rules:++- start with `apiUrl` when the endpoint already matches the request and stream shape your frontend expects+- switch to `processMessage` when you need auth headers, a custom body, dynamic routing, or provider-specific metadata++{/* add visual: flow-chart showing provider choice splitting first by emitted stream format, then by whether messageFormat is needed */}++## Related guides-<Callout type="info">Detailed provider walkthroughs are being consolidated into this page.</Callout>+- [Connecting to LLM](/docs/chat/connecting)+- [Next.js Implementation](/docs/chat/nextjs)+- [The API Contract](/docs/chat/api-contract)diff --git a/docs/content/docs/chat/quick-start.mdx b/docs/content/docs/chat/quick-start.mdxindex 6a6874f09..60bf0f3f2 100644--- a/docs/content/docs/chat/quick-start.mdx+++ b/docs/content/docs/chat/quick-start.mdx@@ -3,15 +3,39 @@ title: Quick Startdescription: Get a working chat UI running in under 5 minutes.----## 1. Create your app+This page shows the scaffolded setup for getting a working chat app running quickly.++If you already have an existing Next.js app, use [Installation](/docs/chat/installation) or the [End-to-End Guide](/docs/chat/from-scratch) instead.-Run the create command. This sets up a Next.js app with **OpenUI Chat** and the **Standard Component Library** pre-configured.+## 1. Create your app-<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>- <Tab value="npx">```bash npx create-openui-chat my-chat-app cd my-chat-app ```</Tab>- <Tab value="pnpm">```bash pnpm create openui-chat my-chat-app cd my-chat-app ```</Tab>- <Tab value="yarn">```bash yarn create openui-chat my-chat-app cd my-chat-app ```</Tab>- <Tab value="bun">```bash bun create openui-chat my-chat-app cd my-chat-app ```</Tab>+Run the create command. This scaffolds a Next.js app with OpenUI Chat already wired to an OpenAI-backed route.++<Tabs groupId="pkg" items={['npx', 'pnpm', 'yarn', 'bun']} persist>+ <Tab value="npx">+ ```bash+ npx create-openui-chat my-chat-app+ cd my-chat-app+ ```+ </Tab>+ <Tab value="pnpm">+ ```bash+ pnpm create openui-chat my-chat-app+ cd my-chat-app+ ```+ </Tab>+ <Tab value="yarn">+ ```bash+ yarn create openui-chat my-chat-app+ cd my-chat-app+ ```+ </Tab>+ <Tab value="bun">+ ```bash+ bun create openui-chat my-chat-app+ cd my-chat-app+ ```+ </Tab></Tabs>## 2. Add your API key@@ -24,35 +48,70 @@ OPENAI_API_KEY=sk-your-key-here## 3. Start the dev server-<Tabs groupId="pkg" items={["npx", "pnpm", "yarn", "bun"]} persist>- <Tab value="npx">```bash npm run dev ```</Tab>- <Tab value="pnpm">```bash pnpm dev ```</Tab>- <Tab value="yarn">```bash yarn dev ```</Tab>- <Tab value="bun">```bash bun dev ```</Tab>+<Tabs groupId="pkg" items={['npx', 'pnpm', 'yarn', 'bun']} persist>+ <Tab value="npx">+ ```bash+ npm run dev+ ```+ </Tab>+ <Tab value="pnpm">+ ```bash+ pnpm dev+ ```+ </Tab>+ <Tab value="yarn">+ ```bash+ yarn dev+ ```+ </Tab>+ <Tab value="bun">+ ```bash+ bun dev+ ```+ </Tab></Tabs>-Open [http://localhost:3000](http://localhost:3000) in your browser. You should see the **Copilot** interface. Try sending a message!+Open [http://localhost:3000](http://localhost:3000) in your browser. You should see the default **FullScreen** chat. Try sending a message.----+You should see a full-page chat experience with streaming responses enabled.++{/* add visual: gif showing the generated app launching, sending a message, and streaming a response in the default scaffold */}## What you just built-The scaffold generated two key files that power the chat experience:+The scaffold generates both the frontend and backend for you.++You do not need to recreate these files during quick start. This section is here so you know what the scaffold already configured.### The Frontend (`app/page.tsx`)-It renders the `<Copilot />` component. This is a "batteries-included" sidebar that handles message history, loading states, and UI rendering.+The frontend renders `FullScreen`, sends requests with `processMessage`, relies on `messageFormat` for OpenAI message conversion, and parses the OpenAI SDK readable stream correctly.```tsx-import { Copilot } from "@openuidev/react-ui";-import { standardLibrary } from "@openuidev/react-ui";+import { openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-headless";+import { FullScreen } from "@openuidev/react-ui";+import { defaultLibrary, defaultPromptOptions } from "@openuidev/react-ui/genui-lib";++const systemPrompt = defaultLibrary.prompt(defaultPromptOptions);export default function Page() {return (- <Copilot- apiUrl="/api/chat"- agentName="Assistant"- componentLibrary={standardLibrary} // Enables Generative UI+ <FullScreen+ processMessage={async ({ messages, abortController }) => {+ return fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages,+ systemPrompt,+ }),+ signal: abortController.signal,+ });+ }}+ messageFormat={openAIMessageFormat}+ streamProtocol={openAIReadableStreamAdapter()}+ componentLibrary={defaultLibrary}+ agentName="OpenUI Chat"/>);}@@ -60,20 +119,34 @@ export default function Page() {### The Backend (`app/api/chat/route.ts`)-A Next.js Route Handler that receives messages and streams the response. It automatically injects the **System Prompt** from the standard library so the LLM knows how to render UI components.+The scaffold also creates a Next.js route handler at `app/api/chat/route.ts`.++That route:++- receives OpenAI-format messages+- optionally prepends `systemPrompt`+- calls OpenAI Chat Completions with streaming enabled+- returns `response.toReadableStream()`++That is why the frontend uses:++- `processMessage` instead of a plain `apiUrl`+- `messageFormat={openAIMessageFormat}` for request conversion+- `openAIReadableStreamAdapter()` for stream parsing+- `defaultLibrary` plus `systemPrompt` for GenUI rendering## Next steps-Now that the app is running, make it yours.+Now that the app is running, choose the next path based on what you want to change.<Cards>- <Card title="Explore Layouts" href="/docs/chat/copilot">- Swap the Copilot for a FullScreen page or BottomTray widget.+ <Card title="End-to-End Guide" href="/docs/chat/from-scratch">+ Recreate the same flow in your own existing app.</Card>- <Card title="Connect Backend" href="/docs/chat/connecting">- Learn how to configure the `apiUrl` and authentication headers.+ <Card title="Understand GenUI" href="/docs/chat/genui">+ Learn how the component library and system prompt work together.</Card><Card title="Go Headless" href="/docs/chat/headless-intro">- Want to build your own UI? Learn about the `ChatProvider`.+ Build your own UI with `ChatProvider` and hooks.</Card></Cards>diff --git a/docs/content/docs/chat/theming.mdx b/docs/content/docs/chat/theming.mdxindex 33b828951..59b35ea52 100644--- a/docs/content/docs/chat/theming.mdx+++ b/docs/content/docs/chat/theming.mdx@@ -3,4 +3,69 @@ title: Themingdescription: Customize colors, typography, and branding for Chat components.----Coming soon.+Built-in chat layouts mount their own `ThemeProvider` by default. Use the `theme` prop to control mode and token overrides, or disable the built-in provider if your app already wraps the UI in its own theme scope.++There are two common theming paths:++- set `theme.mode` when you only need light or dark mode+- pass `lightTheme` and `darkTheme` when you need token-level visual customization++## Set the mode++```tsx+import { FullScreen } from "@openuidev/react-ui";++<FullScreen+ apiUrl="/api/chat"+ theme={{ mode: "dark" }}+ agentName="Assistant"+/>;+```++## Override theme tokens++Use `lightTheme` and `darkTheme` inside the `theme` prop to override the built-in token sets.++```tsx+import { FullScreen, createTheme } from "@openuidev/react-ui";++<FullScreen+ apiUrl="/api/chat"+ theme={{+ mode: "dark",+ lightTheme: createTheme({+ interactiveAccentDefault: "oklch(0.62 0.22 260)",+ }),+ darkTheme: createTheme({+ interactiveAccentDefault: "oklch(0.72 0.18 260)",+ }),+ }}+ agentName="Assistant"+/>;+```++If you only pass `lightTheme`, those overrides are also used as the fallback for dark mode.++## Use your own app-level theme provider++If your app already wraps the page in `ThemeProvider`, disable the built-in wrapper on the chat layout.++```tsx+import { FullScreen } from "@openuidev/react-ui";++<FullScreen+ apiUrl="/api/chat"+ disableThemeProvider+ agentName="Assistant"+/>;+```++`disableThemeProvider` only skips the wrapper. It does not remove any chat functionality.++{/* add visual: image showing the default chat theme beside a custom dark theme override */}++## Related guides++- [FullScreen](/docs/chat/fullscreen)+- [Copilot](/docs/chat/copilot)+- [BottomTray](/docs/chat/bottom-tray)diff --git a/docs/content/docs/chat/welcome.mdx b/docs/content/docs/chat/welcome.mdxindex b457a574d..8e765ca8d 100644--- a/docs/content/docs/chat/welcome.mdx+++ b/docs/content/docs/chat/welcome.mdx@@ -3,11 +3,15 @@ title: Welcome & Startersdescription: Configure the empty-state welcome message and conversation starters.----When there are no messages yet, OpenUI Chat shows a welcome state. You can customize it with:+When there are no messages yet, OpenUI Chat shows a welcome state. The same props work across the built-in layouts, including `Copilot`, `FullScreen`, and `BottomTray`.++You can customize that empty state with:- `welcomeMessage`- `conversationStarters`+## Basic welcome state+```tsximport { Copilot } from "@openuidev/react-ui";@@ -27,3 +31,52 @@ import { Copilot } from "@openuidev/react-ui";````displayText` is what users click. `prompt` is what gets sent to the model.++## Custom welcome component++If you want full control over the empty state, pass a React component instead of a config object.++```tsx+function CustomWelcome() {+ return (+ <div>+ <h2>Welcome back</h2>+ <p>Ask about orders, billing, or product recommendations.</p>+ </div>+ );+}++<Copilot apiUrl="/api/chat" welcomeMessage={CustomWelcome} agentName="Assistant" />;+```++## Conversation starter variants++Use `variant="short"` for compact pill buttons or `variant="long"` for more descriptive list-style starters.++```tsx+<Copilot+ apiUrl="/api/chat"+ conversationStarters={{+ variant: "long",+ options: [+ {+ displayText: "Track my order",+ prompt: "Where is my latest order?",+ },+ {+ displayText: "Return an item",+ prompt: "How do I return a product?",+ },+ ],+ }}+ agentName="Assistant"+/>;+```++{/* add visual: image showing the empty state with a welcome message and both short and long conversation starter variants */}++## Related guides++- [Copilot](/docs/chat/copilot)+- [FullScreen](/docs/chat/fullscreen)+- [BottomTray](/docs/chat/bottom-tray)