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IGN4PSI1IiBjeT0iMTkiIHI9IjEuNSIvPgogIDxsaW5lIHgxPSIxMy41IiB5MT0iMTMuNSIgeDI9IjE4IiB5Mj0iMTgiLz4KICA8Y2lyY2xlIGN4PSIxOSIgY3k9IjE5IiByPSIxLjUiLz4KPC9zdmc+ version: 0.7.3 description: 智能分析长文本并生成交互式思维导图,支持 SVG/Markdown 导出。 """ from pydantic import BaseModel, Field from typing import Optional, Dict, Any import logging import time import re from fastapi import Request from datetime import datetime import pytz from open_webui.utils.chat import generate_chat_completion from open_webui.models.users import Users logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) SYSTEM_PROMPT_MINDMAP_ASSISTANT = """ You are a professional mind map generation assistant, capable of efficiently analyzing long-form text provided by users and structuring its core themes, key concepts, branches, and sub-branches into standard Markdown list syntax for rendering by Markmap.js. Please strictly follow these guidelines: - **Language**: All output must be in the language specified by the user. - **Format**: Your output must strictly be in Markdown list format, wrapped with ```markdown and ```. - Use `#` to define the central theme (root node). - Use `-` with two-space indentation to represent branches and sub-branches. - **Content**: - Identify the central theme of the text as the `#` heading. - Identify main concepts as first-level list items. - Identify supporting details or sub-concepts as nested list items. - Node content should be concise and clear, avoiding verbosity. - **Output Markdown syntax only**: Do not include any additional greetings, explanations, or guiding text. - **If text is too short or cannot generate a valid mind map**: Output a simple Markdown list indicating inability to generate, for example: ```markdown # Unable to Generate Mind Map - Reason: Insufficient or unclear text content ``` """ USER_PROMPT_GENERATE_MINDMAP = """ Please analyze the following long-form text and structure its core themes, key concepts, branches, and sub-branches into standard Markdown list syntax for Markmap.js rendering. --- **User Context Information:** User Name: {user_name} Current Date & Time: {current_date_time_str} Current Weekday: {current_weekday} Current Timezone: {current_timezone_str} User Language: {user_language} --- **Long-form Text Content:** {long_text_content} """ HTML_TEMPLATE_MINDMAP = """ Smart Mind Map: Mind Map Visualization

🧠 Smart Mind Map

