page.mdx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. export const metadata = { title: "AI SDK Integration" }
  2. # AI SDK Integration
  3. Use json-render with the Vercel AI SDK for seamless streaming.
  4. ## Installation
  5. ```bash
  6. npm install ai
  7. ```
  8. ## API Route Setup
  9. ```typescript
  10. // app/api/generate/route.ts
  11. import { streamText } from 'ai';
  12. import { catalog } from '@/lib/catalog';
  13. export async function POST(req: Request) {
  14. const { prompt, currentTree } = await req.json();
  15. // Generate system prompt from catalog
  16. const systemPrompt = catalog.prompt();
  17. // Optionally include current UI state for context
  18. const contextPrompt = currentTree
  19. ? `\n\nCurrent UI state:\n${JSON.stringify(currentTree, null, 2)}`
  20. : '';
  21. const result = streamText({
  22. model: 'anthropic/claude-haiku-4.5',
  23. system: systemPrompt + contextPrompt,
  24. prompt,
  25. });
  26. return result.toTextStreamResponse();
  27. }
  28. ```
  29. ## Client-Side Hook
  30. Use `useUIStream` on the client:
  31. ```tsx
  32. 'use client';
  33. import { useUIStream, Renderer } from '@json-render/react';
  34. function GenerativeUI() {
  35. const { spec, isStreaming, error, send } = useUIStream({
  36. api: '/api/generate',
  37. });
  38. return (
  39. <div>
  40. <button
  41. onClick={() => send('Create a dashboard with metrics')}
  42. disabled={isStreaming}
  43. >
  44. {isStreaming ? 'Generating...' : 'Generate'}
  45. </button>
  46. {error && <p className="text-red-500">{error.message}</p>}
  47. <Renderer spec={spec} registry={registry} loading={isStreaming} />
  48. </div>
  49. );
  50. }
  51. ```
  52. ## Prompt Engineering
  53. The `catalog.prompt()` method creates an optimized system prompt that:
  54. - Lists all available components and their props
  55. - Describes available actions
  56. - Specifies the expected JSON output format
  57. - Includes examples for better generation
  58. ## Custom System Prompts
  59. Pass custom rules to tailor AI behavior:
  60. ```typescript
  61. const systemPrompt = catalog.prompt({
  62. customRules: [
  63. 'Always use Card components for grouping related content',
  64. 'Prefer horizontal layouts (Row) for metrics',
  65. 'Use consistent spacing with padding="md"',
  66. ],
  67. });
  68. ```
  69. ## Next
  70. Learn about [progressive streaming](/docs/streaming).