0
# Async Client Implementations
1
2
Full asynchronous implementations of both DocumentIntelligenceClient and DocumentIntelligenceAdministrationClient with identical functionality to their synchronous counterparts. These async clients provide enhanced performance for concurrent operations and integrate seamlessly with async/await patterns in modern Python applications.
3
4
## Core Imports
5
6
```python
7
from azure.ai.documentintelligence.aio import (
8
DocumentIntelligenceClient,
9
DocumentIntelligenceAdministrationClient
10
)
11
from azure.core.credentials import AzureKeyCredential
12
from azure.identity.aio import DefaultAzureCredential
13
```
14
15
## Capabilities
16
17
### Async Document Intelligence Client
18
19
Asynchronous client for document analysis, batch processing, and classification operations with full async/await support.
20
21
```python { .api }
22
class DocumentIntelligenceClient:
23
"""Async client for document analysis operations."""
24
25
def __init__(
26
self,
27
endpoint: str,
28
credential: Union[AzureKeyCredential, AsyncTokenCredential],
29
*,
30
api_version: str = "2024-11-30",
31
polling_interval: int = 1,
32
**kwargs: Any
33
) -> None:
34
"""
35
Initialize async Document Intelligence client.
36
37
Parameters:
38
- endpoint (str): Document Intelligence service endpoint
39
- credential: Azure key credential or async token credential
40
- api_version (str): API version (default: "2024-11-30")
41
- polling_interval (int): Default LRO polling interval in seconds
42
"""
43
44
async def send_request(
45
self,
46
request: HttpRequest,
47
*,
48
stream: bool = False,
49
**kwargs: Any
50
) -> AsyncHttpResponse:
51
"""Send custom HTTP request."""
52
53
async def close(self) -> None:
54
"""Close the client and release resources."""
55
56
async def __aenter__(self) -> Self:
57
"""Async context manager entry."""
58
59
async def __aexit__(self, *exc_details: Any) -> None:
60
"""Async context manager exit."""
61
```
62
63
### Async Document Analysis Operations
64
65
All document analysis operations with async/await support for concurrent processing.
66
67
```python { .api }
68
async def begin_analyze_document(
69
model_id: str,
70
body: Union[AnalyzeDocumentRequest, JSON, IO[bytes]],
71
*,
72
pages: Optional[str] = None,
73
locale: Optional[str] = None,
74
string_index_type: Optional[Union[str, StringIndexType]] = None,
75
features: Optional[List[Union[str, DocumentAnalysisFeature]]] = None,
76
query_fields: Optional[List[str]] = None,
77
output_content_format: Optional[Union[str, DocumentContentFormat]] = None,
78
output: Optional[List[Union[str, AnalyzeOutputOption]]] = None,
79
**kwargs: Any
80
) -> AnalyzeDocumentLROPoller[AnalyzeResult]:
81
"""
82
Async analyze document with specified model.
83
84
Returns:
85
AnalyzeDocumentLROPoller[AnalyzeResult]: Async-compatible poller
86
"""
87
88
async def begin_analyze_batch_documents(
89
model_id: str,
90
body: Union[AnalyzeBatchDocumentsRequest, JSON, IO[bytes]],
91
**kwargs: Any
92
) -> AsyncLROPoller[AnalyzeBatchResult]:
93
"""Async batch document analysis."""
94
95
async def begin_classify_document(
96
classifier_id: str,
97
body: Union[ClassifyDocumentRequest, JSON, IO[bytes]],
98
*,
99
string_index_type: Optional[Union[str, StringIndexType]] = None,
100
split_mode: Optional[Union[str, SplitMode]] = None,
101
pages: Optional[str] = None,
102
**kwargs: Any
103
) -> AsyncLROPoller[AnalyzeResult]:
104
"""Async document classification."""
105
106
async def get_analyze_result_pdf(
107
model_id: str,
108
result_id: str,
109
**kwargs: Any
110
) -> AsyncIterator[bytes]:
111
"""Get analysis result as searchable PDF (async iterator)."""
112
113
async def get_analyze_result_figure(
114
model_id: str,
115
result_id: str,
116
figure_id: str,
117
**kwargs: Any
118
) -> AsyncIterator[bytes]:
119
"""Get extracted figure as image (async iterator)."""
120
121
async def delete_analyze_result(
122
model_id: str,
123
result_id: str,
124
**kwargs: Any
125
) -> None:
126
"""Delete analysis result."""
127
128
def list_analyze_batch_results(
129
model_id: str,
130
*,
131
skip: Optional[int] = None,
132
top: Optional[int] = None,
133
**kwargs: Any
134
) -> AsyncIterable[AnalyzeBatchOperation]:
135
"""List batch analysis operations (async iterable)."""
136
137
async def get_analyze_batch_result(
138
model_id: str,
139
result_id: str,
140
**kwargs: Any
141
) -> AnalyzeBatchOperation:
142
"""Get specific batch analysis result."""
143
144
async def delete_analyze_batch_result(
145
model_id: str,
146
result_id: str,
147
**kwargs: Any
148
) -> None:
149
"""Delete batch analysis result."""
150
```
151
152
### Async Administration Client
153
154
Asynchronous client for model and classifier management with full async/await support for long-running operations.
155
156
```python { .api }
157
class DocumentIntelligenceAdministrationClient:
158
"""Async client for model and classifier management."""
159
160
def __init__(
161
self,
162
endpoint: str,
163
credential: Union[AzureKeyCredential, AsyncTokenCredential],
164
*,
165
api_version: str = "2024-11-30",
166
polling_interval: int = 1,
167
**kwargs: Any
168
) -> None:
169
"""Initialize async administration client with same parameters as sync version."""
170
171
# Same base methods as DocumentIntelligenceClient (async versions)
172
```
173
174
### Async Model Management Operations
175
176
All model management operations with async/await support for efficient resource management.
177
178
```python { .api }
179
async def begin_build_document_model(
180
body: Union[BuildDocumentModelRequest, JSON, IO[bytes]],
181
**kwargs: Any
182
) -> AsyncLROPoller[DocumentModelDetails]:
183
"""Async build custom document model."""
184
185
async def begin_compose_model(
186
body: Union[ComposeDocumentModelRequest, JSON, IO[bytes]],
187
**kwargs: Any
188
) -> AsyncLROPoller[DocumentModelDetails]:
189
"""Async compose multiple models."""
190
191
async def authorize_model_copy(
192
body: Union[AuthorizeCopyRequest, JSON, IO[bytes]],
193
**kwargs: Any
194
) -> ModelCopyAuthorization:
195
"""Generate authorization for model copy (async)."""
196
197
async def begin_copy_model_to(
198
model_id: str,
199
body: Union[ModelCopyAuthorization, JSON, IO[bytes]],
200
**kwargs: Any
201
) -> AsyncLROPoller[DocumentModelDetails]:
202
"""Async copy model to target resource."""
203
204
async def get_model(
205
model_id: str,
206
**kwargs: Any
207
) -> DocumentModelDetails:
208
"""Get model information (async)."""
209
210
def list_models(
211
**kwargs: Any
212
) -> AsyncIterable[DocumentModelDetails]:
213
"""List all models (async iterable)."""
214
215
async def delete_model(
216
model_id: str,
217
**kwargs: Any
218
) -> None:
219
"""Delete model (async)."""
220
221
async def get_resource_details(
222
**kwargs: Any
223
) -> DocumentIntelligenceResourceDetails:
224
"""Get service resource information (async)."""
225
226
async def get_operation(
227
operation_id: str,
228
**kwargs: Any
229
) -> DocumentIntelligenceOperationDetails:
230
"""Get operation details by ID (async)."""
231
232
def list_operations(
233
**kwargs: Any
234
) -> AsyncIterable[DocumentIntelligenceOperationDetails]:
235
"""List all operations (async iterable)."""
236
```
237
238
### Async Classifier Management Operations
239
240
All classifier management operations with async/await support.
241
242
```python { .api }
243
async def begin_build_classifier(
244
body: Union[BuildDocumentClassifierRequest, JSON, IO[bytes]],
245
**kwargs: Any
246
) -> AsyncLROPoller[DocumentClassifierDetails]:
247
"""Async build document classifier."""
248
249
async def authorize_classifier_copy(
250
body: Union[AuthorizeClassifierCopyRequest, JSON, IO[bytes]],
251
**kwargs: Any
252
) -> ClassifierCopyAuthorization:
253
"""Generate classifier copy authorization (async)."""
254
255
async def begin_copy_classifier_to(
256
classifier_id: str,
257
body: Union[ClassifierCopyAuthorization, JSON, IO[bytes]],
258
**kwargs: Any
259
) -> AsyncLROPoller[DocumentClassifierDetails]:
260
"""Async copy classifier to target resource."""
261
262
async def get_classifier(
263
classifier_id: str,
264
**kwargs: Any
265
) -> DocumentClassifierDetails:
266
"""Get classifier information (async)."""
267
268
def list_classifiers(
269
**kwargs: Any
270
) -> AsyncIterable[DocumentClassifierDetails]:
271
"""List all classifiers (async iterable)."""
272
273
async def delete_classifier(
274
classifier_id: str,
275
**kwargs: Any
276
) -> None:
277
"""Delete classifier (async)."""
278
```
279
280
## Usage Examples
281
282
### Basic Async Document Analysis
283
284
```python
285
import asyncio
286
from azure.ai.documentintelligence.aio import DocumentIntelligenceClient
287
from azure.core.credentials import AzureKeyCredential
288
289
async def analyze_document():
290
async with DocumentIntelligenceClient(
291
endpoint="https://your-resource.cognitiveservices.azure.com/",
292
credential=AzureKeyCredential("your-api-key")
293
) as client:
294
295
with open("invoice.pdf", "rb") as document:
296
poller = await client.begin_analyze_document("prebuilt-invoice", document)
297
result = await poller.result()
298
299
print(f"Document content: {result.content}")
300
for table in result.tables or []:
301
print(f"Table: {table.row_count}x{table.column_count}")
302
303
# Run async function
304
asyncio.run(analyze_document())
305
```
306
307
### Concurrent Document Processing
308
309
```python
310
import asyncio
311
from azure.ai.documentintelligence.aio import DocumentIntelligenceClient
312
313
async def process_documents_concurrently():
314
async with DocumentIntelligenceClient(endpoint, credential) as client:
315
316
# Start multiple analyses concurrently
317
tasks = []
318
for i, document_path in enumerate(document_paths):
319
with open(document_path, "rb") as doc:
320
poller = await client.begin_analyze_document("prebuilt-layout", doc)
321
tasks.append(poller.result())
322
323
# Wait for all analyses to complete
324
results = await asyncio.gather(*tasks)
325
326
for i, result in enumerate(results):
327
print(f"Document {i}: {len(result.pages)} pages")
328
329
asyncio.run(process_documents_concurrently())
330
```
331
332
### Async Model Management
333
334
```python
335
from azure.ai.documentintelligence.aio import DocumentIntelligenceAdministrationClient
336
from azure.ai.documentintelligence.models import BuildDocumentModelRequest, AzureBlobContentSource
337
338
async def build_model_async():
339
async with DocumentIntelligenceAdministrationClient(endpoint, credential) as admin_client:
340
341
build_request = BuildDocumentModelRequest(
342
model_id="async-custom-model",
343
build_mode="neural",
344
training_data_source=AzureBlobContentSource(
345
container_url="https://account.blob.core.windows.net/training"
346
)
347
)
348
349
poller = await admin_client.begin_build_document_model(build_request)
350
model = await poller.result()
351
352
print(f"Model {model.model_id} built successfully")
353
354
asyncio.run(build_model_async())
355
```
356
357
## Async Iterator Support
358
359
The async clients provide async iterator support for paginated operations:
360
361
```python
362
async def list_all_models():
363
async with DocumentIntelligenceAdministrationClient(endpoint, credential) as client:
364
async for model in client.list_models():
365
print(f"Model: {model.model_id} - {model.description}")
366
367
async def list_batch_results():
368
async with DocumentIntelligenceClient(endpoint, credential) as client:
369
async for batch_op in client.list_analyze_batch_results("my-model"):
370
print(f"Batch {batch_op.operation_id}: {batch_op.status}")
371
```
372
373
## Authentication with Async Credentials
374
375
```python
376
from azure.identity.aio import DefaultAzureCredential, ClientSecretCredential
377
378
# Use DefaultAzureCredential for async
379
async with DefaultAzureCredential() as credential:
380
async with DocumentIntelligenceClient(endpoint, credential) as client:
381
# Use client here
382
pass
383
384
# Use specific async credential
385
async_credential = ClientSecretCredential(
386
tenant_id="tenant-id",
387
client_id="client-id",
388
client_secret="client-secret"
389
)
390
391
async with DocumentIntelligenceClient(endpoint, async_credential) as client:
392
# Use client here
393
pass
394
```