Skip to content

sabbathandco/prompt-engine-ts

Repository files navigation

🙏 Inspired by ruvnet/Prompt-Engine

This is a complete TypeScript reimplementation that extends the original template concept.


Prompt Engine

A modern, TypeScript-based prompt template engine with built-in security, monitoring, and minimal dependencies.

Features

  • TypeScript First: Full type safety and modern JavaScript features
  • Minimal Dependencies: Only 3 runtime dependencies (zod, isomorphic-dompurify, @google/generative-ai)
  • Progressive Enhancement: Optional YAML/TOML support via dynamic imports
  • Built-in Security: XSS protection, injection detection, and PII masking
  • Production Monitoring: Native Node.js diagnostics channel integration
  • Cost Tracking: Automatic token usage and cost calculation for major LLM providers
  • VS Code Integration: JSON schema support with IntelliSense
  • CLI Tool: Built-in command-line interface using Node.js native features

Quick Start

# Install
npm install prompt-engine

# Validate a configuration
npx prompt-engine validate config.json

# Initialize a new configuration
npx prompt-engine init my-config.json

Configuration

Create a prompt-engine.config.json file:

{
  "version": "2.0",
  "engine": {
    "defaults": {
      "temperature": 0.7,
      "maxTokens": 2048
    },
    "logging": {
      "level": "info"
    }
  },
  "prompts": [
    {
      "id": "summarize",
      "model": "gpt-4",
      "template": "Summarize the following text: {{text}}",
      "variables": {
        "text": ""
      }
    }
  ]
}

Monitoring

The engine includes built-in observability using Node.js diagnostics channels:

import { monitor, enableAutomaticCostTracking, getMonitoringSummary } from 'prompt-engine/monitoring';

// Enable automatic cost calculation
enableAutomaticCostTracking();

// Listen to events
monitor.on('prompt.complete', (metrics) => {
  console.log(`Cost: $${metrics.cost}, Tokens: ${metrics.totalTokens}`);
});

// Get summary
console.log(getMonitoringSummary());

Security

Built-in security features protect against common vulnerabilities:

import { sanitizePrompt } from 'prompt-engine/security';

// Automatically sanitizes XSS, detects injections, and masks PII
const safe = await sanitizePrompt(userInput);

Development

# Install dependencies
npm install

# Run tests (Node.js built-in test runner)
npm test

# Build
npm run build

# Type check
npm run typecheck

Requirements

  • Node.js >= 18.0.0
  • TypeScript >= 5.0

API

See API.md for detailed API documentation.

Migration

Upgrading from v1.x? See MIGRATION.md for upgrade instructions.

Why Choose This Prompt Engine?

🚀 Competitive Advantages

  • Minimal Dependencies: Only 3 runtime dependencies vs. dozens in alternatives
  • Security-First: Built-in XSS protection, injection detection, and PII masking
  • TypeScript Native: Full type safety and modern JavaScript features
  • Cost Tracking: Automatic token usage and cost calculation for all major LLMs
  • Production Ready: Native Node.js diagnostics, health checks, and monitoring
  • Developer Friendly: CLI tool, JSON schemas, and comprehensive documentation

How We Compare

Feature This Engine LangChain PromptLayer Others
Open Source ✅ MIT ✅ Yes ❌ No Mixed
Dependencies ✅ Only 3 ❌ Heavy ❌ Many Many
Built-in Security ✅ Complete ⚡ Basic ❌ No Limited
TypeScript Native ✅ Yes ✅ Yes ⚡ Partial Mixed
Free to Use ✅ 100% ✅ Yes ⚡ Limited Mixed

Philosophy

This project follows a "progressive enhancement" approach:

  • Core functionality works with minimal dependencies
  • Optional features (YAML/TOML) load on-demand
  • Built-in Node.js features preferred over external packages
  • Type safety without runtime overhead

License

MIT - See LICENSE file for details.

This project includes attribution to the original Prompt-Engine concept by ruvnet.

Examples

Simple Example

In this simple example, we demonstrate how to create a basic prompt that allows users to choose their area of interest and receive content based on their selection.

[prompt]
Author = "rUv"
name = "Area of Interest Selector"
forked_from = "ruvnet"
version = "1.0"

