syedkhizarrayaz/BM-AI-Analysis-And-Alert-Prioritization-Agent
0
1# SystemZ-AI API Documentation2 3Complete Swagger/OpenAPI documentation for all endpoints.4 5## Table of Contents6- [Base URL](#base-url)7- [Authentication](#authentication)8- [Endpoints](#endpoints)9 - [Authentication](#authentication-endpoints)10 - [Model Prediction](#model-prediction-endpoints)11 - [Analysis Generation](#analysis-generation-endpoints)12 13## Base URL14 15```16http://localhost:800017```18 19## Authentication20 21**Important**: Authentication is **optional** and only required when integrating with external systems. For internal system use, authentication is **disabled** by default. All endpoints can be accessed without authentication tokens.22 23If you need authentication for external integrations, use the token endpoint below.24 25---26 27## Endpoints28 29## Authentication Endpoints30 31### POST /api/ai-service/token32 33Generate JWT access token for API authentication (Optional - only for external integrations).34 35**Security**: None (public endpoint)36 37**Note**: This endpoint is optional. Authentication is disabled for internal system use.38 39**Request**:40- **Content-Type**: `application/x-www-form-urlencoded`41- **Body** (form data):42 - `username` (string, required): API username43 - `password` (string, required): API password44 45**Response** (200 OK):46```json47{48 "access_token": "string",49 "token_type": "bearer"50}51```52 53**Example Request**:54```bash55curl -X POST "http://localhost:8000/api/ai-service/token" \56 -H "Content-Type: application/x-www-form-urlencoded" \57 -d "username=admin&password=your_password"58```59 60**Example Response**:61```json62{63 "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTcwNDA5NjAwMH0.example",64 "token_type": "bearer"65}66```67 68---69 70## Model Prediction Endpoints71 72### POST /api/ai-service/predictalertpriority73 74Predict alert classification using ML model with JSON input.75 76**Security**: None (authentication disabled for internal use)77 78**Request**:79- **Content-Type**: `application/json`80- **Body** (JSON):81 82**Example Request Body** (from `aml_alerts_5_test_predict.json`):83```json84{85 "AlertID": 1001,86 "FocusColumnValue": "PK-42101-1234567-1",87 "AlertScore": 85.5,88 "CreateDate": "2025-06-15T10:30:00",89 "riskLevel": "Low",90 "MatchDetails": "{\"id\": \"PK-42101-1234567-1\", \"scenario\": \"Unusually large installment\", \"score\": 85.5, \"riskLevel\": \"Low\"}",91 "MatchInfoJson": "[{\"ID\": \"PK-42101-1234567-1\", \"TRANSACTIONAMOUNT\": 150000, \"CURRENCY\": \"PKR\", \"INSTALLMENTNUMBER\": 1}, {\"ID\": \"PK-42101-1234567-1\", \"TRANSACTIONAMOUNT\": 180000, \"CURRENCY\": \"PKR\", \"INSTALLMENTNUMBER\": 2}, {\"ID\": \"PK-42101-1234567-1\", \"TRANSACTIONAMOUNT\": 200000, \"CURRENCY\": \"PKR\", \"INSTALLMENTNUMBER\": 3}]",92 "ScenarioName": "Unusually large installment",93 "workflow": "Unassigned"94}95```96 97**Request Parameters**:98 99| Parameter | Type | Required | Description | Example |100|-----------|------|----------|-------------|---------|101| `AlertID` | integer | Yes | Unique alert identifier | `1001` |102| `FocusColumnValue` | string | Yes | Customer/entity identifier | `"PK-42101-1234567-1"` |103| `AlertScore` | float | No | Alert risk score (0-100) | `85.5` |104| `CreateDate` | string (ISO 8601) | No | Alert creation date | `"2025-06-15T10:30:00"` |105| `riskLevel` | string | No | Risk level (Low/Medium/High) | `"Low"` |106| `MatchDetails` | string | No | JSON string with match details | `"{\"id\": \"...\", \"scenario\": \"...\"}"` |107| `MatchInfoJson` | string | No | JSON array string with transaction details | `"[{\"ID\": \"...\", \"TRANSACTIONAMOUNT\": 150000}]"` |108| `ScenarioName` | string | No | Alert scenario name | `"Unusually large installment"` |109| `workflow` | string | No | Current workflow status | `"Unassigned"` |110 111**Note**: All fields except `AlertID` and `FocusColumnValue` are optional. The system will use defaults for missing fields.112 113**Response** (200 OK):114```json115{116 "status": 200,117 "message": "Success",118 "data": [119 {120 "AlertID": 1001,121 "FocusColumnValue": "PK-42101-1234567-1",122 "STRScenario": "Unusually large installment",123 "Prediction": "High"124 }125 ]126}127```128 129**Prediction Values**:130- `"High"`: Alert should be escalated/STR filed131- `"Medium"`: Requires investigation132- `"Low"`: Alert can be closed133 134**Error Response** (422 Unprocessable Entity):135```json136{137 "detail": "Validation error: [error details]"138}139```140 141**Error Response** (500 Internal Server Error):142```json143{144 "detail": "An error occurred while predicting alert priority"145}146```147 148**Example Request**:149```bash150curl -X POST "http://localhost:8000/api/ai-service/predictalertpriority" \151 -H "Content-Type: application/json" \152 -d '{153 "AlertID": 1001,154 "FocusColumnValue": "PK-42101-1234567-1",155 "AlertScore": 85.5,156 "CreateDate": "2025-06-15T10:30:00",157 "riskLevel": "Low",158 "MatchInfoJson": "[{\"ID\": \"PK-42101-1234567-1\", \"TRANSACTIONAMOUNT\": 150000, \"CURRENCY\": \"PKR\", \"INSTALLMENTNUMBER\": 1}]",159 "ScenarioName": "Unusually large installment",160 "workflow": "Unassigned"161 }'162```163 164---165 166## Analysis Generation Endpoints167 168### POST /api/ai-service/generateamlanalysisoai169 170Generate AML analysis report using OpenAI GPT models.171 172**Security**: None (authentication disabled for internal use)173 174**Request**:175- **Content-Type**: `application/json`176- **Body** (JSON or array of JSON):177 178**Example Request Body** (from `aml_alerts_2_example.json`):179```json180{181 "AlertID": 1,182 "FilteredTransactions": "[{\"CUSTOMERID\":\"100001\",\"IDENTITYNUMBERS\":\"42101-1234567-1\",\"LOANID\":\"LN2024001\",\"ACCOUNTID\":\"AC100001\",\"CREATEDDATE\":\"2025-06-01 10:15:00\",\"TRANSACTIONAMOUNT\":150000.0,\"CURRENCY\":\"PKR\",\"INSTALLMENTNUMBER\":1,\"EXCESSAMOUNT\":0.0},{\"CUSTOMERID\":\"100001\",\"IDENTITYNUMBERS\":\"42101-1234567-1\",\"LOANID\":\"LN2024001\",\"ACCOUNTID\":\"AC100001\",\"CREATEDDATE\":\"2025-06-15 14:20:00\",\"TRANSACTIONAMOUNT\":180000.0,\"CURRENCY\":\"PKR\",\"INSTALLMENTNUMBER\":2,\"EXCESSAMOUNT\":0.0}]",183 "FocusColumnValue": "100001",184 "KYCMonthlyIncome": "85,000 PKR",185 "KYCNoOfCredits": "3-5",186 "KYCNoOfDebits": "8-12",187 "KYCRiskCategoryValue": "Low",188 "KYCValueOfCredits": "150,000 - 200,000 PKR",189 "KYCValueOfDebits": "80,000 - 120,000 PKR",190 "OccupationValue": "Private Employee",191 "STRCount": 0,192 "STRScenarioHistory": "",193 "ScenarioName": "Unusually large installment",194 "CustomerName": "Muhammad Bilal Sheikh",195 "CUSTOMERID": "100001",196 "BranchID": "KHI-DHA",197 "Country": "Pakistan",198 "CustomerType": "Retail",199 "CustomerStatus": "Retail Customer",200 "CreatedDate": "2020-01-15",201 "RelationshipStartDate": "2020-01-15",202 "RiskScore": "4.2",203 "PreviousAlerts": [],204 "Counterparties": [],205 "BranchQueries": {206 "Requested": "Verification required for loan installments totaling 530,000 PKR within one month, significantly exceeding declared monthly income of 85,000 PKR. Please confirm source of funds and provide documentation for additional income sources.",207 "Response": "Customer stated installments are from remittances received from brother working in UAE, family savings from wedding expenses, and advance salary from employer for Eid holidays. Customer provided remittance receipts and employer letter."208 }209}210```211 212**Request Parameters**:213 214| Parameter | Type | Required | Description | Example |215|-----------|------|----------|-------------|---------|216| `AlertID` | integer | No | Unique alert identifier | `1` |217| `FilteredTransactions` | string | No | JSON array string with transaction details | `"[{\"CUSTOMERID\":\"100001\",\"TRANSACTIONAMOUNT\":150000.0}]"` |218| `FocusColumnValue` | string | No | Customer/entity identifier | `"100001"` |219| `KYCMonthlyIncome` | string | No | Monthly income range | `"85,000 PKR"` |220| `KYCNoOfCredits` | string | No | Expected number of credits | `"3-5"` |221| `KYCNoOfDebits` | string | No | Expected number of debits | `"8-12"` |222| `KYCRiskCategoryValue` | string | No | KYC risk category | `"Low"`, `"Medium"`, `"High"` |223| `KYCValueOfCredits` | string | No | Expected value of credits | `"150,000 - 200,000 PKR"` |224| `KYCValueOfDebits` | string | No | Expected value of debits | `"80,000 - 120,000 PKR"` |225| `OccupationValue` | string | No | Customer occupation | `"Private Employee"` |226| `STRCount` | integer | No | Count of previous STRs | `0` |227| `STRScenarioHistory` | string | No | History of STR scenarios | `""` |228| `ScenarioName` | string | No | Alert scenario name | `"Unusually large installment"` |229| `CustomerName` | string | No | Customer full name | `"Muhammad Bilal Sheikh"` |230| `CUSTOMERID` | string | No | Customer ID | `"100001"` |231| `BranchID` | string | No | Branch identifier | `"KHI-DHA"` |232| `Country` | string | No | Customer country | `"Pakistan"` |233| `CustomerType` | string | No | Customer type | `"Retail"` |234| `CustomerStatus` | string | No | Customer status | `"Retail Customer"` |235| `CreatedDate` | string | No | Account creation date | `"2020-01-15"` |236| `RelationshipStartDate` | string | No | Relationship start date | `"2020-01-15"` |237| `RiskScore` | string | No | Risk score | `"4.2"` |238| `PreviousAlerts` | array | No | Array of previous alert objects | `[]` or `[{"AlertName": "...", "Description": "..."}]` |239| `Counterparties` | array | No | Array of counterparty objects | `[]` or `[{"Name": "...", "Country": "..."}]` |240| `BranchQueries` | object | No | Branch query request/response | `{"Requested": "...", "Response": "..."}` |241 242**Note**: All fields are optional. The system will use defaults for missing fields. Supports both single object and array of objects.243 244**Response** (200 OK):245```json246{247 "status": 200,248 "message": "Success",249 "data": [250 {251 "AlertID": 1,252 "FocusColumnValue": "100001",253 "analysis": "**CONCLUSION UP FRONT**\nESCALATE - Multiple red flags detected...\n\n**INITIAL RISK**\n- Alerted Scenario: Unusually large installment\n..."254 }255 ]256}257```258 259**Error Response** (422 Unprocessable Entity):260```json261{262 "detail": "Validation error: [error details]"263}264```265 266**Error Response** (500 Internal Server Error):267```json268{269 "detail": "An error occurred while generating AML analysis using oai"270}271```272 273**Example Request (Single Alert)**:274```bash275curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysisoai" \276 -H "Content-Type: application/json" \277 -d '{278 "AlertID": 1,279 "FocusColumnValue": "100001",280 "ScenarioName": "Unusually large installment",281 "FilteredTransactions": "[{\"CUSTOMERID\":\"100001\",\"TRANSACTIONAMOUNT\":150000.0,\"CURRENCY\":\"PKR\"}]",282 "KYCMonthlyIncome": "85,000 PKR"283 }'284```285 286**Example Request (Multiple Alerts)**:287```bash288curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysisoai" \289 -H "Content-Type: application/json" \290 -d '[291 {292 "AlertID": 1,293 "FocusColumnValue": "100001",294 "ScenarioName": "Unusually large installment"295 },296 {297 "AlertID": 2,298 "FocusColumnValue": "100002",299 "ScenarioName": "Structuring / Smurfing activity"300 }301 ]'302```303 304---305 306### POST /api/ai-service/generateamlanalysis307 308Generate AML analysis report using Hybrid Template+LLM system.309 310**Security**: None (authentication disabled for internal use)311 312**Request**:313- **Content-Type**: `application/json`314- **Body** (JSON or array of JSON):315 316**Example Request Body** (from `aml_alerts_2_example.json`):317```json318{319 "AlertID": 2,320 "FilteredTransactions": "[{\"CUSTOMERID\":\"100002\",\"IDENTITYNUMBERS\":\"35202-9876543-2\",\"LOANID\":\"\",\"ACCOUNTID\":\"AC100002\",\"CREATEDDATE\":\"2025-06-02 09:30:00\",\"TRANSACTIONAMOUNT\":9500.0,\"CURRENCY\":\"PKR\",\"TRANSACTIONTYPE\":\"Cash Deposit\",\"COUNTERPARTYACCOUNT\":\"\",\"EXCESSAMOUNT\":0.0}]",321 "FocusColumnValue": "100002",322 "KYCMonthlyIncome": "55,000 PKR",323 "KYCNoOfCredits": "7",324 "KYCNoOfDebits": "6",325 "KYCRiskCategoryValue": "Medium",326 "KYCValueOfCredits": "66,500 PKR",327 "KYCValueOfDebits": "56,525 PKR",328 "OccupationValue": "Textile Trader",329 "STRCount": 2,330 "STRScenarioHistory": "Large Cash Deposits, Rapid Fund Transfers",331 "ScenarioName": "Structuring / Smurfing activity",332 "CustomerName": "Ayesha Malik",333 "CUSTOMERID": "100002",334 "BranchID": "LHR-GUL",335 "Country": "Pakistan",336 "CustomerType": "Retail",337 "CustomerStatus": "Retail Customer",338 "CreatedDate": "2019-03-20",339 "RelationshipStartDate": "2019-03-20",340 "RiskScore": "8.5",341 "PreviousAlerts": [342 {343 "AlertName": "Large Cash Deposits",344 "Description": "1,200,000 PKR deposited in cash across multiple transactions in single day",345 "BranchExplanation": "Proceeds from sale of commercial property in Faisalabad",346 "Documentation": "",347 "RiskEscalation": ""348 }349 ],350 "Counterparties": [351 {352 "Name": "Al-Madina Textile Machinery LLC",353 "AccountID": "AE123456789012345678",354 "Country": "United Arab Emirates",355 "Jurisdiction": "Dubai",356 "TransactionAmount": 450000.0,357 "Currency": "PKR",358 "TransactionDate": "2025-06-03 10:15:00",359 "TransactionType": "Wire Transfer",360 "Relationship": "Supplier",361 "RiskLevel": "Medium",362 "ScreeningResult": "No adverse media found"363 }364 ],365 "BranchQueries": {366 "Requested": "Multiple cash deposits totaling 66,500 PKR made in same day, each below 10,000 PKR threshold. Pattern suggests potential structuring to avoid CTR reporting.",367 "Response": "Customer explained these are daily cash collections from retail textile sales at Anarkali Bazaar. Customer provided daily sales register and GST invoices."368 },369 "Cloud": false,370 "anonymous": false371}372```373 374**Request Parameters**:375 376All parameters from `generateamlanalysisoai` plus:377 378| Parameter | Type | Required | Description | Example |379|-----------|------|----------|-------------|---------|380| `Cloud` | boolean | No | Use OpenRouter cloud LLM (requires OPENROUTER_API_KEY). Default: `false` | `false` |381| `llm_on_server` | boolean | No | Use LLM at specified URL. Default: `false` | `false` |382| `url` | string | No | URL of remote Ollama server. Required if `llm_on_server=true` | `"http://remote-ollama:11434"` |383| `anonymous` | boolean | No | Mask PII (Personally Identifiable Information) in the data. When `true`, PII columns specified in `PII_COLUMNS` environment variable will be masked (format: first 2 chars + `***` + last 2 chars). Default: `false` | `false` |384 385**PII Masking**:386- When `anonymous: true`, PII values are masked by keeping the first 2 and last 2 characters, replacing the middle with `***`387- Example: `"Muhammad Bilal Sheikh"` → `"Mu***kh"`, `"100001"` → `"10***01"`388- Masking applies to:389 - Direct fields (CustomerName, CUSTOMERID, FocusColumnValue, etc.)390 - Nested structures (FilteredTransactions JSON, PreviousAlerts, Counterparties)391- PII columns are configurable via `PII_COLUMNS` environment variable (comma-separated list)392- Default PII columns: `CustomerName`, `CUSTOMERID`, `FocusColumnValue`, `IDENTITYNUMBERS`, `ACCOUNTID`, `LOANID`393 394**Response** (200 OK):395```json396{397 "status": 200,398 "message": "Success",399 "data": [400 {401 "AlertID": 2,402 "FocusColumnValue": "100002",403 "analysis": "AML Investigation Report - TMS Case: Structuring / Smurfing activity\n\nCustomer Name: Ayesha Malik\n...",404 "response_time_ms": 1234.56,405 "method": "hybrid_template_only",406 "model": "granite3.1-moe:3b"407 }408 ]409}410```411 412**Response Fields**:413- `analysis`: Complete AML investigation report414- `response_time_ms`: Response time in milliseconds415- `method`: Analysis method used416- `model`: LLM model used417 418**Error Response** (422 Unprocessable Entity):419```json420{421 "detail": "Validation error: [error details]"422}423```424 425**Error Response** (500 Internal Server Error):426```json427{428 "detail": "An error occurred while generating analysis"429}430```431 432**Example Request (Local LLM)**:433```bash434curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysis" \435 -H "Content-Type: application/json" \436 -d '{437 "AlertID": 2,438 "FocusColumnValue": "100002",439 "ScenarioName": "Structuring / Smurfing activity",440 "FilteredTransactions": "[{\"CUSTOMERID\":\"100002\",\"TRANSACTIONAMOUNT\":9500.0,\"CURRENCY\":\"PKR\"}]",441 "Cloud": false442 }'443```444 445**Example Request (Cloud LLM)**:446```bash447curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysis" \448 -H "Content-Type: application/json" \449 -d '{450 "AlertID": 2,451 "FocusColumnValue": "100002",452 "ScenarioName": "Structuring / Smurfing activity",453 "Cloud": true454 }'455```456 457**Example Request (Remote LLM Server)**:458```bash459curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysis" \460 -H "Content-Type: application/json" \461 -d '{462 "AlertID": 2,463 "FocusColumnValue": "100002",464 "ScenarioName": "Structuring / Smurfing activity",465 "llm_on_server": true,466 "url": "http://remote-ollama:11434"467 }'468```469 470**Example Request (With PII Masking)**:471```bash472curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysis" \473 -H "Content-Type: application/json" \474 -d '{475 "AlertID": 2,476 "CustomerName": "Ayesha Malik",477 "CUSTOMERID": "100002",478 "FocusColumnValue": "100002",479 "ScenarioName": "Structuring / Smurfing activity",480 "anonymous": true481 }'482```483 484**Note**: When `anonymous: true`, PII values will be masked. For example:485- `"Ayesha Malik"` → `"Ay***ik"`486- `"100002"` → `"10***02"`487- `"35202-9876543-2"` → `"35***3-2"`488 489---490 491### POST /api/ai-service/generateamlanalysisstreaming492 493Generate AML analysis report with streaming response using Hybrid Template+LLM system.494 495**Security**: None (authentication disabled for internal use)496 497**Request**: Same as `/api/ai-service/generateamlanalysis`498 499**Response**: Server-Sent Events (SSE) stream500 501**Content-Type**: `text/plain`502 503**Response Format**:504```505data: {"AlertID":2,"FocusColumnValue":"100002","analysis":"...","response_time_ms":1234.56,"method":"hybrid_template_only","model":"granite3.1-moe:3b"}506 507data: {"status":"error","message":"Error message"}508 509```510 511**Example Request**:512```bash513curl -X POST "http://localhost:8000/api/ai-service/generateamlanalysisstreaming" \514 -H "Content-Type: application/json" \515 -d '{516 "AlertID": 2,517 "FocusColumnValue": "100002",518 "ScenarioName": "Structuring / Smurfing activity",519 "FilteredTransactions": "[{\"CUSTOMERID\":\"100002\",\"TRANSACTIONAMOUNT\":9500.0}]"520 }' \521 --no-buffer522```523 524**JavaScript Example**:525```javascript526const response = await fetch('http://localhost:8000/api/ai-service/generateamlanalysisstreaming', {527 method: 'POST',528 headers: {529 'Content-Type': 'application/json'530 },531 body: JSON.stringify({532 AlertID: 2,533 FocusColumnValue: "100002",534 ScenarioName: "Structuring / Smurfing activity"535 })536});537 538const reader = response.body.getReader();539const decoder = new TextDecoder();540 541while (true) {542 const { done, value } = await reader.read();543 if (done) break;544 545 const chunk = decoder.decode(value);546 const lines = chunk.split('\n');547 548 for (const line of lines) {549 if (line.startsWith('data: ')) {550 const data = JSON.parse(line.slice(6));551 console.log('Analysis:', data.analysis);552 }553 }554}555```556 557---558 559## Email Alert Endpoints (Optional/Future Feature)560 561**Note**: Email alert endpoints are optional and currently commented out in the application. They are available for future use when email functionality is enabled.562 563### POST /api/ai-service/sendalertsemailjson564 565Send email alerts for high-risk transactions using JSON input.566 567**Security**: None (authentication disabled for internal use)568 569**Status**: Optional/Future Feature (currently disabled)570 571**Request**:572- **Content-Type**: `application/json`573- **Body**:574 575```json576{577 "to_emails": [578 "analyst1@example.com",579 "analyst2@example.com"580 ],581 "alert_details": {582 "AlertID": 12345,583 "FocusColumnValue": "100001",584 "STRCount": 2,585 "RevertedCount": 1,586 "TotalCount": 3,587 "CustomerName": "Muhammad Bilal Sheikh",588 "AccountNumber": "1234567890",589 "TransactionID": 98765,590 "TransactionDate": "2025-06-15"591 }592}593```594 595**Request Parameters**:596 597| Parameter | Type | Required | Description | Example |598|-----------|------|----------|-------------|---------|599| `to_emails` | array[string] | Yes | List of recipient email addresses | `["analyst@example.com"]` |600| `alert_details` | object | Yes | Alert details object | See below |601| `alert_details.AlertID` | integer | Yes | Alert identifier | `12345` |602| `alert_details.FocusColumnValue` | string | Yes | Customer/entity identifier | `"100001"` |603| `alert_details.STRCount` | integer | Yes | Count of previous STRs | `2` |604| `alert_details.RevertedCount` | integer | Yes | Count of reverted alerts | `1` |605| `alert_details.TotalCount` | integer | Yes | Total alert count | `3` |606| `alert_details.CustomerName` | string | Yes | Customer name | `"Muhammad Bilal Sheikh"` |607| `alert_details.AccountNumber` | string | Yes | Account number | `"1234567890"` |608| `alert_details.TransactionID` | integer | Yes | Transaction identifier | `98765` |609| `alert_details.TransactionDate` | string | Yes | Transaction date | `"2025-06-15"` |610 611**Email Conditions**:612Email is sent if:613- `STRCount > 0` OR614- `(RevertedCount / TotalCount) * 100 > 50`615 616**Response** (200 OK):617```json618[619 {620 "status": "success",621 "alert_id": 12345,622 "message": "Email sent successfully for Alert ID: 12345"623 }624]625```626 627**Error Response** (500 Internal Server Error):628```json629{630 "detail": "Error sending alert emails from JSON data"631}632```633 634**Example Request**:635```bash636curl -X POST "http://localhost:8000/api/ai-service/sendalertsemailjson" \637 -H "Content-Type: application/json" \638 -d '{639 "to_emails": ["analyst@example.com"],640 "alert_details": {641 "AlertID": 12345,642 "FocusColumnValue": "100001",643 "STRCount": 2,644 "RevertedCount": 1,645 "TotalCount": 3,646 "CustomerName": "Muhammad Bilal Sheikh",647 "AccountNumber": "1234567890",648 "TransactionID": 98765,649 "TransactionDate": "2025-06-15"650 }651 }'652```653 654---655 656### POST /api/ai-service/sendalertsemaildataframe657 658Send email alerts from database data.659 660**Security**: None (authentication disabled for internal use)661 662**Status**: Optional/Future Feature (currently disabled)663 664**Request**:665- **Content-Type**: `application/json`666- **Body**:667 668```json669[670 "analyst1@example.com",671 "analyst2@example.com"672]673```674 675**Request Parameters**:676 677| Parameter | Type | Required | Description | Example |678|-----------|------|----------|-------------|---------|679| (body) | array[string] | Yes | List of recipient email addresses | `["analyst@example.com"]` |680 681**Response** (200 OK):682```json683[684 {685 "status": "success",686 "alert_id": 12345,687 "message": "Email sent successfully for Alert ID: 12345"688 },689 {690 "status": "error",691 "alert_id": 12346,692 "message": "Failed to send email for Alert ID: 12346: [error]"693 }694]695```696 697**Note**: This endpoint requires:698- Valid `DB_CONNECTION_STR` in environment699- `DATA_TABLE` table exists700- Records with `Prediction = 1` in the table701- Email configuration (`FROM_EMAIL`, `EMAIL_PASSWORD`)702 703**Example Request**:704```bash705curl -X POST "http://localhost:8000/api/ai-service/sendalertsemaildataframe" \706 -H "Content-Type: application/json" \707 -d '["analyst@example.com"]'708```709 710---711 712## Data Models713 714### AnalysisAlertRequest715 716Base model for analysis requests. All fields are optional.717 718**Example from `aml_alerts_2_example.json`**:719```json720{721 "AlertID": 1,722 "FilteredTransactions": "[{\"CUSTOMERID\":\"100001\",\"TRANSACTIONAMOUNT\":150000.0,\"CURRENCY\":\"PKR\"}]",723 "FocusColumnValue": "100001",724 "KYCMonthlyIncome": "85,000 PKR",725 "KYCNoOfCredits": "3-5",726 "KYCNoOfDebits": "8-12",727 "KYCRiskCategoryValue": "Low",728 "KYCValueOfCredits": "150,000 - 200,000 PKR",729 "KYCValueOfDebits": "80,000 - 120,000 PKR",730 "OccupationValue": "Private Employee",731 "STRCount": 0,732 "STRScenarioHistory": "",733 "ScenarioName": "Unusually large installment",734 "CustomerName": "Muhammad Bilal Sheikh",735 "CUSTOMERID": "100001",736 "BranchID": "KHI-DHA",737 "Country": "Pakistan",738 "CustomerType": "Retail",739 "CustomerStatus": "Retail Customer",740 "CreatedDate": "2020-01-15",741 "RelationshipStartDate": "2020-01-15",742 "RiskScore": "4.2",743 "PreviousAlerts": [],744 "Counterparties": [],745 "BranchQueries": {746 "Requested": "Verification required...",747 "Response": "Customer stated..."748 }749}750```751 752### AlertDataRequest753 754Model for prediction requests. All fields are optional except `AlertID` and `FocusColumnValue`.755 756**Example from `aml_alerts_5_test_predict.json`**:757```json758{759 "AlertID": 1001,760 "FocusColumnValue": "PK-42101-1234567-1",761 "AlertScore": 85.5,762 "CreateDate": "2025-06-15T10:30:00",763 "riskLevel": "Low",764 "MatchDetails": "{\"id\": \"PK-42101-1234567-1\", \"scenario\": \"Unusually large installment\", \"score\": 85.5, \"riskLevel\": \"Low\"}",765 "MatchInfoJson": "[{\"ID\": \"PK-42101-1234567-1\", \"TRANSACTIONAMOUNT\": 150000, \"CURRENCY\": \"PKR\", \"INSTALLMENTNUMBER\": 1}, {\"ID\": \"PK-42101-1234567-1\", \"TRANSACTIONAMOUNT\": 180000, \"CURRENCY\": \"PKR\", \"INSTALLMENTNUMBER\": 2}]",766 "ScenarioName": "Unusually large installment",767 "workflow": "Unassigned"768}769```770 771---772 773## Error Responses774 775### Standard Error Format776 777All endpoints return errors in this format:778 779```json780{781 "detail": "Error message or validation errors"782}783```784 785### HTTP Status Codes786 787- **200 OK**: Request successful788- **400 Bad Request**: Invalid request (e.g., wrong credentials)789- **422 Unprocessable Entity**: Validation error790- **500 Internal Server Error**: Server error791 792### Common Error Messages793 7941. **Validation Errors**:795 - `"Validation error: [field errors]"`796 - `"Some fields missing in payload, using defaults"`797 7982. **Server Errors**:799 - `"An error occurred while generating AML analysis using oai"`800 - `"An error occurred while generating analysis"`801 - `"An error occurred while predicting alert priority"`802 - `"Failed to load model: [error]"`803 - `"Database connection failed"`804 805---806 807## Best Practices808 8091. **Always use HTTPS in production**8102. **Validate input data** before sending requests8113. **Handle errors gracefully** in your client code8124. **Use streaming endpoints** for large responses8135. **Monitor response times** for performance optimization8146. **Include all relevant fields** for better analysis quality815 816---817 818## Testing819 820### Using cURL821 822All examples in this documentation use cURL. Make sure to:823- Replace `localhost:8000` with your server URL824- Replace placeholder values with actual data825- Include proper headers826 827### Using Python828 829```python830import requests831 832# Predict alert priority833response = requests.post(834 "http://localhost:8000/api/ai-service/predictalertpriority",835 json={836 "AlertID": 1001,837 "FocusColumnValue": "PK-42101-1234567-1",838 "AlertScore": 85.5,839 "ScenarioName": "Unusually large installment"840 }841)842print(response.json())843 844# Generate analysis845response = requests.post(846 "http://localhost:8000/api/ai-service/generateamlanalysis",847 json={848 "AlertID": 1,849 "FocusColumnValue": "100001",850 "ScenarioName": "Unusually large installment",851 "KYCMonthlyIncome": "85,000 PKR"852 }853)854print(response.json())855```856 857---858 859## Changelog860 861### Version 1.0.0862- Initial API release863- Optional authentication endpoint (for external integrations only)864- Alert priority prediction endpoint865- AML analysis generation endpoints (OpenAI, Hybrid, Streaming)866- Authentication disabled for internal system use867 