Prompts Guide
Overview
Prompts provide pre-defined conversation starters and templates for AI models. In v3.0, prompts are defined using the @Prompt decorator.
Basic Prompt
import { PromptDecorator as Prompt, ExecutionContext } from 'nitrostack';
export class ProductPrompts {
  @Prompt({
    name: 'review_product',
    description: 'Generate a product review template',
    arguments: [
      {
        name: 'product_id',
        description: 'The product to review',
        required: true
      }
    ]
  })
  async getReviewPrompt(args: any, context: ExecutionContext) {
    const product = await this.productService.findById(args.product_id);
    
    return {
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: `Please write a detailed review for: ${product.name}\n\nConsider: quality, value, features, and overall satisfaction.`
          }
        }
      ]
    };
  }
}
@Prompt Decorator
Options
interface PromptOptions {
  name: string;              // Prompt identifier (required)
  description: string;       // What the prompt does (required)
  arguments?: Array<{        // Prompt parameters
    name: string;
    description: string;
    required?: boolean;
  }>;
}
Complete Example
@Prompt({
  name: 'code_review',
  description: 'Generate a code review checklist for a pull request',
  arguments: [
    {
      name: 'language',
      description: 'Programming language (e.g., typescript, python)',
      required: true
    },
    {
      name: 'complexity',
      description: 'Code complexity level (simple, moderate, complex)',
      required: false
    }
  ]
})
async getCodeReviewPrompt(args: any, ctx: ExecutionContext) {
  const language = args.language;
  const complexity = args.complexity || 'moderate';
  
  const checklist = this.getChecklistForLanguage(language, complexity);
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Code Review Checklist for ${language} (${complexity}):\n\n${checklist}`
        }
      }
    ]
  };
}
Prompt Arguments
Optional vs Required
@Prompt({
  name: 'analyze_data',
  arguments: [
    {
      name: 'dataset',
      description: 'The dataset to analyze',
      required: true     // ← Must be provided
    },
    {
      name: 'method',
      description: 'Analysis method',
      required: false    // ← Optional
    }
  ]
})
async getAnalysisPrompt(args: any) {
  const dataset = args.dataset;
  const method = args.method || 'statistical';  // Default
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Analyze ${dataset} using ${method} methods`
        }
      }
    ]
  };
}
Validating Arguments
@Prompt({
  name: 'generate_report',
  arguments: [
    {
      name: 'type',
      description: 'Report type (sales, inventory, analytics)'
    }
  ]
})
async getReportPrompt(args: any, ctx: ExecutionContext) {
  const validTypes = ['sales', 'inventory', 'analytics'];
  
  if (!validTypes.includes(args.type)) {
    throw new Error(`Invalid report type. Must be one of: ${validTypes.join(', ')}`);
  }
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Generate a ${args.type} report for the current period`
        }
      }
    ]
  };
}
Response Format
Simple Text Prompt
return {
  messages: [
    {
      role: 'user',
      content: {
        type: 'text',
        text: 'Your prompt text here'
      }
    }
  ]
};
Multi-Message Prompts
@Prompt({
  name: 'tutoring_session',
  description: 'Start a coding tutoring session'
})
async getTutoringPrompt(args: any) {
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: 'I need help learning Python programming.'
        }
      },
      {
        role: 'assistant',
        content: {
          type: 'text',
          text: 'Great! I\'d be happy to help you learn Python. What\'s your current experience level?'
        }
      },
      {
        role: 'user',
        content: {
          type: 'text',
          text: 'I\'m a complete beginner.'
        }
      }
    ]
  };
}
Prompts with Context
@Prompt({
  name: 'bug_investigation',
  arguments: [
    { name: 'error_message', required: true },
    { name: 'stack_trace', required: false }
  ]
})
async getBugPrompt(args: any) {
  let context = `Error: ${args.error_message}`;
  
  if (args.stack_trace) {
    context += `\n\nStack Trace:\n${args.stack_trace}`;
  }
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `I'm encountering this error:\n\n${context}\n\nCan you help me understand what's wrong and how to fix it?`
        }
      }
    ]
  };
}
Dynamic Prompts
Load Data for Prompts
@Prompt({
  name: 'order_summary',
  arguments: [
    { name: 'order_id', required: true }
  ]
})
async getOrderSummaryPrompt(args: any) {
  // Load order data
  const order = await this.orderService.findById(args.order_id);
  
  const summary = `
Order #${order.id}
Customer: ${order.customerName}
Items: ${order.items.length}
Total: $${order.total}
Status: ${order.status}
`;
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Here's the order summary:\n\n${summary}\n\nCan you provide recommendations for upselling or improving the order?`
        }
      }
    ]
  };
}
Template-Based Prompts
@Injectable()
export class PromptTemplateService {
  getTemplate(type: string, data: any): string {
    const templates = {
      'email': `Draft a professional email:\nTo: ${data.to}\nSubject: ${data.subject}\nContext: ${data.context}`,
      'summary': `Summarize the following:\n\n${data.content}\n\nIn ${data.maxWords || 100} words or less.`,
      'translation': `Translate to ${data.targetLang}:\n\n${data.text}`
    };
    
    return templates[type] || '';
  }
}
export class CommunicationPrompts {
  constructor(private templateService: PromptTemplateService) {}
  
