File size: 10,280 Bytes
665cc97
1c43e67
665cc97
1c43e67
665cc97
1c43e67
665cc97
1c43e67
665cc97
1c43e67
665cc97
1c43e67
665cc97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c43e67
665cc97
1c43e67
665cc97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c43e67
665cc97
 
 
 
 
 
 
 
 
 
 
 
 
1c43e67
 
665cc97
 
 
 
 
 
 
 
 
 
 
1c43e67
665cc97
 
 
 
 
 
 
 
 
 
1c43e67
 
665cc97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c43e67
 
 
665cc97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Architecture Documentation

## System Overview

The Deep-Research PDF Field Extractor is a multi-agent system designed to extract structured data from biotech-related PDFs. The system uses Azure Document Intelligence for document processing and Azure OpenAI for intelligent field extraction.

## Core Architecture

### Multi-Agent Design

The system follows a multi-agent architecture where each agent has a specific responsibility:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   PDFAgent      β”‚    β”‚  TableAgent     β”‚    β”‚  IndexAgent     β”‚
β”‚                 β”‚    β”‚                 β”‚    β”‚                 β”‚
β”‚ β€’ PDF Text      │───▢│ β€’ Table         │───▢│ β€’ Semantic      β”‚
β”‚   Extraction    β”‚    β”‚   Processing    β”‚    β”‚   Indexing      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                β”‚
                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚UniqueIndices    β”‚    β”‚UniqueIndices    β”‚    β”‚FieldMapper      β”‚
β”‚Combinator       β”‚    β”‚LoopAgent        β”‚    β”‚Agent            β”‚
β”‚                 β”‚    β”‚                 β”‚    β”‚                 β”‚
β”‚ β€’ Extract       │───▢│ β€’ Loop through  β”‚    β”‚ β€’ Extract       β”‚
β”‚   combinations  β”‚    β”‚   combinations  β”‚    β”‚   individual    β”‚
β”‚                 β”‚    β”‚ β€’ Add fields    β”‚    β”‚   fields        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Execution Flow

#### Original Strategy Flow
```
1. PDFAgent β†’ Extract text from PDF
2. TableAgent β†’ Process tables with Azure DI
3. IndexAgent β†’ Create semantic search index
4. ForEachField β†’ Iterate through fields
5. FieldMapperAgent β†’ Extract each field value
```

#### Unique Indices Strategy Flow
```
1. PDFAgent β†’ Extract text from PDF
2. TableAgent β†’ Process tables with Azure DI
3. UniqueIndicesCombinator β†’ Extract unique combinations
4. UniqueIndicesLoopAgent β†’ Extract additional fields for each combination
```

## Agent Details

### PDFAgent
- **Purpose**: Extract text content from PDF files
- **Technology**: PyMuPDF (fitz)
- **Output**: Raw text content
- **Error Handling**: Graceful handling of corrupted PDFs

### TableAgent
- **Purpose**: Process tables using Azure Document Intelligence
- **Technology**: Azure DI Layout Analysis
- **Features**: 
  - Table structure preservation
  - Rowspan/colspan handling
  - HTML table generation for debugging
- **Output**: Processed table data

### UniqueIndicesCombinator
- **Purpose**: Extract unique combinations of specified indices
- **Input**: Document text, unique indices descriptions
- **LLM Prompt**: Structured prompt for combination extraction
- **Output**: JSON array of unique combinations
- **Cost Tracking**: Tracks input/output tokens

### UniqueIndicesLoopAgent
- **Purpose**: Extract additional fields for each unique combination
- **Input**: Unique combinations, field descriptions
- **Process**: Loops through each combination
- **LLM Calls**: One call per combination
- **Error Handling**: Continues with partial failures
- **Output**: Complete data with all fields

### FieldMapperAgent
- **Purpose**: Extract individual field values
- **Strategies**: 
  - Page-by-page analysis
  - Semantic search fallback
  - Unique indices strategy
- **Features**: Context-aware extraction
- **Output**: Field values with confidence scores

### IndexAgent
- **Purpose**: Create semantic search indices
- **Technology**: Azure OpenAI Embeddings
- **Features**: Chunk-based indexing
- **Output**: Searchable document index

## Services

### LLMClient
```python
class LLMClient:
    def __init__(self, settings):
        # Azure OpenAI configuration
        self._deployment = settings.AZURE_OPENAI_DEPLOYMENT
        self._max_retries = settings.LLM_MAX_RETRIES
        self._base_delay = settings.LLM_BASE_DELAY
    
    def responses(self, prompt, **kwargs):
        # Retry logic with exponential backoff
        # Cost tracking integration
        # Error handling
```

**Key Features:**
- Retry logic with exponential backoff
- Cost tracking integration
- Error classification (retryable vs non-retryable)
- Jitter to prevent thundering herd

### CostTracker
```python
class CostTracker:
    def __init__(self):
        self.llm_calls: List[LLMCall] = []
        self.current_file_costs = {}
        self.total_costs = {}
    
    def add_llm_tokens(self, input_tokens, output_tokens, description):
        # Track individual LLM calls
        # Calculate costs
        # Store detailed information
```

