|
| 1 | +# AGENTS.md (TDesign ChatEngine) |
| 2 | + |
| 3 | +> **SYSTEM PROMPT / INSTRUCTIONS** |
| 4 | +> This file contains the foundational rules, architectural context, and coding standards for the TDesign ChatEngine SDK. |
| 5 | +> As an AI Agent (Cursor, Copilot, Windsurf), you MUST read and follow these instructions before generating any code using this SDK. |
| 6 | +
|
| 7 | +## 1. Project Context & Identity |
| 8 | +- **Name**: TDesign ChatEngine (React) |
| 9 | +- **Type**: React Component Library / Headless SDK |
| 10 | +- **Goal**: Provide a complete, production-ready solution for building AI chat applications, supporting standard protocols (AG-UI) and Generative UI. |
| 11 | +- **Package**: `@tdesign-react/chat` |
| 12 | +- **Key Features**: |
| 13 | + - Headless `ChatEngine` for logic reuse. |
| 14 | + - `ChatBot` component for out-of-the-box usage. |
| 15 | + - Native support for **AG-UI Protocol** (Agent-User Interaction). |
| 16 | + - **Generative UI** engine (json-render & A2UI support). |
| 17 | + |
| 18 | +## 2. Core Concepts |
| 19 | + |
| 20 | +### 2.1 ChatEngine (Headless Core) |
| 21 | +The `ChatEngine` is the logic core that handles: |
| 22 | +- **Message Management**: Send, receive, update, delete, and history management. |
| 23 | +- **Stream Processing**: Built-in SSE (Server-Sent Events) and fetch stream handling. |
| 24 | +- **Protocol Adaptation**: Adapts backend data to frontend message formats (AG-UI or Custom). |
| 25 | +- **Event Bus**: Pub/Sub system for cross-component communication and side effects. |
| 26 | + |
| 27 | +### 2.2 ChatBot (UI Component) |
| 28 | +`ChatBot` is a high-level component built on top of `ChatEngine` that provides: |
| 29 | +- **Complete UI**: Message list, input area, action bar, and auto-scroll. |
| 30 | +- **Built-in Rendering**: Markdown (Cherry Markdown), Thinking process, Tool calls, Suggestions. |
| 31 | +- **Slot Customization**: `headerSlot`, `messageSlot`, `senderSlot`, `footerSlot`. |
| 32 | + |
| 33 | +### 2.3 AG-UI Protocol |
| 34 | +A standard protocol for AI Agent interaction. |
| 35 | +- **Events**: |
| 36 | + - `TEXT_MESSAGE_*`: Streaming text responses. |
| 37 | + - `THINKING_*`: AI thought process visibility. |
| 38 | + - `TOOL_CALL_*`: Agent tool usage (Start -> Args -> End -> Result). |
| 39 | + - `ACTIVITY_*`: Dynamic content (Charts, Forms) via Snapshots & Deltas. |
| 40 | + - `STATE_*`: Shared agent state synchronization. |
| 41 | +- **Flow**: Stream-based, event-driven architecture. |
| 42 | + |
| 43 | +### 2.4 Generative UI |
| 44 | +Dynamic UI generation based on AI output, adopting the **json-render** (Vercel Labs) philosophy with a dual-layer architecture: |
| 45 | +- **Catalog (Constraint Layer)**: Defines what components AI can use (Zod Schema). |
| 46 | +- **Registry (Render Layer)**: Defines how components are rendered (React implementation). |
| 47 | +- **Protocols**: |
| 48 | + - `json-render`: Native adjacency-list schema (flat structure), details [here](https://json-render.dev/docs). |
| 49 | + - `A2UI`: Google's adjacency-list schema (supported via built-in adapter),details [here](https://a2ui.org/specification/v0.9-a2ui/). |
| 50 | + |
| 51 | +> **Note**: The ChatEngine Generative UI engine is optimized for and exclusively supports these flat adjacency-list schemas for efficient streaming and updates. |
| 52 | +
|
| 53 | +## 3. Key APIs & Hooks |
| 54 | + |
| 55 | +### 3.1 `useChat` |
| 56 | +The main hook for initializing and managing chat state. |
| 57 | + |
| 58 | +```typescript |
| 59 | +const { chatEngine, messages, status } = useChat({ |
| 60 | + chatServiceConfig: { |
| 61 | + endpoint: '/api/chat', |
| 62 | + protocol: 'agui', // Recommended: 'agui' for standard agents |
| 63 | + stream: true, |
| 64 | + // Optional: Custom headers or body |
| 65 | + onRequest: (params) => ({ ...params, headers: { Authorization: '...' } }) |
| 66 | + }, |
| 67 | + defaultMessages: [] // Optional initial messages |
| 68 | +}); |
| 69 | +``` |
| 70 | + |
| 71 | +### 3.2 `useAgentToolcall` |
| 72 | +Registers custom UI components for AI tool calls. |
| 73 | + |
| 74 | +```typescript |
| 75 | +useAgentToolcall({ |
| 76 | + name: 'weather_query', // Must match backend tool name |
| 77 | + component: WeatherCard, // React Component receiving { args, result, status } |
| 78 | + // Optional: Subscribe to specific state keys during execution |
| 79 | + subscribeKey: (props) => props.args?.taskId |
| 80 | +}); |
| 81 | +``` |
| 82 | + |
| 83 | +### 3.3 `useAgentActivity` |
| 84 | +Registers components for dynamic content (Generative UI). |
| 85 | + |
| 86 | +```typescript |
| 87 | +useAgentActivity({ |
| 88 | + activityType: 'stock-chart', // Must match backend activity type |
| 89 | + component: StockChart // React Component receiving { content } |
| 90 | +}); |
| 91 | +``` |
| 92 | + |
| 93 | +### 3.4 `useAgentState` |
| 94 | +Subscribes to shared agent state (AG-UI `STATE_*` events). |
| 95 | + |
| 96 | +```typescript |
| 97 | +const { stateMap, currentStateKey } = useAgentState(); |
| 98 | +// Access state: stateMap['task_1'] |
| 99 | +``` |
| 100 | + |
| 101 | +### 3.5 Generative UI Helpers |
| 102 | +- `generateCatalogPrompt`: Generates system prompt for LLM. |
| 103 | +- `createCustomRegistry`: Creates component registry. |
| 104 | +- `createJsonRenderActivityConfig`: Configures json-render activity. |
| 105 | + |
| 106 | +## 4. Coding Standards & Best Practices |
| 107 | + |
| 108 | +- **Prefer Hooks**: Use `useChat`, `useAgentToolcall`, etc., over direct class instantiation when in React components. |
| 109 | +- **Protocol First**: Prefer `protocol: 'agui'` for standard AI agent integration. It handles streaming, tool calls, and state automatically. |
| 110 | +- **Generative UI Safety**: Always use `Catalog` to constrain AI output. Never allow AI to generate arbitrary HTML/JS. |
| 111 | +- **State Management**: Use `useAgentState` for cross-component state sharing instead of prop drilling or external stores when dealing with Agent state. |
| 112 | +- **Customization**: |
| 113 | + - Use `ChatBot` slots (`messageSlot`, `headerSlot`) for minor tweaks. |
| 114 | + - Use `useChat` + atomic components (`ChatList`, `ChatSender`) for full custom layouts. |
| 115 | + |
| 116 | +## 5. Anti-Patterns (What NOT to do) |
| 117 | + |
| 118 | +- ❌ **Do not** manually parse SSE streams if using `protocol: 'agui'`. The SDK handles this. |
| 119 | +- ❌ **Do not** modify `messages` state directly; use `chatEngine` methods (`sendUserMessage`, `setMessages`). |
| 120 | +- ❌ **Do not** use `dangerouslySetInnerHTML` for AI content; use built-in Markdown or Generative UI components. |
| 121 | +- ❌ **Do not** mix `protocol: 'agui'` with custom `onMessage` parsers unless you strictly need to override specific event handling. |
| 122 | + |
| 123 | +## 6. Scenario Guide & Examples |
| 124 | + |
| 125 | +This section maps common development scenarios to specific implementation patterns and example files found in `packages/pro-components/chat/chat-engine/_example`,and you can also refer to the `packages/pro-components/chat/chat-engine.md`for more details. |
| 126 | + |
| 127 | +### 6.1 Basic Usage Scenarios |
| 128 | + |
| 129 | +#### 6.1.1 Quick Start (Basic Chat) |
| 130 | +- **Goal**: Create a simple chat interface with minimal configuration. |
| 131 | +- **Key Pattern**: `useChat` + `ChatBot` or `ChatList/ChatSender`. |
| 132 | +- **Example**: `basic.tsx` |
| 133 | +```tsx |
| 134 | +// Minimal setup |
| 135 | +const { chatEngine, messages } = useChat({ |
| 136 | + chatServiceConfig: { endpoint: '/api/chat', stream: true } |
| 137 | +}); |
| 138 | +``` |
| 139 | + |
| 140 | +#### 6.1.2 Managing History (Initial Messages) |
| 141 | +- **Goal**: Load chat history or set a welcome message. |
| 142 | +- **Key Pattern**: `defaultMessages` prop or `chatEngine.setMessages()`. |
| 143 | +- **Example**: `initial-messages.tsx` |
| 144 | +```tsx |
| 145 | +// Load history |
| 146 | +<ChatBot defaultMessages={historyMessages} /> |
| 147 | +// Or dynamic load |
| 148 | +useEffect(() => { |
| 149 | + fetchHistory().then(msgs => chatEngine.setMessages(msgs)); |
| 150 | +}, []); |
| 151 | +``` |
| 152 | + |
| 153 | +#### 6.1.3 Controlling the Engine (Instance Methods) |
| 154 | +- **Goal**: Programmatically send messages, stop generation, or clear chat. |
| 155 | +- **Key Pattern**: `chatEngine.sendUserMessage()`, `chatEngine.abort()`, `chatEngine.clearMessages()`. |
| 156 | +- **Example**: `instance-methods.tsx` |
| 157 | + |
| 158 | +#### 6.1.4 Custom UI Rendering |
| 159 | +- **Goal**: Customize message bubbles, action bars, or input areas. |
| 160 | +- **Key Pattern**: Slots (`messageSlot`, `headerSlot`) or Custom Components in `onMessage`. |
| 161 | +- **Example**: `custom-content.tsx` |
| 162 | +```tsx |
| 163 | +// Custom message rendering via slot |
| 164 | +<ChatBot |
| 165 | + messageSlot={(msg) => msg.type === 'custom' ? <MyComponent data={msg.content} /> : null} |
| 166 | +/> |
| 167 | +``` |
| 168 | + |
| 169 | +### 6.2 AG-UI Protocol Scenarios (Agent Integration) |
| 170 | + |
| 171 | +#### 6.2.1 Standard Agent Integration |
| 172 | +- **Goal**: Connect to an AG-UI compliant backend (supports streaming, tools, thinking). |
| 173 | +- **Key Pattern**: `protocol: 'agui'`. |
| 174 | +- **Example**: `agui-basic.tsx` |
| 175 | + |
| 176 | +#### 6.2.2 Tool Calling (Human-in-the-Loop) |
| 177 | +- **Goal**: Render UI for agent tool calls (e.g., weather widget, forms) and handle user interaction. |
| 178 | +- **Key Pattern**: `useAgentToolcall` + `ToolCallRenderer`. |
| 179 | +- **Example**: `agui-toolcall.tsx` |
| 180 | +```tsx |
| 181 | +useAgentToolcall({ |
| 182 | + name: 'search_flight', |
| 183 | + component: ({ args, respond }) => ( |
| 184 | + <FlightForm |
| 185 | + defaultCity={args.city} |
| 186 | + onSubmit={(data) => respond(data)} // Return user input to agent |
| 187 | + /> |
| 188 | + ) |
| 189 | +}); |
| 190 | +``` |
| 191 | + |
| 192 | +#### 6.2.3 Real-time Status Subscription |
| 193 | +- **Goal**: Display agent progress (e.g., "Scanning database...") outside the chat flow. |
| 194 | +- **Key Pattern**: `useAgentState` subscribing to `STATE_SNAPSHOT/DELTA` events. |
| 195 | +- **Example**: `agui-comprehensive.tsx` (See `GlobalProgressBar` component) |
| 196 | +```tsx |
| 197 | +const { stateMap } = useAgentState(); |
| 198 | +const progress = stateMap['current_task']?.percent || 0; |
| 199 | +``` |
| 200 | + |
| 201 | +#### 6.2.4 Dynamic Content (Activity) |
| 202 | +- **Goal**: Display live-updating charts or dashboards driven by the agent. |
| 203 | +- **Key Pattern**: `useAgentActivity` + `ACTIVITY_SNAPSHOT/DELTA` events. |
| 204 | +- **Example**: `agui-activity.tsx` |
| 205 | + |
| 206 | +### 6.3 Advanced / Headless Scenarios |
| 207 | + |
| 208 | +#### 6.3.1 Headless Event Bus |
| 209 | +- **Goal**: Handle side effects (logging, analytics) without UI coupling. |
| 210 | +- **Key Pattern**: `chatEngine.eventBus.on()`. |
| 211 | +- **Example**: `headless-eventbus.tsx` |
| 212 | +```tsx |
| 213 | +chatEngine.eventBus.on(ChatEngineEventType.REQUEST_COMPLETE, (payload) => { |
| 214 | + logAnalytics(payload); |
| 215 | +}); |
| 216 | +``` |
| 217 | + |
| 218 | +#### 6.3.2 Complex Multi-Step Agent |
| 219 | +- **Goal**: Build a complex agent with planning, tools, and dynamic UI. |
| 220 | +- **Key Pattern**: Combining `useAgentToolcall`, `useAgentActivity`, and `useAgentState`. |
| 221 | +- **Example**: `agui-comprehensive.tsx` (Travel Planner Agent) |
0 commit comments