A powerful TypeScript library for building structured prompts using proven prompt engineering frameworks
npm install prompt-fluent-jstypescript
// Scattered, unstructured prompt building
const prompt =
;
// Issues:
// ā No standardization
// ā Hard to reuse components
// ā Difficult to validate
// ā No type safety
// ā Inconsistent structure across team
// ā Manual string concatenation prone to errors
`
$3
Clean, structured, and maintainable prompt building:
`typescript
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 standardization
`
Result: 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
`bash
npm install prompt-fluent-js
`
`bash
yarn add prompt-fluent-js
`
`bash
pnpm add prompt-fluent-js
`
š Quick Start
`typescript
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.
$3
`typescript
// 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();
`
$3
`typescript
// 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();
`
$3
`typescript
// 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();
`
$3
`typescript
// 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();
`
$3
`typescript
// 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();
`
$3
ā
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:
$3
Best for: Simple, straightforward tasks
`typescript
const prompt = createPrompt()
.framework("RTF")
.role("Technical Writer")
.instruction("Write a brief explanation of REST APIs")
.outputFormat("Markdown")
.build();
`
$3
Best for: Professional content requiring fine-grained control
`typescript
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();
`
$3
Best for: Tasks requiring consistent output with examples
`typescript
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();
`
$3
Best for: Enterprise environments with strict requirements
`typescript
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();
`
$3
Best for: Simple automation and data transformation
`typescript
const prompt = createPrompt()
.framework("TAG")
.instruction("Convert CSV data to JSON format")
.inputData("name,email\nJohn,john@email.com")
.outputFormat("JSON array")
.build();
`
$3
Best for: Quality-first content generation
`typescript
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();
`
$3
Best for: Long-form, highly customized content
`typescript
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
$3
`typescript
createPrompt(): IPromptBuilder
`
Creates a new prompt builder instance.
$3
All methods support fluent chaining and return this for convenience.
#### Framework Selection
`typescript
framework(value: PromptFramework): this
`
Set the prompt framework. Available: 'RTF', 'CO-STAR', 'CARE', 'TRACE', 'TAG', 'ERA', 'CREATE'.
#### Core Attributes
`typescript
role(value: string): this
instruction(value: string): this
context(value: any): this
tone(value: string): this
audience(value: string): this
`
#### Input/Output
`typescript
inputData(value: any): this
outputFormat(format: string): this
outputSchema(schema: any): this
language(lang: string): this
length(value: string | number): this
`
#### Constraints
`typescript
addConstraint(constraint: string): this
constraints(...constraints: string[]): this
addNegativeConstraint(constraint: string): this
negativeConstraints(...constraints: string[]): this
`
#### Examples (Few-Shot Learning)
`typescript
addExample(input: any, output: any): this
examples(examples: Array<{ input: any; output: any }>): this
`
#### Advanced Options
`typescript
chainOfThought(enabled: boolean = true): this
temperature(value: number): this
creativity(level: 'low' | 'medium' | 'high' | 'very-high'): this
`
#### Utility Methods
`typescript
reset(): this
getState(): object
build(overrideFramework?: PromptFramework): string
`
š” Advanced Examples
$3
`typescript
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();
`
$3
`typescript
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();
`
$3
`typescript
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");
`
$3
`typescript
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:
`typescript
// 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:
$3
`typescript
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 }],
});
`
$3
`typescript
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);
`
$3
`typescript
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);
``