### Installation using npx Source: https://github.com/puffinsoft/syntux/blob/master/README.md Command to install the Syntux library and its required components into the `lib/getsyntux` folder of your project. ```bash $ npx getsyntux@latest ``` -------------------------------- ### Installing Vercel AI SDK and Anthropic Provider (npm) Source: https://github.com/puffinsoft/syntux/blob/master/README.md Commands to install the Vercel AI SDK, which is used for LLM provider support, and the specific Anthropic provider if you are using Claude models. ```bash $ npm i ai $ npm i @ai-sdk/anthropic (if you're using Claude) ``` -------------------------------- ### Basic GeneratedUI Example Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x A fundamental example of using the GeneratedUI component with an Anthropic Claude model. It demonstrates how to initialize the AI model and pass the data to be displayed, along with a design hint, to generate a UI. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { createAnthropic } from "@ai-sdk/anthropic"; /* this example uses Claude, but all models are supported! */ const anthropic = createAnthropic({ apiKey: ... }) export default function Home(){ const valueToDisplay = { ... }; return } ``` -------------------------------- ### Install Syntux CLI Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Installs the Syntux CLI tool to your Next.js project. This command copies necessary component and spec files into your project's `@/lib/getsyntux` directory, ensuring the React Server Component boundary is respected to prevent API key exposure. ```bash npx getsyntux@0.5 ``` -------------------------------- ### Initialize Syntux Project with CLI Source: https://context7.com/puffinsoft/syntux/llms.txt Initializes Syntux in a Next.js project using the CLI. Run without arguments or with `init` to copy template files to `lib/getsyntux/`. The output indicates installation progress and completion. ```bash # Initialize syntux in your project $ npx getsyntux@latest # Output: # getsyntux: library not detected in package.json. Please install to continue... # ? Run npm install getsyntux? > Yes # getsyntux: installed from npm successfully. # getsyntux: generating files... # getsyntux: installation complete. # Files created: # lib/getsyntux/GeneratedUI.tsx # lib/getsyntux/spec.ts ``` -------------------------------- ### Output Formatting Example Source: https://github.com/puffinsoft/syntux/blob/master/src/templates/spec.md Specifies the required output format: a list of UINodes, separated by newlines. Each node is a JSON object. ```plaintext Input: ... ... ... ... ... ... Output: { ... } ... more lines ``` -------------------------------- ### GeneratedUI Caching Example Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Illustrates how to implement caching for the GeneratedUI component to store and retrieve previously generated UI schemas for a specific user. This example uses a `Map` to store cached results keyed by `userID`, improving performance by skipping regeneration when cached data is available. ```jsx const cache: Map = new Map(); export default function Home(){ const userID = 10; const valueToDisplay = { ... }; return { cache.set(userID, result) }} model={anthropic("claude-sonnet-4-5")} value={valueToDisplay} /> } ``` -------------------------------- ### Basic GeneratedUI Component Usage (JSX) Source: https://github.com/puffinsoft/syntux/blob/master/README.md Demonstrates the fundamental usage of the GeneratedUI component. It requires a model provider (e.g., Anthropic) and a value to display. An optional hint can guide the UI design. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { createAnthropic } from "@ai-sdk/anthropic"; /* this example uses Claude, but all models are supported! */ const anthropic = createAnthropic({ apiKey: ... }) export default function Home(){ const valueToDisplay = { "username": "John", "email": "john@gmail.com", "age": 22 }; return } ``` -------------------------------- ### Skeletonization Example: JSON Input to Skeleton Source: https://github.com/puffinsoft/syntux/wiki/FAQ Demonstrates how the `skeletonize` prop transforms a complex JSON input, including nested objects and arrays, into a simplified skeleton. This skeleton retains property names and type information (e.g., 'string', 'array') while reducing the overall data size. ```json // input { "prop1": "unsafe input here", "prop2": "unsafe input here", "prop3": [ { "abc": "hello", "def": "world" }, { "abc": "monte", "def": "carlo" }, ], "prop4": { "nestedProp": "unsafe input here" } } // skeletonized { "prop1": "string", "prop2": "string", "prop3": [ { "abc": "string", "def": "string" }, ], "prop4": { "nestedProp": "string" } } ``` -------------------------------- ### Action Handling with $action Source: https://github.com/puffinsoft/syntux/blob/master/src/templates/spec.md Demonstrates how to attach event handlers like 'onClick' using the '$action' schema. Arguments can be hardcoded values or dynamically bound values. ```javascript "props": { "onClick": { "$action": "addToCart", "args": [ { "$bind": "$item.id" }, 1 ] } } // This calls the `addToCart` action with the item's ID and the number 1. ``` -------------------------------- ### Generate Component Definitions CLI Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Use the `npx getsyntux generate-defs` command to automatically create component definitions. This CLI tool parses component files, prompts for descriptions, and generates JSON-compatible definitions for easy integration into the `components` property. ```bash $ npx getsyntux generate-defs ./path/to/component.tsx ``` ```bash $ npx getsyntux generate-defs .\lib\Button.tsx getsyntux: parsing file... getsyntux: found 1 component(s) with prop definitions [Button] getsyntux: component #1: Button √ What does this component do? (optional) ... displays an interactive button getsyntux: generated definitions (safe to copy & paste directly): { name: "Button", props: "{ text: string, disabled: boolean }", component: Button, context: "displays an interactive button" }, ``` -------------------------------- ### Data Binding with $bind Source: https://github.com/puffinsoft/syntux/blob/master/src/templates/spec.md Illustrates how to use the '$bind' directive for dynamic data linking in content or props. Supports global properties, loop items, and referencing the entire global object. ```javascript // Global properties: "$bind": "path.to.prop" // Loop Item: "$bind": "$item.path.prop" (current item in a loop) // Reference global object: "$bind": "$" ``` -------------------------------- ### Integrate Custom Components with GeneratedUI (React/JSX) Source: https://context7.com/puffinsoft/syntux/llms.txt Shows how to provide custom React components to the GeneratedUI component for the LLM to utilize. This involves defining components with their names, prop signatures, and references, enabling more tailored UI generation. Dependencies include GeneratedUI, an AI SDK, and the custom React components. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { createAnthropic } from "@ai-sdk/anthropic"; // Custom components (must be client components with "use client") function MetricCard({ title, value, trend }: { title: string; value: number; trend: "up" | "down" }) { return (

