prompt-fluent-js
v0.1.0
Published
A powerful TypeScript library for building structured prompts using proven prompt engineering frameworks
Maintainers
Readme
Prompt Fluent JS
A powerful and flexible TypeScript library for building structured prompts for Large Language Models (LLMs) using the Builder pattern and proven prompt engineering frameworks.
🔍 The Problem vs The Solution
❌ Without Prompt Fluent JS
Building prompts manually is messy, inconsistent, and hard to maintain:
// Scattered, unstructured prompt building
const prompt = `
You are an expert Python developer with 10+ years of experience.
Task: Explain the concept of decorators in Python
Context: The explanation should be suitable for beginner programmers who are just learning about functions.
Requirements:
- Use simple language
- Include code examples
- Keep it under 500 words
Tone: Friendly and encouraging
Output Format: Markdown with code blocks
`;
// Issues:
// ❌ No standardization
// ❌ Hard to reuse components
// ❌ Difficult to validate
// ❌ No type safety
// ❌ Inconsistent structure across team
// ❌ Manual string concatenation prone to errors✅ With Prompt Fluent JS
Clean, structured, and maintainable prompt building:
import { createPrompt } from "prompt-fluent-js";
const prompt = createPrompt()
.framework("CO-STAR")
.role("Expert Python developer with 10+ years of experience")
.instruction("Explain the concept of decorators in Python")
.context("The explanation should be suitable for beginner programmers")
.audience("Beginner programmers learning about functions")
.tone("Friendly and encouraging")
.outputFormat("Markdown with code blocks")
.constraints(
"Use simple language",
"Include code examples",
"Keep it under 500 words"
)
.build();
// Benefits:
// ✅ Follows proven prompt engineering frameworks
// ✅ Fully reusable and composable
// ✅ Type-safe with TypeScript
// ✅ Consistent structure guaranteed
// ✅ Easy to test and validate
// ✅ Team-wide standardizationResult: Better prompts, faster development, and more consistent AI outputs! 🚀
🎯 Why Prompt Fluent JS?
Building effective prompts for LLMs can be challenging and inconsistent. Prompt Fluent JS solves this by providing:
- ✨ Structured Approach: Use battle-tested prompt engineering frameworks
- 🔧 Fluent API: Intuitive, chainable method calls for building prompts
- 📦 Type-Safe: Full TypeScript support with comprehensive type definitions
- 🎨 7 Frameworks: Choose from RTF, CO-STAR, CARE, TRACE, TAG, ERA, and CREATE
- 🚀 Zero Dependencies: Lightweight and fast
- 🔄 Flexible: Switch frameworks on-the-fly or build custom structures
- 📝 Well-Documented: Extensive documentation and examples
📦 Installation
npm install prompt-fluent-jsyarn add prompt-fluent-jspnpm add prompt-fluent-js🚀 Quick Start
import { createPrompt } from "prompt-fluent-js";
const prompt = createPrompt()
.framework("CO-STAR")
.role("Expert Python Developer")
.instruction("Explain the concept of decorators in Python")
.audience("Beginner programmers")
.tone("Friendly and encouraging")
.outputFormat("Markdown with code examples")
.build();
console.log(prompt);🔄 Reusability & Constants
One of the most powerful features of Prompt Fluent JS is the ability to reuse prompt components and create reusable constants. This promotes consistency across your application and follows the DRY (Don't Repeat Yourself) principle.
📦 Creating Reusable Roles
// roles.ts
export const ROLES = {
PYTHON_EXPERT: "Expert Python developer with 10+ years of experience",
TECH_WRITER:
"Senior technical writer specializing in developer documentation",
DATA_SCIENTIST:
"Data scientist with expertise in machine learning and statistics",
CODE_REVIEWER:
"Senior software engineer focused on code quality and best practices",
};
// usage.ts
import { createPrompt } from "prompt-fluent-js";
import { ROLES } from "./roles";
const prompt = createPrompt()
.role(ROLES.PYTHON_EXPERT)
.instruction("Explain decorators")
.build();🎯 Reusable Constraints
// constraints.ts
export const COMMON_CONSTRAINTS = {
CODE_QUALITY: [
"Follow language best practices",
"Include error handling",
"Add helpful comments",
],
DOCUMENTATION: [
"Use clear, concise language",
"Include code examples",
"Explain edge cases",
],
OUTPUT_FORMAT: [
"Use proper markdown formatting",
"Structure content with headers",
"Include a summary section",
],
};
// usage.ts
const prompt = createPrompt()
.instruction("Write a Python function")
.constraints(...COMMON_CONSTRAINTS.CODE_QUALITY)
.constraints(...COMMON_CONSTRAINTS.DOCUMENTATION)
.build();🧩 Partial Prompt Templates
// templates.ts
import { createPrompt } from "prompt-fluent-js";
// Base template for code generation
export const codeGenerationTemplate = () =>
createPrompt()
.framework("CO-STAR")
.role("Expert Software Engineer")
.tone("Professional and precise")
.outputFormat("Markdown with code blocks")
.constraints(
"Follow industry best practices",
"Include error handling",
"Add inline comments for clarity"
);
// Base template for data extraction
export const dataExtractionTemplate = () =>
createPrompt()
.framework("CARE")
.outputFormat("JSON")
.constraints(
"Preserve all relevant information",
"Use consistent field names",
"Validate data types"
);
// usage.ts - Reuse and customize templates
const pythonPrompt = codeGenerationTemplate()
.instruction("Create a function to validate email addresses")
.language("Python")
.build();
const jsPrompt = codeGenerationTemplate()
.instruction("Create a function to validate email addresses")
.language("JavaScript")
.build();🏭 Factory Pattern for Team Consistency
// promptFactory.ts
import { createPrompt } from "prompt-fluent-js";
export class CompanyPromptFactory {
private static readonly DEFAULT_CONSTRAINTS = [
"Follow company style guide",
"Ensure GDPR compliance",
"Use inclusive language",
];
static createDocumentationPrompt(instruction: string) {
return createPrompt()
.framework("CO-STAR")
.role("Technical Documentation Specialist")
.instruction(instruction)
.tone("Professional and clear")
.constraints(...this.DEFAULT_CONSTRAINTS)
.outputFormat("Markdown");
}
static createCodeReviewPrompt(code: string, language: string) {
return createPrompt()
.framework("TRACE")
.role("Senior Code Reviewer")
.instruction("Review the provided code and suggest improvements")
.inputData(code)
.context(`Programming language: ${language}`)
.constraints(
...this.DEFAULT_CONSTRAINTS,
"Focus on security, performance, and maintainability",
"Provide specific examples for improvements"
);
}
static createDataTransformPrompt(inputData: any, targetSchema: any) {
return createPrompt()
.framework("CARE")
.instruction("Transform input data to match the target schema")
.inputData(inputData)
.outputSchema(targetSchema)
.constraints(...this.DEFAULT_CONSTRAINTS);
}
}
// usage.ts
const docPrompt = CompanyPromptFactory.createDocumentationPrompt(
"Document the authentication API"
).build();
const reviewPrompt = CompanyPromptFactory.createCodeReviewPrompt(
myCode,
"TypeScript"
).build();🔧 Configuration Objects
// config.ts
export const PROMPT_CONFIGS = {
blog: {
framework: "CREATE" as const,
role: "Professional Content Writer",
tone: "Engaging and informative",
constraints: [
"SEO-optimized",
"Include actionable takeaways",
"Use short paragraphs for readability",
],
length: "1500-2000 words",
},
codeGen: {
framework: "CO-STAR" as const,
role: "Senior Software Developer",
outputFormat: "Code with comments",
constraints: [
"Production-ready code",
"Include unit tests",
"Follow SOLID principles",
],
},
};
// Apply configuration
const blogPrompt = createPrompt()
.framework(PROMPT_CONFIGS.blog.framework)
.role(PROMPT_CONFIGS.blog.role)
.tone(PROMPT_CONFIGS.blog.tone)
.constraints(...PROMPT_CONFIGS.blog.constraints)
.length(PROMPT_CONFIGS.blog.length)
.instruction("Write about AI trends in 2026")
.build();💡 Benefits of Reusability
✅ Consistency: Same prompts across your application
✅ Maintainability: Update once, apply everywhere
✅ Team Alignment: Shared templates ensure uniform output quality
✅ Version Control: Track changes to prompts over time
✅ Testing: Test prompt templates independently
✅ DRY Principle: Don't repeat yourself - reuse components
This approach is especially powerful in microservices, CI/CD pipelines, and enterprise applications where consistency and maintainability are critical!
📚 Frameworks
Prompt Fluent JS supports 7 different prompt engineering frameworks, each optimized for specific use cases:
🎯 RTF (Role, Task, Format)
Best for: Simple, straightforward tasks
const prompt = createPrompt()
.framework("RTF")
.role("Technical Writer")
.instruction("Write a brief explanation of REST APIs")
.outputFormat("Markdown")
.build();⭐ CO-STAR (Context, Objective, Style, Tone, Audience, Response)
Best for: Professional content requiring fine-grained control
const prompt = createPrompt()
.framework("CO-STAR")
.context("We are building a new e-commerce platform")
.instruction("Generate product descriptions")
.tone("Professional and persuasive")
.audience("Online shoppers aged 25-45")
.outputFormat("JSON")
.constraints("Keep descriptions under 150 words", "Focus on benefits")
.build();🎯 CARE (Context, Action, Result, Example)
Best for: Tasks requiring consistent output with examples
const prompt = createPrompt()
.framework("CARE")
.context("Converting customer feedback to structured data")
.instruction("Extract sentiment and key topics")
.addExample(
"The product is amazing but shipping was slow",
'{ "sentiment": "mixed", "topics": ["product_quality", "shipping_speed"] }'
)
.outputFormat("JSON")
.build();🏢 TRACE (Task, Role, Audience, Context, Expectations)
Best for: Enterprise environments with strict requirements
const prompt = createPrompt()
.framework("TRACE")
.instruction("Generate quarterly business report")
.role("Business Analyst")
.audience("C-level executives")
.context("Q4 2025 performance data")
.constraints(
"Must include financial metrics",
"Follow company style guide",
"Maximum 2 pages"
)
.build();⚡ TAG (Task, Action, Goal)
Best for: Simple automation and data transformation
const prompt = createPrompt()
.framework("TAG")
.instruction("Convert CSV data to JSON format")
.inputData("name,email\nJohn,[email protected]")
.outputFormat("JSON array")
.build();🎖️ ERA (Expectation, Role, Action)
Best for: Quality-first content generation
const prompt = createPrompt()
.framework("ERA")
.constraints(
"Must be technically accurate",
"Use clear, concise language",
"Include code examples"
)
.role("Senior Software Engineer")
.instruction("Document the authentication flow")
.build();🎨 CREATE (Character, Request, Examples, Additions, Type, Extras)
Best for: Long-form, highly customized content
const prompt = createPrompt()
.framework("CREATE")
.role("Educational content creator specializing in programming")
.instruction("Create a comprehensive tutorial on async/await")
.context("Target audience has basic JavaScript knowledge")
.addExample(
"Basic promise",
"fetch(url).then(res => res.json()).then(data => console.log(data))"
)
.outputFormat("Markdown with code blocks")
.constraints("Include practical examples", "Explain common pitfalls")
.language("English")
.length("2000-3000 words")
.build();🔧 API Reference
Factory Function
createPrompt(): IPromptBuilderCreates a new prompt builder instance.
Builder Methods
All methods support fluent chaining and return this for convenience.
Framework Selection
framework(value: PromptFramework): thisSet the prompt framework. Available: 'RTF', 'CO-STAR', 'CARE', 'TRACE', 'TAG', 'ERA', 'CREATE'.
Core Attributes
role(value: string): this
instruction(value: string): this
context(value: any): this
tone(value: string): this
audience(value: string): thisInput/Output
inputData(value: any): this
outputFormat(format: string): this
outputSchema(schema: any): this
language(lang: string): this
length(value: string | number): thisConstraints
addConstraint(constraint: string): this
constraints(...constraints: string[]): this
addNegativeConstraint(constraint: string): this
negativeConstraints(...constraints: string[]): thisExamples (Few-Shot Learning)
addExample(input: any, output: any): this
examples(examples: Array<{ input: any; output: any }>): thisAdvanced Options
chainOfThought(enabled: boolean = true): this
temperature(value: number): this
creativity(level: 'low' | 'medium' | 'high' | 'very-high'): thisUtility Methods
reset(): this
getState(): object
build(overrideFramework?: PromptFramework): string💡 Advanced Examples
Complex Data Transformation
const prompt = createPrompt()
.framework("CARE")
.context("E-commerce product data needs standardization")
.instruction("Transform raw product data into our standard schema")
.inputData({
title: "iPhone 15 Pro",
cost: 999,
category: "electronics",
})
.addExample(
{ title: "Samsung Galaxy", cost: 899, category: "electronics" },
{
name: "Samsung Galaxy",
price: { amount: 899, currency: "USD" },
category: { primary: "Electronics", subcategory: "Smartphones" },
}
)
.outputSchema({
name: "string",
price: { amount: "number", currency: "string" },
category: { primary: "string", subcategory: "string" },
})
.constraints(
"Preserve all information",
"Standardize category names",
"Add currency as USD if not specified"
)
.build();Content Generation with Multiple Constraints
const prompt = createPrompt()
.framework("CO-STAR")
.context("Creating blog content for a tech startup")
.instruction("Write an engaging blog post about AI trends in 2026")
.role("Senior Tech Content Writer")
.tone("Professional yet approachable")
.audience("Tech-savvy professionals and decision makers")
.outputFormat("Markdown with sections")
.constraints(
"Include real-world examples",
"Back claims with data or research",
"SEO-optimized with relevant keywords"
)
.negativeConstraints(
"Avoid technical jargon without explanation",
"No promotional language",
"Don't make unsubstantiated claims"
)
.length("1500-2000 words")
.language("English")
.creativity("medium")
.build();Dynamic Framework Switching
const builder = createPrompt()
.role("Software Architect")
.instruction("Design a microservices architecture")
.context("E-commerce platform with 1M users");
// Try different frameworks
const simplePrompt = builder.build("TAG");
const detailedPrompt = builder.build("CO-STAR");
const enterprisePrompt = builder.build("TRACE");Chain of Thought Reasoning
const prompt = createPrompt()
.framework("CO-STAR")
.role("Math Tutor")
.instruction("Solve this word problem step by step")
.inputData(
"If a train travels 120 km in 2 hours, how far will it travel in 5 hours at the same speed?"
)
.chainOfThought(true)
.audience("Middle school students")
.outputFormat("Show each step clearly")
.build();🛠️ Type Conversion
The library automatically handles type conversion for context, inputData, and examples:
// Strings: used as-is
.context('Background information')
// Objects: converted to formatted JSON
.context({ user: 'John', role: 'admin' })
// Arrays: converted to formatted JSON
.inputData(['item1', 'item2', 'item3'])
// Numbers: converted to strings
.inputData(42)
// Booleans: converted to strings
.context(true)📖 Framework Selection Guide
| Framework | Complexity | Use Case | Strength | | --------- | ---------- | -------------------- | ------------- | | RTF | Low | Simple tasks | Simplicity | | CO-STAR | High | Professional content | Completeness | | CARE | Medium | Consistent output | Examples | | TRACE | High | Enterprise | Expectations | | TAG | Low | Automation | Minimalism | | ERA | Medium | Quality-first | Standards | | CREATE | High | Long-form content | Customization |
Integration Examples
Prompt Fluent JS works seamlessly with any LLM provider:
OpenAI
import { createPrompt } from "prompt-fluent-js";
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const prompt = createPrompt()
.framework("CO-STAR")
.role("Expert developer")
.instruction("Explain async/await")
.build();
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: prompt }],
});Google Gemini
import { createPrompt } from "prompt-fluent-js";
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = createPrompt()
.framework("CARE")
.instruction("Extract data from text")
.build();
const result = await model.generateContent(prompt);LangChain
import { createPrompt } from "prompt-fluent-js";
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({ modelName: "gpt-4" });
const prompt = createPrompt()
.framework("TRACE")
.instruction("Generate report")
.build();
const response = await llm.invoke(prompt);🤝 Contributing
Contributions are welcome! This is an open-source project under the MIT license.
📄 License
MIT License - see LICENSE file for details.
👨💻 Author
Rafael
Built with ❤️ for the developer community. Happy prompting! 🚀