# initial prompt
# Purpose: The initial prompt welcomes the user to the Area of Interest Selector and explains the purpose of the bot.
# It also informs the user that the bot will demonstrate how to create a basic prompt that allows users to choose their area of interest and receive content based on their selection.
init = "Welcome to the Area of Interest Selector. This bot will demonstrate how to create a basic prompt that allows users to choose their area of interest and receive content based on their selection. Let's get started!"

[prompt.features.personalization.domains]
Description = "Choose your area of interest."
Domain_A = "Science"
Domain_B = "History"

[prompt.commands.commands]
Description = "Available commands."
help = "Get help."
choose_domain = "Choose your area of interest."

Advanced Example

In this advanced example, we demonstrate how to create a more complex prompt that includes additional personalization options, such as content complexity and interaction styles.

[prompt]
Author = "rUv"
name = "Advanced Prompt Engine Template Creator"
forked_from = "ruvnet"
version = "1.0"

# initial prompt
init = "Welcome to the Advanced Prompt Engine Template Creator. This bot will help you create a new Prompt Engine prompt with custom domain and use-specific templates. Let's get started!"

[prompt.features.personalization]
Description = "Personalized settings."

[prompt.features.personalization.domains]
Description = "Choose your area of interest."
Domain_A = "Science"
Domain_B = "History"

[prompt.features.personalization.complexity]
description = "Choose content complexity level."
Level_1 = "Basic"
Level_10 = "Advanced"

[prompt.features.personalization.interaction_styles]
Description = "Choose interaction style."
Style_A = "Text-based"
Style_B = "Voice-based"

[prompt.commands]
Description = "Available commands."
prefix = "Choose one of the following commands:"

[prompt.commands.commands]
help = "Get help."
choose_domain = "Choose your area of interest."
choose_complexity = "Choose content complexity level."
choose_interaction = "Choose interaction style."

Educational Platforms

# Prompt Engine Template for Educational Platforms

[prompt]
Author = "ChatGPT"
name = "Educational Platform"
version = "1.0.0"

# initial prompt
init = "Welcome to the Educational Platform! This bot will help you personalize your learning experience. Choose your area of interest and adapt to your level of expertise. Let's get started!"

[prompt.features.personalization]
Description = "Personalized learning experience."

[prompt.features.personalization.domains]
Description = "Choose area of interest."
Mathematics = "Learn about algebra, calculus, and geometry."
Science = "Explore physics, chemistry, and biology."

[prompt.features.personalization.complexity]
description = "Adapt to learner's level of expertise."
Level_1 = "Basic concepts and general overview."
Level_10 = "Advanced topics and in-depth analysis."

[prompt.commands]
Description = "Commands for interaction."
start = "Start the learning session."
stop = "End the learning session."

Customer Support

[prompt]
Author = "ChatGPT"
name = "Customer Support"
version = "1.0.0"

# initial prompt
init = "Welcome to Customer Support. How may I assist you today?"

[prompt.features.personalization]
Description = "Dynamic customer support."

[prompt.features.personalization.tone_styles]
Description = "Tone of the support."
Friendly = "Friendly and approachable tone."
Formal = "Formal and professional tone."

[prompt.commands]
Description = "Commands for assistance."
help = "Get help with a specific issue."
feedback = "Provide feedback about the service."

Content Exploration

[prompt]
Author = "ChatGPT"
name = "Content Exploration"
version = "1.0.0"

# initial prompt
init = "Welcome to the Content Exploration bot. This bot will help you explore different types of content in an interactive way. Let's get started!"

[prompt.features.personalization]
Description = "Interactive content exploration."

[prompt.features.personalization.presentation_styles]
Description = "Presentation of content."
List = "Display content as a list."
Grid = "Display content in a grid layout."

[prompt.commands]
Description = "Commands for navigation."
next = "Go to the next page of content."
previous = "Go to the previous page of content."
search = "Search for specific content."

Virtual Assistants

[prompt]
name = "Virtual Assistant"
author = "ChatGPT"
version = "1.0.0"

# initial prompt
init = "Welcome to Virtual Assistant. This bot provides personalized virtual assistance with conversational or command-based interaction. How can I assist you?"

