| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- export const metadata = { title: "AI SDK Integration" }
- # AI SDK Integration
- Use json-render with the Vercel AI SDK for seamless streaming.
- ## Installation
- ```bash
- npm install ai
- ```
- ## API Route Setup
- ```typescript
- // app/api/generate/route.ts
- import { streamText } from 'ai';
- import { catalog } from '@/lib/catalog';
- export async function POST(req: Request) {
- const { prompt, currentTree } = await req.json();
-
- // Generate system prompt from catalog
- const systemPrompt = catalog.prompt();
-
- // Optionally include current UI state for context
- const contextPrompt = currentTree
- ? `\n\nCurrent UI state:\n${JSON.stringify(currentTree, null, 2)}`
- : '';
- const result = streamText({
- model: 'anthropic/claude-haiku-4.5',
- system: systemPrompt + contextPrompt,
- prompt,
- });
- return result.toTextStreamResponse();
- }
- ```
- ## Client-Side Hook
- Use `useUIStream` on the client:
- ```tsx
- 'use client';
- import { useUIStream, Renderer } from '@json-render/react';
- function GenerativeUI() {
- const { spec, isStreaming, error, send } = useUIStream({
- api: '/api/generate',
- });
- return (
- <div>
- <button
- onClick={() => send('Create a dashboard with metrics')}
- disabled={isStreaming}
- >
- {isStreaming ? 'Generating...' : 'Generate'}
- </button>
-
- {error && <p className="text-red-500">{error.message}</p>}
-
- <Renderer spec={spec} registry={registry} loading={isStreaming} />
- </div>
- );
- }
- ```
- ## Prompt Engineering
- The `catalog.prompt()` method creates an optimized system prompt that:
- - Lists all available components and their props
- - Describes available actions
- - Specifies the expected JSON output format
- - Includes examples for better generation
- ## Custom System Prompts
- Pass custom rules to tailor AI behavior:
- ```typescript
- const systemPrompt = catalog.prompt({
- customRules: [
- 'Always use Card components for grouping related content',
- 'Prefer horizontal layouts (Row) for metrics',
- 'Use consistent spacing with padding="md"',
- ],
- });
- ```
- ## Next
- Learn about [progressive streaming](/docs/streaming).
|