  @Prompt({
    name: 'compose_email',
    arguments: [
      { name: 'to', required: true },
      { name: 'subject', required: true },
      { name: 'context', required: true }
    ]
  })
  async getEmailPrompt(args: any) {
    const text = this.templateService.getTemplate('email', args);
    
    return {
      messages: [
        {
          role: 'user',
          content: { type: 'text', text }
        }
      ]
    };
  }
}
Guards
Protected Prompts
@Prompt({ name: 'admin_report' })
@UseGuards(JWTGuard, AdminGuard)  // ← Auth required
async getAdminReportPrompt(args: any, ctx: ExecutionContext) {
  const userId = ctx.auth?.subject;
  ctx.logger.info(`Admin ${userId} requested report prompt`);
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: 'Generate a comprehensive admin report with user activity, system health, and revenue metrics.'
        }
      }
    ]
  };
}
Dependency Injection
Use Services
@Injectable()
export class ReportService {
  async getMetrics() {
    // Load metrics from database
  }
}
export class ReportPrompts {
  constructor(private reportService: ReportService) {}  // ← Injected
  
  @Prompt({
    name: 'weekly_report',
    description: 'Generate weekly performance report'
  })
  async getWeeklyReportPrompt(args: any) {
    const metrics = await this.reportService.getMetrics();
    
    return {
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: `Generate a weekly report with these metrics:\n${JSON.stringify(metrics, null, 2)}`
          }
        }
      ]
    };
  }
}
Examples
Code Generation Prompt
@Prompt({
  name: 'generate_api_endpoint',
  description: 'Generate REST API endpoint code',
  arguments: [
    { name: 'resource', required: true },
    { name: 'operations', required: true },
    { name: 'framework', required: false }
  ]
})
async getApiEndpointPrompt(args: any) {
  const resource = args.resource;
  const operations = args.operations.split(',');
  const framework = args.framework || 'express';
  
  const prompt = `
Generate ${framework} API endpoints for the ${resource} resource.
Operations needed: ${operations.join(', ')}
Requirements:
- Input validation
- Error handling
- RESTful conventions
- TypeScript with proper types
- Async/await patterns
Please provide complete, production-ready code.
`;
  
  return {
    messages: [
      {
        role: 'user',
        content: { type: 'text', text: prompt.trim() }
      }
    ]
  };
}
Documentation Prompt
@Prompt({
  name: 'document_function',
  description: 'Generate documentation for a function',
  arguments: [
    { name: 'code', required: true },
    { name: 'style', required: false }
  ]
})
async getDocPrompt(args: any) {
  const style = args.style || 'jsdoc';
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Generate ${style} documentation for this function:\n\n${args.code}\n\nInclude: description, parameters, return value, and usage examples.`
        }
      }
    ]
  };
}
Testing Prompt
@Prompt({
  name: 'generate_tests',
  description: 'Generate unit tests for code',
  arguments: [
    { name: 'code', required: true },
    { name: 'framework', required: false }
  ]
})
async getTestsPrompt(args: any) {
  const framework = args.framework || 'jest';
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Generate ${framework} unit tests for:\n\n${args.code}\n\nCover: happy path, edge cases, error handling, and mocking if needed.`
        }
      }
    ]
  };
}
Debugging Prompt
@Prompt({
  name: 'debug_help',
  description: 'Get debugging assistance',
  arguments: [
    { name: 'code', required: true },
    { name: 'issue', required: true }
  ]
})
async getDebugPrompt(args: any) {
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `I'm having this issue:\n${args.issue}\n\nWith this code:\n\`\`\`\n${args.code}\n\`\`\`\n\nCan you help me identify the problem and suggest a fix?`
        }
      }
    ]
  };
}
Data Analysis Prompt
@Prompt({
  name: 'analyze_sales',
  description: 'Analyze sales data and provide insights',
  arguments: [
    { name: 'period', required: true },
    { name: 'region', required: false }
  ]
})
async getSalesAnalysisPrompt(args: any) {
  const data = await this.salesService.getData(args.period, args.region);
  
  return {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Analyze this sales data:\n\n${JSON.stringify(data, null, 2)}\n\nProvide: trends, insights, recommendations, and areas of concern.`
        }
      }
    ]
  };
}
Best Practices
1. Clear Descriptions
// ✅ Good
@Prompt({
  name: 'refactor_code',
  description: 'Generate suggestions to refactor and improve code quality'
})
// ❌ Avoid
@Prompt({
  name: 'refactor_code',
  description: 'Refactor'
})
2. Provide Context
// ✅ Good - Includes context
return {
  messages: [{
    role: 'user',
    content: {
      type: 'text',
      text: `As a senior developer, review this code:\n\n${code}\n\nFocus on: security, performance, maintainability`
    }
  }]
};
// ❌ Avoid - No context
return {
  messages: [{
    role: 'user',
    content: { type: 'text', text: code }
  }]
};
3. Structure Complex Prompts
// ✅ Good - Well-structured
const prompt = `
Task: Generate API documentation
Input: ${code}
Format:
- Endpoint description
- Request parameters
- Response format
- Error codes
- Usage examples
Style: Professional, concise
`;
// ❌ Avoid - Unstructured
const prompt = `document this ${code}`;
4. Validate Arguments
// ✅ Good
async getPrompt(args: any) {
  if (!args.required_field) {
    throw new Error('required_field is mandatory');
  }
  // ... continue
}
// ❌ Avoid - No validation
async getPrompt(args: any) {
  // Assumes args.required_field exists
}
5. Use Templates
// ✅ Good - Reusable templates
@Injectable()
export class PromptTemplates {
  codeReview(language: string, code: string) {
    return `Review this ${language} code:\n\n${code}`;
  }
}
// ❌ Avoid - Hardcoded everywhere
async getPrompt() {
  return { messages: [{ role: 'user', content: { type: 'text', text: 'hardcoded text' } }] };
}
Next Steps
Pro Tip: Prompts are great for providing context-aware conversation starters that help AI models understand what you want!