route.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { streamText } from 'ai';
  2. import { gateway } from '@ai-sdk/gateway';
  3. export const maxDuration = 30;
  4. const SYSTEM_PROMPT = `You are a UI generator that outputs JSONL (JSON Lines) patches to build a contact form.
  5. AVAILABLE COMPONENTS:
  6. - Form: { title?: string } - Form container with optional title. Has children.
  7. - Input: { label: string, name: string } - Text input field
  8. - Textarea: { label: string, name: string } - Multi-line text area
  9. - Button: { label: string, action: string } - Clickable button
  10. OUTPUT FORMAT:
  11. Output JSONL where each line is a patch operation:
  12. - {"op":"set","path":"/root","value":"element-key"} - Set root element
  13. - {"op":"add","path":"/elements/key","value":{...}} - Add an element
  14. ELEMENT STRUCTURE:
  15. {
  16. "key": "unique-key",
  17. "type": "ComponentType",
  18. "props": { ... },
  19. "children": ["child-key-1", "child-key-2"]
  20. }
  21. RULES:
  22. 1. First set /root to the root element's key
  23. 2. Add each element with a unique key using /elements/{key}
  24. 3. Parent elements list child keys in their "children" array
  25. 4. Stream elements progressively - parent first, then children
  26. 5. Each element must have: key, type, props
  27. 6. Children array contains STRING KEYS, not nested objects
  28. EXAMPLE - Contact Form:
  29. {"op":"set","path":"/root","value":"form"}
  30. {"op":"add","path":"/elements/form","value":{"key":"form","type":"Form","props":{"title":"Contact Us"},"children":["name","email","message","submit"]}}
  31. {"op":"add","path":"/elements/name","value":{"key":"name","type":"Input","props":{"label":"Name","name":"name"}}}
  32. {"op":"add","path":"/elements/email","value":{"key":"email","type":"Input","props":{"label":"Email","name":"email"}}}
  33. {"op":"add","path":"/elements/message","value":{"key":"message","type":"Textarea","props":{"label":"Message","name":"message"}}}
  34. {"op":"add","path":"/elements/submit","value":{"key":"submit","type":"Button","props":{"label":"Send Message","action":"submit"}}}
  35. Generate JSONL patches for the user's request:`;
  36. const MAX_PROMPT_LENGTH = 140;
  37. export async function POST(req: Request) {
  38. const { prompt } = await req.json();
  39. const sanitizedPrompt = String(prompt || '').slice(0, MAX_PROMPT_LENGTH);
  40. const result = streamText({
  41. model: gateway('openai/gpt-4o-mini'),
  42. system: SYSTEM_PROMPT,
  43. prompt: sanitizedPrompt,
  44. temperature: 0.7,
  45. });
  46. return result.toTextStreamResponse();
  47. }