**Key Features:**
- Individual call tracking
- Cost calculation based on Azure pricing
- Detailed breakdown by operation
- Session and total cost tracking

### AzureDIService
```python
class AzureDIService:
    def extract_tables(self, pdf_bytes):
        # Azure DI Layout Analysis
        # Table structure preservation
        # HTML debugging output
```

**Key Features:**
- Layout analysis for complex documents
- Table structure preservation
- Debug output generation
- Error handling for DI operations

## Data Flow

### Context Management
The system uses a context dictionary to pass data between agents:

```python
ctx = {
    "pdf_file": pdf_file,
    "text": extracted_text,
    "fields": field_list,
    "unique_indices": unique_indices,
    "field_descriptions": field_descriptions,
    "cost_tracker": cost_tracker,
    "results": [],
    "strategy": strategy
}
```

### Result Processing
Results are processed through multiple stages:

1. **Raw Extraction**: LLM responses in JSON format
2. **Validation**: JSON parsing and structure validation
3. **Flattening**: Convert to tabular format
4. **DataFrame**: Final structured output

## Error Handling Strategy

### Retry Logic
```python
def _should_retry(self, exception) -> bool:
    # Retry on 5xx errors
    if hasattr(exception, 'status_code'):
        return exception.status_code >= 500
    # Retry on connection errors
    return any(error in str(exception) for error in ['Timeout', 'Connection'])
```

### Graceful Degradation
- Continue processing with partial failures
- Return null values for failed extractions
- Log detailed error information
- Maintain cost tracking during failures

### Error Classification
- **Retryable**: 503, 500, connection timeouts
- **Non-retryable**: 400, 401, validation errors
- **Fatal**: Configuration errors, missing dependencies

## Performance Considerations

### Optimization Strategies
1. **Parallel Processing**: Independent field extraction
2. **Caching**: Session state for field descriptions
3. **Batching**: Group similar operations
4. **Early Termination**: Stop on critical failures

### Resource Management
- **Memory**: Efficient text processing
- **API Limits**: Respect Azure rate limits
- **Cost Control**: Detailed tracking and alerts
- **Timeout Handling**: Configurable timeouts

## Security

### Data Protection
- No persistent storage of sensitive data
- Secure API key management
- Session-based data handling
- Log sanitization

### Access Control
- Environment variable configuration
- API key validation
- Error message sanitization

## Monitoring and Observability

### Logging Strategy
```python
# Structured logging with levels
logger.info(f"Processing {len(combinations)} combinations")
logger.debug(f"LLM response: {response[:200]}...")
logger.error(f"Failed to extract field: {field}")
```

### Metrics Collection
- LLM call counts and durations
- Token usage and costs
- Success/failure rates
- Processing times

### Debug Information
- Detailed execution traces
- Cost breakdown tables
- Error context and stack traces
- Performance metrics

## Configuration Management

### Settings Structure
```python
class Settings(BaseSettings):
    # Azure OpenAI
    AZURE_OPENAI_ENDPOINT: str
    AZURE_OPENAI_API_KEY: str
    AZURE_OPENAI_DEPLOYMENT: str
    
    # Azure Document Intelligence
    AZURE_DI_ENDPOINT: str
    AZURE_DI_KEY: str
    
    # Retry Configuration
    LLM_MAX_RETRIES: int = 5
    LLM_BASE_DELAY: float = 1.0
    LLM_MAX_DELAY: float = 60.0
```

### Environment Variables
- `.env` file support
- Environment variable override
- Validation and defaults
- Secure key management

## Testing Strategy

### Unit Tests
- Individual agent testing
- Service layer testing
- Mock external dependencies
- Cost tracking validation

### Integration Tests
- End-to-end workflows
- Error scenario testing
- Performance benchmarking
- Cost accuracy validation

### Test Coverage
- Core functionality: 90%+
- Error handling: 100%
- Cost tracking: 100%
- Retry logic: 100%

## Deployment

### Requirements
- Python 3.9+
- Azure OpenAI access
- Azure Document Intelligence access
- Streamlit for UI

### Dependencies
```
azure-ai-documentintelligence
openai
streamlit
pandas
pymupdf
pydantic-settings
```

### Environment Setup
1. Install dependencies
2. Configure environment variables
3. Set up Azure resources
4. Test connectivity
5. Deploy application

## Future Enhancements

### Planned Features
- **Batch Processing**: Multiple document processing
- **Custom Models**: Domain-specific extraction
- **Advanced Caching**: Redis-based caching
- **API Endpoints**: REST API for integration
- **Real-time Processing**: Streaming document processing

### Scalability Improvements
- **Microservices**: Agent separation
- **Queue System**: Asynchronous processing
- **Load Balancing**: Multiple instances
- **Database Integration**: Persistent storage

### Performance Optimizations
- **Vector Search**: Enhanced semantic search
- **Model Optimization**: Smaller, faster models
- **Parallel Processing**: Multi-threaded extraction
- **Memory Optimization**: Efficient data structures