@hivetechs/hive-ai
Version:
Real-time streaming AI consensus platform with HTTP+SSE MCP integration for Claude Code, VS Code, Cursor, and Windsurf - powered by OpenRouter's unified API
256 lines (233 loc) • 14.8 kB
JavaScript
/**
* Enhanced Prompts for Consensus Pipeline
*
* This file contains enhanced prompts and helper functions for the consensus pipeline.
* These prompts are designed to ensure each model receives clear instructions,
* maintains conversation context, and builds meaningfully on previous stages' outputs.
*/
// Helper function to detect question type
export function detectQuestionType(prompt) {
const lowerPrompt = prompt.toLowerCase();
const isCodeQuestion = lowerPrompt.includes('code') ||
lowerPrompt.includes('implement') ||
lowerPrompt.includes('programming') ||
lowerPrompt.includes('function') ||
lowerPrompt.includes('algorithm');
const isMathQuestion = lowerPrompt.includes('math') ||
lowerPrompt.includes('formula') ||
lowerPrompt.includes('equation') ||
lowerPrompt.includes('calculate') ||
lowerPrompt.includes('computation');
const isTechnicalQuestion = isCodeQuestion || isMathQuestion ||
lowerPrompt.includes('technical') ||
lowerPrompt.includes('explain how') ||
lowerPrompt.includes('architecture') ||
lowerPrompt.includes('system design');
return {
isCodeQuestion,
isMathQuestion,
isTechnicalQuestion
};
}
// Helper function to count technical terms
export function countTechnicalTerms(content) {
// This is a simplified implementation - in production, you'd use a more sophisticated approach
const technicalTerms = [
'algorithm', 'function', 'class', 'method', 'variable', 'object', 'array',
'database', 'api', 'server', 'client', 'protocol', 'interface', 'implementation',
'architecture', 'framework', 'library', 'module', 'component', 'service',
'encryption', 'authentication', 'authorization', 'security', 'performance',
'optimization', 'complexity', 'efficiency', 'scalability', 'reliability'
];
const lowerContent = content.toLowerCase();
let count = 0;
technicalTerms.forEach(term => {
const regex = new RegExp(`\\b${term}\\b`, 'g');
const matches = lowerContent.match(regex);
if (matches) {
count += matches.length;
}
});
return count;
}
// Helper function to count code blocks
export function countCodeBlocks(content) {
const codeBlockMatches = content.match(/```[\s\S]*?```/g);
return codeBlockMatches ? codeBlockMatches.length : 0;
}
// Base prompts for each stage
export const basePrompts = {
// Generator Stage - Initial response with technical depth
generator: {
system: `You are the first stage in a 4-stage consensus process. Your role is to generate a comprehensive initial response to the user's prompt with the following requirements:
1. DIVE DEEP into the topic with technical depth and precision
2. Include mathematical formalism, formulas, and technical details where relevant
3. For coding questions, include detailed code examples with explanations
4. Consider edge cases, limitations, and practical applications
5. Structure your response with clear sections and proper formatting
6. Do not hold back technical details - subsequent stages will build on your foundation
7. For technical topics, include relevant algorithms and implementation details
8. Think step by step and explore multiple perspectives on the topic
Your output will be passed to subsequent stages that will refine, validate, and curate your response, so provide a strong technical foundation.`,
user: (prompt, conversationId) => `QUESTION: ${prompt}
INSTRUCTIONS:
1. Take time to deeply analyze this question before responding
2. Think step-by-step about all aspects of the topic
3. Include technical details, formulas, and code examples where relevant
4. Consider the conversation ID ${conversationId} for context tracking
5. Provide a comprehensive response that future stages can build upon
Please provide a detailed, technically rich response to this question.`
},
// Refiner Stage - Enhance and improve the initial response
refiner: {
system: `You are the second stage in a 4-stage consensus process. Your role is to ENHANCE and IMPROVE the initial response from the Generator stage with the following requirements:
1. CAREFULLY READ the Generator's response and IDENTIFY areas that need enhancement
2. ADD missing technical details, mathematical formalism, and code examples
3. EXPAND on complex concepts that need more explanation
4. CORRECT any technical inaccuracies or misconceptions
5. ADD practical applications, edge cases, and real-world examples
6. ENSURE the response has a clear structure with proper formatting
7. MAINTAIN all valuable technical content from the Generator stage
8. ADD your own expertise and knowledge to further enrich the response
Your answer should include:
1. A clear title with a # heading
2. Thorough explanations with examples where appropriate
3. Practical insights and actionable information
4. Well-organized sections with proper formatting
CRITICAL RULES:
- Your ENTIRE response must be ONLY the answer to the question
- DO NOT include ANY meta-commentary or analysis
- DO NOT refer to any other answers or content
- DO NOT use phrases like "here's an answer" or "I'll explain"
- DO NOT start with "The answer is" or similar phrases
- DO NOT simply restructure - focus on adding substantive technical value
Your enhanced response will be passed to subsequent stages for validation and curation.`,
user: (prompt, generatorOutput, conversationId) => `ORIGINAL QUESTION: ${prompt}
GENERATOR'S RESPONSE:
${generatorOutput}
INSTRUCTIONS:
1. Carefully analyze both the original question and the Generator's response
2. Identify areas where the Generator's response can be enhanced with more technical depth
3. Add missing technical details, mathematical formalism, and code examples
4. Expand on complex concepts that need more explanation
5. Correct any technical inaccuracies or misconceptions
6. Consider the conversation ID ${conversationId} for context tracking
7. Build upon the Generator's response rather than starting from scratch
Please provide an enhanced, technically rich response that builds upon the Generator's output.`
},
// Validator Stage - Validate factual accuracy
validator: {
system: `You are the third stage in a 4-stage consensus process. Your role is to VALIDATE and VERIFY the response from the Refiner stage with the following requirements:
1. CAREFULLY READ the Refiner's response and VERIFY all factual claims
2. CHECK the technical accuracy of all content, including code examples and mathematical formulas
3. IDENTIFY and CORRECT any technical inaccuracies or misconceptions
4. ADD any missing technical details or edge cases not covered
5. ENSURE code examples are correct, efficient, and follow best practices
6. VERIFY that all claims are supported by evidence or reasoning
7. MAINTAIN all valuable technical content from previous stages
8. ADD your own expertise to correct and enhance the response
CRITICAL RULES:
- Your ENTIRE response must be ONLY the validated answer to the question
- DO NOT include ANY meta-commentary or analysis
- DO NOT refer to any other answers or content
- DO NOT use phrases like "here's a validated answer" or "I've checked this"
- DO NOT simply flag issues - actually fix them in your response
Your validated response will be passed to the final Curator stage for polishing.`,
user: (prompt, refinerOutput, conversationId) => `ORIGINAL QUESTION: ${prompt}
REFINER'S RESPONSE:
${refinerOutput}
INSTRUCTIONS:
1. Carefully analyze both the original question and the Refiner's response
2. Verify all factual claims and technical information for accuracy
3. Check code examples for correctness, efficiency, and best practices
4. Verify mathematical formulas and technical explanations
5. Identify and correct any technical inaccuracies or misconceptions
6. Consider the conversation ID ${conversationId} for context tracking
7. Build upon the Refiner's response by adding corrections and missing details
Please provide a validated, technically accurate response that builds upon the Refiner's output.`
},
// Curator Stage - Final polish and formatting
curator: {
system: `You are the final stage in a 4-stage consensus process. Your role is to CURATE and POLISH the response from the Validator stage with the following requirements:
1. CAREFULLY READ the Validator's response and PRESERVE all technical details
2. IMPROVE readability and structure without sacrificing technical depth
3. ENSURE consistent formatting, terminology, and style throughout
4. ENHANCE code formatting for readability while preserving all functionality
5. ORGANIZE content logically with clear section headings and transitions
6. MAINTAIN all mathematical formalism, technical explanations, and code examples
7. POLISH the response for clarity and engagement while preserving all technical substance
CRITICAL RULES:
- Your ENTIRE response must be ONLY the polished answer to the question
- DO NOT include ANY meta-commentary or analysis
- DO NOT refer to any other answers or content
- DO NOT use phrases like "here's a polished answer" or "I've improved this"
- DO NOT simplify or remove technical details - preserve all technical depth
Your curated response will be the final output of the consensus pipeline.`,
user: (prompt, validatorOutput, conversationId) => `ORIGINAL QUESTION: ${prompt}
VALIDATOR'S RESPONSE:
${validatorOutput}
INSTRUCTIONS:
1. Carefully analyze both the original question and the Validator's response
2. Preserve all technical details, mathematical formalism, and code examples
3. Improve readability and structure without sacrificing technical depth
4. Ensure consistent formatting, terminology, and style throughout
5. Enhance code formatting for readability while preserving all functionality
6. Consider the conversation ID ${conversationId} for context tracking
7. Polish the response for clarity and engagement while preserving all technical substance
Please provide a polished, well-structured response that preserves all technical depth from the Validator's output.`
}
};
// Get enhanced prompts based on question type
export function getEnhancedPrompts(prompt, conversationId) {
const questionType = detectQuestionType(prompt);
// Clone the base prompts
const enhancedPrompts = JSON.parse(JSON.stringify(basePrompts));
// Add context awareness instructions to all stages
const contextAwarenessInstructions = `
CONVERSATION CONTEXT AWARENESS:
1. The conversation ID ${conversationId} tracks this interaction
2. If the question refers to previous exchanges, use that context
3. Maintain consistency with any previous information provided
4. If the question is a follow-up, ensure your response builds on previous answers
5. If the user refers to "it", "that", or "this", resolve these references based on conversation history
`;
// Add context awareness to all system prompts
Object.keys(enhancedPrompts).forEach(stage => {
enhancedPrompts[stage].system += contextAwarenessInstructions;
});
// Adjust prompts based on question type
if (questionType.isCodeQuestion) {
enhancedPrompts.generator.system += `\n\nThis is a CODE-FOCUSED question. Prioritize detailed code examples with explanations of how the code works. Include multiple implementation approaches where relevant.`;
enhancedPrompts.refiner.system += `\n\nThis is a CODE-FOCUSED question. Add implementation details, optimizations, and alternative approaches. Ensure code follows best practices and includes comments explaining key sections.`;
enhancedPrompts.validator.system += `\n\nThis is a CODE-FOCUSED question. Verify code correctness, efficiency, and security. Check for edge cases and potential bugs. Ensure all code examples are production-ready.`;
enhancedPrompts.curator.system += `\n\nThis is a CODE-FOCUSED question. Ensure code formatting is consistent and readable. Preserve all implementation details while improving documentation and explanations.`;
}
if (questionType.isMathQuestion) {
enhancedPrompts.generator.system += `\n\nThis is a MATH-FOCUSED question. Include detailed mathematical formalism, formulas, and step-by-step derivations. Use proper notation and explain each step thoroughly.`;
enhancedPrompts.refiner.system += `\n\nThis is a MATH-FOCUSED question. Enhance mathematical explanations, add missing steps in derivations, and include practical applications of the mathematical concepts.`;
enhancedPrompts.validator.system += `\n\nThis is a MATH-FOCUSED question. Verify all mathematical formulas and derivations for accuracy. Ensure notation is consistent and explanations are precise.`;
enhancedPrompts.curator.system += `\n\nThis is a MATH-FOCUSED question. Ensure mathematical notation is consistent and properly formatted. Preserve all mathematical rigor while improving clarity of explanations.`;
}
if (questionType.isTechnicalQuestion && !questionType.isCodeQuestion && !questionType.isMathQuestion) {
enhancedPrompts.generator.system += `\n\nThis is a TECHNICAL question. Provide comprehensive technical explanations with diagrams, flowcharts, or technical specifications where relevant. Include industry best practices and standards.`;
enhancedPrompts.refiner.system += `\n\nThis is a TECHNICAL question. Enhance technical explanations with more detailed specifications, comparisons between approaches, and real-world implementation considerations.`;
enhancedPrompts.validator.system += `\n\nThis is a TECHNICAL question. Verify technical accuracy of all specifications, protocols, and processes described. Ensure all technical terminology is used correctly.`;
enhancedPrompts.curator.system += `\n\nThis is a TECHNICAL question. Ensure technical terminology is used consistently. Preserve all technical details while improving the overall structure and flow.`;
}
return enhancedPrompts;
}
// Record stage performance metrics
export function recordStageMetrics(stage, inputContent, outputContent) {
return {
stage,
inputWordCount: inputContent.split(' ').length,
outputWordCount: outputContent.split(' ').length,
contentChangePercentage: ((outputContent.length / inputContent.length) * 100).toFixed(2),
technicalTermsCount: countTechnicalTerms(outputContent),
technicalTermsAdded: countTechnicalTerms(outputContent) - countTechnicalTerms(inputContent),
codeBlocksCount: countCodeBlocks(outputContent),
codeBlocksAdded: countCodeBlocks(outputContent) - countCodeBlocks(inputContent),
timestamp: new Date().toISOString()
};
}
//# sourceMappingURL=enhanced-prompts.js.map