### Basic API Setup Source: https://superduperai.co/docs/image-generation Sets up the base URL for the SuperDuperAI API and defines common headers, including authorization with an API token. ```typescript const API_BASE = 'https://editor.superduperai.co/api/v1'; const headers = { 'Authorization': `Bearer ${your_api_token}`, 'Content-Type': 'application/json' }; ``` -------------------------------- ### SuperDuperAI Video Generation API Setup Source: https://superduperai.co/docs/video-generation Sets up the base URL and authorization headers for interacting with the SuperDuperAI Video Generation API. Requires an API token for authentication. ```typescript const API_BASE = 'https://editor.superduperai.co/api/v1'; const headers = { 'Authorization': `Bearer ${your_api_token}`, 'Content-Type': 'application/json' }; ``` -------------------------------- ### Example llms.txt for FastHTML Source: https://llmstxt.org/ Demonstrates the structure and content of an llms.txt file, including project description, important notes, documentation links, and example links. ```markdown # FastHTML > FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore's `FT` "FastTags" into a library for creating server-rendered hypermedia applications. Important notes: - Although parts of its API are inspired by FastAPI, it is *not* compatible with FastAPI syntax and is not targeted at creating API services - FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte. ## Docs - [FastHTML quick start](https://fastht.ml/docs/tutorials/quickstart_for_web_devs.html.md): A brief overview of many FastHTML features - [HTMX reference](https://github.com/bigskysoftware/htmx/blob/master/www/content/reference.md): Brief description of all HTMX attributes, CSS classes, headers, events, extensions, js lib methods, and config options ## Examples - [Todo list application](https://github.com/AnswerDotAI/fasthtml/blob/main/examples/adv_app.py): Detailed walk-thru of a complete CRUD app in FastHTML showing idiomatic use of FastHTML and HTMX patterns. ## Optional - [Starlette full documentation](https://gist.github.com/jph00/809e4a4808d4510be0e3dc9565e9cbd3/raw/9b717589ca44cedc8aaf00b2b8cacef922964c0f/starlette-sml.md): A subset of the Starlette documentation useful for FastHTML development. ``` -------------------------------- ### JavaScript Implementation Example Source: https://llmstxt.org/ A sample JavaScript implementation for processing llms.txt files, demonstrating how to integrate the specification into web projects using JavaScript. ```javascript // Placeholder for a sample JavaScript implementation // This would typically involve fetching an llms.txt file and processing its content. async function loadLLMContext(filePath) { try { const response = await fetch(filePath); if (!response.ok) { throw new Error(`Failed to fetch ${filePath}: ${response.statusText}`); } const text = await response.text(); // Further processing of the text content to prepare for LLM // For example, parsing markdown, extracting links, etc. console.log('Successfully loaded llms.txt content:', text.substring(0, 200) + '...'); return text; // Or a processed version } catch (error) { console.error('Error loading LLM context:', error); return null; } } // Example usage: // loadLLMContext('/docs/llms.txt').then(context => { // if (context) { // // Use the context data // } // }); ``` -------------------------------- ### Copy Prompt Example Source: https://superduperai.co/tool/veo3-prompt-generator Demonstrates how a prompt is copied to the clipboard, typically used in a user interface to provide feedback on successful copy operations. ```javascript console.log('Copied prompt:', prompt) ``` -------------------------------- ### Model Selection Guide for LLM Use Cases Source: https://superduperai.co/docs/image-generation Provides a function to select the most appropriate LLM model based on the use case (general or editing) and budget (low, medium, high). It maps these criteria to specific model names for image generation. ```typescript const selectModel = (useCase: string, budget: 'low' | 'medium' | 'high') => { const models = { low: { general: 'comfyui/flux', editing: 'comfyui/flux/inpainting' }, medium: { general: 'google-cloud/imagen3', editing: 'google-cloud/imagen3-edit' }, high: { general: 'google-cloud/imagen4-ultra', editing: 'azure-openai/gpt-image-1-edit' } }; const category = useCase.includes('edit') ? 'editing' : 'general'; return models[budget][category]; }; ``` -------------------------------- ### Create Product Demo Video (TypeScript) Source: https://superduperai.co/docs/video-generation Generates a professional product demonstration video. It constructs a detailed prompt based on product name and features, then calls the video generation API. The function waits for the video to be ready before returning its URL. ```typescript const createProductDemo = async (productName: string, features: string[]) => { const prompt = `Professional product demonstration of ${productName} showcasing ${features.join(', ')}, clean background, smooth camera movements`; const response = await fetch(`${API_BASE}/file/generate-video`, { method: 'POST', headers, body: JSON.stringify({ config: { prompt, generation_config_name: 'google-cloud/veo2-text2video', params: { duration: 8, aspect_ratio: '16:9', quality: 'hd' } } }) }); const fileData = await response.json(); return await waitForVideo(fileData.id); }; // Example const demo = await createProductDemo("smartphone", ["camera", "display", "battery"]); ``` -------------------------------- ### Create Product Mockups with Image Generation Source: https://superduperai.co/docs/image-generation Generates a professional product mockup image based on a given product name and setting. It constructs a detailed prompt for the image generation API and waits for the image to be ready. ```typescript const createProductMockup = async (product: string, setting: string) => { const prompt = `Professional product photo of ${product} on ${setting}, clean background, studio lighting, high resolution`; const imageId = await generateImage(prompt); return await waitForImage(imageId); }; // Example const mockup = await createProductMockup("wireless headphones", "marble surface"); ``` -------------------------------- ### Generate and Wait for Image Source: https://superduperai.co/docs/image-generation Demonstrates a complete workflow for generating an image from a text prompt and then polling the API to retrieve the image URL once generation is complete. It includes functions for initiating generation and checking status. ```typescript const generateImage = async (prompt: string) => { const response = await fetch(`${API_BASE}/file/generate-image`, { method: 'POST', headers, body: JSON.stringify({ config: { prompt: prompt, generation_config_name: 'comfyui/flux', // Free model params: { width: 1024, height: 1024, quality: 'hd' } } }) }); const [fileData] = await response.json(); // Returns array return fileData.id; }; // Wait for generation to complete const waitForImage = async (fileId: string) => { while (true) { const response = await fetch(`${API_BASE}/file/${fileId}`, { headers }); const status = await response.json(); if (status.url) return status.url; // Ready! if (status.error) throw new Error(status.error); await new Promise(r => setTimeout(r, 2000)); // Wait 2 seconds } }; // Complete workflow const imageUrl = await generateImage("A beautiful sunset over mountains"); const finalUrl = await waitForImage(imageUrl); console.log('Generated image:', finalUrl); ``` -------------------------------- ### Implement Server-Sent Events (SSE) with Fallback Source: https://superduperai.co/docs/image-generation Demonstrates how to establish a Server-Sent Events (SSE) connection for real-time updates and includes a fallback mechanism to polling if SSE fails. It handles message parsing, error events, and connection cleanup. ```typescript const watchWithSSE = (fileId: string, onUpdate: (data: any) => void) => { const eventSource = new EventSource(`${API_BASE}/events/file.${fileId}`, { headers: { 'Authorization': `Bearer ${your_api_token}` } }); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); onUpdate(data); if (data.url || data.error) { eventSource.close(); } }; eventSource.onerror = (error) => { console.warn('SSE connection failed, falling back to polling'); eventSource.close(); // Fallback to polling method }; // Cleanup after 5 minutes setTimeout(() => { eventSource.close(); }, 300000); return eventSource; }; // Usage with fallback const generateWithRealtime = async (prompt: string) => { const imageId = await generateImage(prompt); // Try SSE first, fallback to polling return new Promise((resolve, reject) => { let resolved = false; // SSE attempt const sse = watchWithSSE(imageId, (data) => { if (data.url && !resolved) { resolved = true; resolve(data.url); } }); // Polling fallback after 10 seconds setTimeout(async () => { if (!resolved) { sse.close(); try { const url = await pollForCompletion(imageId); if (!resolved) { resolved = true; resolve(url); } } catch (error) { if (!resolved) { resolved = true; reject(error); } } } }, 10000); }); }; ``` -------------------------------- ### Batch Video Generation Source: https://superduperai.co/docs/video-generation Enables generating multiple videos sequentially from a list of prompts to manage API rate limits. It processes prompts one by one, handling potential errors for each generation task and collecting results. ```typescript const generateVideoSeries = async (prompts: string[], model = 'comfyui/ltx') => { const results = []; // Generate videos sequentially to avoid rate limits for (const prompt of prompts) { try { // Placeholder for actual video generation and waiting calls // const videoId = await generateVideo(prompt, model); // const videoUrl = await waitForVideo(videoId); const videoUrl = `http://example.com/video_${prompt.replace(/ /g, '_')}.mp4`; // Mock URL results.push({ prompt, url: videoUrl, success: true }); } catch (error: any) { results.push({ prompt, error: error.message, success: false }); } // Small delay between generations await new Promise(r => setTimeout(r, 2000)); } return results; }; ``` -------------------------------- ### Create Lip Sync Video with API Source: https://superduperai.co/docs/video-generation Generates a lip-sync video by synchronizing lip movements with provided audio. It makes a POST request to a video generation API endpoint, specifying video and audio IDs, and then waits for the video to be ready. ```typescript const createLipSyncVideo = async (videoId: string, audioId: string) => { const response = await fetch(`${API_BASE}/file/generate-video`, { method: 'POST', headers, body: JSON.stringify({ config: { prompt: "Synchronize lip movements with audio", generation_config_name: 'comfyui/lip-sync', references: [videoId, audioId], // Video and audio files params: { sync_accuracy: 'high', preserve_quality: true } } }) }); const fileData = await response.json(); return await waitForVideo(fileData.id); }; ``` -------------------------------- ### Calculate Video Generation Cost in TypeScript Source: https://superduperai.co/docs/video-generation Provides a TypeScript function to estimate video generation costs. It maps model names to prices per second and calculates the total cost based on video duration. Includes an example usage. ```typescript const calculateVideoCost = (model: string, duration: number) => { const pricing = { 'comfyui/ltx': 0.40, 'comfyui/lip-sync': 0.40, 'fal-ai/kling-video/v2.1/standard/image-to-video': 1.00, 'fal-ai/minimax/video-01/image-to-video': 1.20, 'fal-ai/minimax/video-01-live/image-to-video': 1.20, 'google-cloud/veo2-text2video': 2.00, 'google-cloud/veo2': 2.00, 'fal-ai/kling-video/v2.1/pro/image-to-video': 2.00, 'google-cloud/veo3-text2video': 3.00, 'google-cloud/veo3': 3.00, 'azure-openai/sora': 10.00 }; const pricePerSecond = pricing[model] || 0; return pricePerSecond * duration; }; // Example const cost = calculateVideoCost('google-cloud/veo2-text2video', 8); console.log(`Cost: ${cost.toFixed(2)}`); // Cost: $16.00 ``` -------------------------------- ### GLightbox Initialization and Events Source: https://llmstxt.org/ Initializes the GLightbox library for image lightboxes and sets up event listeners for slide transitions. It customizes the behavior for `slide_before_load` to handle data URIs for images and `slide_after_load` to trigger math typesetting. ```javascript var lightboxQuarto = GLightbox({"closeEffect":"zoom","descPosition":"bottom","loop":false,"openEffect":"zoom","selector":".lightbox"}); (function() { let previousOnload = window.onload; window.onload = () => { if (previousOnload) { previousOnload(); } lightboxQuarto.on('slide_before_load', (data) => { const { slideIndex, slideNode, slideConfig, player, trigger } = data; const href = trigger.getAttribute('href'); if (href !== null) { const imgEl = window.document.querySelector(`a[href="${href}"] img`); if (imgEl !== null) { const srcAttr = imgEl.getAttribute("src"); if (srcAttr && srcAttr.startsWith("data:")) { slideConfig.href = srcAttr; } } } }); lightboxQuarto.on('slide_after_load', (data) => { const { slideIndex, slideNode, slideConfig, player, trigger } = data; if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(slideNode); } }); }; })(); ``` -------------------------------- ### Website Configuration Source: https://llmstxt.org/ Configuration object for website features, potentially related to search or navigation. It specifies settings like panel placement, search shortcuts, and language-specific search UI text. ```json { "location": "navbar", "copy-button": false, "collapse-after": 3, "panel-placement": "end", "type": "overlay", "limit": 50, "keyboard-shortcut": [ "f", "/", "s" ], "show-item-context": false, "language": { "search-no-results-text": "No results", "search-matching-documents-text": "matching documents", "search-copy-link-title": "Copy link to search", "search-hide-matches-text": "Hide additional matches", "search-more-match-text": "more match in this document", "search-more-matches-text": "more matches in this document", "search-clear-button-title": "Clear", "search-text-placeholder": "", "search-detached-cancel-button-title": "Cancel", "search-submit-button-title": "Submit", "search-label": "Search" } } ``` -------------------------------- ### Batch Image Generation Function Source: https://superduperai.co/docs/image-generation An asynchronous function to generate multiple images concurrently from a list of prompts. It utilizes Promise.all for efficient parallel execution and waits for all generations to complete. ```typescript const generateBatch = async (prompts: string[], model = 'comfyui/flux') => { // Assume generateImage is defined elsewhere // const generations = prompts.map(prompt => generateImage(prompt, model)); // const imageIds = await Promise.all(generations); // Mocking imageIds for demonstration const imageIds = prompts.map((_, i) => `mock-id-${i}`); // Wait for all to complete // const imageUrls = await Promise.all( // imageIds.map(id => waitForImage(id)) // ); // Mocking imageUrls for demonstration const imageUrls = imageIds.map(id => `http://example.com/batch/${id}.png`); return imageUrls; }; // Usage example: // const urls = await generateBatch([ // "Red sports car", // "Blue mountain landscape", // "Modern office interior" // ]); // console.log(urls); ``` -------------------------------- ### SuperDuperAI Video Generation Models Source: https://superduperai.co/docs/video-generation Details the available AI models for video generation, categorized by pricing tiers (Budget-Friendly and Premium). Includes model names, types, pricing per second, estimated costs for 5-second videos, and primary use cases or providers. ```APIDOC SuperDuperAI Video Generation Models: Budget-Friendly Models (No VIP Required): - Model: `comfyui/ltx` Type: Image-to-Video Price/sec: $0.40 5-sec Cost: $2.00 Best For: Animating images - Model: `comfyui/lip-sync` Type: Video-to-Video Price/sec: $0.40 5-sec Cost: $2.00 Best For: Lip synchronization Premium Models (VIP Required): Text-to-Video (3 models): - Model: `google-cloud/veo2-text2video` Duration Options: 5-8 seconds Price/sec: $2.00 5-sec Cost: $10.00 Provider: Google Cloud - Model: `google-cloud/veo3-text2video` Duration Options: 5-8 seconds Price/sec: $3.00 5-sec Cost: $15.00 Provider: Google Cloud - Model: `azure-openai/sora` Duration Options: 5-20 seconds Price/sec: $2.00 5-sec Cost: $10.00 Provider: Azure OpenAI Image-to-Video (6 models): - Model: `fal-ai/kling-video/v2.1/standard/image-to-video` Duration Options: 5-10 seconds Price/sec: $1.00 5-sec Cost: $5.00 Provider: FAL AI - Model: `fal-ai/minimax/video-01/image-to-video` Duration Options: 5 seconds Price/sec: $1.20 5-sec Cost: $6.00 Provider: FAL AI - Model: `fal-ai/minimax/video-01-live/image-to-video` Duration Options: 5 seconds Price/sec: $1.20 5-sec Cost: $6.00 Provider: FAL AI - Model: `google-cloud/veo2` Duration Options: 5-8 seconds Price/sec: $2.00 5-sec Cost: $10.00 Provider: Google Cloud - Model: `fal-ai/kling-video/v2.1/pro/image-to-video` Duration Options: 5-10 seconds Price/sec: $2.00 5-sec Cost: $10.00 Provider: FAL AI - Model: `google-cloud/veo3` Duration Options: 5-8 seconds Price/sec: $3.00 5-sec Cost: $15.00 Provider: Google Cloud ``` -------------------------------- ### API Response Structure for File Objects Source: https://superduperai.co/docs/image-generation Defines the expected structure of the response when querying for generated files. It includes identifiers, generation details, and status information for the generated images. ```apidoc API Response Structure: [ { "id": "string", // Unique identifier for the file object "image_generation_id": "string", // Identifier for the specific image generation task "image_generation": { "generation_config": { "name": "string", // Name of the generation configuration used (e.g., "comfyui/flux") "price_per_generation": "number" // Cost associated with this generation } }, "url": "string | null", // URL to the generated image, null if not ready "thumbnail_url": "string | null", // URL to the thumbnail, null if not ready "tasks": [] // Array of tasks associated with the generation, empty when complete } ] ``` -------------------------------- ### React Component for Video Generation Source: https://superduperai.co/docs/video-generation A React component demonstrating how to integrate video generation functionality. It manages loading states, progress updates, and displays the generated video or error messages. ```typescript import React, { useState } from 'react'; // Assume generateVideo and waitForVideo are imported or defined elsewhere // const generateVideo = async (prompt: string): Promise => { ... }; // const waitForVideo = async (videoId: string): Promise => { ... }; const VideoGeneratorComponent: React.FC = () => { const [loading, setLoading] = useState(false); const [videoUrl, setVideoUrl] = useState(null); const [progress, setProgress] = useState(0); const handleGenerateVideo = async (prompt: string) => { setLoading(true); setProgress(0); setVideoUrl(null); try { // Placeholder for actual video generation call // const videoId = await generateVideo(prompt); const videoId = 'mock-video-id'; // Mock ID for example // Simulate polling with progress updates const progressInterval = setInterval(() => { setProgress(prev => { if (prev >= 90) { clearInterval(progressInterval); return 90; } return prev + 10; }); }, 10000); // Update every 10 seconds // Placeholder for actual video waiting call // const url = await waitForVideo(videoId); const url = 'http://example.com/mock-video.mp4'; // Mock URL clearInterval(progressInterval); setProgress(100); setVideoUrl(url); } catch (error) { console.error('Video generation failed:', error); setProgress(0); // Reset progress on error } finally { setLoading(false); } }; return (
{loading && (
Generating video... {progress}%
)} {videoUrl && (

Generated Video:

)}
); }; export default VideoGeneratorComponent; ``` -------------------------------- ### ClipboardJS for Copy-to-Clipboard Functionality Source: https://llmstxt.org/ Initializes ClipboardJS to enable copy-to-clipboard functionality for elements with the 'code-copy-button' class. It handles copying code content, including annotations, and provides visual feedback on success. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } const onCopySuccess = function(e) { const button = e.trigger; button.blur(); button.classList.add('code-copy-button-checked'); var currentTitle = button.getAttribute("title"); button.setAttribute("title", "Copied!"); let tooltip; if (window.bootstrap) { button.setAttribute("data-bs-toggle", "tooltip"); button.setAttribute("data-bs-placement", "left"); button.setAttribute("data-bs-title", "Copied!"); tooltip = new bootstrap.Tooltip(button, { trigger: "manual", customClass: "code-copy-button-tooltip", offset: [0, -8] }); tooltip.show(); } setTimeout(function() { if (tooltip) { tooltip.hide(); button.removeAttribute("data-bs-title"); button.removeAttribute("data-bs-toggle"); button.removeAttribute("data-bs-placement"); } button.setAttribute("title", currentTitle); button.classList.remove('code-copy-button-checked'); }, 1000); e.clearSelection(); } const getTextToCopy = function(trigger) { const codeEl = trigger.previousElementSibling.cloneNode(true); for (const childEl of codeEl.children) { if (isCodeAnnotation(childEl)) { childEl.remove(); } } return codeEl.innerText; } const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', { text: getTextToCopy }); clipboard.on('success', onCopySuccess); if (window.document.getElementById('quarto-embedded-source-code-modal')) { const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', { text: getTextToCopy, container: window.document.getElementById('quarto-embedded-source-code-modal') }); clipboardModal.on('success', onCopySuccess); } ``` -------------------------------- ### Tippy.js Tooltip Initialization Source: https://llmstxt.org/ Defines a helper function `tippyHover` to initialize tippy.js tooltips with custom configurations for content, triggers, and themes. This is used for enhancing elements like footnote references. ```JavaScript function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { const config = { allowHTML: true, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Robust Image Generation with Retries Source: https://superduperai.co/docs/image-generation A function designed for resilient image generation, incorporating automatic retries with exponential backoff in case of transient errors. It handles potential failures during the generation process. ```typescript const robustImageGeneration = async (prompt: string, retries = 3) => { for (let attempt = 1; attempt <= retries; attempt++) { try { const response = await optimizedGeneration(prompt); if (response.ok) { return await response.json(); } // Handle non-2xx responses if necessary console.error(`Attempt ${attempt} failed with status: ${response.status}`); } catch (error) { console.error(`Attempt ${attempt} failed with error:`, error); } // Exponential backoff if (attempt < retries) { await new Promise(r => setTimeout(r, 1000 * attempt)); } } throw new Error('Image generation failed after multiple retries.'); }; ``` -------------------------------- ### Cross-Reference Processing and Tooltip Integration Source: https://llmstxt.org/ This snippet details the logic for processing cross-references (xrefs) within a web page. It utilizes tippy.js for hover-based tooltips, fetching content for external links, parsing HTML, and rendering processed content. It includes error handling for URL parsing and content fetching, and dynamically enables/shows tooltips. ```javascript function processXRef(id, note) { let container = window.document.createElement("div"); if (note.children.length > 0) { for (var i = 0; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } } for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) {}); } ``` -------------------------------- ### Polling for Generation Completion Source: https://superduperai.co/docs/image-generation Provides a robust method for polling the API to check the status of an image generation task. It includes a timeout mechanism to prevent indefinite waiting and polls at regular intervals. ```typescript const pollForCompletion = async (fileId: string, timeout = 300000) => { const startTime = Date.now(); while (Date.now() - startTime setTimeout(r, 2000)); // Poll every 2 seconds } throw new Error('Generation timeout'); }; ``` -------------------------------- ### VitePress Plugin for llms.txt Source: https://llmstxt.org/ A VitePress plugin designed to automatically generate LLM-friendly documentation from files adhering to the llms.txt specification, enhancing content discoverability for AI models. ```javascript // vitepress-plugin-llms configuration example // In your vitepress config file (e.g., vite.config.js or vite.config.ts) import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import llmsPlugin from 'vitepress-plugin-llms'; export default defineConfig({ plugins: [ vue(), llmsPlugin({ // Plugin options can be configured here // For example, specifying the path to llms.txt files llmsTxtPath: '/docs/llms.txt', // Other options like output format, etc. }) ] }); ``` -------------------------------- ### Optimized Image Generation Function Source: https://superduperai.co/docs/image-generation An asynchronous function to generate images with optimized parameters. It accepts a prompt and optional configuration for model, size, and quality, making API calls to the generation endpoint. ```typescript const optimizedGeneration = async (prompt: string, options = {}) => { const { model = 'comfyui/flux', size = 'large', quality = 'hd' } = options; const sizes = { small: { width: 512, height: 512 }, medium: { width: 768, height: 768 }, large: { width: 1024, height: 1024 }, ultra: { width: 1536, height: 1536 } }; return fetch(`${API_BASE}/file/generate-image`, { method: 'POST', headers, body: JSON.stringify({ config: { prompt, generation_config_name: model, params: { ...sizes[size], quality, // Auto-optimization enabled enhance: true, seed: Math.floor(Math.random() * 1000000) // For reproducible results } } }) }); }; ``` -------------------------------- ### Initialize DOMContentLoaded Listener Source: https://llmstxt.org/ Sets up an event listener for the DOMContentLoaded event to initialize various interactive features on the page, such as anchor link generation and copy-to-clipboard functionality. ```JavaScript window.document.addEventListener("DOMContentLoaded", function (event) { const icon = ""; const anchorJS = new window.AnchorJS(); anchorJS.options = { placement: 'right', icon: icon }; anchorJS.add('.anchored'); const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } const onCopySuccess = function(e) { // button target const button = e.trigger; // don't keep focus button.blur(); // flash "checked" button.classList.add('code-copy-button-checked'); var currentTitle = button.getAttribute("title"); button.setAttribute("title", "Copied!"); let tooltip; if (window.bootstrap) { button.setAttribute("data-bs-toggle", "tooltip"); button.setAttribute("data-bs-placement", "left"); button.setAttribute("data-bs-title", "Copied!"); tooltip = new bootstrap.Tooltip(button, { trigger: "manual", customClass: "code-copy-button-tooltip", offset: [0, -8] }); tooltip.show(); } setTimeout(function() { if (tooltip) { tooltip.hide(); button.removeAttribute("data-bs-title"); button.removeAttribute("data-bs-toggle"); button.removeAttribute("data-bs-placement"); } button.setAttribute("title", currentTitle); button.classList.remove('code-copy-button-checked'); }, 1000); // clear code selection e.clearSelection(); } const getTextToCopy = function(trigger) { const codeEl = trigger.previousElementSibling.cloneNode(true); for (const childEl of codeEl.children) { if (isCodeAnnotation(childEl)) { childEl.remove(); } } return codeEl.innerText; } const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', { text: getTextToCopy }); clipboard.on('success', onCopySuccess); if (window.document.getElementById('quarto-embedded-source-code-modal')) { const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', { text: getTextToCopy, container: window.document.getElementById('quarto-embedded-source-code-modal') }); clipboardModal.on('success', onCopySuccess); } var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//); var mailtoRegex = new RegExp(/^mailto:/); var filterRegex = new RegExp("https:\/\/llmstxt.org\/"); var isInternal = (href) => { return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href); } // Inspect non-navigation links and adorn them if external var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)'); for (var i=0; i { // Strip column container classes const stripColumnClz = (el) => { el.classList.remove("page-full", "page-columns"); if (el.children) { for (const child of el.children) { stripColumnClz(child); } } } stripColumnClz(note) if (id === null || id.startsWith('sec-')) { // Special case sections, only their first couple elements const container = document.createElement("div"); if (note.children && note.children.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i] if (child.tag ``` -------------------------------- ### Robust Video Generation with Retries Source: https://superduperai.co/docs/video-generation Implements a robust video generation function that includes error handling and automatic retries. It attempts the generation process multiple times with exponential backoff delays in case of failures. ```typescript const robustVideoGeneration = async ( prompt: string, model = 'comfyui/ltx', maxRetries = 2 ) => { for (let attempt = 1; attempt <= maxRetries; attempt++) { try { const response = await fetch(`${API_BASE}/file/generate-video`, { method: 'POST', headers, body: JSON.stringify({ config: { prompt, generation_config_name: model, params: { duration: 5, aspect_ratio: '16:9', quality: 'hd' } } }) }); if (!response.ok) { throw new Error(`API error: ${response.statusText}`); } const fileData = await response.json(); return await waitForVideo(fileData.id); } catch (error) { console.error(`Attempt ${attempt} failed:`, error); if (attempt === maxRetries) { throw error; // Re-throw the last error if all retries fail } // Wait before retrying with exponential backoff await new Promise(r => setTimeout(r, 5000 * attempt)); } } }; ``` -------------------------------- ### Drupal LLM Support Module Source: https://llmstxt.org/ A Drupal Recipe providing comprehensive support for the llms.txt proposal on Drupal 10.3+ sites, enabling LLM-friendly content generation and integration within the Drupal ecosystem. ```php // Example of how Drupal LLM Support might be configured or used. // This is conceptual as it's a Drupal Recipe. // In a Drupal module or configuration file: // Assuming a service or API endpoint is provided by the module // Example: Fetching LLM context for a node // $node_id = 123; // $llm_context = Drupal::service('llm_support.context_generator')->getNodeContext($node_id); // Or via Drush command: // drush llm-support:generate-context --node-id=123 // The module would likely parse content and potentially llms.txt files // associated with nodes or site structure. ``` -------------------------------- ### Configure AnchorJS for Anchored Elements Source: https://llmstxt.org/ Configures AnchorJS to add anchor links to elements with the 'anchored' class, specifying placement and icon for improved navigation. ```JavaScript const icon = ""; const anchorJS = new window.AnchorJS(); anchorJS.options = { placement: 'right', icon: icon }; anchorJS.add('.anchored'); ```