~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Add detailed logging to track Ollama port switching issue
LearningCircuitb2143a775315
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex fc47a2786c..1d830f8112 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -397,6 +397,18 @@ def get_llm(llm = ChatOllama(model=model_name, base_url=base_url, **common_params)++ # Log the actual client configuration after creation+ logger.info(f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}")+ if hasattr(llm, '_client'):+ client = llm._client+ logger.info(f"ChatOllama _client type: {type(client)}")+ if hasattr(client, '_client'):+ inner_client = client._client+ logger.info(f"ChatOllama inner client type: {type(inner_client)}")+ if hasattr(inner_client, 'base_url'):+ logger.info(f"ChatOllama inner client base_url: {inner_client.base_url}")+# Test invoke to validate model workslogger.info("Testing Ollama model with simple invocation")test_result = llm.invoke("Hello")@@ -545,7 +557,33 @@ def wrap_llm_without_think_tags(self.base_llm = base_llmdef invoke(self, *args, **kwargs):- response = self.base_llm.invoke(*args, **kwargs)+ # Log detailed request information for Ollama models+ if hasattr(self.base_llm, 'base_url'):+ logger.info(f"LLM Request - Base URL: {self.base_llm.base_url}")+ logger.info(f"LLM Request - Model: {getattr(self.base_llm, 'model', 'unknown')}")+ logger.info(f"LLM Request - Args count: {len(args)}, Kwargs: {list(kwargs.keys())}")++ # Log the prompt if it's in args+ if args and len(args) > 0:+ prompt_text = str(args[0])[:200] + "..." if len(str(args[0])) > 200 else str(args[0])+ logger.info(f"LLM Request - Prompt preview: {prompt_text}")++ # Check if there's any client configuration+ if hasattr(self.base_llm, '_client'):+ client = self.base_llm._client+ if hasattr(client, '_client') and hasattr(client._client, 'base_url'):+ logger.info(f"LLM Request - Client base URL: {client._client.base_url}")++ try:+ response = self.base_llm.invoke(*args, **kwargs)+ logger.info(f"LLM Response - Success, type: {type(response)}")+ except Exception as e:+ logger.error(f"LLM Request - Failed with error: {str(e)}")+ # Log any URL information from the error+ error_str = str(e)+ if "http://" in error_str or "https://" in error_str:+ logger.error(f"LLM Request - Error contains URL info: {error_str}")+ raise# Process the response content if it has a content attributeif hasattr(response, "content"):diff --git a/src/local_deep_research/error_handling/__init__.py b/src/local_deep_research/error_handling/__init__.pynew file mode 100644index 0000000000..7917030c2a--- /dev/null+++ b/src/local_deep_research/error_handling/__init__.py@@ -0,0 +1,15 @@+"""+Error Handling Module for Local Deep Research++This module provides comprehensive error handling capabilities including:+- Error categorization and analysis+- LLM-powered error explanations+- User-friendly error report generation+- Integration with partial research results+"""++from .error_reporter import ErrorReporter+from .llm_explainer import LLMExplainer+from .report_generator import ErrorReportGenerator++__all__ = ["ErrorReporter", "LLMExplainer", "ErrorReportGenerator"]\ No newline at end of filediff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.pynew file mode 100644index 0000000000..f4f05d2850--- /dev/null+++ b/src/local_deep_research/error_handling/error_reporter.py@@ -0,0 +1,207 @@+"""+ErrorReporter - Main error categorization and handling logic+"""++import re+from enum import Enum+from typing import Dict, Optional, Any+from loguru import logger+++class ErrorCategory(Enum):+ """Categories of errors that can occur during research"""+ CONNECTION_ERROR = "connection_error"+ MODEL_ERROR = "model_error"+ SEARCH_ERROR = "search_error"+ SYNTHESIS_ERROR = "synthesis_error"+ FILE_ERROR = "file_error"+ UNKNOWN_ERROR = "unknown_error"+++class ErrorReporter:+ """+ Analyzes and categorizes errors to provide better user feedback+ """++ def __init__(self):+ self.error_patterns = {+ ErrorCategory.CONNECTION_ERROR: [+ r"POST predict.*EOF",+ r"Connection refused",+ r"timeout",+ r"Connection.*failed",+ r"HTTP error \d+",+ r"network.*error",+ ],+ ErrorCategory.MODEL_ERROR: [+ r"Model.*not found",+ r"Invalid.*model",+ r"Ollama.*not available",+ r"API key.*invalid",+ r"Authentication.*error",+ ],+ ErrorCategory.SEARCH_ERROR: [+ r"Search.*failed",+ r"No search results",+ r"Search engine.*error",+ r"Rate limit.*exceeded",+ ],+ ErrorCategory.SYNTHESIS_ERROR: [+ r"Error.*synthesis",+ r"Failed.*generate",+ r"Synthesis.*timeout",+ ],+ ErrorCategory.FILE_ERROR: [+ r"Permission denied",+ r"File.*not found",+ r"Cannot write.*file",+ r"Disk.*full",+ ]+ }++ def categorize_error(self, error_message: str) -> ErrorCategory:+ """+ Categorize an error based on its message++ Args:+ error_message: The error message to categorize++ Returns:+ ErrorCategory: The categorized error type+ """+ error_message = str(error_message).lower()++ for category, patterns in self.error_patterns.items():+ for pattern in patterns:+ if re.search(pattern.lower(), error_message):+ logger.debug(f"Categorized error as {category.value}: {pattern}")+ return category++ return ErrorCategory.UNKNOWN_ERROR++ def get_user_friendly_title(self, category: ErrorCategory) -> str:+ """+ Get a user-friendly title for an error category++ Args:+ category: The error category++ Returns:+ str: User-friendly title+ """+ titles = {+ ErrorCategory.CONNECTION_ERROR: "Connection Issue",+ ErrorCategory.MODEL_ERROR: "Model Configuration Problem",+ ErrorCategory.SEARCH_ERROR: "Search Service Error",+ ErrorCategory.SYNTHESIS_ERROR: "Report Generation Error",+ ErrorCategory.FILE_ERROR: "File System Error",+ ErrorCategory.UNKNOWN_ERROR: "Unexpected Error",+ }+ return titles.get(category, "Error")++ def get_suggested_actions(self, category: ErrorCategory) -> list:+ """+ Get suggested actions for resolving an error++ Args:+ category: The error category++ Returns:+ list: List of suggested actions+ """+ suggestions = {+ ErrorCategory.CONNECTION_ERROR: [+ "Check if the LLM service (Ollama/LM Studio) is running",+ "Verify network connectivity",+ "Try switching to a different model provider",+ "Check the service logs for more details",+ ],+ ErrorCategory.MODEL_ERROR: [+ "Verify the model name is correct",+ "Check if the model is downloaded and available",+ "Validate API keys if using external services",+ "Try switching to a different model",+ ],+ ErrorCategory.SEARCH_ERROR: [+ "Check internet connectivity",+ "Try reducing the number of search results",+ "Wait a moment and try again",+ "Check if search service is configured correctly",+ ],+ ErrorCategory.SYNTHESIS_ERROR: [+ "The research data was collected successfully",+ "Try switching to a different model for report generation",+ "Check the partial results below",+ "Review the detailed logs for more information",+ ],+ ErrorCategory.FILE_ERROR: [+ "Check disk space availability",+ "Verify write permissions",+ "Try changing the output directory",+ "Restart the application",+ ],+ ErrorCategory.UNKNOWN_ERROR: [+ "Check the detailed logs below for more information",+ "Try running the research again",+ "Report this issue if it persists",+ "Contact support with the error details",+ ],+ }+ return suggestions.get(category, ["Check the logs for more details"])++ def analyze_error(self, error_message: str, context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:+ """+ Perform comprehensive error analysis++ Args:+ error_message: The error message to analyze+ context: Optional context information++ Returns:+ dict: Comprehensive error analysis+ """+ category = self.categorize_error(error_message)++ analysis = {+ "category": category,+ "title": self.get_user_friendly_title(category),+ "original_error": error_message,+ "suggestions": self.get_suggested_actions(category),+ "severity": self._determine_severity(category),+ "recoverable": self._is_recoverable(category),+ }++ # Add context-specific information+ if context:+ analysis["context"] = context+ analysis["has_partial_results"] = bool(+ context.get("findings") or+ context.get("current_knowledge") or+ context.get("search_results")+ )++ return analysis++ def _determine_severity(self, category: ErrorCategory) -> str:+ """Determine error severity level"""+ severity_map = {+ ErrorCategory.CONNECTION_ERROR: "high",+ ErrorCategory.MODEL_ERROR: "high",+ ErrorCategory.SEARCH_ERROR: "medium",+ ErrorCategory.SYNTHESIS_ERROR: "low", # Can often show partial results+ ErrorCategory.FILE_ERROR: "medium",+ ErrorCategory.UNKNOWN_ERROR: "high",+ }+ return severity_map.get(category, "medium")++ def _is_recoverable(self, category: ErrorCategory) -> bool:+ """Determine if error is recoverable with user action"""+ recoverable = {+ ErrorCategory.CONNECTION_ERROR: True,+ ErrorCategory.MODEL_ERROR: True,+ ErrorCategory.SEARCH_ERROR: True,+ ErrorCategory.SYNTHESIS_ERROR: True,+ ErrorCategory.FILE_ERROR: True,+ ErrorCategory.UNKNOWN_ERROR: False,+ }+ return recoverable.get(category, False)\ No newline at end of filediff --git a/src/local_deep_research/error_handling/llm_explainer.py b/src/local_deep_research/error_handling/llm_explainer.pynew file mode 100644index 0000000000..ef3fa018b8--- /dev/null+++ b/src/local_deep_research/error_handling/llm_explainer.py@@ -0,0 +1,167 @@+"""+LLMExplainer - Generate helpful error explanations using LLM+"""++from typing import Optional, Dict, Any+from loguru import logger+from .error_reporter import ErrorCategory+++class LLMExplainer:+ """+ Uses LLM to generate helpful explanations for errors+ """++ def __init__(self, llm=None):+ """+ Initialize LLM explainer++ Args:+ llm: Optional LLM instance to use for explanations+ """+ self.llm = llm+ self.explanation_templates = {+ ErrorCategory.CONNECTION_ERROR: """+ You encountered a connection problem while the system was trying to communicate with your AI model service.+ This typically happens when the model service (like Ollama or LM Studio) isn't running or isn't accessible.++ The good news is this is usually easy to fix by checking that your AI service is properly started.+ """,+ ErrorCategory.MODEL_ERROR: """+ There was an issue with the AI model configuration. This could mean the model you selected+ isn't available, or there's a problem with your API credentials.++ You can often resolve this by checking your model settings or trying a different model.+ """,+ ErrorCategory.SEARCH_ERROR: """+ The system had trouble searching for information. This might be due to internet connectivity+ issues or problems with the search service.++ Your research can usually be retried once the connection is restored.+ """,+ ErrorCategory.SYNTHESIS_ERROR: """+ The research data was successfully collected, but there was an issue generating the final report.+ This often happens due to temporary model connectivity issues.++ The partial research results are still available and useful, even though the final synthesis failed.+ """,+ ErrorCategory.FILE_ERROR: """+ There was a problem saving the research results to your computer. This could be due to+ insufficient permissions or disk space.++ Your research data is still available, but the file couldn't be written.+ """,+ ErrorCategory.UNKNOWN_ERROR: """+ An unexpected error occurred during your research. While this is frustrating,+ the detailed logs can help identify what went wrong.++ This type of error helps improve the system when reported.+ """+ }++ def generate_explanation(self, error_analysis: Dict[str, Any]) -> str:+ """+ Generate a helpful explanation for an error++ Args:+ error_analysis: Error analysis from ErrorReporter++ Returns:+ str: Human-friendly explanation+ """+ category = error_analysis.get("category")+ original_error = error_analysis.get("original_error", "")+ context = error_analysis.get("context", {})++ # Try to use LLM for explanation if available+ if self.llm:+ try:+ llm_explanation = self._generate_llm_explanation(category, original_error, context)+ if llm_explanation:+ return llm_explanation+ except Exception as e:+ logger.warning(f"Failed to generate LLM explanation: {e}")++ # Fallback to template-based explanation+ return self._get_template_explanation(category, error_analysis)++ def _generate_llm_explanation(self, category: ErrorCategory, error_message: str, context: Dict[str, Any]) -> Optional[str]:+ """+ Use LLM to generate explanation++ Args:+ category: Error category+ error_message: Original error message+ context: Error context++ Returns:+ Optional[str]: LLM-generated explanation+ """+ try:+ # Prepare prompt for LLM+ prompt = f"""+You are helping a user understand what went wrong with their research process.+Please provide a brief, friendly, and helpful explanation of this error.++Error Category: {category.value}+Technical Error: {error_message}+Context: {context}++Please explain:+1. What happened in simple terms+2. Why this might have occurred+3. That partial results may still be available+4. Reassurance that this can usually be fixed++Keep it concise, helpful, and friendly. Avoid technical jargon.+"""++ response = self.llm.invoke(prompt)+ return str(response.content) if hasattr(response, 'content') else str(response)++ except Exception as e:+ logger.warning(f"LLM explanation generation failed: {e}")+ return None++ def _get_template_explanation(self, category: ErrorCategory, error_analysis: Dict[str, Any]) -> str:+ """+ Get template-based explanation as fallback++ Args:+ category: Error category+ error_analysis: Error analysis data++ Returns:+ str: Template-based explanation+ """+ base_explanation = self.explanation_templates.get(+ category,+ self.explanation_templates[ErrorCategory.UNKNOWN_ERROR]+ ).strip()++ # Add context-specific information+ has_partial = error_analysis.get("has_partial_results", False)+ if has_partial:+ base_explanation += "\n\n✅ **Good news:** Some research data was successfully collected and is shown below."++ return base_explanation++ def generate_quick_tip(self, category: ErrorCategory) -> str:+ """+ Generate a quick tip for the error category++ Args:+ category: Error category++ Returns:+ str: Quick tip+ """+ tips = {+ ErrorCategory.CONNECTION_ERROR: "💡 **Quick Fix:** Check if your AI service (Ollama/LM Studio) is running",+ ErrorCategory.MODEL_ERROR: "💡 **Quick Fix:** Try switching to a different model in settings",+ ErrorCategory.SEARCH_ERROR: "💡 **Quick Fix:** Check your internet connection and try again",+ ErrorCategory.SYNTHESIS_ERROR: "💡 **Good News:** Your research data was collected successfully",+ ErrorCategory.FILE_ERROR: "💡 **Quick Fix:** Check available disk space and file permissions",+ ErrorCategory.UNKNOWN_ERROR: "💡 **Next Step:** Check the detailed logs below for more information",+ }+ return tips.get(category, "💡 **Tip:** Try running the research again or check the logs for details")\ No newline at end of filediff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.pynew file mode 100644index 0000000000..3a47b0afdb--- /dev/null+++ b/src/local_deep_research/error_handling/report_generator.py@@ -0,0 +1,363 @@+"""+ErrorReportGenerator - Create user-friendly error reports+"""++from datetime import datetime+from typing import Dict, Any, Optional, List+from loguru import logger++from .error_reporter import ErrorReporter, ErrorCategory+from .llm_explainer import LLMExplainer+++class ErrorReportGenerator:+ """+ Generates comprehensive, user-friendly error reports+ """++ def __init__(self, llm=None):+ """+ Initialize error report generator++ Args:+ llm: Optional LLM instance for generating explanations+ """+ self.error_reporter = ErrorReporter()+ self.llm_explainer = LLMExplainer(llm)++ def generate_error_report(+ self,+ error_message: str,+ query: str,+ partial_results: Optional[Dict[str, Any]] = None,+ search_iterations: int = 0,+ research_id: Optional[int] = None+ ) -> str:+ """+ Generate a comprehensive error report++ Args:+ error_message: The error that occurred+ query: The research query+ partial_results: Any partial results that were collected+ search_iterations: Number of search iterations completed+ research_id: Research ID for reference++ Returns:+ str: Formatted error report in Markdown+ """+ # Analyze the error+ context = {+ "query": query,+ "search_iterations": search_iterations,+ "research_id": research_id,+ "partial_results": partial_results+ }++ if partial_results:+ context.update(partial_results)++ error_analysis = self.error_reporter.analyze_error(error_message, context)++ # Generate explanation+ explanation = self.llm_explainer.generate_explanation(error_analysis)+ quick_tip = self.llm_explainer.generate_quick_tip(error_analysis["category"])++ # Build the simplified report+ report_parts = []++ # Header with user-friendly error message and logs reference+ user_friendly_message = self._make_error_user_friendly(error_message)+ report_parts.append(f"# ⚠️ Research Failed")+ report_parts.append(f"\n**What happened:** {user_friendly_message}")+ report_parts.append(f"\n*For detailed error information, scroll down to the research logs and select \"Errors\" from the filter.*")++ # Support links - moved up for better visibility+ report_parts.append(f"\n## 💬 Get Help")+ report_parts.append("We're here to help you get this working:")+ report_parts.append("- **Chat with the community:** [Discord #help-and-support](https://discord.gg/ttcqQeFcJ3)")+ report_parts.append("- **Report bugs:** [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues)")+ report_parts.append("- **Join discussions:** [Reddit r/LocalDeepResearch](https://www.reddit.com/r/LocalDeepResearch/) *(checked less frequently)*")++ # Show partial results if available (in expandable section)+ if error_analysis.get("has_partial_results"):+ partial_content = self._format_partial_results(partial_results)+ if partial_content:+ report_parts.append(f"\n<details>\n<summary>📊 Partial Results Available</summary>\n\n{partial_content}\n</details>")++ # Technical error (collapsed)+ if user_friendly_message != error_message:+ report_parts.append(f"\n<details>\n<summary>🔧 Technical Details</summary>\n\n**Original Error:**\n```\n{error_message}\n```\n</details>")++ return "\n".join(report_parts)++ def _format_partial_results(self, partial_results: Optional[Dict[str, Any]]) -> str:+ """+ Format partial results for display++ Args:+ partial_results: Partial results data++ Returns:+ str: Formatted partial results+ """+ if not partial_results:+ return ""++ formatted_parts = []++ # Current knowledge summary+ if "current_knowledge" in partial_results:+ knowledge = partial_results["current_knowledge"]+ if knowledge and len(knowledge.strip()) > 50:+ formatted_parts.append("### Research Summary\n")+ formatted_parts.append(knowledge[:1000] + "..." if len(knowledge) > 1000 else knowledge)+ formatted_parts.append("")++ # Search results+ if "search_results" in partial_results:+ results = partial_results["search_results"]+ if results:+ formatted_parts.append("### Search Results Found\n")+ for i, result in enumerate(results[:5], 1): # Show top 5+ title = result.get("title", "Untitled")+ url = result.get("url", "")+ formatted_parts.append(f"{i}. **{title}**")+ if url:+ formatted_parts.append(f" - URL: {url}")+ formatted_parts.append("")++ # Findings+ if "findings" in partial_results:+ findings = partial_results["findings"]+ if findings:+ formatted_parts.append("### Research Findings\n")+ for i, finding in enumerate(findings[:3], 1): # Show top 3+ content = finding.get("content", "")+ if content and not content.startswith("Error:"):+ phase = finding.get("phase", f"Finding {i}")+ formatted_parts.append(f"**{phase}:**")+ formatted_parts.append(content[:500] + "..." if len(content) > 500 else content)+ formatted_parts.append("")++ if formatted_parts:+ formatted_parts.append("*Note: The above results were successfully collected before the error occurred.*")++ return "\n".join(formatted_parts) if formatted_parts else ""++ def _extract_stack_trace(self, error_message: str) -> Optional[str]:+ """+ Extract stack trace from error message if present++ Args:+ error_message: The error message++ Returns:+ str: Stack trace if found, None otherwise+ """+ # Look for common stack trace patterns+ lines = error_message.split('\n')+ stack_lines = []+ in_stack = False++ for line in lines:+ # Common stack trace indicators+ if any(indicator in line.lower() for indicator in [+ 'traceback', 'stack trace', 'at ', 'file "',+ 'line ', 'error:', 'exception:', 'caused by:'+ ]):+ in_stack = True+ stack_lines.append(line)+ elif in_stack and line.strip():+ # Continue collecting stack trace lines+ if line.startswith(' ') or 'at ' in line or 'File "' in line:+ stack_lines.append(line)+ elif not line.strip():+ # Empty line might still be part of stack+ stack_lines.append(line)+ else:+ # Looks like end of stack trace+ break++ # Return stack trace if we found a substantial one+ if len(stack_lines) > 1:+ return '\n'.join(stack_lines)++ return None++ def _get_technical_context(self, error_analysis: Dict[str, Any], partial_results: Optional[Dict[str, Any]]) -> str:+ """+ Get additional technical context for the error++ Args:+ error_analysis: Error analysis results+ partial_results: Partial results if available++ Returns:+ str: Technical context information+ """+ context_parts = []++ # Add timing information if available+ if partial_results:+ if "start_time" in partial_results:+ context_parts.append(f"- **Start Time:** {partial_results['start_time']}")++ if "last_activity" in partial_results:+ context_parts.append(f"- **Last Activity:** {partial_results['last_activity']}")++ # Add model information+ if "model_config" in partial_results:+ config = partial_results["model_config"]+ context_parts.append(f"- **Model:** {config.get('model_name', 'Unknown')}")+ context_parts.append(f"- **Provider:** {config.get('provider', 'Unknown')}")++ # Add search information+ if "search_config" in partial_results:+ search_config = partial_results["search_config"]+ context_parts.append(f"- **Search Engine:** {search_config.get('engine', 'Unknown')}")+ context_parts.append(f"- **Max Results:** {search_config.get('max_results', 'Unknown')}")++ # Add any error codes or HTTP status+ if "status_code" in partial_results:+ context_parts.append(f"- **Status Code:** {partial_results['status_code']}")++ if "error_code" in partial_results:+ context_parts.append(f"- **Error Code:** {partial_results['error_code']}")++ # Add error-specific context based on category+ category = error_analysis.get("category")+ if category:+ if "connection" in category.value.lower():+ context_parts.append(f"- **Network Error:** Connection-related issue detected")+ context_parts.append(f"- **Retry Recommended:** Check service status and try again")+ elif "model" in category.value.lower():+ context_parts.append(f"- **Model Error:** Issue with AI model or configuration")+ context_parts.append(f"- **Check:** Model service availability and parameters")++ return "\n".join(context_parts) if context_parts else ""++ def _get_research_logs(self, research_id: int) -> Optional[str]:+ """+ Fetch logs from the database for this specific research run++ Args:+ research_id: The research ID to fetch logs for++ Returns:+ str: Formatted logs or None if no logs found+ """+ try:+ # Import here to avoid circular imports+ from local_deep_research.web.database.models import ResearchLog+ from local_deep_research.web.database.database import get_db_session++ with get_db_session() as session:+ # Get all logs for this research, ordered by timestamp+ logs = session.query(ResearchLog).filter(+ ResearchLog.research_id == research_id+ ).order_by(ResearchLog.timestamp.asc()).all()++ if not logs:+ return None++ # Format logs for display+ log_parts = []+ error_logs = []+ warning_logs = []+ info_logs = []++ for log in logs:+ timestamp = log.timestamp.strftime('%H:%M:%S')+ location = f"{log.module}:{log.function}:{log.line_no}"++ # Categorize logs+ if log.level in ['ERROR', 'CRITICAL']:+ error_logs.append(f"**{timestamp}** `{log.level}` [{location}]\n```\n{log.message}\n```")+ elif log.level == 'WARNING':+ warning_logs.append(f"**{timestamp}** `{log.level}` [{location}] {log.message}")+ elif log.level in ['INFO', 'MILESTONE']:+ info_logs.append(f"**{timestamp}** `{log.level}` {log.message}")++ # Show errors first (most important)+ if error_logs:+ log_parts.append("### 🚨 Errors and Exceptions\n")+ log_parts.extend(error_logs[:5]) # Show last 5 errors+ if len(error_logs) > 5:+ log_parts.append(f"\n*({len(error_logs) - 5} more errors - see full logs panel)*")+ log_parts.append("")++ # Then warnings+ if warning_logs:+ log_parts.append("### ⚠️ Warnings\n")+ log_parts.extend(warning_logs[-3:]) # Show last 3 warnings+ if len(warning_logs) > 3:+ log_parts.append(f"\n*({len(warning_logs) - 3} more warnings - see full logs panel)*")+ log_parts.append("")++ # Finally recent activity (info logs)+ if info_logs:+ log_parts.append("### ℹ️ Recent Activity\n")+ log_parts.extend(info_logs[-5:]) # Show last 5 info logs+ if len(info_logs) > 5:+ log_parts.append(f"\n*({len(info_logs) - 5} more info logs - see full logs panel)*")++ # Add summary+ total_logs = len(logs)+ log_parts.append(f"\n**Total logs for this research:** {total_logs}")+ log_parts.append(f"**Errors:** {len(error_logs)} | **Warnings:** {len(warning_logs)} | **Info:** {len(info_logs)}")++ return "\n".join(log_parts) if log_parts else None++ except Exception as e:+ logger.warning(f"Could not fetch research logs for ID {research_id}: {e}")+ return f"*Could not fetch logs from database: {str(e)}*"++ def generate_quick_error_summary(self, error_message: str) -> Dict[str, str]:+ """+ Generate a quick error summary for API responses++ Args:+ error_message: The error message++ Returns:+ dict: Quick error summary+ """+ error_analysis = self.error_reporter.analyze_error(error_message)++ return {+ "title": error_analysis["title"],+ "category": error_analysis["category"].value,+ "severity": error_analysis["severity"],+ "quick_fix": self.llm_explainer.generate_quick_tip(error_analysis["category"]),+ "recoverable": error_analysis["recoverable"]+ }++ def _make_error_user_friendly(self, error_message: str) -> str:+ """+ Replace cryptic technical error messages with user-friendly versions++ Args:+ error_message: The original technical error message++ Returns:+ str: User-friendly error message, or original if no replacement found+ """+ # Dictionary of technical errors to user-friendly messages+ error_replacements = {+ "max_workers must be greater than 0": (+ "This is typically an issue with the LLM not being available."+ ),+ "POST predict.*EOF": (+ "Lost connection to Ollama. This usually means Ollama stopped responding or there's a network issue. Try restarting Ollama or checking if it's still running."+ )+ }++ # Check each pattern and replace if found+ for pattern, replacement in error_replacements.items():+ import re+ if re.search(pattern, error_message, re.IGNORECASE):+ return f"{replacement}\n\nTechnical error: {error_message}"++ # If no specific replacement found, return original message+ return error_message\ No newline at end of file