docflow-sdk is the official Python SDK for TextIn Docflow, providing workspace management, document classification, intelligent review, type-safe response models, and comprehensive error handling.
Use category_keyword_rules when creating or updating a category. Positive rule groups are combined with OR; a negative rule group match excludes the category.By default, the SDK paginates through enabled categories in the workspace and prechecks cross-category, same-type rule-group conflicts before sending the request. Set check_keyword_rule_conflicts=False to skip this extra client-side check; the server always performs the final conflict validation.
On create, omitting this parameter leaves rules unconfigured; dual empty arrays have the same effect.
On update, omit it or pass None for no change; a valid object replaces all rules; only dual empty arrays clear them. {} and blank strings are invalid.
In the SDK, a rule group’s group_name is optional: positive groups default to group_1, group_2, and so on, while a negative group defaults to exclude. It is display/tracking metadata only and does not affect matching or conflict detection; names returned by the API are preserved on a subsequent update.
Keywords preserve their original case and whitespace. Each keyword must be non-empty and at most 50 characters, and the same original string cannot appear twice within a group. A group has at most 20 keywords; a category has at most 10 positive and 1 negative group; min_hit must be from 1 to the number of group keywords.
Positive and negative rules in the same category cannot contain the same original keyword string. Other enabled categories in the workspace cannot have a same-type rule group with the same original keyword set. The SDK pre-validates rules it can determine locally; the service performs final validation, and a cross-category conflict returns 1005015019.
Field Management
# Bind category contextcat = client.workspace("123").category("456")# Batch add fieldscat.fields.batch_add(fields=[ {"name": "Tax Rate", "description": "Tax rate percentage"}])# Get field listfields = cat.fields.list()for field in fields.fields: print(f"{field.id}: {field.name}")# Batch update fieldscat.fields.batch_update(fields=[ {"field_id": "789", "name": "Tax Rate (%)", "required": True}])# Delete fieldcat.fields.delete(field_ids=["789"])
import time# Poll until recognition completesmax_wait = 60wait_interval = 3elapsed = 0while elapsed < max_wait: result = client.file.fetch( workspace_id="123", batch_number=batch_number ) if result.files and result.files[0].recognition_status == 1: file_info = result.files[0] print(f"Recognition Complete: {file_info.name}") # Access extracted field data if file_info.data and 'fields' in file_info.data: for field in file_info.data['fields']: print(f"{field['name']}: {field['value']}") # Access table data if file_info.data and 'items' in file_info.data: for row in file_info.data['items']: print(row) break time.sleep(wait_interval) elapsed += wait_interval
import time# Poll until review completesmax_wait = 120wait_interval = 5elapsed = 0while elapsed < max_wait: result = client.review.get_task_result( workspace_id="123", task_id=task_id ) status = result.get('status') # Status: 0=Pending, 1=Passed, 2=Failed, 4=Not Passed, 7=Recognition Failed if status in (1, 2, 4, 7): print("Review Complete") # Output review results stats = result.get('statistics', {}) print(f"Rules Passed: {stats.get('pass_count', 0)}") print(f"Rules Failed: {stats.get('failure_count', 0)}") # Detailed review results for group in result.get('groups', []): print(f"\n【{group['group_name']}】") for task in group.get('review_tasks', []): result_icon = "✓" if task['review_result'] == 0 else "✗" print(f" {result_icon} {task['rule_name']}") print(f" {task['reasoning']}") break time.sleep(wait_interval) elapsed += wait_interval
Enumeration Types
The SDK provides complete enumeration type definitions to avoid parameter errors:
from docflow import ( ExtractModel, # Extraction model type EnabledStatus, # Enabled status (for queries) EnabledFlag, # Enabled flag (for updates) AuthScope, # Permission scope FieldType, # Field type MismatchAction, # Mismatch handling mode RecognitionStatus, # Recognition status)# ExtractModel - Extraction modelExtractModel.Model_1 # Fast speed, stable extraction resultsExtractModel.Model_2 # Suitable for complex document understandingExtractModel.Model_3 # Multimodal, suitable for simple extraction# AuthScope - Permission scopeAuthScope.PRIVATE # 0 - Private permissionAuthScope.PUBLIC # 1 - Public permission# EnabledStatus - Enabled status (for queries)EnabledStatus.ALL # "all" - AllEnabledStatus.DISABLED # "0" - DisabledEnabledStatus.ENABLED # "1" - Enabled# EnabledFlag - Enabled flag (for updates)EnabledFlag.DISABLED # 0 - DisabledEnabledFlag.ENABLED # 1 - Enabled# FieldType - Field transformation typeFieldType.DATETIME # "datetime" - Date timeFieldType.ENUMERATE # "enumerate" - EnumerationFieldType.REGEX # "regex" - Regular expression# RecognitionStatus - Recognition statusRecognitionStatus.PENDING # 0 - Pending recognitionRecognitionStatus.SUCCESS # 1 - Recognition successfulRecognitionStatus.FAILED # 2 - Recognition failed
Auto-Pagination Iterator
Use iterators to automatically handle pagination without manual looping:
# Workspace iteratorfor workspace in client.workspace.iter(): print(f"{workspace.workspace_id}: {workspace.name}") if some_condition: break # Can break anytime# Category iteratorfor category in client.category.iter(workspace_id="123"): print(f"{category.category_id}: {category.name}")# Limit maximum pagesfor category in client.category.iter(workspace_id="123", max_pages=5): print(category.name)# Convert to list (get all data)all_workspaces = list(client.workspace.iter())
Error Handling
The SDK provides comprehensive error classification for precise handling of different exception scenarios.
Error Types
Error Class
Description
DocflowException
Base error class, catches all SDK errors
ValidationError
Parameter validation failure
AuthenticationError
Authentication failure (app-id or secret-code error)
PermissionDeniedError
Insufficient permissions
ResourceNotFoundError
Resource does not exist
APIError
API call failure (HTTP 4xx/5xx)
NetworkError
Network connection error
Error Handling Example
from docflow.exceptions import ( DocflowException, AuthenticationError, ValidationError, ResourceNotFoundError, APIError,)try: workspace = client.workspace.get(workspace_id="123")except AuthenticationError as e: print(f"Authentication failed: {e.message}")except ResourceNotFoundError as e: print(f"Workspace not found: {e.message}")except ValidationError as e: print(f"Validation failed: {e.message}")except APIError as e: print(f"API error [HTTP {e.status_code}]: {e.message}")except DocflowException as e: print(f"SDK error: {e.message}")
Internationalization (i18n)
The SDK supports multilingual error messages:
from docflow import DocflowClient, set_language# Use Englishset_language('en_US')client = DocflowClient.from_env()# Use Chinese (default)set_language('zh_CN')# Dynamically switch languageclient.set_language('en_US')# Get current languagecurrent_lang = client.get_language() # 'en_US' or 'zh_CN'