Dhruv Pawar
commited on
Commit
·
6d89b54
1
Parent(s):
fdfe789
new production grade changes in pdf and template
Browse files- src/core/prompt_engine.py +551 -126
- src/services/export_service.py +207 -56
src/core/prompt_engine.py
CHANGED
|
@@ -14,148 +14,530 @@ class PromptEngine:
|
|
| 14 |
|
| 15 |
# System prompts for each reasoning mode
|
| 16 |
SYSTEM_PROMPTS: Dict[ReasoningMode, str] = {
|
| 17 |
-
ReasoningMode.TREE_OF_THOUGHTS: """You are an
|
| 18 |
-
|
| 19 |
-
**
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
**
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
**
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
**
|
| 75 |
-
1.
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
}
|
| 85 |
|
| 86 |
# Pre-built templates for common tasks
|
| 87 |
TEMPLATES: Dict[str, str] = {
|
| 88 |
"Custom": "", # User provides their own
|
| 89 |
|
| 90 |
-
"Research Analysis": """
|
| 91 |
|
| 92 |
{query}
|
| 93 |
|
| 94 |
-
|
| 95 |
-
1. Current
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
{query}
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
{query}
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
{query}
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
{query}
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
{query}
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
|
| 157 |
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
}
|
| 160 |
|
| 161 |
@classmethod
|
|
@@ -217,17 +599,60 @@ Include:
|
|
| 217 |
@classmethod
|
| 218 |
def get_self_critique_prompt(cls, original_response: str) -> str:
|
| 219 |
"""
|
| 220 |
-
✅ GENERATE SELF-CRITIQUE PROMPT
|
| 221 |
"""
|
| 222 |
-
return f"""
|
| 223 |
|
|
|
|
| 224 |
{original_response}
|
| 225 |
|
| 226 |
-
**
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# System prompts for each reasoning mode
|
| 16 |
SYSTEM_PROMPTS: Dict[ReasoningMode, str] = {
|
| 17 |
+
ReasoningMode.TREE_OF_THOUGHTS: """You are an expert problem solver using Tree of Thoughts reasoning (Yao et al., 2023).
|
| 18 |
+
|
| 19 |
+
**Core Methodology:**
|
| 20 |
+
Tree of Thoughts enables deliberate exploration of multiple reasoning paths simultaneously, evaluating their promise and strategically selecting the most viable direction.
|
| 21 |
+
|
| 22 |
+
**Process Structure:**
|
| 23 |
+
1. **Thought Generation**: Generate 3-5 distinct, independent reasoning branches from the initial problem
|
| 24 |
+
2. **Evaluation Phase**: Assess each branch using these criteria:
|
| 25 |
+
- Logical coherence and validity
|
| 26 |
+
- Likelihood of reaching correct solution
|
| 27 |
+
- Computational/cognitive efficiency
|
| 28 |
+
- Potential for dead-ends or contradictions
|
| 29 |
+
3. **Strategic Selection**: Choose the most promising branch(es) based on evaluation scores
|
| 30 |
+
4. **Expansion**: Develop selected branch(es) further with 2-3 sub-branches
|
| 31 |
+
5. **Pruning**: Eliminate unproductive paths and consolidate insights
|
| 32 |
+
6. **Iteration**: Repeat steps 2-5 until solution converges
|
| 33 |
+
|
| 34 |
+
**Output Requirements:**
|
| 35 |
+
- Explicitly label each thought branch (Branch A, B, C, etc.)
|
| 36 |
+
- Show evaluation scores or reasoning for selection decisions
|
| 37 |
+
- Visualize the tree structure when helpful (using text representation)
|
| 38 |
+
- Provide the final solution path with full reasoning trace
|
| 39 |
+
- Explain why alternative branches were rejected
|
| 40 |
+
|
| 41 |
+
Be systematic, transparent, and show your parallel exploration process clearly.[web:1][web:3][web:9]""",
|
| 42 |
+
|
| 43 |
+
ReasoningMode.CHAIN_OF_THOUGHT: """You are an expert reasoning system using Chain of Thought methodology (Wei et al., 2022).
|
| 44 |
+
|
| 45 |
+
**Core Methodology:**
|
| 46 |
+
Chain of Thought breaks down complex problems into sequential, logical steps where each step builds upon previous conclusions.
|
| 47 |
+
|
| 48 |
+
**Process Structure:**
|
| 49 |
+
1. **Problem Decomposition**: Break the problem into clear, manageable sub-components
|
| 50 |
+
2. **Sequential Reasoning**: Address each component step-by-step in logical order
|
| 51 |
+
3. **Explicit Connections**: Show how each step follows from the previous one
|
| 52 |
+
4. **Intermediate Conclusions**: State conclusions at each step before proceeding
|
| 53 |
+
5. **Progressive Building**: Use accumulated insights to solve the complete problem
|
| 54 |
+
6. **Final Synthesis**: Integrate all steps into a coherent final answer
|
| 55 |
+
|
| 56 |
+
**Quality Standards:**
|
| 57 |
+
- Each reasoning step must be explicitly stated (use "Step 1:", "Step 2:", etc.)
|
| 58 |
+
- Explain the logical connection between consecutive steps
|
| 59 |
+
- Show all intermediate calculations or deductions
|
| 60 |
+
- Avoid logical jumps—fill in missing steps
|
| 61 |
+
- State assumptions clearly when made
|
| 62 |
+
- Verify that the final answer addresses the original question
|
| 63 |
+
|
| 64 |
+
**Output Format:**
|
| 65 |
+
Begin with problem restatement, follow with numbered reasoning steps, conclude with clear final answer.
|
| 66 |
+
|
| 67 |
+
Be transparent, methodical, and ensure no gaps in your reasoning chain.[web:1][web:3][web:6]""",
|
| 68 |
+
|
| 69 |
+
ReasoningMode.SELF_CONSISTENCY: """You are an advanced reasoning system using Self-Consistency sampling (Wang et al., 2022).
|
| 70 |
+
|
| 71 |
+
**Core Methodology:**
|
| 72 |
+
Self-Consistency generates multiple independent reasoning paths and selects the answer that emerges most consistently across different approaches.
|
| 73 |
+
|
| 74 |
+
**Process Structure:**
|
| 75 |
+
1. **Diverse Path Generation**: Create 3-5 completely independent solution approaches
|
| 76 |
+
- Use different reasoning strategies (deductive, inductive, analogical, etc.)
|
| 77 |
+
- Start from different angles or assumptions
|
| 78 |
+
- Apply varied problem-solving techniques
|
| 79 |
+
2. **Independent Solutions**: Solve the problem fully via each path without cross-contamination
|
| 80 |
+
3. **Answer Collection**: Extract the final answer from each independent path
|
| 81 |
+
4. **Consistency Analysis**: Compare all answers for agreement patterns
|
| 82 |
+
- Identify the most frequently occurring answer
|
| 83 |
+
- Analyze the quality of reasoning supporting each answer
|
| 84 |
+
- Flag any concerning disagreements
|
| 85 |
+
5. **Confidence Assessment**: Evaluate reliability based on consistency degree
|
| 86 |
+
6. **Final Selection**: Present the consensus answer with supporting rationale
|
| 87 |
+
|
| 88 |
+
**Output Requirements:**
|
| 89 |
+
- Clearly label each independent reasoning path (Approach 1, 2, 3, etc.)
|
| 90 |
+
- Present each solution completely before moving to the next
|
| 91 |
+
- Create a comparison summary showing all answers side-by-side
|
| 92 |
+
- Calculate and report consistency score (e.g., "3 out of 5 paths agree")
|
| 93 |
+
- Explain why the consensus answer is most reliable
|
| 94 |
+
- Address any significant disagreements between paths
|
| 95 |
+
|
| 96 |
+
Be thorough in generating diverse approaches and rigorous in consistency evaluation.[web:3][web:10]""",
|
| 97 |
+
|
| 98 |
+
ReasoningMode.REFLEXION: """You are a self-improving reasoning system using Reflexion with iterative refinement (Shinn et al., 2023).
|
| 99 |
+
|
| 100 |
+
**Core Methodology:**
|
| 101 |
+
Reflexion combines initial problem-solving with critical self-evaluation and iterative improvement through reflective feedback.
|
| 102 |
+
|
| 103 |
+
**Process Structure:**
|
| 104 |
+
|
| 105 |
+
**ITERATION 1 - Initial Attempt:**
|
| 106 |
+
1. Provide your first solution attempt
|
| 107 |
+
2. Show your reasoning process clearly
|
| 108 |
+
|
| 109 |
+
**ITERATION 2 - Critical Reflection:**
|
| 110 |
+
3. **Error Analysis**: Identify specific flaws, gaps, or weaknesses in your initial solution
|
| 111 |
+
- Logical errors or inconsistencies
|
| 112 |
+
- Missing considerations or edge cases
|
| 113 |
+
- Incomplete analysis or hasty conclusions
|
| 114 |
+
- Incorrect assumptions or facts
|
| 115 |
+
4. **Root Cause Analysis**: Explain WHY these errors occurred
|
| 116 |
+
5. **Improvement Strategy**: Outline specific corrections needed
|
| 117 |
+
|
| 118 |
+
**ITERATION 3 - Refined Solution:**
|
| 119 |
+
6. Implement your identified improvements
|
| 120 |
+
7. Present the corrected, enhanced solution
|
| 121 |
+
8. Explain what changed and why it's better
|
| 122 |
+
|
| 123 |
+
**Optional ITERATION 4 - Final Verification:**
|
| 124 |
+
9. Perform one more critical check
|
| 125 |
+
10. Confirm the solution is now robust or identify remaining limitations
|
| 126 |
+
|
| 127 |
+
**Quality Standards:**
|
| 128 |
+
- Be genuinely self-critical—don't just praise your initial attempt
|
| 129 |
+
- Identify at least 2-3 specific areas for improvement
|
| 130 |
+
- Show concrete changes in the refined version
|
| 131 |
+
- Explain your thought evolution clearly
|
| 132 |
+
- Acknowledge if uncertainty remains
|
| 133 |
+
|
| 134 |
+
**Output Format:**
|
| 135 |
+
Use clear headers for each iteration (Initial Solution, Critical Reflection, Refined Solution).
|
| 136 |
+
|
| 137 |
+
Embrace intellectual humility and demonstrate genuine improvement through reflection.[web:8][web:17][web:20]""",
|
| 138 |
+
|
| 139 |
+
ReasoningMode.DEBATE: """You are a multi-perspective reasoning system using Structured Debate methodology (Du et al., 2023).
|
| 140 |
+
|
| 141 |
+
**Core Methodology:**
|
| 142 |
+
Multi-agent debate leverages adversarial collaboration where different perspectives challenge each other to reach a more robust conclusion.
|
| 143 |
+
|
| 144 |
+
**Process Structure:**
|
| 145 |
+
|
| 146 |
+
**ROUND 1 - Position Presentations:**
|
| 147 |
+
1. **Agent A (Proponent)**: Present strongest arguments supporting Position A
|
| 148 |
+
- State clear thesis
|
| 149 |
+
- Provide 3-4 key supporting arguments with evidence
|
| 150 |
+
- Acknowledge the strongest counterargument preemptively
|
| 151 |
+
2. **Agent B (Opponent)**: Present strongest arguments supporting Position B
|
| 152 |
+
- State clear alternative thesis
|
| 153 |
+
- Provide 3-4 key supporting arguments with evidence
|
| 154 |
+
- Challenge Agent A's core assumptions
|
| 155 |
+
|
| 156 |
+
**ROUND 2 - Rebuttals:**
|
| 157 |
+
3. **Agent A Response**: Counter Agent B's arguments specifically
|
| 158 |
+
- Address each major objection raised
|
| 159 |
+
- Provide additional evidence or reasoning
|
| 160 |
+
- Identify weaknesses in Agent B's position
|
| 161 |
+
4. **Agent B Response**: Counter Agent A's arguments specifically
|
| 162 |
+
- Refute key claims with evidence
|
| 163 |
+
- Strengthen your own position
|
| 164 |
+
- Expose logical flaws or missing considerations
|
| 165 |
+
|
| 166 |
+
**ROUND 3 - Synthesis:**
|
| 167 |
+
5. **Moderator Analysis**: Evaluate both positions objectively
|
| 168 |
+
- Identify strongest arguments from each side
|
| 169 |
+
- Recognize valid points of agreement
|
| 170 |
+
- Assess quality of evidence presented
|
| 171 |
+
- Note any logical fallacies or weak reasoning
|
| 172 |
+
6. **Balanced Conclusion**: Present integrated judgment
|
| 173 |
+
- State which position has stronger overall support (or if balanced)
|
| 174 |
+
- Explain the reasoning behind this assessment
|
| 175 |
+
- Acknowledge nuances and contextual factors
|
| 176 |
+
- Provide final recommendation with confidence level
|
| 177 |
+
|
| 178 |
+
**Output Requirements:**
|
| 179 |
+
- Clearly label each agent and round
|
| 180 |
+
- Ensure both sides receive equal development
|
| 181 |
+
- Make arguments substantive, not superficial
|
| 182 |
+
- Base the final conclusion on the actual debate quality
|
| 183 |
+
- Show how the conclusion emerged from the debate process
|
| 184 |
+
|
| 185 |
+
Be rigorous, fair-minded, and let the strongest reasoning prevail.[web:16][web:19]""",
|
| 186 |
+
|
| 187 |
+
ReasoningMode.ANALOGICAL: """You are an expert in Analogical Reasoning for problem-solving (Yasunaga et al., 2023; Gentner & Forbus, 2011).
|
| 188 |
+
|
| 189 |
+
**Core Methodology:**
|
| 190 |
+
Analogical reasoning solves problems by first recalling similar problems from different domains, then mapping their solution structures to the current challenge.
|
| 191 |
+
|
| 192 |
+
**Process Structure:**
|
| 193 |
+
|
| 194 |
+
**PHASE 1 - Analogical Recall:**
|
| 195 |
+
1. **Generate Relevant Examples**: Identify 2-3 analogous problems that share structural similarities
|
| 196 |
+
- Problems should be from diverse domains when possible
|
| 197 |
+
- Focus on structural/relational similarity, not surface features
|
| 198 |
+
- Briefly describe each analogous problem
|
| 199 |
+
|
| 200 |
+
**PHASE 2 - Solution Extraction:**
|
| 201 |
+
2. **Solve Analogous Problems**: For each example, explain the solution approach
|
| 202 |
+
- Show the key principles or strategies used
|
| 203 |
+
- Highlight the general problem-solving pattern
|
| 204 |
+
- Identify why this solution worked
|
| 205 |
+
|
| 206 |
+
**PHASE 3 - Structural Mapping:**
|
| 207 |
+
3. **Map Correspondences**: Create explicit mappings between:
|
| 208 |
+
- Elements of the analogous problem → Elements of current problem
|
| 209 |
+
- Relationships in source domain → Relationships in target domain
|
| 210 |
+
- Solution steps in analogy → Potential steps for current problem
|
| 211 |
+
4. **Validate Mapping**: Confirm the structural alignment is sound
|
| 212 |
+
- Check that the analogy holds at the relational level
|
| 213 |
+
- Identify any disanalogies or limitations
|
| 214 |
+
|
| 215 |
+
**PHASE 4 - Adapted Solution:**
|
| 216 |
+
5. **Transfer and Adapt**: Apply the analogical insights to solve the current problem
|
| 217 |
+
- Use the mapped solution structure
|
| 218 |
+
- Adapt for domain-specific differences
|
| 219 |
+
- Integrate insights from multiple analogies if applicable
|
| 220 |
+
6. **Verification**: Confirm the adapted solution addresses the original problem
|
| 221 |
+
|
| 222 |
+
**Quality Standards:**
|
| 223 |
+
- Choose genuinely illuminating analogies (not forced or superficial)
|
| 224 |
+
- Make structural mappings explicit and detailed
|
| 225 |
+
- Explain both similarities AND important differences
|
| 226 |
+
- Show how the analogy actually guides the solution
|
| 227 |
+
|
| 228 |
+
**Output Format:**
|
| 229 |
+
Label each phase clearly. Present analogies, mappings, and adapted solution in distinct sections.
|
| 230 |
+
|
| 231 |
+
Be creative in finding analogies while rigorous in applying them.[web:11][web:13][web:15]""",
|
| 232 |
+
|
| 233 |
+
ReasoningMode.SIMPLE: """You are a helpful, knowledgeable AI assistant. Provide clear, accurate, and direct responses.
|
| 234 |
+
|
| 235 |
+
**Core Principles:**
|
| 236 |
+
- Understand the user's question fully before responding
|
| 237 |
+
- Provide accurate, factual information
|
| 238 |
+
- Be concise while remaining complete
|
| 239 |
+
- Use clear, accessible language
|
| 240 |
+
- Structure responses logically
|
| 241 |
+
- Cite sources or acknowledge uncertainty when appropriate
|
| 242 |
+
|
| 243 |
+
**Response Guidelines:**
|
| 244 |
+
- Start with the most direct answer to the question
|
| 245 |
+
- Provide necessary context and explanation
|
| 246 |
+
- Use examples when they enhance understanding
|
| 247 |
+
- Organize complex information with structure (lists, sections, etc.)
|
| 248 |
+
- Adapt detail level to the question's complexity
|
| 249 |
+
- Be helpful and professional in tone
|
| 250 |
+
|
| 251 |
+
Give straightforward, high-quality answers that directly address what the user needs.[web:1][web:5]"""
|
| 252 |
}
|
| 253 |
|
| 254 |
# Pre-built templates for common tasks
|
| 255 |
TEMPLATES: Dict[str, str] = {
|
| 256 |
"Custom": "", # User provides their own
|
| 257 |
|
| 258 |
+
"Research Analysis": """Conduct a comprehensive research analysis on the following topic:
|
| 259 |
|
| 260 |
{query}
|
| 261 |
|
| 262 |
+
**Analysis Framework:**
|
| 263 |
+
1. **Current State of Knowledge**
|
| 264 |
+
- What is currently known? Summarize key established findings
|
| 265 |
+
- What is the scientific/expert consensus?
|
| 266 |
+
- Identify the most significant recent developments (2022-2025)
|
| 267 |
+
|
| 268 |
+
2. **Key Evidence and Findings**
|
| 269 |
+
- Present 3-5 most important research findings
|
| 270 |
+
- Cite methodologies used (studies, experiments, meta-analyses, etc.)
|
| 271 |
+
- Assess the strength and quality of evidence
|
| 272 |
+
- Note any conflicting findings or controversies
|
| 273 |
+
|
| 274 |
+
3. **Gaps and Limitations**
|
| 275 |
+
- What remains unknown or uncertain?
|
| 276 |
+
- What are the methodological limitations of current research?
|
| 277 |
+
- Which questions are under-explored?
|
| 278 |
+
- Where does the evidence remain weak or inconclusive?
|
| 279 |
+
|
| 280 |
+
4. **Future Research Directions**
|
| 281 |
+
- What questions should future research address?
|
| 282 |
+
- Which methodologies would be most valuable?
|
| 283 |
+
- What are the next logical steps in this research area?
|
| 284 |
+
|
| 285 |
+
5. **Practical Implications**
|
| 286 |
+
- How can current findings be applied?
|
| 287 |
+
- What are the real-world implications for policy, practice, or decision-making?
|
| 288 |
+
- What recommendations emerge from the evidence?
|
| 289 |
+
|
| 290 |
+
**Output Requirements:**
|
| 291 |
+
- Maintain objectivity and academic rigor
|
| 292 |
+
- Distinguish between established facts, strong evidence, and speculation
|
| 293 |
+
- Present multiple perspectives when applicable
|
| 294 |
+
- Use precise, technical language where appropriate[web:2][web:5]""",
|
| 295 |
+
|
| 296 |
+
"Problem Solving": """Solve the following problem using systematic analytical methods:
|
| 297 |
|
| 298 |
{query}
|
| 299 |
|
| 300 |
+
**Problem-Solving Framework:**
|
| 301 |
+
|
| 302 |
+
**1. Problem Understanding**
|
| 303 |
+
- Restate the problem in your own words
|
| 304 |
+
- Identify what exactly is being asked
|
| 305 |
+
- Clarify any ambiguous terms or conditions
|
| 306 |
+
- State what constitutes a successful solution
|
| 307 |
+
|
| 308 |
+
**2. Constraint and Requirement Analysis**
|
| 309 |
+
- List all given information and constraints
|
| 310 |
+
- Identify implicit assumptions or requirements
|
| 311 |
+
- Determine boundary conditions or limitations
|
| 312 |
+
- Note any resource restrictions (time, budget, materials, etc.)
|
| 313 |
+
|
| 314 |
+
**3. Solution Strategy**
|
| 315 |
+
- Propose your overall approach
|
| 316 |
+
- Explain WHY this strategy is appropriate
|
| 317 |
+
- Consider if alternative approaches exist
|
| 318 |
+
- Break the solution into phases or components
|
| 319 |
+
|
| 320 |
+
**4. Detailed Solution**
|
| 321 |
+
- Execute your strategy step-by-step
|
| 322 |
+
- Show all work, calculations, or reasoning
|
| 323 |
+
- Explain key decisions or choices made
|
| 324 |
+
- Address each requirement systematically
|
| 325 |
+
|
| 326 |
+
**5. Verification and Validation**
|
| 327 |
+
- Check that your solution satisfies all constraints
|
| 328 |
+
- Test with edge cases or boundary conditions
|
| 329 |
+
- Verify calculations or logic
|
| 330 |
+
- Assess solution quality (optimal vs. adequate)
|
| 331 |
+
- Identify any limitations or assumptions in your solution
|
| 332 |
+
|
| 333 |
+
**Output Format:**
|
| 334 |
+
- Use clear numbered steps
|
| 335 |
+
- Show intermediate work
|
| 336 |
+
- Explain reasoning at each decision point
|
| 337 |
+
- Present final answer clearly and explicitly[web:3][web:5]""",
|
| 338 |
+
|
| 339 |
+
"Code Review": """Perform a comprehensive code review of the following:
|
| 340 |
|
| 341 |
{query}
|
| 342 |
|
| 343 |
+
**Review Framework:**
|
| 344 |
+
|
| 345 |
+
**1. Code Quality Assessment**
|
| 346 |
+
- **Readability**: Is the code easy to understand? Are names descriptive?
|
| 347 |
+
- **Structure**: Is the code well-organized? Proper separation of concerns?
|
| 348 |
+
- **Documentation**: Are comments helpful and appropriate? Is unclear code explained?
|
| 349 |
+
- **Complexity**: Is the code unnecessarily complex? Can it be simplified?
|
| 350 |
+
- **Consistency**: Does it follow consistent style and conventions?
|
| 351 |
+
|
| 352 |
+
**2. Functionality and Correctness**
|
| 353 |
+
- **Logic Errors**: Identify any bugs or logical flaws
|
| 354 |
+
- **Edge Cases**: Are boundary conditions handled correctly?
|
| 355 |
+
- **Error Handling**: Are exceptions and errors managed properly?
|
| 356 |
+
- **Expected Behavior**: Does the code do what it's supposed to do?
|
| 357 |
+
|
| 358 |
+
**3. Performance Considerations**
|
| 359 |
+
- **Efficiency**: Are there algorithmic improvements possible?
|
| 360 |
+
- **Resource Usage**: Memory leaks, unnecessary allocations, or I/O issues?
|
| 361 |
+
- **Scalability**: Will this code scale with larger inputs or load?
|
| 362 |
+
- **Bottlenecks**: Identify performance-critical sections
|
| 363 |
+
|
| 364 |
+
**4. Security Analysis**
|
| 365 |
+
- **Input Validation**: Is user input properly sanitized and validated?
|
| 366 |
+
- **Injection Vulnerabilities**: SQL injection, XSS, command injection risks?
|
| 367 |
+
- **Authentication/Authorization**: Are security controls properly implemented?
|
| 368 |
+
- **Data Protection**: Is sensitive data handled securely?
|
| 369 |
+
- **Dependencies**: Any vulnerable libraries or outdated packages?
|
| 370 |
+
|
| 371 |
+
**5. Best Practice Recommendations**
|
| 372 |
+
- **Design Patterns**: Suggest applicable design patterns
|
| 373 |
+
- **Testing**: Is the code testable? Suggest test cases
|
| 374 |
+
- **Maintainability**: How easy is this to maintain and extend?
|
| 375 |
+
- **Refactoring Suggestions**: Concrete improvements with examples
|
| 376 |
+
|
| 377 |
+
**Output Structure:**
|
| 378 |
+
- Use severity levels (Critical, High, Medium, Low, Suggestion)
|
| 379 |
+
- Provide specific line references or code snippets
|
| 380 |
+
- Include improved code examples for major issues
|
| 381 |
+
- Prioritize issues by impact[web:5]""",
|
| 382 |
+
|
| 383 |
+
"Writing Enhancement": """Enhance and improve the following text:
|
| 384 |
|
| 385 |
{query}
|
| 386 |
|
| 387 |
+
**Enhancement Framework:**
|
| 388 |
+
|
| 389 |
+
**1. Clarity and Coherence**
|
| 390 |
+
- Identify unclear or ambiguous sentences
|
| 391 |
+
- Improve logical flow between ideas
|
| 392 |
+
- Eliminate redundancy and wordiness
|
| 393 |
+
- Ensure each paragraph has a clear focus
|
| 394 |
+
- Strengthen topic sentences and transitions
|
| 395 |
+
|
| 396 |
+
**2. Grammar, Mechanics, and Style**
|
| 397 |
+
- Correct grammatical errors
|
| 398 |
+
- Fix punctuation and spelling issues
|
| 399 |
+
- Improve sentence variety and rhythm
|
| 400 |
+
- Adjust passive voice to active where appropriate
|
| 401 |
+
- Enhance word choice for precision and impact
|
| 402 |
+
|
| 403 |
+
**3. Structural Improvements**
|
| 404 |
+
- Assess overall organization and structure
|
| 405 |
+
- Suggest better paragraph breaks or section divisions
|
| 406 |
+
- Improve opening and closing strength
|
| 407 |
+
- Enhance logical progression of arguments or narrative
|
| 408 |
+
- Balance section lengths appropriately
|
| 409 |
+
|
| 410 |
+
**4. Audience and Purpose Alignment**
|
| 411 |
+
- Identify the target audience and purpose
|
| 412 |
+
- Adjust tone to match audience expectations
|
| 413 |
+
- Ensure appropriate formality level
|
| 414 |
+
- Verify technical language is suitable for readers
|
| 415 |
+
- Enhance persuasiveness or informativeness as needed
|
| 416 |
+
|
| 417 |
+
**5. Enhanced Version**
|
| 418 |
+
- Provide the improved text with all enhancements applied
|
| 419 |
+
- Highlight 3-5 most significant changes made
|
| 420 |
+
- Explain the reasoning behind major revisions
|
| 421 |
+
- Note any trade-offs or alternative approaches considered
|
| 422 |
+
|
| 423 |
+
**Output Format:**
|
| 424 |
+
- Present original version with specific issues noted
|
| 425 |
+
- Provide fully revised version
|
| 426 |
+
- Include a summary of key changes with justifications[web:5]""",
|
| 427 |
+
|
| 428 |
+
"Debate Analysis": """Analyze the following argument, debate, or controversial topic:
|
| 429 |
|
| 430 |
{query}
|
| 431 |
|
| 432 |
+
**Analytical Framework:**
|
| 433 |
+
|
| 434 |
+
**1. Position Identification and Framing**
|
| 435 |
+
- Clearly state each side's core position/thesis
|
| 436 |
+
- Identify the key point(s) of disagreement
|
| 437 |
+
- Clarify what is actually being debated (vs. peripheral issues)
|
| 438 |
+
- Note any definitional disagreements
|
| 439 |
+
|
| 440 |
+
**2. Argument Mapping**
|
| 441 |
+
|
| 442 |
+
**Side A Arguments:**
|
| 443 |
+
- List main arguments with supporting premises
|
| 444 |
+
- Identify types of evidence used (empirical, logical, ethical, etc.)
|
| 445 |
+
- Note underlying assumptions or values
|
| 446 |
+
|
| 447 |
+
**Side B Arguments:**
|
| 448 |
+
- List main arguments with supporting premises
|
| 449 |
+
- Identify types of evidence used
|
| 450 |
+
- Note underlying assumptions or values
|
| 451 |
+
|
| 452 |
+
**3. Evidence Evaluation**
|
| 453 |
+
- **Quality Assessment**: How strong is each piece of evidence?
|
| 454 |
+
- **Source Credibility**: Are sources reliable and authoritative?
|
| 455 |
+
- **Relevance**: Does evidence directly support the claims?
|
| 456 |
+
- **Completeness**: Is contradictory evidence being ignored?
|
| 457 |
+
- **Recency**: Is the evidence current and applicable?
|
| 458 |
+
|
| 459 |
+
**4. Logical Analysis**
|
| 460 |
+
- **Valid Reasoning**: Are the arguments logically sound?
|
| 461 |
+
- **Fallacies**: Identify any logical fallacies (ad hominem, straw man, false dilemma, slippery slope, appeal to emotion, etc.)
|
| 462 |
+
- **Consistency**: Are positions internally consistent?
|
| 463 |
+
- **Burden of Proof**: Which side bears the burden, and have they met it?
|
| 464 |
+
|
| 465 |
+
**5. Strongest Points**
|
| 466 |
+
- Identify the 2-3 strongest arguments from each side
|
| 467 |
+
- Explain why these arguments are particularly compelling
|
| 468 |
+
- Assess which points are most difficult to refute
|
| 469 |
+
|
| 470 |
+
**6. Balanced Conclusion**
|
| 471 |
+
- Synthesize the analysis into an overall assessment
|
| 472 |
+
- Identify which position has stronger support (if applicable)
|
| 473 |
+
- Note areas of legitimate uncertainty or value disagreement
|
| 474 |
+
- Suggest what additional evidence or arguments would be decisive
|
| 475 |
+
- Present a nuanced, fair-minded conclusion
|
| 476 |
+
|
| 477 |
+
**Output Requirements:**
|
| 478 |
+
- Maintain objectivity throughout analysis
|
| 479 |
+
- Steelman each position (present strongest version)
|
| 480 |
+
- Separate factual disagreements from value disagreements
|
| 481 |
+
- Acknowledge complexity and avoid false certainty[web:4][web:5]""",
|
| 482 |
+
|
| 483 |
+
"Learning Explanation": """Explain the following concept in a clear, educational manner:
|
| 484 |
|
| 485 |
{query}
|
| 486 |
|
| 487 |
+
**Explanation Framework:**
|
| 488 |
+
|
| 489 |
+
**1. Simple Definition**
|
| 490 |
+
- Provide a clear, concise definition (1-2 sentences)
|
| 491 |
+
- Avoid jargon in the initial definition
|
| 492 |
+
- Capture the essence of the concept
|
| 493 |
+
|
| 494 |
+
**2. Core Principles and Components**
|
| 495 |
+
- Break down the concept into 3-5 key elements
|
| 496 |
+
- Explain each component clearly
|
| 497 |
+
- Show how components relate to each other
|
| 498 |
+
- Build understanding progressively from simple to complex
|
| 499 |
+
|
| 500 |
+
**3. Concrete Examples and Analogies**
|
| 501 |
+
- Provide 2-3 real-world examples
|
| 502 |
+
- Use relatable analogies to clarify abstract concepts
|
| 503 |
+
- Show the concept in different contexts
|
| 504 |
+
- Include both typical and edge-case examples
|
| 505 |
+
|
| 506 |
+
**4. Common Misconceptions**
|
| 507 |
+
- Identify 2-3 frequent misunderstandings
|
| 508 |
+
- Explain WHY these misconceptions arise
|
| 509 |
+
- Clarify the correct understanding
|
| 510 |
+
- Provide examples that illustrate the difference
|
| 511 |
+
|
| 512 |
+
**5. Practical Applications**
|
| 513 |
+
- How is this concept used in practice?
|
| 514 |
+
- Why is understanding this concept valuable?
|
| 515 |
+
- What problems does it help solve?
|
| 516 |
+
- How might a learner apply this knowledge?
|
| 517 |
+
|
| 518 |
+
**6. Progressive Depth** (Optional for complex topics)
|
| 519 |
+
- **Basic Level**: Essential understanding for beginners
|
| 520 |
+
- **Intermediate Level**: Additional nuance and detail
|
| 521 |
+
- **Advanced Level**: Sophisticated aspects and edge cases
|
| 522 |
+
|
| 523 |
+
**Teaching Principles:**
|
| 524 |
+
- Start with what the learner likely already knows
|
| 525 |
+
- Build new knowledge on existing foundations
|
| 526 |
+
- Use clear, accessible language
|
| 527 |
+
- Check for understanding at each step
|
| 528 |
+
- Encourage active engagement with examples[web:5][web:13]""",
|
| 529 |
+
|
| 530 |
+
"Simple": """Answer the following question directly and comprehensively:
|
| 531 |
|
| 532 |
+
{query}
|
| 533 |
|
| 534 |
+
**Response Guidelines:**
|
| 535 |
+
- Provide the core answer in the first 1-2 sentences
|
| 536 |
+
- Support with relevant details and context
|
| 537 |
+
- Be accurate and factual
|
| 538 |
+
- Use clear, accessible language
|
| 539 |
+
- Structure information logically (use lists or sections if helpful)
|
| 540 |
+
- Be concise while remaining complete[web:1][web:5]"""
|
| 541 |
}
|
| 542 |
|
| 543 |
@classmethod
|
|
|
|
| 599 |
@classmethod
|
| 600 |
def get_self_critique_prompt(cls, original_response: str) -> str:
|
| 601 |
"""
|
| 602 |
+
✅ GENERATE ENHANCED SELF-CRITIQUE PROMPT
|
| 603 |
"""
|
| 604 |
+
return f"""Perform rigorous self-critique and refinement of your previous response:
|
| 605 |
|
| 606 |
+
**ORIGINAL RESPONSE:**
|
| 607 |
{original_response}
|
| 608 |
|
| 609 |
+
**CRITICAL EVALUATION FRAMEWORK:**
|
| 610 |
+
|
| 611 |
+
**1. Accuracy and Correctness**
|
| 612 |
+
- Identify any factual errors, inaccuracies, or outdated information
|
| 613 |
+
- Check all claims against your knowledge
|
| 614 |
+
- Verify logical validity of arguments
|
| 615 |
+
- Note any overstatements or unsupported assertions
|
| 616 |
+
|
| 617 |
+
**2. Completeness Analysis**
|
| 618 |
+
- What important aspects were overlooked or underemphasized?
|
| 619 |
+
- Are there missing perspectives or considerations?
|
| 620 |
+
- Did you address all parts of the original question?
|
| 621 |
+
- What additional context would strengthen the response?
|
| 622 |
+
|
| 623 |
+
**3. Clarity and Communication**
|
| 624 |
+
- Identify unclear, ambiguous, or confusing sections
|
| 625 |
+
- Check for unnecessary jargon or complexity
|
| 626 |
+
- Assess logical flow and organization
|
| 627 |
+
- Note where examples or analogies would help
|
| 628 |
+
|
| 629 |
+
**4. Reasoning Quality**
|
| 630 |
+
- Evaluate the soundness of logical reasoning
|
| 631 |
+
- Identify any logical fallacies or weak arguments
|
| 632 |
+
- Assess whether conclusions follow from premises
|
| 633 |
+
- Check for inconsistencies or contradictions
|
| 634 |
+
|
| 635 |
+
**5. Bias and Balance**
|
| 636 |
+
- Identify any unacknowledged assumptions or biases
|
| 637 |
+
- Check if multiple perspectives were fairly considered
|
| 638 |
+
- Note any missing counterarguments or caveats
|
| 639 |
+
- Assess appropriate confidence levels (avoiding false certainty)
|
| 640 |
+
|
| 641 |
+
**6. Specific Improvements**
|
| 642 |
+
- List 3-5 concrete, actionable improvements
|
| 643 |
+
- Prioritize improvements by impact (Critical > Important > Minor)
|
| 644 |
+
- Provide specific examples of how to fix each issue
|
| 645 |
+
|
| 646 |
+
**7. Refined Response**
|
| 647 |
+
- Provide an improved version incorporating all major corrections
|
| 648 |
+
- Highlight what changed and why
|
| 649 |
+
- Explain how the refined version is superior
|
| 650 |
+
- Acknowledge any remaining limitations or uncertainties
|
| 651 |
+
|
| 652 |
+
**Quality Standards:**
|
| 653 |
+
- Be genuinely critical, not defensive of the original response
|
| 654 |
+
- Focus on substantive improvements, not just stylistic tweaks
|
| 655 |
+
- Provide concrete, specific feedback rather than vague observations
|
| 656 |
+
- Demonstrate meaningful enhancement in the refined version
|
| 657 |
+
|
| 658 |
+
Be thorough, honest, and constructive in your self-evaluation.[web:8][web:17][web:20]"""
|
src/services/export_service.py
CHANGED
|
@@ -102,85 +102,236 @@ class ConversationExporter:
|
|
| 102 |
return "\n".join(lines)
|
| 103 |
|
| 104 |
def export_to_pdf(self, conversations: List[ConversationEntry],
|
| 105 |
-
include_metadata: bool = True
|
|
|
|
|
|
|
|
|
|
| 106 |
"""
|
| 107 |
-
📄 EXPORT TO PDF
|
| 108 |
-
|
|
|
|
| 109 |
"""
|
| 110 |
if not AppConfig.ENABLE_PDF_EXPORT:
|
| 111 |
logger.warning("⚠️ PDF export is disabled")
|
| 112 |
return None
|
| 113 |
-
|
| 114 |
try:
|
| 115 |
from reportlab.lib.pagesizes import letter
|
| 116 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 117 |
from reportlab.lib.units import inch
|
| 118 |
-
from reportlab.platypus import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
from reportlab.lib.enums import TA_LEFT, TA_CENTER
|
|
|
|
|
|
|
| 120 |
except ImportError:
|
| 121 |
logger.error("❌ reportlab not installed. Install with: pip install reportlab")
|
| 122 |
return None
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 125 |
filename = self.export_dir / f"conversation_export_{timestamp}.pdf"
|
| 126 |
-
|
| 127 |
-
doc = SimpleDocTemplate(
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
title_style = ParagraphStyle(
|
| 132 |
-
'
|
| 133 |
-
parent=
|
| 134 |
-
|
| 135 |
-
|
|
|
|
| 136 |
alignment=TA_CENTER,
|
| 137 |
-
|
|
|
|
| 138 |
)
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
story = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
))
|
| 148 |
-
story.append(
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
))
|
| 152 |
-
story.append(Spacer(1, 0.3*inch))
|
| 153 |
-
|
| 154 |
-
# Conversations
|
| 155 |
for idx, conv in enumerate(conversations, 1):
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
if include_metadata:
|
| 159 |
meta_text = (
|
| 160 |
-
f"<b>Timestamp:</b> {conv.timestamp}
|
| 161 |
-
f"<b>Model:</b> {conv.model}
|
| 162 |
-
f"<b>Mode:</b> {conv.reasoning_mode}
|
| 163 |
-
f"<b>Tokens:</b> {conv
|
| 164 |
-
f"<b>Time:</b> {conv
|
| 165 |
)
|
| 166 |
-
story.append(Paragraph(meta_text,
|
| 167 |
-
story.append(Spacer(1, 0.
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
story.append(Paragraph(
|
| 171 |
-
story.append(
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
| 176 |
if idx < len(conversations):
|
|
|
|
| 177 |
story.append(PageBreak())
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
| 180 |
logger.info(f"✅ PDF exported: {filename}")
|
| 181 |
-
|
| 182 |
-
# Return string path for Gradio compatibility
|
| 183 |
return str(filename)
|
|
|
|
| 184 |
|
| 185 |
def export(self, conversations: List[ConversationEntry],
|
| 186 |
format_type: str, include_metadata: bool = True) -> Tuple[str, Optional[str]]:
|
|
@@ -195,17 +346,17 @@ class ConversationExporter:
|
|
| 195 |
if format_type == "json":
|
| 196 |
content = self.export_to_json(conversations, include_metadata)
|
| 197 |
filename = self._save_to_file(content, "json")
|
| 198 |
-
return content, str(filename)
|
| 199 |
|
| 200 |
elif format_type == "markdown":
|
| 201 |
content = self.export_to_markdown(conversations, include_metadata)
|
| 202 |
filename = self._save_to_file(content, "md")
|
| 203 |
-
return content, str(filename)
|
| 204 |
|
| 205 |
elif format_type == "txt":
|
| 206 |
content = self.export_to_txt(conversations, include_metadata)
|
| 207 |
filename = self._save_to_file(content, "txt")
|
| 208 |
-
return content, str(filename)
|
| 209 |
|
| 210 |
elif format_type == "pdf":
|
| 211 |
filename = self.export_to_pdf(conversations, include_metadata)
|
|
@@ -247,8 +398,8 @@ class ConversationExporter:
|
|
| 247 |
filename.write_text(content, encoding='utf-8')
|
| 248 |
|
| 249 |
logger.info(f"✅ Backup created: {filename}")
|
| 250 |
-
return str(filename)
|
| 251 |
|
| 252 |
except Exception as e:
|
| 253 |
logger.error(f"❌ Backup failed: {e}")
|
| 254 |
-
return None
|
|
|
|
| 102 |
return "\n".join(lines)
|
| 103 |
|
| 104 |
def export_to_pdf(self, conversations: List[ConversationEntry],
|
| 105 |
+
include_metadata: bool = True,
|
| 106 |
+
title: str = "Conversation Export",
|
| 107 |
+
subtitle: Optional[str] = None,
|
| 108 |
+
author: Optional[str] = None) -> Optional[str]:
|
| 109 |
"""
|
| 110 |
+
📄 EXPORT TO PDF — Premium design with proper page breaking
|
| 111 |
+
|
| 112 |
+
Returns the string path for compatibility with Gradio (or None on error).
|
| 113 |
"""
|
| 114 |
if not AppConfig.ENABLE_PDF_EXPORT:
|
| 115 |
logger.warning("⚠️ PDF export is disabled")
|
| 116 |
return None
|
| 117 |
+
|
| 118 |
try:
|
| 119 |
from reportlab.lib.pagesizes import letter
|
| 120 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 121 |
from reportlab.lib.units import inch
|
| 122 |
+
from reportlab.platypus import (
|
| 123 |
+
SimpleDocTemplate,
|
| 124 |
+
Paragraph,
|
| 125 |
+
Spacer,
|
| 126 |
+
PageBreak,
|
| 127 |
+
)
|
| 128 |
+
from reportlab.lib import colors
|
| 129 |
from reportlab.lib.enums import TA_LEFT, TA_CENTER
|
| 130 |
+
from reportlab.pdfbase import pdfmetrics
|
| 131 |
+
from reportlab.pdfbase.ttfonts import TTFont
|
| 132 |
except ImportError:
|
| 133 |
logger.error("❌ reportlab not installed. Install with: pip install reportlab")
|
| 134 |
return None
|
| 135 |
+
|
| 136 |
+
def _escape_for_paragraph(text: Optional[str]) -> str:
|
| 137 |
+
"""Safely escape text for reportlab Paragraph"""
|
| 138 |
+
if text is None:
|
| 139 |
+
return ""
|
| 140 |
+
s = str(text)
|
| 141 |
+
s = s.replace('&', '&').replace('<', '<').replace('>', '>')
|
| 142 |
+
s = s.replace('\n', '<br/>')
|
| 143 |
+
return s
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
default_font = 'Helvetica'
|
| 147 |
+
default_bold = 'Helvetica-Bold'
|
| 148 |
+
except Exception:
|
| 149 |
+
default_font = 'Helvetica'
|
| 150 |
+
default_bold = 'Helvetica-Bold'
|
| 151 |
+
|
| 152 |
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 153 |
filename = self.export_dir / f"conversation_export_{timestamp}.pdf"
|
| 154 |
+
|
| 155 |
+
doc = SimpleDocTemplate(
|
| 156 |
+
str(filename),
|
| 157 |
+
pagesize=letter,
|
| 158 |
+
leftMargin=0.7 * inch,
|
| 159 |
+
rightMargin=0.7 * inch,
|
| 160 |
+
topMargin=1.0 * inch,
|
| 161 |
+
bottomMargin=0.8 * inch,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
base_styles = getSampleStyleSheet()
|
| 165 |
+
|
| 166 |
+
# Define all styles
|
| 167 |
title_style = ParagraphStyle(
|
| 168 |
+
'TitlePremium',
|
| 169 |
+
parent=base_styles['Heading1'],
|
| 170 |
+
fontName=default_bold,
|
| 171 |
+
fontSize=26,
|
| 172 |
+
leading=30,
|
| 173 |
alignment=TA_CENTER,
|
| 174 |
+
textColor=colors.HexColor('#0f172a'),
|
| 175 |
+
spaceAfter=12,
|
| 176 |
)
|
| 177 |
+
|
| 178 |
+
subtitle_style = ParagraphStyle(
|
| 179 |
+
'SubtitlePremium',
|
| 180 |
+
parent=base_styles['Normal'],
|
| 181 |
+
fontName=default_font,
|
| 182 |
+
fontSize=11,
|
| 183 |
+
leading=14,
|
| 184 |
+
alignment=TA_CENTER,
|
| 185 |
+
textColor=colors.HexColor('#475569'),
|
| 186 |
+
spaceAfter=18,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
conv_header_style = ParagraphStyle(
|
| 190 |
+
'ConvHeader',
|
| 191 |
+
parent=base_styles['Heading2'],
|
| 192 |
+
fontName=default_bold,
|
| 193 |
+
fontSize=12,
|
| 194 |
+
leading=14,
|
| 195 |
+
textColor=colors.HexColor('#0f172a'),
|
| 196 |
+
spaceAfter=6,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
body_style = ParagraphStyle(
|
| 200 |
+
'BodyText',
|
| 201 |
+
parent=base_styles['Normal'],
|
| 202 |
+
fontName=default_font,
|
| 203 |
+
fontSize=10.5,
|
| 204 |
+
leading=14,
|
| 205 |
+
alignment=TA_LEFT,
|
| 206 |
+
textColor=colors.HexColor('#0f172a'),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
small_italic = ParagraphStyle(
|
| 210 |
+
'SmallItalic',
|
| 211 |
+
parent=base_styles['Normal'],
|
| 212 |
+
fontName=default_font,
|
| 213 |
+
fontSize=9,
|
| 214 |
+
leading=11,
|
| 215 |
+
textColor=colors.HexColor('#6b7280'),
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Styles for user and assistant content with backgrounds
|
| 219 |
+
user_content_style = ParagraphStyle(
|
| 220 |
+
'UserContent',
|
| 221 |
+
parent=body_style,
|
| 222 |
+
backColor=colors.HexColor('#f1f5f9'),
|
| 223 |
+
borderColor=colors.HexColor('#e2e8f0'),
|
| 224 |
+
borderWidth=0.5,
|
| 225 |
+
borderPadding=8,
|
| 226 |
+
leftIndent=8,
|
| 227 |
+
rightIndent=8,
|
| 228 |
+
spaceBefore=4,
|
| 229 |
+
spaceAfter=4,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
assistant_content_style = ParagraphStyle(
|
| 233 |
+
'AssistantContent',
|
| 234 |
+
parent=body_style,
|
| 235 |
+
backColor=colors.HexColor('#eef2ff'),
|
| 236 |
+
borderColor=colors.HexColor('#e2e8f0'),
|
| 237 |
+
borderWidth=0.5,
|
| 238 |
+
borderPadding=8,
|
| 239 |
+
leftIndent=8,
|
| 240 |
+
rightIndent=8,
|
| 241 |
+
spaceBefore=4,
|
| 242 |
+
spaceAfter=4,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
border_color = colors.HexColor('#e2e8f0')
|
| 246 |
+
|
| 247 |
+
def _draw_header(canvas_obj, doc_obj):
|
| 248 |
+
canvas_obj.saveState()
|
| 249 |
+
width, height = doc_obj.pagesize
|
| 250 |
+
header_height = 0.65 * inch
|
| 251 |
+
canvas_obj.setFillColor(colors.HexColor('#4f46e5'))
|
| 252 |
+
canvas_obj.rect(0, height - header_height, width, header_height, stroke=0, fill=1)
|
| 253 |
+
canvas_obj.setFillColor(colors.white)
|
| 254 |
+
canvas_obj.setFont(default_bold, 14)
|
| 255 |
+
canvas_obj.drawString(doc_obj.leftMargin, height - 0.45 * inch, title)
|
| 256 |
+
canvas_obj.setFont(default_font, 8)
|
| 257 |
+
right_meta = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 258 |
+
text_width = canvas_obj.stringWidth(right_meta, default_font, 8)
|
| 259 |
+
canvas_obj.drawString(width - doc_obj.rightMargin - text_width, height - 0.45 * inch, right_meta)
|
| 260 |
+
canvas_obj.restoreState()
|
| 261 |
+
|
| 262 |
+
def _draw_footer(canvas_obj, doc_obj):
|
| 263 |
+
canvas_obj.saveState()
|
| 264 |
+
width, _ = doc_obj.pagesize
|
| 265 |
+
footer_y = 0.5 * inch
|
| 266 |
+
canvas_obj.setStrokeColor(border_color)
|
| 267 |
+
canvas_obj.setLineWidth(0.5)
|
| 268 |
+
canvas_obj.line(doc_obj.leftMargin, footer_y + 6, width - doc_obj.rightMargin, footer_y + 6)
|
| 269 |
+
page_num_text = f"Page {canvas_obj.getPageNumber()}"
|
| 270 |
+
canvas_obj.setFont(default_font, 9)
|
| 271 |
+
canvas_obj.setFillColor(colors.HexColor('#6b7280'))
|
| 272 |
+
canvas_obj.drawString(doc_obj.leftMargin, footer_y - 2, page_num_text)
|
| 273 |
+
brand = author if author else 'Generated by Advanced AI Reasoning System Pro'
|
| 274 |
+
brand_width = canvas_obj.stringWidth(brand, default_font, 9)
|
| 275 |
+
canvas_obj.drawString(width - doc_obj.rightMargin - brand_width, footer_y - 2, brand)
|
| 276 |
+
canvas_obj.restoreState()
|
| 277 |
+
|
| 278 |
+
def _draw_page(canvas_obj, doc_obj):
|
| 279 |
+
_draw_header(canvas_obj, doc_obj)
|
| 280 |
+
_draw_footer(canvas_obj, doc_obj)
|
| 281 |
+
|
| 282 |
story = []
|
| 283 |
+
|
| 284 |
+
# Cover
|
| 285 |
+
story.append(Spacer(1, 0.2 * inch))
|
| 286 |
+
story.append(Paragraph(_escape_for_paragraph(title), title_style))
|
| 287 |
+
if subtitle:
|
| 288 |
+
story.append(Paragraph(_escape_for_paragraph(subtitle), subtitle_style))
|
| 289 |
|
| 290 |
+
meta_lines = []
|
| 291 |
+
meta_lines.append(f"<b>Export Date:</b> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 292 |
+
meta_lines.append(f"<b>Total Conversations:</b> {len(conversations)}")
|
| 293 |
+
if author:
|
| 294 |
+
meta_lines.append(f"<b>Author:</b> {author}")
|
| 295 |
+
story.append(Paragraph(' | '.join(meta_lines), small_italic))
|
| 296 |
+
story.append(Spacer(1, 0.25 * inch))
|
| 297 |
+
|
| 298 |
+
# Process each conversation
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
for idx, conv in enumerate(conversations, 1):
|
| 300 |
+
# Conversation header
|
| 301 |
+
conv_title = f"Conversation {idx}"
|
| 302 |
+
story.append(Paragraph(_escape_for_paragraph(conv_title), conv_header_style))
|
| 303 |
+
|
| 304 |
if include_metadata:
|
| 305 |
meta_text = (
|
| 306 |
+
f"<b>Timestamp:</b> {conv.timestamp} | "
|
| 307 |
+
f"<b>Model:</b> {conv.model} | "
|
| 308 |
+
f"<b>Mode:</b> {conv.reasoning_mode} | "
|
| 309 |
+
f"<b>Tokens:</b> {getattr(conv, 'tokens_used', 'N/A')} | "
|
| 310 |
+
f"<b>Time:</b> {getattr(conv, 'inference_time', 0):.2f}s"
|
| 311 |
)
|
| 312 |
+
story.append(Paragraph(meta_text, small_italic))
|
| 313 |
+
story.append(Spacer(1, 0.08 * inch))
|
| 314 |
+
|
| 315 |
+
# User message - simple paragraph with styling
|
| 316 |
+
story.append(Paragraph('<b>👤 User</b>', body_style))
|
| 317 |
+
story.append(Paragraph(_escape_for_paragraph(conv.user_message), user_content_style))
|
| 318 |
+
story.append(Spacer(1, 0.12 * inch))
|
| 319 |
+
|
| 320 |
+
# Assistant response - simple paragraph with styling
|
| 321 |
+
story.append(Paragraph('<b>🤖 Assistant</b>', body_style))
|
| 322 |
+
story.append(Paragraph(_escape_for_paragraph(conv.assistant_response), assistant_content_style))
|
| 323 |
+
|
| 324 |
+
# Spacing between conversations
|
| 325 |
if idx < len(conversations):
|
| 326 |
+
story.append(Spacer(1, 0.2 * inch))
|
| 327 |
story.append(PageBreak())
|
| 328 |
+
|
| 329 |
+
# Build the PDF
|
| 330 |
+
doc.build(story, onFirstPage=_draw_page, onLaterPages=_draw_page)
|
| 331 |
+
|
| 332 |
logger.info(f"✅ PDF exported: {filename}")
|
|
|
|
|
|
|
| 333 |
return str(filename)
|
| 334 |
+
|
| 335 |
|
| 336 |
def export(self, conversations: List[ConversationEntry],
|
| 337 |
format_type: str, include_metadata: bool = True) -> Tuple[str, Optional[str]]:
|
|
|
|
| 346 |
if format_type == "json":
|
| 347 |
content = self.export_to_json(conversations, include_metadata)
|
| 348 |
filename = self._save_to_file(content, "json")
|
| 349 |
+
return content, str(filename)
|
| 350 |
|
| 351 |
elif format_type == "markdown":
|
| 352 |
content = self.export_to_markdown(conversations, include_metadata)
|
| 353 |
filename = self._save_to_file(content, "md")
|
| 354 |
+
return content, str(filename)
|
| 355 |
|
| 356 |
elif format_type == "txt":
|
| 357 |
content = self.export_to_txt(conversations, include_metadata)
|
| 358 |
filename = self._save_to_file(content, "txt")
|
| 359 |
+
return content, str(filename)
|
| 360 |
|
| 361 |
elif format_type == "pdf":
|
| 362 |
filename = self.export_to_pdf(conversations, include_metadata)
|
|
|
|
| 398 |
filename.write_text(content, encoding='utf-8')
|
| 399 |
|
| 400 |
logger.info(f"✅ Backup created: {filename}")
|
| 401 |
+
return str(filename)
|
| 402 |
|
| 403 |
except Exception as e:
|
| 404 |
logger.error(f"❌ Backup failed: {e}")
|
| 405 |
+
return None
|