-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2070 lines (1770 loc) · 85.6 KB
/
api.py
File metadata and controls
2070 lines (1770 loc) · 85.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
REST API for DocAutomate Framework
Provides endpoints for document ingestion and workflow management
"""
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks, Body, Request, Depends
from fastapi.security import APIKeyHeader
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, ValidationError
from typing import List, Dict, Any, Optional, Union
import asyncio
import logging
import os
from pathlib import Path
import tempfile
import shutil
import json
# Import our modules
from ingester import DocumentIngester, Document
from extractor import ActionExtractor, ExtractedAction
from workflow import WorkflowEngine, WorkflowRun, WorkflowStatus
from workflow_matcher import WorkflowMatcher
from services.claude_service import claude_service
from claude_cli import SuperClaudeMCP
from utils.file_operations import FileOperations
from utils.metrics import collect_health_metrics, format_duration
from enum import Enum
from email_ingester import ingest_email as ingest_email_message
from config import settings
# Set up logging with more detail
import uuid
from datetime import datetime
logging.basicConfig(
level=logging.DEBUG if os.getenv("DEBUG") else logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
)
logger = logging.getLogger(__name__)
# Request tracking
def generate_request_id():
"""Generate unique request ID for tracking"""
return str(uuid.uuid4())[:8]
def format_processing_time(seconds: Optional[float]) -> Optional[str]:
"""Return a consistent string (e.g. '5.20s') for processing durations."""
if seconds is None:
return None
try:
value = float(seconds)
except (TypeError, ValueError):
return None
return f"{value:.2f}s"
api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)
async def require_api_key(provided_key: Optional[str] = Depends(api_key_header)) -> Optional[str]:
expected = settings.api_key
if expected:
if provided_key != expected:
logger.warning("Unauthorized request blocked", extra={"principal": provided_key})
raise HTTPException(status_code=401, detail="Invalid or missing API key")
logger.debug("API key accepted", extra={"principal": provided_key})
return provided_key
# Initialize FastAPI app
app = FastAPI(
title="DocAutomate API",
description="Enterprise Document Ingestion and Action Automation Framework",
version="1.0.0",
dependencies=[Depends(require_api_key)]
)
templates = Jinja2Templates(directory="templates/web")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure appropriately for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize components
document_ingester = DocumentIngester()
action_extractor = ActionExtractor()
workflow_engine = WorkflowEngine()
workflow_matcher = WorkflowMatcher(workflow_engine)
# In-memory orchestration status tracking
orchestration_status = {}
class OrchestrationStatus(Enum):
"""Orchestration status enumeration"""
QUEUED = "queued"
RUNNING = "running"
ANALYSIS = "analysis"
CONSENSUS = "consensus"
REMEDIATION = "remediation"
VALIDATION = "validation"
COMPLETED = "completed"
FAILED = "failed"
# Pydantic models for API
class DocumentUploadResponse(BaseModel):
document_id: str
filename: str
status: str
message: str
extracted_actions: Optional[List[Dict]]
delegation_status: str
delegation_details: Optional[Dict[str, Any]] = None
class WorkflowExecutionRequest(BaseModel):
document_id: str
workflow_name: str
parameters: Dict[str, Any]
auto_execute: bool = False
class WorkflowExecutionResponse(BaseModel):
run_id: str
workflow_name: str
document_id: str
status: str
message: str
class DocumentStatusResponse(BaseModel):
document_id: str
filename: str
status: str
ingested_at: str
content_type: str
size_bytes: Optional[int]
claude_agent: Optional[str]
quality_score: Optional[float]
claude_analysis: Optional[Dict]
workflow_runs: List[str]
extracted_actions: Optional[List[Dict]]
delegation_status: str
delegation_details: Optional[Dict[str, Any]] = None
class WorkflowRunStatusResponse(BaseModel):
run_id: str
workflow_name: str
status: str
started_at: str
completed_at: Optional[str]
current_step: Optional[str]
outputs: Dict[str, Any]
step_history: List[Dict[str, Any]]
duration_seconds: Optional[float]
duration_formatted: Optional[str]
summary: Optional[Dict[str, Any]]
error: Optional[str]
class OrchestrationRequest(BaseModel):
document_id: str
workflow_type: str = "full" # full, analysis_only, remediation_only
agents: Optional[List[str]] = None
models: Optional[List[str]] = None
config: Optional[Dict[str, Any]] = None
class OrchestrationResponse(BaseModel):
orchestration_id: str
document_id: str
status: str
message: str
results: Optional[Dict[str, Any]] = None
class AnalysisRequest(BaseModel):
agents: Optional[List[str]] = None
parallel: bool = True
claude_config: Optional[Dict[str, Any]] = None
class ConsensusRequest(BaseModel):
analysis_data: Dict[str, Any]
models: Optional[List[str]] = None
metadata: Optional[Dict[str, Any]] = None
consensus_config: Optional[Dict[str, Any]] = None
class RemediationRequest(BaseModel):
issues: List[Dict[str, Any]]
template: Optional[str] = None
class ValidationRequest(BaseModel):
original_content: str
remediated_content: str
validation_type: str = "quality" # quality, security, compliance
class FolderCompressionRequest(BaseModel):
folder_path: str
output_name: Optional[str] = None
output_filename: Optional[str] = None
include_patterns: Optional[List[str]] = None
exclude_patterns: Optional[List[str]] = None
compression_level: int = 6
use_dsl: bool = True
class FolderCompressionResponse(BaseModel):
success: bool
output_path: Optional[str]
archive_path: Optional[str]
files_compressed: Optional[int]
files_included: Optional[int]
original_size_bytes: Optional[int]
compressed_size_bytes: Optional[int]
compression_ratio: Optional[str]
duration_seconds: Optional[float]
error: Optional[str]
workflow_run_id: Optional[str] = None
class ActionExtractionResponse(BaseModel):
document_id: str
status: str
extracted_actions: List[Dict[str, Any]]
auto_triggered_workflows: int
analysis_summary: Dict[str, Any]
class ActionExtractionRequest(BaseModel):
auto_execute: bool = False
class DocumentConversionRequest(BaseModel):
document_id: Optional[str] = None
input_path: Optional[str] = None
output_path: Optional[str] = None
output_format: str = "pdf"
target_format: Optional[str] = None
quality: str = "high"
preserve_formatting: bool = True
use_dsl: bool = True
class DocumentConversionResponse(BaseModel):
success: bool
output_path: Optional[str]
archive_path: Optional[str]
conversion_method: Optional[str]
original_file: Optional[str]
file_size_bytes: Optional[int]
conversion_time_seconds: Optional[float]
error: Optional[str]
workflow_run_id: Optional[str] = None
results: Optional[List[Dict[str, Any]]] = None
processing_time: Optional[str] = None
processing_time_seconds: Optional[float] = None
class BatchConversionRequest(BaseModel):
input_files: List[str]
document_ids: Optional[List[str]] = None
output_directory: str
conversion_type: str = "docx_to_pdf"
target_format: Optional[str] = None
parallel: bool = True
max_workers: int = 4
use_dsl: bool = True
class EmailIngestionRequest(BaseModel):
raw_email: str
source: Optional[str] = "mailbox"
auto_process: bool = True
class EmailAttachmentInfo(BaseModel):
document_id: str
filename: str
delegation_status: str
class EmailIngestionResponse(BaseModel):
email_document: DocumentUploadResponse
attachments: List[EmailAttachmentInfo]
EXTRACTION_ERROR_PHRASES = [
'i need your permission',
'please grant permission',
'permission to read',
'allow access',
'grant access',
'claude code is required'
]
async def _extract_actions_for_document(
document: Document,
request_id: str,
run_workflows: bool = True
) -> Dict[str, Any]:
"""Shared extraction workflow for background and synchronous requests"""
logger.info(f"[{request_id}] Extracting actions for document {document.id}")
logger.info(
f"[{request_id}] Delegation status: {document.delegation_status}",
extra={
"delegation_status": document.delegation_status,
"delegation_details": document.delegation_details,
},
)
text_content = document.text or ""
if len(text_content) < 50:
logger.error(f"[{request_id}] Document {document.id} has insufficient text content ({len(text_content)} chars)")
document.status = "failed"
document.error = "Insufficient text content extracted"
await document_ingester._store_document(document)
return {"actions": [], "auto_runs": 0, "analysis_summary": {}, "status": document.status}
text_lower = text_content.lower()
for phrase in EXTRACTION_ERROR_PHRASES:
if phrase in text_lower:
logger.error(f"[{request_id}] Document {document.id} contains extraction error: '{phrase}'")
document.status = "extraction_failed"
document.error = "Text extraction failed - permission or processing error detected"
await document_ingester._store_document(document)
return {"actions": [], "auto_runs": 0, "analysis_summary": {}, "status": document.status}
document_type = (document.metadata or {}).get('document_type', 'general')
actions = await action_extractor.extract_actions(
text_content,
document_type=document_type
)
actions_payload: List[Dict[str, Any]] = []
high_confidence = 0
for index, action in enumerate(actions, start=1):
if action.confidence_score >= 0.85:
high_confidence += 1
if not action.action_id:
action.action_id = f"{document.id}-act-{uuid.uuid4().hex[:8]}"
logger.debug(
f"[{request_id}] Action {index}: id={action.action_id}, type={action.action_type}, "
f"workflow={action.workflow_name}, confidence={action.confidence_score:.2f}"
)
actions_payload.append(action.dict())
score_values = [payload.get('confidence_score', 0.0) for payload in actions_payload]
avg_quality = sum(score_values) / len(score_values) if score_values else 0.0
quality_score = round(avg_quality, 2) if score_values else 0.0
def _confidence_to_severity(score: float) -> str:
if score >= 0.9:
return "high"
if score >= 0.75:
return "medium"
return "low"
issues_found: List[Dict[str, Any]] = []
for payload in actions_payload:
parameters = payload.get('parameters') or {}
location: Optional[Any] = parameters.get('location')
if not location:
location_details: Dict[str, Any] = {}
for key in ("section", "page", "page_number", "lines", "paragraph"):
if key in parameters and parameters[key]:
normalized_key = "page" if key == "page_number" else key
location_details[normalized_key] = parameters[key]
if location_details:
location = location_details
if not location:
for entity in payload.get('entities', []):
entity_location = entity.get('location')
if entity_location:
location = entity_location
break
issues_found.append({
"type": payload.get("action_type"),
"severity": _confidence_to_severity(payload.get("confidence_score", 0.0)),
"description": payload.get("description"),
"location": location
})
recommendations: List[str] = []
for payload in actions_payload:
description = payload.get("description")
if description and description not in recommendations:
recommendations.append(description)
primary_agent = (
(document.metadata or {}).get('claude_agent')
or document.primary_agent
or 'requirements-analyst'
)
analysis_summary = {
"primary_agent": primary_agent,
"quality_score": quality_score if score_values else None,
"issues_found": issues_found,
"recommendations": recommendations,
"total_actions": len(actions_payload),
"high_confidence_actions": high_confidence,
"document_type": document_type
}
document.metadata = document.metadata or {}
document.metadata.setdefault('document_type', document_type)
document.metadata['last_extracted_at'] = datetime.utcnow().isoformat()
document.metadata['claude_analysis'] = analysis_summary
document.metadata['quality_score'] = quality_score if score_values else None
document.metadata['claude_agent'] = primary_agent
document.extracted_actions = actions_payload
document.quality_score = document.metadata['quality_score']
document.primary_agent = primary_agent
document.analysis_summary = analysis_summary
if document.quality_score is not None and document.quality_score < 0.9:
document.status = "manual_review"
document.metadata['manual_review'] = True
document.metadata['manual_review_reason'] = "quality_below_threshold"
elif not actions_payload:
document.status = "processed_no_actions"
else:
document.status = "processed" if len(text_content) > 100 else "partial"
auto_executed_count = 0
if run_workflows and actions:
for action in actions:
if action.confidence_score < 0.85:
continue
try:
match_context = {
'action_type': action.action_type,
'parameters': action.parameters,
'document_type': document.metadata.get('document_type', 'general')
}
match_result = await workflow_matcher.match(action.workflow_name, match_context)
resolved_workflow = match_result.matched_workflow
if resolved_workflow != action.workflow_name:
logger.info(
f"[{request_id}] Workflow matched: '{action.workflow_name}' -> '{resolved_workflow}' "
f"(confidence: {match_result.confidence:.2f}, reason: {match_result.reason})"
)
if match_result.reasoning:
logger.debug(f"[{request_id}] Match reasoning: {match_result.reasoning}")
if match_result.confidence < 0.3:
logger.warning(
f"[{request_id}] No suitable workflow match for '{action.workflow_name}' "
f"(confidence: {match_result.confidence:.2f})"
)
continue
if match_result.confidence < 0.7:
logger.warning(
f"[{request_id}] Low confidence match: '{action.workflow_name}' -> '{resolved_workflow}' "
f"(confidence: {match_result.confidence:.2f})"
)
if resolved_workflow not in workflow_engine.workflows:
logger.warning(f"[{request_id}] Resolved workflow '{resolved_workflow}' not found in engine")
continue
params = dict(action.parameters)
params['document_id'] = document.id
if resolved_workflow == 'document_signature':
if 'parties' not in params:
if 'party1' in params and 'party2' in params:
params['parties'] = [params.pop('party1'), params.pop('party2')]
elif 'party' in params:
params['parties'] = [params.pop('party')]
if 'document_type' not in params:
params['document_type'] = document.metadata.get('document_type', 'general')
logger.info(
f"[{request_id}] Auto-executing workflow {resolved_workflow} "
f"(confidence: {action.confidence_score:.2f})"
)
run = await workflow_engine.execute_workflow(
workflow_name=resolved_workflow,
document_id=document.id,
initial_parameters=params
)
if document.workflow_runs is None:
document.workflow_runs = []
document.workflow_runs.append(run.run_id)
auto_executed_count += 1
except ValueError as e:
logger.warning(f"[{request_id}] Validation error for workflow {action.workflow_name}: {e}")
logger.debug(f"[{request_id}] Stack trace:", exc_info=True)
except Exception as exc:
logger.error(f"[{request_id}] Failed to auto-execute workflow {action.workflow_name}: {exc}")
logger.debug(f"[{request_id}] Stack trace:", exc_info=True)
document.metadata['auto_triggered_workflows'] = auto_executed_count
await document_ingester._store_document(document)
return {
"actions": actions_payload,
"auto_runs": auto_executed_count,
"analysis_summary": analysis_summary,
"status": document.status
}
# Background task for processing document
async def process_document_background(document: Document, request_id: str = None):
"""Background task to extract actions from document"""
request_id = request_id or generate_request_id()
start_time = datetime.now()
logger.info(f"[{request_id}] Starting background processing for document {document.id}")
logger.debug(f"[{request_id}] Document details: filename={document.filename}, size={len(document.text) if document.text else 0} chars")
try:
result = await _extract_actions_for_document(document, request_id, run_workflows=True)
processing_time = (datetime.now() - start_time).total_seconds()
logger.info(
f"[{request_id}] Successfully processed document {document.id} in {processing_time:.2f}s: "
f"{len(result['actions'])} actions extracted (auto workflows: {result['auto_runs']})"
)
except Exception as e:
processing_time = (datetime.now() - start_time).total_seconds()
logger.error(f"[{request_id}] Failed to process document {document.id} after {processing_time:.2f}s: {e}")
logger.debug(f"[{request_id}] Stack trace:", exc_info=True)
document.status = "failed"
await document_ingester._store_document(document)
# API Endpoints
@app.get("/")
async def root():
"""Root endpoint with API information aligned to README contract"""
api_port = int(os.getenv("API_PORT", "8000"))
base_url = f"http://localhost:{api_port}"
return {
"name": "DocAutomate API",
"version": "2.0.0",
"description": "Enterprise Document Processing via Claude Code Delegation",
"documentation": f"{base_url}/docs",
"health": f"{base_url}/health",
"features": [
"Universal document processing",
"Pure Claude Code delegation",
"Multi-agent orchestration",
"DSL-driven configuration",
"Multi-model consensus validation",
"Desktop GUI application"
],
"endpoints": {
"upload": "/documents/upload",
"list_documents": "/documents",
"document_status": "/documents/{document_id}",
"email_ingest": "/emails/ingest",
"execute_workflow": "/workflows/execute",
"list_workflows": "/workflows",
"workflow_status": "/workflows/runs/{run_id}",
"compress_folder": "/documents/compress-folder",
"convert_document": "/documents/convert/docx-to-pdf",
"batch_convert": "/documents/convert/batch",
"orchestrate": "/orchestrate/workflow"
}
}
def _doc_to_view(doc: Document) -> Dict[str, Any]:
metadata = doc.metadata or {}
return {
"id": doc.id,
"filename": doc.filename,
"status": doc.status,
"ingested_at": doc.ingested_at,
"content_type": doc.content_type,
"quality_score": doc.quality_score if doc.quality_score is not None else metadata.get("quality_score"),
"primary_agent": doc.primary_agent or metadata.get("claude_agent"),
"workflow_runs": (doc.workflow_runs or []),
}
def _run_to_view(run: WorkflowRun) -> Dict[str, Any]:
status = run.status.value if isinstance(run.status, WorkflowStatus) else run.status
return {
"run_id": run.run_id,
"workflow_name": run.workflow_name,
"document_id": run.document_id,
"status": status,
"started_at": run.started_at,
"completed_at": run.completed_at,
"duration": format_duration(run.total_duration_seconds),
}
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
documents = document_ingester.list_documents()
runs = workflow_engine.list_runs()[:50]
metrics_payload = collect_health_metrics(document_ingester, workflow_engine, claude_service)
workflow_overview = []
for name, definition in workflow_engine.workflows.items():
meta = definition.get("metadata", {})
metrics = workflow_engine.get_workflow_metrics(name)
workflow_overview.append({
"name": name,
"description": definition.get("description", ""),
"tags": meta.get("tags", []),
"run_count": metrics.get("run_count"),
"success_rate": metrics.get("success_rate"),
"average_duration": metrics.get("average_duration_formatted"),
})
context = {
"request": request,
"documents": [_doc_to_view(doc) for doc in documents],
"workflow_runs": [_run_to_view(run) for run in runs],
"metrics": metrics_payload,
"workflows": workflow_overview,
}
return templates.TemplateResponse("index.html", context)
@app.post("/documents/upload", response_model=DocumentUploadResponse)
async def upload_document(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
auto_process: bool = True
):
"""Upload a document for processing"""
request_id = generate_request_id()
start_time = datetime.now()
logger.info(f"[{request_id}] Document upload started: filename={file.filename}, content_type={file.content_type}, auto_process={auto_process}")
tmp_path = None
try:
# Get file size
file.file.seek(0, 2) # Seek to end
file_size = file.file.tell()
file.file.seek(0) # Reset to beginning
logger.info(f"[{request_id}] File size: {file_size} bytes ({file_size / 1024:.2f} KB)")
# Save uploaded file to temp location
logger.debug(f"[{request_id}] Saving uploaded file to temporary location")
with tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename).suffix) as tmp_file:
shutil.copyfileobj(file.file, tmp_file)
tmp_path = tmp_file.name
logger.debug(f"[{request_id}] Temporary file created: {tmp_path}")
# Ingest document
logger.info(f"[{request_id}] Starting document ingestion for: {file.filename}")
ingestion_start = datetime.now()
document = await document_ingester.ingest_file(tmp_path)
ingestion_time = (datetime.now() - ingestion_start).total_seconds()
logger.info(
f"[{request_id}] Document ingested in {ingestion_time:.2f}s: id={document.id}, "
f"status={document.status}, delegation={document.delegation_status}"
)
# Clean up temp file
logger.debug(f"[{request_id}] Cleaning up temporary file: {tmp_path}")
Path(tmp_path).unlink()
tmp_path = None # Mark as cleaned
# Process in background if requested
if auto_process:
logger.info(f"[{request_id}] Queuing document {document.id} for background processing")
background_tasks.add_task(process_document_background, document, request_id)
message = "Document uploaded and queued for processing"
else:
logger.info(f"[{request_id}] Document {document.id} uploaded without auto-processing")
message = "Document uploaded successfully"
upload_time = (datetime.now() - start_time).total_seconds()
logger.info(f"[{request_id}] Document upload completed in {upload_time:.2f}s: {file.filename} -> {document.id}")
return DocumentUploadResponse(
document_id=document.id,
filename=document.filename,
status=document.status,
message=message,
extracted_actions=None,
delegation_status=document.delegation_status,
delegation_details=document.delegation_details,
)
except Exception as e:
upload_time = (datetime.now() - start_time).total_seconds()
logger.error(f"[{request_id}] Failed to upload document after {upload_time:.2f}s: {file.filename}")
logger.error(f"[{request_id}] Error details: {e}")
logger.debug(f"[{request_id}] Stack trace:", exc_info=True)
# Clean up temp file if it exists
if tmp_path and Path(tmp_path).exists():
logger.debug(f"[{request_id}] Cleaning up temporary file after error: {tmp_path}")
Path(tmp_path).unlink()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/emails/ingest", response_model=EmailIngestionResponse)
async def ingest_email_endpoint(request: EmailIngestionRequest):
"""Ingest a raw email payload (RFC822) and optional attachments."""
request_id = generate_request_id()
logger.info(f"[{request_id}] Email ingestion started (source={request.source})")
try:
result = await ingest_email_message(
document_ingester=document_ingester,
raw_email=request.raw_email,
source=request.source or "mailbox",
auto_process=request.auto_process,
)
email_doc_response = DocumentUploadResponse(
document_id=result.email_document.id,
filename=result.email_document.filename,
status=result.email_document.status,
message="Email ingested successfully",
extracted_actions=None,
delegation_status=result.email_document.delegation_status,
delegation_details=result.email_document.delegation_details,
)
attachment_infos = [
EmailAttachmentInfo(
document_id=attachment.id,
filename=attachment.filename,
delegation_status=attachment.delegation_status,
)
for attachment in result.attachment_documents
]
logger.info(
f"[{request_id}] Email ingestion completed: email_doc={result.email_document.id}, "
f"attachments={len(attachment_infos)}"
)
return EmailIngestionResponse(email_document=email_doc_response, attachments=attachment_infos)
except Exception as exc:
logger.error(f"[{request_id}] Email ingestion failed: {exc}")
raise HTTPException(status_code=500, detail=str(exc))
@app.get("/documents", response_model=List[DocumentStatusResponse])
async def list_documents(status: Optional[str] = None):
"""List all documents, optionally filtered by status"""
try:
documents = document_ingester.list_documents(status=status)
return [
DocumentStatusResponse(
document_id=doc.id,
filename=doc.filename,
status=doc.status,
ingested_at=doc.ingested_at,
content_type=doc.content_type,
size_bytes=(doc.metadata or {}).get('size_bytes'),
claude_agent=doc.primary_agent or (doc.metadata or {}).get('claude_agent'),
quality_score=doc.quality_score if doc.quality_score is not None else (doc.metadata or {}).get('quality_score'),
claude_analysis=doc.analysis_summary or (doc.metadata or {}).get('claude_analysis'),
workflow_runs=doc.workflow_runs or [],
extracted_actions=doc.extracted_actions,
delegation_status=doc.delegation_status,
delegation_details=doc.delegation_details,
)
for doc in documents
]
except Exception as e:
logger.error(f"Failed to list documents: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/documents/{document_id}", response_model=DocumentStatusResponse)
async def get_document_status(document_id: str):
"""Get status of a specific document"""
try:
document = document_ingester.get_document(document_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found")
metadata = document.metadata or {}
return DocumentStatusResponse(
document_id=document.id,
filename=document.filename,
status=document.status,
ingested_at=document.ingested_at,
content_type=document.content_type,
size_bytes=metadata.get('size_bytes'),
claude_agent=document.primary_agent or metadata.get('claude_agent'),
quality_score=document.quality_score if document.quality_score is not None else metadata.get('quality_score'),
claude_analysis=document.analysis_summary or metadata.get('claude_analysis'),
workflow_runs=document.workflow_runs or [],
extracted_actions=document.extracted_actions,
delegation_status=document.delegation_status,
delegation_details=document.delegation_details,
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get document status: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/documents/{document_id}/extract", response_model=ActionExtractionResponse)
async def extract_actions(document_id: str, request: Optional[ActionExtractionRequest] = None):
"""Manually trigger action extraction for a document and return structured results"""
request_id = generate_request_id()
logger.info(f"[{request_id}] Manual action extraction requested for document {document_id}")
try:
document = document_ingester.get_document(document_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found")
extraction_request = request or ActionExtractionRequest()
result = await _extract_actions_for_document(
document=document,
request_id=request_id,
run_workflows=extraction_request.auto_execute
)
return ActionExtractionResponse(
document_id=document.id,
status=result["status"],
extracted_actions=result["actions"],
auto_triggered_workflows=result["auto_runs"],
analysis_summary=result["analysis_summary"]
)
except HTTPException:
raise
except Exception as e:
logger.error(f"[{request_id}] Failed to extract actions: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/documents/{document_id}/actions", response_model=ActionExtractionResponse)
async def get_document_actions(document_id: str):
"""Retrieve previously extracted actions for a document"""
document = document_ingester.get_document(document_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found")
actions = document.extracted_actions or []
analysis_summary = document.analysis_summary or (document.metadata or {}).get('claude_analysis') or {}
auto_runs = (document.metadata or {}).get('auto_triggered_workflows', 0)
return ActionExtractionResponse(
document_id=document.id,
status=document.status,
extracted_actions=actions,
auto_triggered_workflows=auto_runs,
analysis_summary=analysis_summary
)
@app.get("/workflows")
async def list_workflows():
"""List available workflows"""
try:
workflow_details = []
for name, workflow in workflow_engine.workflows.items():
steps = workflow.get("steps", [])
metadata = workflow.get("metadata", {})
metrics = workflow_engine.get_workflow_metrics(name)
step_metrics_map = {m["step_id"]: m for m in metrics.get("step_metrics", [])}
enriched_steps = []
for step in steps:
step_id = step.get("id")
metric = step_metrics_map.get(step_id, {})
enriched_steps.append({
"id": step_id,
"type": step.get("type"),
"description": step.get("description", ""),
"average_duration_seconds": metric.get("average_duration_seconds"),
"average_duration_formatted": metric.get("average_duration_formatted"),
"runs": metric.get("runs"),
"success_count": metric.get("success_count"),
"failure_count": metric.get("failure_count")
})
metrics_with_sla = dict(metrics)
metrics_with_sla["sla_hours"] = metadata.get("sla_hours")
metrics_with_sla["average_duration_hours"] = (
metrics.get("average_duration_seconds") / 3600
if metrics.get("average_duration_seconds")
else None
)
workflow_details.append({
"name": name,
"description": workflow.get("description", ""),
"version": workflow.get("version", "1.0.0"),
"parameters": workflow.get("parameters", []),
"step_count": len(steps),
"steps": enriched_steps,
"metadata": metadata,
"tags": metadata.get("tags", []),
"metrics": metrics_with_sla
})
return {
"workflows": workflow_details,
"total": len(workflow_details)
}
except Exception as e:
logger.error(f"Failed to list workflows: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/workflows/{workflow_name}")
async def get_workflow(workflow_name: str):
"""Get detailed definition of a specific workflow"""
try:
if workflow_name not in workflow_engine.workflows:
raise HTTPException(status_code=404, detail="Workflow not found")
workflow = workflow_engine.workflows[workflow_name]
steps = workflow.get("steps", [])
metadata = workflow.get("metadata", {})
metrics = workflow_engine.get_workflow_metrics(workflow_name)
return {
"name": workflow.get("name", workflow_name),
"description": workflow.get("description", ""),
"version": workflow.get("version", "1.0.0"),
"parameters": workflow.get("parameters", []),
"step_count": len(steps),
"steps": steps,
"metadata": metadata,
"tags": metadata.get("tags", []),
"metrics": metrics
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get workflow {workflow_name}: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/workflows/execute", response_model=WorkflowExecutionResponse)
async def execute_workflow(request: WorkflowExecutionRequest, background_tasks: BackgroundTasks):
"""Execute a workflow for a document"""
request_id = generate_request_id()
start_time = datetime.now()
logger.info(f"[{request_id}] Workflow execution requested: workflow={request.workflow_name}, document={request.document_id}, auto={request.auto_execute}")
logger.debug(f"[{request_id}] Parameters: {request.parameters}")
try:
# Validate document exists
logger.debug(f"[{request_id}] Validating document {request.document_id}")
document = document_ingester.get_document(request.document_id)
if not document:
logger.warning(f"[{request_id}] Document not found: {request.document_id}")
raise HTTPException(status_code=404, detail="Document not found")
# Use intelligent workflow matching
match_context = {
'parameters': request.parameters,
'document_id': request.document_id
}
match_result = await workflow_matcher.match(request.workflow_name, match_context)
resolved_workflow = match_result.matched_workflow
# Log the matching decision
if resolved_workflow != request.workflow_name:
logger.info(f"[{request_id}] Workflow matched: '{request.workflow_name}' -> '{resolved_workflow}' "
f"(confidence: {match_result.confidence:.2f}, reason: {match_result.reason})")
if match_result.reasoning:
logger.debug(f"[{request_id}] Match reasoning: {match_result.reasoning}")
# Check confidence threshold
if match_result.confidence < 0.3:
logger.warning(f"[{request_id}] No suitable workflow match for '{request.workflow_name}' "
f"(confidence: {match_result.confidence:.2f})")
raise HTTPException(status_code=404,
detail=f"No suitable workflow match for '{request.workflow_name}' (confidence: {match_result.confidence:.2f})")
# Warn on low confidence matches but proceed
if match_result.confidence < 0.7:
logger.warning(f"[{request_id}] Low confidence match: '{request.workflow_name}' -> '{resolved_workflow}' "
f"(confidence: {match_result.confidence:.2f})")
# Validate workflow exists
if resolved_workflow not in workflow_engine.workflows: