# Services API Reference Complete API reference documentation for all services in the Gateway application. This document provides detailed method signatures, parameters, return types, examples, and usage guidelines for each service. ## Table of Contents 1. [Introduction](#introduction) 2. [AI Service API](#ai-service-api) 3. [Chat Service API](#chat-service-api) 4. [Extraction Service API](#extraction-service-api) 5. [Generation Service API](#generation-service-api) 6. [Neutralization Service API](#neutralization-service-api) 7. [SharePoint Service API](#sharepoint-service-api) 8. [Ticket Service API](#ticket-service-api) 9. [Utils Service API](#utils-service-api) 10. [Common Patterns](#common-patterns) 11. [Error Handling](#error-handling) --- ## Introduction All services are accessed through the `Services` container, which is initialized with user and workflow context: ```python from modules.services import Services from modules.datamodels.datamodelUam import User from modules.datamodels.datamodelChat import ChatWorkflow # Initialize services services = Services(user=current_user, workflow=current_workflow) # Access any service result = await services.ai.someMethod() ``` ### Service Access Pattern ```mermaid graph LR User[User Code] --> Container[Services Container] Container --> AI[services.ai] Container --> Chat[services.chat] Container --> Extract[services.extraction] Container --> Gen[services.generation] Container --> Neut[services.neutralization] Container --> SP[services.sharepoint] Container --> Ticket[services.ticket] Container --> Utils[services.utils] style Container fill:#e1f5ff,stroke:#01579b,stroke-width:2px ``` --- ## AI Service API **Location**: `modules/services/serviceAi/mainServiceAi.py` ### Overview The AI Service provides methods for interacting with AI models for planning, document processing, text generation, image generation, and web operations. ### Class: `AiService` #### Initialization ```python class AiService: def __init__(self, serviceCenter=None) -> None: """ Initialize AI service with service center access. Args: serviceCenter: Services container instance """ ``` The AI Service is automatically initialized by the Services container. Access via: ```python services.ai.method_name() ``` --- ### Method: `callAiPlanning` Planning AI calls for task planning, action planning, and intent analysis. #### Signature ```python async def callAiPlanning( prompt: str, placeholders: Optional[List[PromptPlaceholder]] = None, debugType: Optional[str] = None ) -> str ``` #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prompt` | `str` | Yes | The planning prompt template | | `placeholders` | `List[PromptPlaceholder]` | No | List of placeholder replacements using `{{KEY:name}}` format | | `debugType` | `str` | No | Debug file type identifier (e.g., 'taskplan', 'actionplan', 'intentanalysis') | #### Returns - **Type**: `str` - **Description**: Planning JSON response from the AI model #### Behavior - Always uses static parameters optimized for planning tasks - Operation type: `PLAN` - Priority: `QUALITY` - Processing mode: `DETAILED` - No compression applied to prompt or context - Returns single-shot JSON (no iterative generation) #### Example Usage ```python # Basic planning call planning_result = await services.ai.callAiPlanning( prompt="Analyze the user's request and create a task plan", debugType="taskplan" ) # With placeholders from modules.datamodels.datamodelChat import PromptPlaceholder placeholders = [ PromptPlaceholder( label="user_request", content="Create a quarterly sales report" ), PromptPlaceholder( label="available_documents", content="3 documents available: sales_q1.xlsx, sales_q2.xlsx, sales_q3.xlsx" ) ] planning_result = await services.ai.callAiPlanning( prompt=""" Analyze this request: {{KEY:user_request}} Available resources: {{KEY:available_documents}} Create a task plan in JSON format. """, placeholders=placeholders, debugType="taskplan" ) ``` #### Error Handling ```python try: result = await services.ai.callAiPlanning(prompt="...") except Exception as e: logger.error(f"Planning call failed: {str(e)}") # Handle error ``` --- ### Method: `callAiDocuments` Document generation AI call for all non-planning operations including document processing, generation, and web operations. #### Signature ```python async def callAiDocuments( prompt: str, documents: Optional[List[ChatDocument]] = None, options: Optional[AiCallOptions] = None, outputFormat: Optional[str] = None, title: Optional[str] = None ) -> Union[str, Dict[str, Any]] ``` #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prompt` | `str` | Yes | The main prompt for the AI call | | `documents` | `List[ChatDocument]` | No | List of documents to process | | `options` | `AiCallOptions` | No | AI call configuration options (auto-analyzed if not provided) | | `outputFormat` | `str` | No | Output format for document generation (html, pdf, docx, xlsx, csv, json, md, txt, png) | | `title` | `str` | No | Title for generated documents | #### Returns - **Type**: `Union[str, Dict[str, Any]]` - **Description**: - If `outputFormat` is specified: Dictionary with generated document(s) - If no `outputFormat`: String with processed text #### Document Result Format When `outputFormat` is specified, returns: ```python { "success": True, "content": {...}, # Structured JSON content "documents": [ { "documentName": "report.pdf", "documentData": "", "mimeType": "application/pdf", "title": "Quarterly Report" } ], "is_multi_file": False, "format": "pdf", "title": "Quarterly Report", "split_strategy": "single", "total_documents": 1, "processed_documents": 1 } ``` #### Behavior - **Auto-analysis**: If `options` is None or `options.operationType` is None, automatically analyzes prompt to determine optimal parameters - **Document Processing**: If `documents` provided, extracts and processes content - **Iterative Generation**: Supports multi-iteration generation with automatic continuation - **Progress Tracking**: Provides granular progress updates - **Format-Specific Handling**: Different behavior for image generation, web operations, and document generation #### Example Usage ##### Text Processing ```python # Process documents and return text result = await services.ai.callAiDocuments( prompt="Summarize the key findings from these documents", documents=chat_documents, options=AiCallOptions( operationType=OperationTypeEnum.DATA_ANALYSE, priority=PriorityEnum.BALANCED, processingMode=ProcessingModeEnum.BASIC ) ) # Returns: str with summary text ``` ##### Document Generation ```python # Generate PDF report result = await services.ai.callAiDocuments( prompt="Create a comprehensive quarterly sales report", documents=sales_documents, outputFormat="pdf", title="Q4 2024 Sales Report" ) # Returns: Dict with PDF document data ``` ##### Image Generation ```python # Generate image result = await services.ai.callAiDocuments( prompt="Generate a professional bar chart showing sales by region", outputFormat="base64", options=AiCallOptions( operationType=OperationTypeEnum.IMAGE_GENERATE, priority=PriorityEnum.BALANCED ) ) # Returns: Dict with base64-encoded image ``` ##### Web Search ```python # Web search operation search_prompt = json.dumps({ "query": "latest AI developments 2024", "max_results": 5 }) result = await services.ai.callAiDocuments( prompt=search_prompt, options=AiCallOptions( operationType=OperationTypeEnum.WEB_SEARCH, priority=PriorityEnum.SPEED ) ) # Returns: str with search results ``` ##### Auto-Analysis Mode ```python # Let AI analyze the prompt and determine parameters result = await services.ai.callAiDocuments( prompt="Extract key insights from these contracts and create a summary", documents=contract_documents ) # AI automatically determines operation type, priority, and processing mode ``` #### Advanced Options ```python from modules.datamodels.datamodelAi import ( AiCallOptions, OperationTypeEnum, PriorityEnum, ProcessingModeEnum ) options = AiCallOptions( operationType=OperationTypeEnum.DATA_EXTRACT, priority=PriorityEnum.QUALITY, processingMode=ProcessingModeEnum.DETAILED, compressPrompt=False, # Don't compress prompt (important for JSON templates) compressContext=False # Don't compress context ) result = await services.ai.callAiDocuments( prompt=detailed_extraction_prompt, documents=documents, options=options, outputFormat="json", title="Extracted Data" ) ``` #### Operation Types | Operation Type | Description | Use Case | |----------------|-------------|----------| | `PLAN` | Task and action planning | Strategic planning, workflow design | | `DATA_EXTRACT` | Extract structured data | Parse documents, extract entities | | `DATA_ANALYSE` | Analyze and summarize | Insights, summaries, analysis | | `TEXT_GENERATE` | Generate text content | Articles, reports, descriptions | | `IMAGE_GENERATE` | Generate images | Charts, diagrams, illustrations | | `WEB_SEARCH` | Search the web | Research, fact-checking | | `WEB_CRAWL` | Crawl web pages | Deep content extraction | #### Priority Levels | Priority | Description | Performance | |----------|-------------|-------------| | `SPEED` | Fast responses | Lower quality, faster | | `BALANCED` | Balance speed/quality | Good for most cases | | `QUALITY` | Best quality | Slower, higher quality | #### Processing Modes | Mode | Description | Detail Level | |------|-------------|--------------| | `BASIC` | Simple processing | Quick, basic analysis | | `STANDARD` | Normal processing | Standard detail | | `DETAILED` | Comprehensive processing | Deep analysis | --- ### Method: `callAiText` Process documents with text extraction and AI analysis. #### Signature ```python async def callAiText( prompt: str, documents: Optional[List[ChatDocument]], options: AiCallOptions, operationId: Optional[str] = None ) -> str ``` #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prompt` | `str` | Yes | Processing prompt | | `documents` | `List[ChatDocument]` | No | Documents to process | | `options` | `AiCallOptions` | Yes | AI call options | | `operationId` | `str` | No | Operation ID for progress tracking | #### Returns - **Type**: `str` - **Description**: Processed text result #### Behavior - Automatically extracts content from documents - Applies model-aware chunking if needed - Processes chunks in parallel - Merges results intelligently - Tracks progress if `operationId` provided #### Example Usage ```python # Process documents with text extraction result = await services.ai.callAiText( prompt="Extract all dates and amounts from these invoices", documents=invoice_documents, options=AiCallOptions( operationType=OperationTypeEnum.DATA_EXTRACT, priority=PriorityEnum.BALANCED ), operationId="extract_invoices_123" ) ``` --- ## Chat Service API **Location**: `modules/services/serviceChat/mainServiceChat.py` ### Overview The Chat Service manages workflow operations, message handling, document resolution, connection management, and progress tracking. ### Class: `ChatService` #### Initialization ```python class ChatService: def __init__(self, serviceCenter): """ Initialize Chat service with service center access. Args: serviceCenter: Services container instance """ ``` Access via: ```python services.chat.method_name() ``` --- ### Document Resolution Methods #### Method: `getChatDocumentsFromDocumentList` Resolve document references to actual ChatDocument objects. ##### Signature ```python def getChatDocumentsFromDocumentList( documentList: List[str] ) -> List[ChatDocument] ``` ##### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `documentList` | `List[str]` | Yes | List of document references | ##### Returns - **Type**: `List[ChatDocument]` - **Description**: Resolved ChatDocument objects with file access ##### Document Reference Formats Three reference formats are supported: 1. **docItem**: Single document by ID ```python "docItem::" ``` 2. **docList with message ID**: All documents from a specific message ```python "docList::