@lantos1618/better-ui 0.2.2 β†’ 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +381 -114
  2. package/package.json +7 -1
package/README.md CHANGED
@@ -1,190 +1,457 @@
1
1
  # Better UI - AUI (Assistant-UI) System
2
2
 
3
- A concise and elegant tool system for Next.js that enables AI assistants to control both frontend and backend through a fluent API.
3
+ > A powerful, type-safe tool system for Next.js that enables AI assistants to control both frontend and backend operations through a fluent API.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@lantos1618/better-ui.svg)](https://www.npmjs.com/package/@lantos1618/better-ui)
6
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue)](https://www.typescriptlang.org/)
8
+ [![Next.js](https://img.shields.io/badge/Next.js-15.5-black)](https://nextjs.org/)
9
+
10
+ ## 🎯 What is Better UI?
11
+
12
+ Better UI is an **AI-first UI framework** that revolutionizes how AI assistants interact with web applications. It provides a clean, type-safe abstraction layer that allows AI models to execute both frontend and backend operations seamlessly.
13
+
14
+ ### Key Benefits
15
+
16
+ - **πŸš€ Minimal Boilerplate**: Create powerful tools with just 2 required methods
17
+ - **πŸ”’ Type Safety**: Full TypeScript + Zod schema validation
18
+ - **🎨 AI-Native**: Built specifically for AI assistants to control applications
19
+ - **⚑ Performance**: Smart client-side caching and optimization
20
+ - **πŸ”§ Extensible**: Easy to create custom tools for any use case
21
+
22
+ ## πŸ“¦ Installation
23
+
24
+ ```bash
25
+ npm install @lantos1618/better-ui
26
+ # or
27
+ yarn add @lantos1618/better-ui
28
+ # or
29
+ bun add @lantos1618/better-ui
30
+ ```
4
31
 
5
32
  ## πŸš€ Quick Start
6
33
 
34
+ ### 1. Simple Tool (2 methods only!)
35
+
7
36
  ```tsx
8
- // Simple tool - just 2 methods
9
- const simpleTool = aui
37
+ import { aui } from '@lantos1618/better-ui';
38
+ import { z } from 'zod';
39
+
40
+ const weatherTool = aui
10
41
  .tool('weather')
11
42
  .input(z.object({ city: z.string() }))
12
43
  .execute(async ({ input }) => ({ temp: 72, city: input.city }))
13
44
  .render(({ data }) => <div>{data.city}: {data.temp}Β°</div>);
45
+ ```
14
46
 
15
- // Complex tool - adds client optimization
16
- const complexTool = aui
47
+ ### 2. Advanced Tool with Client Optimization
48
+
49
+ ```tsx
50
+ const searchTool = aui
17
51
  .tool('search')
18
52
  .input(z.object({ query: z.string() }))
19
53
  .execute(async ({ input }) => db.search(input.query))
20
54
  .clientExecute(async ({ input, ctx }) => {
21
- // Only when you need caching, offline, etc.
55
+ // Optional: Add caching, offline support, optimistic updates
22
56
  const cached = ctx.cache.get(input.query);
23
57
  return cached || ctx.fetch('/api/tools/search', { body: input });
24
58
  })
25
59
  .render(({ data }) => <SearchResults results={data} />);
26
60
  ```
27
61
 
28
- ## ✨ Features
62
+ ## πŸ’» AI SDK Integration (Vercel AI SDK)
29
63
 
30
- - **Fluent API**: Chain methods for clean, readable tool definitions
31
- - **Type Safety**: Full TypeScript support with Zod schemas
32
- - **Minimal Boilerplate**: Only `input()` and `execute()` are required
33
- - **Dual Execution**: Server-side execution with optional client-side optimization
34
- - **React Integration**: Seamless rendering of tool results
35
- - **AI-Ready**: Designed for AI assistants to control UI/backend
64
+ Better UI seamlessly integrates with Vercel's AI SDK for building chat interfaces:
36
65
 
37
- ## πŸ—οΈ Architecture
66
+ ### Basic Chat Integration
38
67
 
39
- ```
40
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
41
- β”‚ Client │────▢│ AUI System │────▢│ Server β”‚
42
- β”‚ Component β”‚ β”‚ β”‚ β”‚ Handler β”‚
43
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
44
- β”‚ β”‚ β”‚
45
- β–Ό β–Ό β–Ό
46
- ToolRenderer ClientExecutor ToolExecutor
47
- (optional) (server-side)
68
+ ```tsx
69
+ // app/api/chat/route.ts
70
+ import { openai } from '@ai-sdk/openai';
71
+ import { streamText, convertToCoreMessages } from 'ai';
72
+ import { aui } from '@lantos1618/better-ui';
73
+ import { z } from 'zod';
74
+
75
+ // Define your tools
76
+ const weatherTool = aui
77
+ .tool('getWeather')
78
+ .description('Get current weather for a city')
79
+ .input(z.object({
80
+ city: z.string().describe('City name'),
81
+ unit: z.enum(['celsius', 'fahrenheit']).optional()
82
+ }))
83
+ .execute(async ({ input }) => {
84
+ // Fetch real weather data
85
+ const response = await fetch(`https://api.weather.com/v1/weather?city=${input.city}`);
86
+ return response.json();
87
+ });
88
+
89
+ const stockTool = aui
90
+ .tool('getStockPrice')
91
+ .description('Get current stock price')
92
+ .input(z.object({
93
+ symbol: z.string().describe('Stock symbol (e.g., AAPL)')
94
+ }))
95
+ .execute(async ({ input }) => {
96
+ const response = await fetch(`https://api.stocks.com/v1/quote/${input.symbol}`);
97
+ return response.json();
98
+ });
99
+
100
+ // Convert to AI SDK format
101
+ const tools = {
102
+ getWeather: weatherTool.toAISDKTool(),
103
+ getStockPrice: stockTool.toAISDKTool(),
104
+ };
105
+
106
+ export async function POST(req: Request) {
107
+ const { messages } = await req.json();
108
+
109
+ const result = await streamText({
110
+ model: openai('gpt-4'),
111
+ messages: convertToCoreMessages(messages),
112
+ tools,
113
+ maxToolRoundtrips: 5,
114
+ });
115
+
116
+ return result.toDataStreamResponse();
117
+ }
48
118
  ```
49
119
 
50
- ## πŸ“¦ Installation
120
+ ### React Chat Component
51
121
 
52
- ```bash
53
- npm install
54
- npm run dev
122
+ ```tsx
123
+ // app/chat/page.tsx
124
+ 'use client';
125
+
126
+ import { useChat } from 'ai/react';
127
+ import { ToolExecutorProvider, ToolRenderer } from '@lantos1618/better-ui/client';
128
+
129
+ export default function ChatPage() {
130
+ const { messages, input, handleInputChange, handleSubmit } = useChat();
131
+
132
+ return (
133
+ <ToolExecutorProvider tools={[weatherTool, stockTool]}>
134
+ <div className="flex flex-col h-screen">
135
+ <div className="flex-1 overflow-y-auto p-4">
136
+ {messages.map((message) => (
137
+ <div key={message.id} className="mb-4">
138
+ <div className="font-bold">{message.role}:</div>
139
+ <div>{message.content}</div>
140
+
141
+ {/* Render tool calls with Better UI */}
142
+ {message.toolInvocations?.map((toolCall) => (
143
+ <ToolRenderer
144
+ key={toolCall.toolCallId}
145
+ toolCall={toolCall}
146
+ tool={tools[toolCall.toolName]}
147
+ />
148
+ ))}
149
+ </div>
150
+ ))}
151
+ </div>
152
+
153
+ <form onSubmit={handleSubmit} className="p-4 border-t">
154
+ <input
155
+ value={input}
156
+ onChange={handleInputChange}
157
+ placeholder="Ask about weather or stocks..."
158
+ className="w-full p-2 border rounded"
159
+ />
160
+ </form>
161
+ </div>
162
+ </ToolExecutorProvider>
163
+ );
164
+ }
55
165
  ```
56
166
 
57
- ## πŸ› οΈ API Reference
167
+ ### Advanced Chat with Multiple Tools
58
168
 
59
- ### Tool Builder
169
+ ```tsx
170
+ // lib/ai-tools.ts
171
+ import { aui } from '@lantos1618/better-ui';
172
+ import { z } from 'zod';
173
+
174
+ // Database search tool
175
+ export const searchDatabaseTool = aui
176
+ .tool('searchDatabase')
177
+ .description('Search internal database')
178
+ .input(z.object({
179
+ query: z.string(),
180
+ filters: z.object({
181
+ category: z.string().optional(),
182
+ dateRange: z.object({
183
+ start: z.string().optional(),
184
+ end: z.string().optional(),
185
+ }).optional(),
186
+ }).optional(),
187
+ }))
188
+ .execute(async ({ input }) => {
189
+ // Your database logic
190
+ return await db.search(input.query, input.filters);
191
+ })
192
+ .clientExecute(async ({ input, ctx }) => {
193
+ // Client-side caching
194
+ const cacheKey = JSON.stringify(input);
195
+ const cached = ctx.cache.get(cacheKey);
196
+ if (cached && Date.now() - cached.timestamp < 60000) {
197
+ return cached.data;
198
+ }
199
+
200
+ const result = await ctx.fetch('/api/search', {
201
+ method: 'POST',
202
+ body: JSON.stringify(input)
203
+ });
204
+
205
+ ctx.cache.set(cacheKey, { data: result, timestamp: Date.now() });
206
+ return result;
207
+ })
208
+ .render(({ data }) => (
209
+ <div className="grid gap-2">
210
+ {data.results.map((item) => (
211
+ <div key={item.id} className="p-2 border rounded">
212
+ <h3>{item.title}</h3>
213
+ <p>{item.description}</p>
214
+ </div>
215
+ ))}
216
+ </div>
217
+ ));
60
218
 
61
- - `.tool(name)` - Create a new tool builder
62
- - `.input(schema)` - Define input validation with Zod
63
- - `.execute(handler)` - Server-side execution logic
64
- - `.clientExecute(handler)` - Optional client-side execution
65
- - `.render(component)` - React component for rendering results
66
- - `.description(text)` - Optional tool description
67
- - Returns a built tool object ready to use (no build step needed)
219
+ // Chart generation tool
220
+ export const createChartTool = aui
221
+ .tool('createChart')
222
+ .description('Generate interactive charts')
223
+ .input(z.object({
224
+ type: z.enum(['line', 'bar', 'pie', 'scatter']),
225
+ data: z.array(z.object({
226
+ label: z.string(),
227
+ value: z.number(),
228
+ })),
229
+ title: z.string().optional(),
230
+ }))
231
+ .execute(async ({ input }) => input)
232
+ .render(({ data }) => (
233
+ <ChartComponent type={data.type} data={data.data} title={data.title} />
234
+ ));
68
235
 
69
- ### React Components
236
+ // Form generation tool
237
+ export const generateFormTool = aui
238
+ .tool('generateForm')
239
+ .description('Create dynamic forms')
240
+ .input(z.object({
241
+ fields: z.array(z.object({
242
+ name: z.string(),
243
+ type: z.enum(['text', 'number', 'email', 'select', 'checkbox']),
244
+ label: z.string(),
245
+ required: z.boolean().optional(),
246
+ options: z.array(z.string()).optional(),
247
+ })),
248
+ submitUrl: z.string(),
249
+ }))
250
+ .execute(async ({ input }) => input)
251
+ .render(({ data }) => (
252
+ <DynamicForm fields={data.fields} submitUrl={data.submitUrl} />
253
+ ));
254
+ ```
255
+
256
+ ### Streaming with Tool Results
70
257
 
71
258
  ```tsx
72
- import { ToolExecutorProvider, ToolRenderer, useToolExecutor } from '@/lib/aui/client';
259
+ // app/api/chat/route.ts
260
+ import { streamText } from 'ai';
261
+ import { openai } from '@ai-sdk/openai';
262
+
263
+ export async function POST(req: Request) {
264
+ const { messages } = await req.json();
265
+
266
+ const result = await streamText({
267
+ model: openai('gpt-4'),
268
+ messages,
269
+ tools: {
270
+ searchDatabase: searchDatabaseTool.toAISDKTool(),
271
+ createChart: createChartTool.toAISDKTool(),
272
+ generateForm: generateFormTool.toAISDKTool(),
273
+ },
274
+ toolChoice: 'auto', // Let AI decide when to use tools
275
+ async onToolCall({ toolCall, toolResult }) {
276
+ // Log tool usage for analytics
277
+ console.log(`Tool ${toolCall.toolName} called with:`, toolCall.args);
278
+ console.log(`Result:`, toolResult);
279
+ },
280
+ });
281
+
282
+ return result.toDataStreamResponse();
283
+ }
284
+ ```
285
+
286
+ ## πŸ› οΈ Pre-built Tools
287
+
288
+ Better UI comes with a comprehensive set of pre-built tools:
289
+
290
+ ### DOM Manipulation Tools
291
+ - `clickTool` - Click elements on the page
292
+ - `typeTool` - Type text into inputs
293
+ - `scrollTool` - Scroll to elements
294
+ - `selectTool` - Select dropdown options
295
+
296
+ ### API Tools
297
+ - `fetchTool` - Make HTTP requests
298
+ - `graphqlTool` - Execute GraphQL queries
73
299
 
74
- // Provider setup
75
- <ToolExecutorProvider tools={[weatherTool, searchTool]}>
300
+ ### Form Tools
301
+ - `formGeneratorTool` - Create dynamic forms
302
+ - `formValidatorTool` - Validate form data
303
+
304
+ ### Data Tools
305
+ - `databaseQueryTool` - Query databases
306
+ - `dataTransformTool` - Transform data structures
307
+
308
+ ### State Management
309
+ - `stateManagerTool` - Manage application state
310
+ - `localStorageTool` - Persist data locally
311
+
312
+ ## πŸ“š Full API Reference
313
+
314
+ ### Core Builder Methods
315
+
316
+ ```typescript
317
+ aui
318
+ .tool(name: string) // Create tool with name
319
+ .description(text: string) // Add description (for AI)
320
+ .tags(...tags: string[]) // Add tags for discovery
321
+ .input(schema: ZodSchema) // Input validation schema
322
+ .execute(handler: ExecuteHandler) // Server-side logic (required)
323
+ .clientExecute(handler: ClientHandler) // Client-side logic (optional)
324
+ .render(component: RenderFunction) // React component (optional)
325
+ .stream(handler: StreamHandler) // Streaming support (optional)
326
+ ```
327
+
328
+ ### React Hooks & Components
329
+
330
+ ```tsx
331
+ // Provider for tool execution
332
+ <ToolExecutorProvider tools={tools}>
76
333
  <App />
77
334
  </ToolExecutorProvider>
78
335
 
79
- // Render a tool result
80
- <ToolRenderer toolCall={toolCall} tool={weatherTool} />
336
+ // Render tool results
337
+ <ToolRenderer toolCall={toolCall} tool={tool} />
81
338
 
82
- // Hook usage
339
+ // Hook for manual execution
83
340
  const executor = useToolExecutor();
84
341
  const result = await executor.execute(toolCall);
342
+
343
+ // Hook for tool discovery
344
+ const tools = useToolRegistry();
345
+ const weatherTools = tools.getByTag('weather');
85
346
  ```
86
347
 
87
- ## πŸ”§ Usage Examples
348
+ ### AI Assistant Integration
88
349
 
89
- ### Basic Tool
90
- ```tsx
91
- const weatherTool = aui
92
- .tool('weather')
93
- .input(z.object({ city: z.string() }))
94
- .execute(async ({ input }) => {
95
- const response = await fetch(`/api/weather?city=${input.city}`);
96
- return response.json();
97
- })
98
- .render(({ data }) => (
99
- <div className="weather-card">
100
- <h3>{data.city}</h3>
101
- <p>{data.temp}Β°F</p>
102
- </div>
103
- ));
104
- ```
350
+ ```typescript
351
+ import { createAIAssistant } from '@lantos1618/better-ui';
105
352
 
106
- ### Tool with Client Optimization
107
- ```tsx
108
- const searchTool = aui
109
- .tool('search')
110
- .input(z.object({ query: z.string() }))
111
- .execute(async ({ input }) => {
112
- return await database.search(input.query);
113
- })
114
- .clientExecute(async ({ input, ctx }) => {
115
- // Client-side caching and offline support
116
- const cached = ctx.cache.get(input.query);
117
- if (cached) return cached;
118
-
119
- const result = await ctx.fetch('/api/aui', {
120
- method: 'POST',
121
- body: JSON.stringify({
122
- toolCall: { toolName: 'search', input }
123
- })
124
- });
125
-
126
- ctx.cache.set(input.query, result);
127
- return result;
128
- })
129
- .render(({ data }) => <SearchResults results={data} />);
353
+ const assistant = createAIAssistant({
354
+ model: 'gpt-4',
355
+ tools: [weatherTool, searchTool],
356
+ systemPrompt: 'You are a helpful assistant.',
357
+ });
358
+
359
+ const response = await assistant.chat('What\'s the weather in NYC?');
130
360
  ```
131
361
 
132
- ## πŸ—‚οΈ Project Structure
362
+ ## πŸ—οΈ Architecture
133
363
 
134
364
  ```
135
- better-ui/
136
- β”œβ”€β”€ app/ # Next.js app directory
137
- β”‚ β”œβ”€β”€ api/ # API routes
138
- β”‚ └── aui-demo/ # Demo pages
139
- β”œβ”€β”€ lib/aui/ # AUI system core
140
- β”‚ β”œβ”€β”€ core/ # Core builder and registry
141
- β”‚ β”œβ”€β”€ client/ # Client-side execution
142
- β”‚ β”œβ”€β”€ server/ # Server-side execution
143
- β”‚ β”œβ”€β”€ tools/ # Example tools
144
- β”‚ └── types/ # TypeScript definitions
145
- β”œβ”€β”€ examples/ # Usage examples
146
- └── agent/ # Development metadata
365
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
366
+ β”‚ AI Model │────▢│ AUI System │────▢│ Your App β”‚
367
+ β”‚ (GPT, etc) β”‚ β”‚ β”‚ β”‚ β”‚
368
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
369
+ β”‚ β”‚ β”‚
370
+ β–Ό β–Ό β–Ό
371
+ Tool Calls Tool Registry Tool Execution
372
+ Type Validation React Rendering
373
+ Client/Server Split State Management
147
374
  ```
148
375
 
149
376
  ## πŸ§ͺ Testing
150
377
 
151
378
  ```bash
379
+ # Run all tests
152
380
  npm test
381
+
382
+ # Run with coverage
383
+ npm run test:coverage
384
+
385
+ # Type checking
153
386
  npm run type-check
387
+
388
+ # Linting
154
389
  npm run lint
155
390
  ```
156
391
 
157
- ## πŸš€ Development
392
+ ## πŸš€ Deployment
393
+
394
+ ### Vercel Deployment
158
395
 
159
396
  ```bash
160
- # Start development server
161
- npm run dev
397
+ # Install Vercel CLI
398
+ npm i -g vercel
399
+
400
+ # Deploy
401
+ vercel
402
+
403
+ # Deploy with environment variables
404
+ vercel --env API_KEY=xxx
405
+ ```
406
+
407
+ ### Environment Variables
162
408
 
163
- # Build for production
164
- npm run build
409
+ ```env
410
+ # Required for AI features
411
+ OPENAI_API_KEY=your_api_key
165
412
 
166
- # Start production server
167
- npm start
413
+ # Optional
414
+ DATABASE_URL=your_db_url
415
+ REDIS_URL=your_redis_url
168
416
  ```
169
417
 
170
- ## πŸ“š Documentation
418
+ ## πŸ“– Examples
171
419
 
172
- - [AUI System Overview](AUI.md) - Detailed system documentation
173
- - [Examples](./examples/) - Complete usage examples
174
- - [API Reference](./lib/aui/README.md) - Core API documentation
420
+ Check out our example applications:
421
+
422
+ - [Chat Application](./examples/chat-app) - Full chat UI with tool execution
423
+ - [Dashboard](./examples/dashboard) - Analytics dashboard with AI controls
424
+ - [Form Builder](./examples/form-builder) - Dynamic form generation
425
+ - [Data Explorer](./examples/data-explorer) - Database exploration tool
175
426
 
176
427
  ## 🀝 Contributing
177
428
 
429
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
430
+
178
431
  1. Fork the repository
179
- 2. Create a feature branch
180
- 3. Make your changes
181
- 4. Add tests
182
- 5. Submit a pull request
432
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
433
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
434
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
435
+ 5. Open a Pull Request
183
436
 
184
437
  ## πŸ“„ License
185
438
 
186
- This project is private and proprietary.
439
+ MIT License - see [LICENSE](LICENSE) for details.
440
+
441
+ ## πŸ™ Acknowledgments
442
+
443
+ Built with:
444
+ - [Next.js](https://nextjs.org/) - The React framework
445
+ - [TypeScript](https://www.typescriptlang.org/) - Type safety
446
+ - [Zod](https://zod.dev/) - Schema validation
447
+ - [Vercel AI SDK](https://sdk.vercel.ai/) - AI integration
448
+
449
+ ## πŸ“ž Support
450
+
451
+ - [GitHub Issues](https://github.com/lantos1618/better-ui/issues)
452
+ - [Documentation](https://docs.better-ui.dev)
453
+ - Email: support@better-ui.dev
187
454
 
188
455
  ---
189
456
 
190
- Built with ❀️ using Next.js, TypeScript, and Zod.
457
+ Built with ❀️ by the Better UI team
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lantos1618/better-ui",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "A modern UI framework for building AI-powered applications",
5
5
  "main": "lib/aui/index.ts",
6
6
  "types": "lib/aui/index.ts",
@@ -28,8 +28,14 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@ai-sdk/openai": "^2.0.20",
31
+ "@dnd-kit/core": "^6.3.1",
32
+ "@dnd-kit/sortable": "^10.0.0",
31
33
  "@sendgrid/mail": "^8.1.5",
34
+ "@types/lodash": "^4.17.20",
32
35
  "ai": "^5.0.23",
36
+ "framer-motion": "^12.23.12",
37
+ "lodash": "^4.17.21",
38
+ "lucide-react": "^0.543.0",
33
39
  "magicpath-ai": "^1.1.2",
34
40
  "next": "^15.5.0",
35
41
  "react": "^18.3.0",