{title}

{value} {trend === "up" ? "+" : "-"}
); } function DataTable({ headers, rows }: { headers: string[]; rows: any[][] }) { return ( {headers.map((h, i) => )}{rows.map((row, i) => {row.map((cell, j) => )})}
{h}
{cell}
); } const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); export default function Analytics() { const analyticsData = { metrics: { revenue: 50000, users: 1234, conversion: 3.2 }, transactions: [ { id: "TX001", amount: 99.99, status: "completed" }, { id: "TX002", amount: 149.99, status: "pending" } ] }; return ( ); } ``` -------------------------------- ### Array Iteration with __ForEach__ Source: https://github.com/puffinsoft/syntux/blob/master/src/templates/spec.md Explains how to render arrays using the '__ForEach__' component. A 'source' prop defines the array to iterate over, and subsequent nodes act as templates for each item. ```javascript {"id":"loop_1", "parentId":"root", "type":"__ForEach__", "props":{"source":"authors"}} {"id":"card_1", "parentId":"loop_1", "type":"div", "props":{"className":"card"}, "content": {"$bind": "$item.name"}} ``` -------------------------------- ### Define Server Action with Metadata Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Shows how to define a server action for use with the GeneratedUI component. The `defineTool` function is used to attach metadata to the asynchronous function, including parameter types and a description of its functionality, which is crucial for the LLM to understand and utilize the action correctly. ```jsx import { defineTool } from "getsyntux"; const actions = { "action_name": defineTool(async () => { "use server"; }) } ``` ```javascript const myFunction = async (id: string) => { "use server"; /* ... */ } defineTool(myFunction, "id: string", "what does this function do?") ``` -------------------------------- ### Generate Component Definitions with CLI Source: https://context7.com/puffinsoft/syntux/llms.txt Automatically generates component definitions from TypeScript files for the `components` prop. It parses prop types and prompts for context descriptions. The input is a path to a TypeScript component file, and the output is the generated definitions. ```bash $ npx getsyntux generate-defs ./components/Button.tsx # Output: # getsyntux: parsing file... # getsyntux: found 1 component(s) with prop definitions [Button] # getsyntux: component #1: Button # ? What does this component do? (optional) ... displays an interactive button # # getsyntux: generated definitions (safe to copy & paste directly): ``` -------------------------------- ### Define Server Actions with defineTool in React Source: https://context7.com/puffinsoft/syntux/llms.txt Attaches server actions to UI events using the `actions` prop and `defineTool` for LLM parameter understanding. It requires `getsyntux` and `@ai-sdk/anthropic` dependencies. Input is a `postId` and `currentState` (for toggle), output is a revalidated path. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { defineTool } from "getsyntux"; import { createAnthropic } from "@ai-sdk/anthropic"; import { revalidatePath } from "next/cache"; const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); export default function PostManager() { const posts = [ { id: 1, title: "First Post", published: true }, { id: 2, title: "Draft Post", published: false }, { id: 3, title: "Another Post", published: true } ]; const actions = { deletePost: defineTool( async (postId: number) => { "use server"; await db.posts.delete({ where: { id: postId } }); revalidatePath("/posts"); }, "postId: number", "Permanently deletes a post by its ID" ), togglePublish: defineTool( async (postId: number, currentState: boolean) => { "use server"; await db.posts.update({ where: { id: postId }, data: { published: !currentState } }); revalidatePath("/posts"); }, "postId: number, currentState: boolean", "Toggles the published state of a post" ), refreshList: defineTool( async () => { "use server"; revalidatePath("/posts"); }, "", "Refreshes the post list" ) }; return ( ); } // LLM generates UI with onClick handlers bound to the defined actions ``` -------------------------------- ### Generate UI with GeneratedUI Component (React/JSX) Source: https://context7.com/puffinsoft/syntux/llms.txt Demonstrates the basic usage of the GeneratedUI component to render user data. It takes a data value and an LLM model, returning a dynamically generated React UI. Dependencies include the GeneratedUI component and an AI SDK for model integration. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { createAnthropic } from "@ai-sdk/anthropic"; const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); export default function UserProfile() { const userData = { username: "johndoe", email: "john@example.com", age: 28, subscriptionTier: "premium", posts: [ { id: 1, title: "Hello World", likes: 42 }, { id: 2, title: "My Journey", likes: 128 } ] }; return ( Loading UI...} /> ); } // Output: LLM-generated React UI displaying the user profile with posts ``` -------------------------------- ### GeneratedUI with Caching (TypeScript) Source: https://github.com/puffinsoft/syntux/blob/master/README.md Illustrates how to implement caching for generated UIs. A Map is used to store previously generated UI results, keyed by a user ID. The `cached` prop provides the initial UI, and `onGenerate` updates the cache. ```typescript const cache: Map = new Map(); export default function Home(){ const userID = 10; const valueToDisplay = { /* ... */ }; return { cache.set(userID, result) }} model={anthropic("claude-sonnet-4-5")} value={valueToDisplay} /> } ``` -------------------------------- ### Input Processing Rules Overview Source: https://github.com/puffinsoft/syntux/blob/master/src/templates/spec.md Outlines the rules for processing input, including parsing component specifications, user context, available actions, data values, and skeleton flags. ```plaintext 1. Parse Specs: Read `AllowedComponents` and `ComponentContext`. 2. Parse Context: Read `UserContext`. 3. Parse Actions: Read `AvailableActions`. 4. Parse Data: Analyze `Value`. 5. Check Skeleton: Read `IsSkeleton`. ``` -------------------------------- ### Create Data Skeleton with getsyntux Source: https://context7.com/puffinsoft/syntux/llms.txt Programmatically generates a skeleton of input data, useful for preprocessing data before sending it to an LLM. This utility helps in manually controlling the data structure. ```typescript import { create_skeleton } from "getsyntux"; const userData = { name: "John Doe", email: "john@example.com", orders: [ { id: 1, total: 99.99, items: ["Widget", "Gadget"] }, { id: 2, total: 149.99, items: ["Tool"] } ], preferences: { theme: "dark", notifications: true } }; const skeleton = create_skeleton(userData); console.log(skeleton); // Output: // { // name: "string", // email: "string", // orders: [{ id: "number", total: "number", items: ["string"] }], // preferences: { theme: "string", notifications: "boolean" } // } ``` -------------------------------- ### GeneratedUI Component Usage Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Demonstrates how to use the GeneratedUI component in a React application. It accepts various props to control the AI generation process, including the data to display, the AI model to use, design hints, server actions, allowed components, placeholder elements, caching mechanisms, and callbacks for generation events. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; { "use server"; }) }} components?={[...]}} placeholder?={
Awaiting stream...
} cached?={cacheStr} onGenerate?={(str) => { cacheStr = str }} skeletonize?={false} /> ``` -------------------------------- ### Cache Generated UIs with GeneratedUI Component (React/JSX) Source: https://context7.com/puffinsoft/syntux/llms.txt Illustrates how to cache generated UI schemas to optimize performance by avoiding redundant LLM calls. The `onGenerate` callback stores the schema, and the `cached` prop allows subsequent renders to use the stored schema. This requires the GeneratedUI component and an AI SDK. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { createAnthropic } from "@ai-sdk/anthropic"; const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); const schemaCache: Map = new Map(); export default async function Dashboard({ userId }: { userId: number }) { const dashboardData = await fetchUserDashboard(userId); const cachedSchema = schemaCache.get(userId); return ( { schemaCache.set(userId, schema); }} hint="Executive dashboard with KPIs and charts" /> ); } // First render: generates and caches schema // Subsequent renders: uses cached schema, no LLM call ``` -------------------------------- ### Define Custom Server Actions with Syntux Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Perform server actions automatically attached to component events using `defineTool`. Actions are defined as asynchronous functions with optional type and description parameters, ensuring server-side logic is correctly integrated. ```jsx import { defineTool } from "getsyntux"; export default function Home(){ const valueToDisplay = { ... }; { "use server"; /* ... */ }, "id: string", "deletes post with id"), "refresh": defineTool(async () => { "use server"; /* ... */}) }} /> } ``` -------------------------------- ### Define Custom React Components with Syntux Source: https://github.com/puffinsoft/syntux/wiki/v0.5.x Integrate custom React components by providing their name, TypeScript props definition, and optionally a context description. This allows for seamless use of both custom and third-party components within the Syntux framework. ```jsx import { CustomOne, CustomTwo } from '@/my_components' export default function Home(){ const valueToDisplay = { ... }; } ``` -------------------------------- ### React Interface Schema Binding Rules Source: https://context7.com/puffinsoft/syntux/llms.txt Explains the binding rules for data and actions within the React interface schema. It covers global properties, loop item properties, root values, and action binding syntax. ```typescript // Binding rules: // - Global property: { "$bind": "path.to.prop" } // - Loop item property: { "$bind": "$item.path.prop" } // - Root value: { "$bind": "$" } // Action binding: // { "$action": "actionName", "args": [literal, {"$bind": "path"}] } ``` -------------------------------- ### Parse LLM Response Schemas with ResponseParser in TypeScript Source: https://context7.com/puffinsoft/syntux/llms.txt A utility class for parsing React Interface Schema from LLM streams. It handles incremental updates and can load complete schemas from cache. Dependencies include `getsyntux`. Input is a `ReadableStream` or a cached schema string, and the output is the parsed schema object. ```typescript import { ResponseParser } from "getsyntux"; // Streaming usage const parser = new ResponseParser(); async function handleStream(stream: ReadableStream) { const reader = stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; // Returns true if UI update is warranted if (parser.addDelta(value)) { console.log("Schema updated:", parser.schema); // Trigger re-render with updated schema } } // Flush remaining buffer parser.finish(); return parser.schema; // Output: { componentMap: {...}, childrenMap: {...}, root: {...} } } // Loading from cache const cachedParser = new ResponseParser(); cachedParser.addDelta(cachedSchemaString); cachedParser.finish(); const schema = cachedParser.schema; ``` -------------------------------- ### React Interface Schema Format for UI Nodes Source: https://context7.com/puffinsoft/syntux/llms.txt Defines the newline-delimited JSON format for representing UI nodes in React. Each node includes an id, parentId, type, and optional props or content with data bindings. ```json {"id":"root_1","parentId":null,"type":"div","props":{"className":"container"}} {"id":"header_1","parentId":"root_1","type":"h1","content":{"$bind":"title"}} {"id":"loop_1","parentId":"root_1","type":"__ForEach__","props":{"source":"items"}} {"id":"card_1","parentId":"loop_1","type":"div","props":{"className":"card"}} {"id":"name_1","parentId":"card_1","type":"span","content":{"$bind":"$item.name"}} {"id":"btn_1","parentId":"card_1","type":"button","props":{"onClick":{"$action":"deleteItem","args":[{"$bind":"$item.id"}]}},"content":"Delete"} ``` -------------------------------- ### Skeletonize Large Arrays with Syntux Source: https://github.com/puffinsoft/syntux/wiki/FAQ Use the `skeletonize` prop with Syntux's `GeneratedUI` component to handle large arrays efficiently. This prop preserves type information while reducing the data passed to the LLM, preventing excessive token usage and potential security risks. ```jsx const myArrayToDisplay = [ ... 1000 items ... ]; ``` -------------------------------- ### Skeletonize Large Arrays for LLM Input in React Source: https://context7.com/puffinsoft/syntux/llms.txt Compresses large arrays or sanitizes untrusted input for LLM processing using the `skeletonize` prop. It preserves type information while stripping actual values. This is useful for performance and security when dealing with extensive datasets. The input is a large dataset, and the output is a skeletonized representation sent to the LLM. ```jsx import { GeneratedUI } from "@/lib/getsyntux/GeneratedUI"; import { createAnthropic } from "@ai-sdk/anthropic"; const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); export default function LargeDatasetViewer() { // Large dataset with 10,000 items const largeDataset = Array.from({ length: 10000 }, (_, i) => ({ id: i, name: `Item ${i}`, price: Math.random() * 100, category: ["electronics", "clothing", "food"][i % 3] })); return ( ); } // Skeletonized value sent to LLM: // [{ "id": "number", "name": "string", "price": "number", "category": "string" }] // LLM designs UI based on structure, actual data bound at render time ``` -------------------------------- ### UINode Interface Definition Source: https://github.com/puffinsoft/syntux/blob/master/src/templates/spec.md Defines the structure of a UI node object, including its ID, parent ID, type, properties, and content. Content can be a string or a data binding object. ```typescript type UINode = { id: string; // A unique ID (e.g., "node_1", "header_main") parentId: string | null; // The ID of the container this node lives inside. type: string; // HTML tag ("div") or Component Name ("Card") props?: Record; // Attributes (className, variant, etc.) or props to a component content?: string | { "$bind": string }; // Optional text content or data binding } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.