File size: 6,393 Bytes
f39ba75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# agents/mnemonic_agent.py
"""
Mnemonic Creation Agent - Creates memory aids and tricks using Generative AI.
"""
import re
from .agent_helpers import format_history_for_prompt
class MnemonicAgent:
    def __init__(self, gemini_model=None):
        """
        Initializes the agent with the Gemini model.

        Args:
            gemini_model: An instance of the Gemini model client.
        """
        self.model = gemini_model

    def _extract_topic(self, query: str) -> str:
        """A simple helper to extract the core topic from the user's query."""
        # Remove common phrases used to request mnemonics
        patterns = [
            r"make a mnemonic for",
            r"create a mnemonic for",
            r"give me a mnemonic for",
            r"mnemonic for",
            r"memory aid for"
        ]
        topic = query.lower()
        for p in patterns:
            topic = re.sub(p, "", topic)
        
        # Clean up any extra whitespace
        return topic.strip()
    def process_query(self, query: str, file_context: str = "", chat_history: list = None):
        """
        Processes a query to generate a mnemonic.

        Args:
            query (str): The user's full query (e.g., "Give me a mnemonic for glycolysis steps").
            file_context (str): Optional context from uploaded files.
            chat_history (list): The history of the conversation.

        Returns:
            dict: A dictionary containing the response message and agent metadata.
        """
        if not self.model:
            return {'message': "🧠 My creative circuits are offline! The Gemini API key is missing.", 'agent_used': 'mnemonic_creation', 'status': 'error_no_api_key'}

        history_for_prompt = format_history_for_prompt(chat_history)
        topic = self._extract_topic(query)
        context_section = f"---\nCONTEXT FROM KNOWLEDGE BASE:\n{file_context}\n---" if file_context else ""
        prompt = f"""You are "Mnemonic Master," a creative AI that creates memorable mnemonics for B.Pharmacy students.
        **CRITICAL INSTRUCTION FOR CITATIONS:** When you use information from the KNOWLEDGE BASE CONTEXT, you MUST cite the source at the end of the relevant sentence using the format `[Source: filename, Page: page_number]`.
get the topic from {topic}
CONVERSATION HISTORY:
{context_section}
{history_for_prompt}
CURRENT TASK:
User: {query}

Based on the CURRENT TASK and conversation history, generate a clever mnemonic (acronym, rhyme, or story). If the user is asking for a modification of a previous mnemonic, adjust it accordingly. Explain how the mnemonic works. Be encouraging and fun! with emojis and  like tenali ramakrishna
"""
        try:
            response = self.model.generate_content(prompt)
            return {'message': response.text, 'agent_used': 'mnemonic_creation', 'status': 'success'}
        except Exception as e:
            print(f"Mnemonic Agent Error: {e}")
            return {'message': f"My creative spark fizzled out. Error: {e}", 'agent_used': 'mnemonic_creation', 'status': 'error_api_call'}

    # def process_query(self, query: str, file_context: str = "",chat_history: list = None):
#         """
#         Processes a query to generate a mnemonic.

#         Args:
#             query (str): The user's full query (e.g., "Give me a mnemonic for glycolysis steps").
#             file_context (str): Optional context from uploaded files (usually not needed for mnemonics).
        
#         Returns:
#             dict: A dictionary containing the response message and agent metadata.
#         """
#         # Fallback response if the AI model is not configured
#         if not self.model:
#             return {
#                 'message': "🧠 **Mnemonic Master**\n\nMy creative circuits are offline! The Gemini API key is missing, so I can't generate mnemonics right now. Please configure the API key to enable this feature.",
#                 'agent_type': 'mnemonic_creation',
#                 'status': 'error_no_api_key'
#             }

#         topic = self._extract_topic(query)
#         if not topic:
#             return {
#                 'message': "Please tell me what topic you need a mnemonic for! For example, try 'mnemonic for Krebs cycle intermediates'.",
#                 'agent_type': 'mnemonic_creation',
#                 'status': 'error_no_topic'
#             }
#          # --- NEW LOGIC ---
#         task_description = f"Generate a clever mnemonic for the B.Pharmacy topic: **{topic.title()}**."

#         if file_context:
#             task_description += f"\n\nIf relevant, you can use the following text from the student's uploaded notes for context:\n---\n{file_context}\n---"


#         # Construct a specialized prompt for the Gemini model
#         prompt = f"""
# You are "Mnemonic Master," a creative and witty AI that excels at creating memorable mnemonics for B.Pharmacy students in India.

# **Your Task:**
# {task_description}

# **Topic:** "{topic}"

# **Instructions:**
# 1.  **Analyze the Topic:** Identify the key items to be memorized (e.g., steps, drug names, classifications).
# 2.  **Create the Mnemonic:** Design a creative acronym, rhyme, or short, vivid story.
# 3.  **Explain It:** Clearly state the mnemonic and then explain how it maps to the concepts.
# 4.  **Tone:** Be encouraging, fun, and use emojis! The language should be simple and relatable.

# **Example Output Format:**

# 🧠 **Mnemonic for [Topic Name]**

# Here's a fun way to remember it!

# **The Mnemonic:**
# "[The actual acronym or rhyme]"

# **How it works:**
# * **[Letter 1]** stands for [Concept 1]
# * **[Letter 2]** stands for [Concept 2]
# * ...and so on!

# Keep up the great work! You've got this! 💪
# """

#         try:
#             # Generate content using the AI model
#             ai_response = self.model.generate_content(prompt,chat_history)
#             return {
#                 'message': ai_response.text,
#                 'agent_used': 'mnemonic_creation',
#                 'status': 'success'
#             }
#         except Exception as e:
#             print(f"Mnemonic Agent Error: {e}")
#             return {
#                 'message': f"Oh no! My creative spark fizzled out. I ran into an error: {str(e)}",
#                 'agent_type': 'mnemonic_creation',
#                 'status': 'error_api_call'
#             }