User: {user_name} Analysis Time: {current_date_time_str} Weekday: {current_weekday_zh}
""" class Action: class Valves(BaseModel): show_status: bool = Field( default=True, description="Whether to show action status updates in the chat interface.", ) LLM_MODEL_ID: str = Field( default="gemini-2.5-flash", description="Built-in LLM model ID for text analysis.", ) MIN_TEXT_LENGTH: int = Field( default=100, description="Minimum text length (character count) required for mind map analysis.", ) def __init__(self): self.valves = self.Valves() self.weekday_map = { "Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday", "Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sunday": "Sunday", } def _extract_markdown_syntax(self, llm_output: str) -> str: match = re.search(r"```markdown\s*(.*?)\s*```", llm_output, re.DOTALL) if match: extracted_content = match.group(1).strip() else: logger.warning( "LLM output did not strictly follow the expected Markdown format, treating the entire output as summary." ) extracted_content = llm_output.strip() return extracted_content.replace("", "<\\/script>") async def action( self, body: dict, __user__: Optional[Dict[str, Any]] = None, __event_emitter__: Optional[Any] = None, __request__: Optional[Request] = None, ) -> Optional[dict]: logger.info("Action: Smart Mind Map (v0.7.2) started") if isinstance(__user__, (list, tuple)): user_language = ( __user__[0].get("language", "en-US") if __user__ else "en-US" ) user_name = __user__[0].get("name", "User") if __user__[0] else "User" user_id = ( __user__[0]["id"] if __user__ and "id" in __user__[0] else "unknown_user" ) elif isinstance(__user__, dict): user_language = __user__.get("language", "en-US") user_name = __user__.get("name", "User") user_id = __user__.get("id", "unknown_user") try: shanghai_tz = pytz.timezone("Asia/Shanghai") current_datetime_shanghai = datetime.now(shanghai_tz) current_date_time_str = current_datetime_shanghai.strftime( "%Y-%m-%d %H:%M:%S" ) current_weekday_en = current_datetime_shanghai.strftime("%A") current_weekday_zh = self.weekday_map.get(current_weekday_en, "Unknown") current_year = current_datetime_shanghai.strftime("%Y") current_timezone_str = "Asia/Shanghai" except Exception as e: logger.warning(f"Failed to get timezone info: {e}, using default values.") now = datetime.now() current_date_time_str = now.strftime("%Y-%m-%d %H:%M:%S") current_weekday_zh = "Unknown" current_year = now.strftime("%Y") current_timezone_str = "Unknown" if __event_emitter__: await __event_emitter__( { "type": "notification", "data": { "type": "info", "content": "Smart Mind Map is starting, generating mind map for you...", }, } ) messages = body.get("messages") if ( not messages or not isinstance(messages, list) or not messages[-1].get("content") ): error_message = "Unable to retrieve valid user message content." if __event_emitter__: await __event_emitter__( { "type": "notification", "data": {"type": "error", "content": error_message}, } ) return { "messages": [{"role": "assistant", "content": f"❌ {error_message}"}] } parts = re.split(r"```html.*?```", messages[-1]["content"], flags=re.DOTALL) long_text_content = "" if parts: for part in reversed(parts): if part.strip(): long_text_content = part.strip() break if not long_text_content: long_text_content = messages[-1]["content"].strip() if len(long_text_content) < self.valves.MIN_TEXT_LENGTH: short_text_message = f"Text content is too short ({len(long_text_content)} characters), unable to perform effective analysis. Please provide at least {self.valves.MIN_TEXT_LENGTH} characters of text." if __event_emitter__: await __event_emitter__( { "type": "notification", "data": {"type": "warning", "content": short_text_message}, } ) return { "messages": [ {"role": "assistant", "content": f"⚠️ {short_text_message}"} ] } if self.valves.show_status and __event_emitter__: await __event_emitter__( { "type": "status", "data": { "description": "Smart Mind Map: Analyzing text structure in depth...", "done": False, "hidden": False, }, } ) try: unique_id = f"id_{int(time.time() * 1000)}" formatted_user_prompt = USER_PROMPT_GENERATE_MINDMAP.format( user_name=user_name, current_date_time_str=current_date_time_str, current_weekday=current_weekday_zh, current_timezone_str=current_timezone_str, user_language=user_language, long_text_content=long_text_content, ) llm_payload = { "model": self.valves.LLM_MODEL_ID, "messages": [ {"role": "system", "content": SYSTEM_PROMPT_MINDMAP_ASSISTANT}, {"role": "user", "content": formatted_user_prompt}, ], "temperature": 0.5, "stream": False, } user_obj = Users.get_user_by_id(user_id) if not user_obj: raise ValueError(f"Unable to get user object, user ID: {user_id}") llm_response = await generate_chat_completion( __request__, llm_payload, user_obj ) if ( not llm_response or "choices" not in llm_response or not llm_response["choices"] ): raise ValueError("LLM response format is incorrect or empty.") assistant_response_content = llm_response["choices"][0]["message"][ "content" ] markdown_syntax = self._extract_markdown_syntax(assistant_response_content) final_html_content = ( HTML_TEMPLATE_MINDMAP.replace("{unique_id}", unique_id) .replace("{user_language}", user_language) .replace("{user_name}", user_name) .replace("{current_date_time_str}", current_date_time_str) .replace("{current_weekday_zh}", current_weekday_zh) .replace("{current_year}", current_year) .replace("{markdown_syntax}", markdown_syntax) ) html_embed_tag = f"```html\n{final_html_content}\n```" body["messages"][-1]["content"] = f"{long_text_content}\n\n{html_embed_tag}" if self.valves.show_status and __event_emitter__: await __event_emitter__( { "type": "status", "data": { "description": "Smart Mind Map: Drawing completed!", "done": True, "hidden": False, }, } ) await __event_emitter__( { "type": "notification", "data": { "type": "success", "content": f"Mind map has been generated, {user_name}!", }, } ) logger.info("Action: Smart Mind Map (v0.7.2) completed successfully") except Exception as e: error_message = f"Smart Mind Map processing failed: {str(e)}" logger.error(f"Smart Mind Map error: {error_message}", exc_info=True) user_facing_error = f"Sorry, Smart Mind Map encountered an error during processing: {str(e)}.\nPlease check the Open WebUI backend logs for more details." body["messages"][-1][ "content" ] = f"{long_text_content}\n\n❌ **Error:** {user_facing_error}" if __event_emitter__: if self.valves.show_status: await __event_emitter__( { "type": "status", "data": { "description": "Smart Mind Map: Processing failed.", "done": True, "hidden": False, }, } ) await __event_emitter__( { "type": "notification", "data": { "type": "error", "content": f"Smart Mind Map generation failed, {user_name}!", }, } ) return body