# prompts.chat prompts.chat is an open-source AI prompt library and developer toolkit that enables users to discover, share, and create AI prompts for various applications. The platform combines a Next.js web application (prompts.chat-v2) with a developer-focused npm package (`prompts.chat`) that provides utilities for prompt engineering, variable detection, similarity checking, and structured prompt building. The project serves as both a community-driven prompt marketplace with features like voting, collections, comments, and user profiles, as well as a programmatic toolkit for developers who need to work with prompts in their applications. Key capabilities include a fluent DSL for building structured prompts, multi-format parsing (YAML, JSON, Markdown), variable normalization across different syntaxes, content similarity detection for duplicate prevention, and local quality validation. ## REST API Endpoints ### List Prompts Retrieves paginated public prompts with filtering and sorting options. Supports filtering by type, category, tags, and text search query. ```bash # Get first page of prompts curl "https://prompts.chat/api/prompts?page=1&perPage=24" # Filter by type and category curl "https://prompts.chat/api/prompts?type=TEXT&category=coding&sort=upvotes" # Search with multiple tags (comma-separated) curl "https://prompts.chat/api/prompts?tag=coding,productivity&q=react" # Response structure { "prompts": [ { "id": "clx...", "title": "Code Review Assistant", "slug": "code-review-assistant", "description": "Reviews code for best practices", "content": "You are an expert code reviewer...", "type": "TEXT", "author": { "id": "...", "name": "John", "username": "john", "verified": true }, "category": { "id": "...", "name": "Development", "slug": "development" }, "tags": [{ "tag": { "id": "...", "name": "coding", "slug": "coding" }}], "voteCount": 42, "contributorCount": 3 } ], "total": 150, "page": 1, "perPage": 24, "totalPages": 7 } ``` ### Create Prompt Creates a new prompt with validation, duplicate detection, and automatic quality checking. Requires authentication. ```bash curl -X POST "https://prompts.chat/api/prompts" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "title": "TypeScript Code Reviewer", "description": "Reviews TypeScript code for bugs and best practices", "content": "You are a senior TypeScript developer. Review the following code:\n\n${code}\n\nProvide feedback on:\n1. Type safety\n2. Error handling\n3. Best practices", "type": "TEXT", "categoryId": "category-id-here", "tagIds": ["tag-id-1", "tag-id-2"], "isPrivate": false, "bestWithModels": ["gpt-4", "claude-3"], "structuredFormat": "JSON" }' # Success response { "id": "clx...", "title": "TypeScript Code Reviewer", "slug": "typescript-code-reviewer", "content": "You are a senior TypeScript developer...", "type": "TEXT", "author": { "id": "...", "name": "...", "username": "...", "verified": false } } # Error responses # 401 - Unauthorized: { "error": "unauthorized", "message": "You must be logged in" } # 409 - Duplicate: { "error": "content_exists", "existingPromptSlug": "existing-prompt" } # 429 - Rate limit: { "error": "rate_limit", "message": "Please wait 30 seconds..." } ``` ### Get Single Prompt Retrieves a specific prompt by ID with author info, tags, categories, and version history. ```bash curl "https://prompts.chat/api/prompts/clx123abc" # Response { "id": "clx123abc", "title": "Code Review Assistant", "slug": "code-review-assistant", "content": "You are an expert code reviewer...", "type": "TEXT", "author": { "id": "...", "name": "John", "username": "john", "verified": true }, "versions": [ { "version": 2, "content": "...", "changeNote": "Added TypeScript support" }, { "version": 1, "content": "...", "changeNote": "Initial version" } ], "voteCount": 42, "hasVoted": false } ``` ### Update Prompt Updates an existing prompt. Only the owner or admins can edit. Creates a new version if content changes. ```bash curl -X PATCH "https://prompts.chat/api/prompts/clx123abc" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "title": "Enhanced Code Review Assistant", "content": "You are an expert code reviewer with 10+ years experience...", "tagIds": ["new-tag-id"], "bestWithModels": ["gpt-4", "claude-3-opus"] }' ``` ### Vote on Prompt Upvote or remove upvote from a prompt. Requires authentication. ```bash # Upvote curl -X POST "https://prompts.chat/api/prompts/clx123abc/vote" \ -H "Authorization: Bearer " # Response: { "voted": true, "voteCount": 43 } # Remove upvote curl -X DELETE "https://prompts.chat/api/prompts/clx123abc/vote" \ -H "Authorization: Bearer " # Response: { "voted": false, "voteCount": 42 } ``` ### Search Prompts Quick search by title with autocomplete support. Minimum 2 characters required. ```bash curl "https://prompts.chat/api/prompts/search?q=code+review&limit=10&ownerOnly=false" # Response { "prompts": [ { "id": "...", "title": "Code Review Assistant", "slug": "code-review-assistant", "author": { "username": "john" }}, { "id": "...", "title": "React Code Reviewer", "slug": "react-code-reviewer", "author": { "username": "jane" }} ] } ``` ### AI-Powered Semantic Search Semantic search using embeddings for finding conceptually similar prompts. ```bash curl "https://prompts.chat/api/search/ai?q=help%20me%20write%20better%20python%20code&limit=20" # Response { "results": [ { "id": "...", "title": "Python Best Practices", "score": 0.95 }, { "id": "...", "title": "Code Quality Reviewer", "score": 0.87 } ], "query": "help me write better python code", "count": 20 } ``` ### Collection Management Save and manage favorite prompts in a personal collection. ```bash # Get user's collection curl "https://prompts.chat/api/collection" \ -H "Authorization: Bearer " # Add to collection curl -X POST "https://prompts.chat/api/collection" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{"promptId": "clx123abc"}' # Response: { "collection": {...}, "added": true } # Remove from collection curl -X DELETE "https://prompts.chat/api/collection?promptId=clx123abc" \ -H "Authorization: Bearer " # Response: { "removed": true } ``` ## NPM Package - prompts.chat ### Installation and Basic Import ```bash npm install prompts.chat ``` ```typescript import { builder, chat, variables, similarity, quality, parser, templates, chatPresets } from 'prompts.chat'; ``` ### Prompt Builder - Fluent DSL Create structured prompts with a fluent API for defining roles, tasks, constraints, and output formats. ```typescript import { builder, templates } from 'prompts.chat'; // Build a structured prompt const codeReviewPrompt = builder() .role("Senior TypeScript Developer") .context("You are reviewing a production Next.js application") .task("Analyze the following code for bugs, performance issues, and best practices") .constraints([ "Be concise but thorough", "Focus on critical issues first", "Suggest specific improvements" ]) .output("JSON with { bugs: [], suggestions: [], overallScore: number }") .variable("code", { required: true, description: "The code to review" }) .example( "function add(a, b) { return a + b }", '{ "bugs": [], "suggestions": ["Add TypeScript types"], "overallScore": 85 }' ) .build(); console.log(codeReviewPrompt.content); // Output: // You are Senior TypeScript Developer. // // ## Context // You are reviewing a production Next.js application // // ## Task // Analyze the following code for bugs, performance issues, and best practices // // ## Constraints // 1. Be concise but thorough // 2. Focus on critical issues first // 3. Suggest specific improvements // // ## Output Format // JSON with { bugs: [], suggestions: [], overallScore: number } // // ## Examples // ### Example 1 // **Input:** function add(a, b) { return a + b } // **Output:** { "bugs": [], "suggestions": ["Add TypeScript types"], "overallScore": 85 } // // ## Variables // - ${code} - The code to review (required) // Using pre-built templates const translatePrompt = templates.translation("English", "Spanish"); const debugPrompt = templates.debug({ language: "TypeScript", errorType: "type mismatch" }); const testPrompt = templates.unitTest({ framework: "Jest", coverage: "comprehensive" }); const sqlPrompt = templates.sql({ dialect: "postgresql", optimize: true }); console.log(translatePrompt.build().content); ``` ### Chat Prompt Builder Build conversational prompts with personas, contexts, reasoning styles, and output formatting. ```typescript import { chat, chatPresets } from 'prompts.chat'; // Build a complex chat prompt const assistantPrompt = chat() .role("helpful coding assistant specialized in React and TypeScript") .tone(['professional', 'friendly']) .expertise(['coding', 'teaching']) .context("Building a production e-commerce application") .audience("intermediate developers learning advanced patterns") .task("Explain the concept and provide working examples") .constraints([ "Use TypeScript with strict mode", "Follow React best practices", "Include error handling" ]) .stepByStep() .detailed() .withExamples() .example( "How do I handle async state in React?", "Use React Query or SWR for server state management..." ) .json({ name: "ResponseFormat", schema: { explanation: "string", codeExample: "string", tips: "string[]" } }) .user("How do I implement optimistic updates?") .build(); console.log(assistantPrompt.systemPrompt); console.log(assistantPrompt.messages); // Array of { role, content } messages // Use presets for common scenarios const coderAssistant = chatPresets.coder("TypeScript") .task("Review this React component") .user("function MyComponent() { ... }"); const tutorAssistant = chatPresets.tutor("Machine Learning") .user("Explain gradient descent"); const jsonResponder = chatPresets.jsonResponder("User", { name: "string", age: "number", email: "string" }).user("Extract user info from: John, 25, john@example.com"); // Export to different formats console.log(assistantPrompt.toJSON()); // JSON string console.log(assistantPrompt.toYAML()); // YAML string console.log(assistantPrompt.toMarkdown()); // Markdown documentation ``` ### Variable Detection and Normalization Detect and normalize variable placeholders across different syntax formats. ```typescript import { variables, detectVariables, compile, extractVariables } from 'prompts.chat'; // Detect variables in different formats const prompt = "Hello {{name}}, you are a [ROLE]. Your task is ${task}."; const detected = variables.detect(prompt); console.log(detected); // [ // { original: "{{name}}", name: "name", pattern: "double_curly", startIndex: 6, endIndex: 14 }, // { original: "[ROLE]", name: "ROLE", pattern: "single_bracket", startIndex: 26, endIndex: 32 } // ] // Normalize all variables to ${var} format const normalized = variables.normalize(prompt); console.log(normalized); // "Hello ${name}, you are a ${role}. Your task is ${task}." // Extract variables from normalized format const vars = extractVariables(normalized); console.log(vars); // [{ name: "name" }, { name: "role" }, { name: "task" }] // Compile a template with values const template = "Hello ${name}, you are a ${role:developer}. Today is ${date}."; const compiled = compile(template, { name: "Alice", date: "Monday" }); console.log(compiled); // "Hello Alice, you are a developer. Today is Monday." // Compile with defaults disabled const compiledNoDefaults = compile(template, { name: "Alice" }, { useDefaults: false }); console.log(compiledNoDefaults); // "Hello Alice, you are a ${role:developer}. Today is ${date}." ``` ### Similarity Detection Compare prompts for content similarity and detect duplicates using Jaccard and n-gram algorithms. ```typescript import { similarity, calculateSimilarity, isSimilarContent, findDuplicates } from 'prompts.chat'; const prompt1 = "You are an expert code reviewer. Review the following code for bugs."; const prompt2 = "You are a skilled code reviewer. Analyze the following code for issues."; const prompt3 = "Write a poem about nature and seasons."; // Calculate similarity score (0-1) const score = similarity.calculate(prompt1, prompt2); console.log(score); // 0.78 - similar prompts const score2 = similarity.calculate(prompt1, prompt3); console.log(score2); // 0.12 - very different // Check if content is duplicate (default threshold 0.85) const isDupe = similarity.isDuplicate(prompt1, prompt2); console.log(isDupe); // false (0.78 < 0.85) const isDupe2 = isSimilarContent(prompt1, prompt2, 0.7); console.log(isDupe2); // true (0.78 >= 0.7) // Find duplicate groups in an array of prompts const prompts = [ { id: 1, content: "You are an expert code reviewer..." }, { id: 2, content: "Write a poem about nature..." }, { id: 3, content: "You are a skilled code reviewer..." }, { id: 4, content: "Create poetry about the natural world..." } ]; const duplicateGroups = findDuplicates(prompts, 0.7); console.log(duplicateGroups); // [ // [{ id: 1, content: "..." }, { id: 3, content: "..." }], // [{ id: 2, content: "..." }, { id: 4, content: "..." }] // ] // Deduplicate keeping first occurrence const unique = similarity.deduplicate(prompts, 0.7); console.log(unique.length); // 2 ``` ### Quality Validation Validate prompt quality locally without API calls. Checks for common issues and provides suggestions. ```typescript import { quality, checkQuality, isValidPrompt, getSuggestions } from 'prompts.chat'; const prompt = `Act as a senior software engineer with 10 years of experience. Your task is to review the provided code and identify: 1. Bugs and potential issues 2. Performance problems 3. Security vulnerabilities Constraints: - Be thorough but concise - Focus on critical issues first - Provide specific code examples for fixes Example: Input: function add(a, b) { return a + b; } Output: { "issues": [], "score": 95 }`; const result = quality.check(prompt); console.log(result); // { // valid: true, // score: 0.92, // issues: [], // stats: { // characterCount: 412, // wordCount: 68, // sentenceCount: 8, // variableCount: 0, // hasRole: true, // hasTask: true, // hasConstraints: true, // hasExamples: true // } // } // Check problematic prompt const badPrompt = "asdf"; const badResult = quality.check(badPrompt); console.log(badResult); // { // valid: false, // score: 0.15, // issues: [ // { type: 'error', code: 'TOO_SHORT', message: 'Prompt is too short (4 chars, minimum 20)' }, // { type: 'warning', code: 'FEW_WORDS', message: 'Prompt has very few words...' } // ] // } // Quick validation const isValid = isValidPrompt(prompt); console.log(isValid); // true // Get improvement suggestions const suggestions = getSuggestions("Write code for me."); console.log(suggestions); // [ // "Add a role definition (e.g., 'Act as a...')", // "Consider adding constraints or rules for better control", // "Consider adding variables (${var}) to make the prompt reusable" // ] ``` ### Prompt Parsing Parse prompts from various file formats (YAML, JSON, Markdown, plain text). ```typescript import { parser, parsePrompt, toYaml, toJson, interpolate, getSystemPrompt } from 'prompts.chat'; // Parse YAML prompt const yamlContent = ` name: Code Reviewer description: Reviews code for quality issues model: gpt-4 modelParameters: temperature: 0.3 maxTokens: 2000 messages: - role: system content: | You are an expert code reviewer. Analyze code for bugs and best practices. - role: user content: "Review this: {{code}}" variables: code: description: The code to review required: true `; const parsed = parser.parse(yamlContent); console.log(parsed); // { // name: "Code Reviewer", // description: "Reviews code for quality issues", // model: "gpt-4", // modelParameters: { temperature: 0.3, maxTokens: 2000 }, // messages: [ // { role: "system", content: "You are an expert code reviewer..." }, // { role: "user", content: "Review this: {{code}}" } // ], // variables: { code: { description: "The code to review", required: true }} // } // Parse JSON prompt const jsonContent = `{ "name": "Translator", "messages": [ { "role": "system", "content": "You are a professional translator." }, { "role": "user", "content": "Translate: {{text}}" } ] }`; const parsedJson = parser.parse(jsonContent, 'json'); // Parse Markdown with frontmatter const mdContent = `--- name: Writing Assistant model: claude-3 --- You are a skilled writing assistant. Help the user improve their writing.`; const parsedMd = parser.parse(mdContent, 'markdown'); // Interpolate variables const withValues = interpolate(parsed, { code: "function add(a,b) { return a+b }" }); console.log(withValues.messages[1].content); // "Review this: function add(a,b) { return a+b }" // Convert to different formats const asYaml = toYaml(parsed); const asJson = toJson(parsed, true); // pretty-printed // Get system prompt content const systemContent = getSystemPrompt(parsed); console.log(systemContent); // "You are an expert code reviewer..." ``` ### Media Prompt Builders (Image, Video, Audio) Specialized builders for generating prompts for media generation models. ```typescript import { image, video, audio } from 'prompts.chat'; // Build an image generation prompt const imagePrompt = image() .subject({ main: "majestic lion", action: "resting", details: ["golden mane", "intense gaze"] }) .style({ artStyle: "hyperrealistic", mood: "powerful" }) .camera({ angle: "eye-level", shotType: "portrait", lens: "85mm" }) .lighting({ type: "golden-hour", timeOfDay: "sunset", direction: "side" }) .environment({ setting: "African savanna", weather: "clear", atmosphere: "warm" }) .color({ palette: "warm", temperature: "golden", saturation: "rich" }) .composition({ framing: "rule-of-thirds", focus: "sharp", depthOfField: "shallow" }) .technical({ aspectRatio: "3:2", quality: "ultra-high" }) .build(); console.log(imagePrompt.prompt); // "A majestic lion resting with golden mane, intense gaze, in African savanna at sunset, // golden-hour lighting from side, hyperrealistic style, powerful mood, eye-level portrait shot // with 85mm lens, warm color palette, rule-of-thirds composition, shallow depth of field, // 3:2 aspect ratio, ultra-high quality" // Build a video generation prompt const videoPrompt = video() .scene({ description: "Ocean waves crashing on rocks", duration: 5 }) .subject({ main: "lighthouse", action: "standing tall", movement: "static" }) .camera({ movement: "slow-dolly", angle: "low", shotType: "establishing" }) .style({ visualStyle: "cinematic", mood: "dramatic" }) .audio({ ambience: "ocean waves", music: "orchestral" }) .technical({ resolution: "4K", fps: 24 }) .build(); // Build an audio/music generation prompt const audioPrompt = audio() .genre({ primary: "electronic", secondary: ["ambient", "downtempo"] }) .mood({ primary: "atmospheric", energy: "medium" }) .tempo({ bpm: 90, feel: "laid-back" }) .instrumentation({ primary: ["synthesizer", "pads"], secondary: ["soft-drums"] }) .structure({ intro: 8, verse: 16, chorus: 16, outro: 8 }) .production({ style: "modern", mixing: "wide-stereo" }) .build(); ``` ## Summary prompts.chat provides a comprehensive solution for prompt engineering workflows, from discovery and sharing through its web platform to programmatic prompt construction via its npm package. The REST API enables integration with external tools and workflows, supporting prompt management, search, collections, and community features like voting and comments. Developers can query and create prompts programmatically while leveraging AI-powered semantic search. The npm package excels at prompt engineering tasks including building structured prompts with the fluent DSL, normalizing variables across different syntaxes ({{var}}, [VAR], ${var}), detecting duplicate content before submission, validating prompt quality without external APIs, and parsing prompts from multiple file formats. The chat builder with its presets provides model-agnostic conversation prompts with sophisticated reasoning styles (chain-of-thought, step-by-step, first-principles) and output formatting. Together, these tools form a complete toolkit for developers building AI-powered applications that rely on high-quality, reusable prompts.