import logging import uuid from typing import Dict, Any, List, Optional from modules.datamodels.datamodelUam import User, UserConnection from modules.datamodels.datamodelChat import ChatDocument, ChatMessage from modules.datamodels.datamodelChat import ExtractedContent from modules.services.serviceDocument.mainServiceDocumentExtraction import DocumentExtractionService from modules.services.serviceDocument.documentUtility import getFileExtension, getMimeTypeFromExtension, detectContentTypeFromData from modules.shared.timezoneUtils import get_utc_timestamp logger = logging.getLogger(__name__) class WorkflowService: """Service class containing methods for document processing, chat operations, and workflow management""" def __init__(self, serviceCenter): self.serviceCenter = serviceCenter self.user = serviceCenter.user self.workflow = serviceCenter.workflow self.interfaceChat = serviceCenter.interfaceChat self.interfaceComponent = serviceCenter.interfaceComponent self.interfaceApp = serviceCenter.interfaceApp async def summarizeChat(self, messages: List[ChatMessage]) -> str: """ Summarize chat messages from last to first message with status="first" Args: messages: List of chat messages to summarize Returns: str: Summary of the chat in user's language """ try: # Get messages from last to first, stopping at first message with status="first" relevantMessages = [] for msg in reversed(messages): relevantMessages.append(msg) if msg.status == "first": break # Create prompt for AI prompt = f"""You are an AI assistant providing a summary of a chat conversation. Please respond in '{self.user.language}' language. Chat History: {chr(10).join(f"- {msg.message}" for msg in reversed(relevantMessages))} Instructions: 1. Summarize the conversation's key points and outcomes 2. Be concise but informative 3. Use a professional but friendly tone 4. Focus on important decisions and next steps if any Please provide a comprehensive summary of this conversation.""" # Get summary using AI service directly (avoiding circular dependency) from modules.services.serviceAi.mainServiceAi import AiService ai_service = AiService(self) return await ai_service.callAi( prompt=prompt, documents=None, options={ "process_type": "text", "operation_type": "generate_content", "priority": "speed", "compress_prompt": True, "compress_documents": False, "max_cost": 0.01 } ) except Exception as e: logger.error(f"Error summarizing chat: {str(e)}") return f"Error summarizing chat: {str(e)}" def getChatDocumentsFromDocumentList(self, documentList: List[str]) -> List[ChatDocument]: """Get ChatDocuments from a list of document references using all three formats.""" try: all_documents = [] for doc_ref in documentList: if doc_ref.startswith("docItem:"): # docItem:: - extract ID and find document parts = doc_ref.split(':') if len(parts) >= 2: doc_id = parts[1] # Find the document by ID for message in self.workflow.messages: if message.documents: for doc in message.documents: if doc.id == doc_id: doc_name = getattr(doc, 'fileName', 'unknown') logger.debug(f"Found docItem reference {doc_ref}: {doc_name}") all_documents.append(doc) break elif doc_ref.startswith("docList:"): # docList::