Spaces:
Sleeping
Sleeping
# 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' | |
# } |