[prompt.features.personalization]
Description = "Personalized virtual assistance."

[prompt.features.personalization.interaction_styles]
Description = "Interaction style with the virtual assistant."
Conversational = "Conversational and natural language interaction."
Command_Based = "Command-based interaction with specific keywords."

[prompt.commands]
Description = "Commands for virtual assistant."
ask = "Ask a question to the virtual assistant."
reminder = "Set a reminder or schedule an event."

Interactive Narratives

[prompt]
name = "Interactive Narrative"
version = "1.0.0"
Author = "ChatGPT"
forked_from = ""
init = "Welcome to the Interactive Narrative Bot. This bot will take you through a narrative adventure, where you can make choices and create your own story. Let's get started!"

[prompt.features.personalization]
Description = "Interactive storytelling experience."

[prompt.features.personalization.branches]
Description = "Branching narrative paths."
Path_A = "Follow the first narrative path."
Path_B = "Follow the second narrative path."

[prompt.commands]
Description = "Commands for interactive narrative."
choose = "Make a choice in the narrative."
continue = "Continue to the next part of the story."

Production Deployment

Environment Variables

The engine supports configuration through environment variables:

# API Keys
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GEMINI_API_KEY=...
export PERPLEXITY_API_KEY=pplx-...

# Engine Configuration
export PROMPT_ENGINE_DEFAULT_MODEL=gpt-4
export PROMPT_ENGINE_TEMPERATURE=0.7
export PROMPT_ENGINE_MAX_TOKENS=2048

# Security Settings
export PROMPT_ENGINE_CHECK_INJECTION=true
export PROMPT_ENGINE_CHECK_PII=false
export PROMPT_ENGINE_SANITIZE_HTML=true
export PROMPT_ENGINE_MAX_LENGTH=5000

# Rate Limiting
export PROMPT_ENGINE_RATE_LIMIT_ENABLED=true
export PROMPT_ENGINE_RATE_LIMIT_WINDOW_MS=60000
export PROMPT_ENGINE_RATE_LIMIT_MAX_REQUESTS=60

# Logging
export PROMPT_ENGINE_LOG_LEVEL=info
export PROMPT_ENGINE_LOG_FORMAT=json

Docker Support

FROM node:20-alpine

WORKDIR /app

# Copy package files
COPY package*.json ./
RUN npm ci --only=production

# Copy application
COPY dist ./dist

# Set Node.js to production
ENV NODE_ENV=production

# Run as non-root user
USER node

CMD ["node", "dist/index.js"]

Health Checks

The engine includes built-in health check endpoints:

import { createHealthCheck } from 'prompt-engine/health';

const health = createHealthCheck({
  checks: ['memory', 'api-keys', 'rate-limits']
});

// Express example
app.get('/health', async (req, res) => {
  const status = await health.check();
  res.status(status.healthy ? 200 : 503).json(status);
});

Performance Optimization

Caching

Built-in caching for prompt templates and API responses:

import { Configuration } from 'prompt-engine';

const config = await Configuration.create({
  caching: {
    enabled: true,
    ttl: 3600, // 1 hour
    maxSize: 100 // MB
  }
});

Connection Pooling

Optimized connection management for API providers:

import { createConnectionPool } from 'prompt-engine/optimization';

const pool = createConnectionPool({
  maxConnections: 10,
  keepAlive: true,
  timeout: 30000
});

Testing

Unit Testing

import { test } from 'node:test';
import { strictEqual } from 'node:assert';
import { sanitizePrompt } from 'prompt-engine/security';

test('sanitizes user input', async () => {
  const input = '<script>alert("xss")</script>';
  const result = await sanitizePrompt(input);
  strictEqual(result, '');
});

Integration Testing

# Run integration tests
npm run test:integration

# Run with coverage
npm run test:coverage

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Setup

  1. Fork the repository
  2. Clone your fork
  3. Install dependencies: npm install
  4. Create a feature branch: git checkout -b feature/your-feature
  5. Make your changes
  6. Run tests: npm test
  7. Submit a pull request

Code Style

  • ESLint configuration included
  • Prettier formatting
  • Conventional commits recommended

About

TypeScript implementation of Prompt Engine with security, monitoring, and minimal dependencies

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published