API Reference¶
Complete reference for all public APIs.
DocumentProcessor¶
DocumentProcessor(provider: Union[str, Provider] = 'gemini', model_name: str = 'gemini-2.5-flash', api_key: Optional[str] = None, security: Optional[SecurityPlugin] = None, on_pre_process: Optional[PreProcessCallback] = None, on_post_process: Optional[PostProcessCallback] = None, on_error: Optional[ErrorCallback] = None)
¶
Main document processing class for extracting structured data from documents.
The DocumentProcessor orchestrates document extraction using pluggable providers,
with optional security layer and Pydantic model support. It automatically detects
file types, applies security checks, and validates output against schemas.
| ATTRIBUTE | DESCRIPTION |
|---|---|
security |
Optional security plugin/chain for input/output validation.
|
Example
Basic usage with schema:
from strutex import DocumentProcessor, Object, String, Number
schema = Object(properties={
"invoice_number": String(),
"total": Number()
})
processor = DocumentProcessor(provider="gemini")
result = processor.process("invoice.pdf", "Extract data", schema)
print(result["invoice_number"])
With callbacks:
processor = DocumentProcessor(
provider="gemini",
on_post_process=lambda result, ctx: {**result, "processed": True}
)
With decorator:
Initialize the document processor.
| PARAMETER | DESCRIPTION |
|---|---|
provider
|
Provider name (e.g., "gemini", "openai") or a
TYPE:
|
model_name
|
LLM model name to use (only when provider is a string).
TYPE:
|
api_key
|
API key for the provider. Falls back to environment variables
(e.g.,
TYPE:
|
security
|
Optional
TYPE:
|
on_pre_process
|
Callback called before processing. Receives (file_path, prompt, schema, mime_type, context) and can return a dict with modified values.
TYPE:
|
on_post_process
|
Callback called after processing. Receives (result, context) and can return a modified result dict.
TYPE:
|
on_error
|
Callback called on error. Receives (error, file_path, context) and can return a fallback result or None to propagate the error.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the specified provider is not found in the registry. |
Example
Source code in strutex/processor.py
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 | |
__del__()
¶
Unregister hooks when processor is garbage collected.
Source code in strutex/processor.py
on_error(func: ErrorCallback) -> ErrorCallback
¶
Decorator to register an error hook.
The hook receives (error, file_path, context) and can return a fallback result dict. Return None to propagate the original error.
Example
Source code in strutex/processor.py
on_post_process(func: PostProcessCallback) -> PostProcessCallback
¶
Decorator to register a post-process hook.
The hook receives (result, context) and can return a modified result dict.
Example
Source code in strutex/processor.py
on_pre_process(func: PreProcessCallback) -> PreProcessCallback
¶
Decorator to register a pre-process hook.
The hook receives (file_path, prompt, schema, mime_type, context) and can return a dict with modified values for 'prompt' or other parameters.
Example
Source code in strutex/processor.py
process(file_path: str, prompt: str, schema: Optional[Schema] = None, model: Optional[Type] = None, security: Optional[Union[SecurityPlugin, bool]] = None, **kwargs) -> Any
¶
Process a document and extract structured data.
This method automatically detects the file type, applies security validation (if enabled), sends the document to the LLM provider, and validates the output.
| PARAMETER | DESCRIPTION |
|---|---|
file_path
|
Absolute path to the source file (PDF, Excel, or Image).
TYPE:
|
prompt
|
Natural language instruction for extraction.
TYPE:
|
schema
|
A [
TYPE:
|
model
|
A Pydantic
TYPE:
|
security
|
Override security setting for this request.
-
TYPE:
|
**kwargs
|
Additional provider-specific options.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Extracted data as a dictionary, or a Pydantic model instance if |
Any
|
was provided. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If neither |
SecurityError
|
If security validation fails (input or output rejected). |
Example
Source code in strutex/processor.py
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 | |
options: show_root_heading: true members: - init - process
Schema Types¶
String(description: str = None, nullable: bool = False)
¶
options: show_root_heading: true
Number(description: str = None, nullable: bool = False)
¶
options: show_root_heading: true
Integer(description: str = None, nullable: bool = False)
¶
options: show_root_heading: true
Boolean(description: str = None, nullable: bool = False)
¶
options: show_root_heading: true
Array(items: Schema, description: str = None, nullable: bool = False)
¶
Bases: Schema
Represents a list of items. :param items: The Schema definition for the items inside the array.
Source code in strutex/types.py
options: show_root_heading: true
Object(properties: Dict[str, Schema], description: str = None, required: Optional[List[str]] = None, nullable: bool = False)
¶
Bases: Schema
Represents a nested object (dictionary).
:param properties: Dictionary mapping field names to Schema objects. :param required: List of keys that are mandatory. If None, ALL properties are assumed required. Pass [] explicitly if no fields are required.
Source code in strutex/types.py
options: show_root_heading: true
Plugin System¶
PluginRegistry
¶
Central registry for all plugin types with lazy loading.
Plugins are stored as EntryPoint objects and only loaded when first accessed via get(). This improves startup time and avoids importing unused dependencies.
Usage
Get a plugin (loads on first access)¶
cls = PluginRegistry.get("provider", "gemini")
List all plugins (does not load them)¶
all_providers = PluginRegistry.list("provider")
Force discovery from entry points¶
count = PluginRegistry.discover()
clear(plugin_type: Optional[str] = None) -> None
classmethod
¶
Clear registered plugins.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
If provided, only clear this type. Otherwise clear all.
TYPE:
|
Source code in strutex/plugins/registry.py
discover(group_prefix: str = 'strutex', force: bool = False) -> int
classmethod
¶
Discover and register plugins from entry points.
Scans for entry points matching the pattern: - strutex.providers - strutex.validators - strutex.postprocessors - strutex.security - etc.
Entry points are stored for lazy loading - they are not imported until first use via get().
| PARAMETER | DESCRIPTION |
|---|---|
group_prefix
|
Entry point group prefix (default: "strutex")
TYPE:
|
force
|
Force re-discovery even if already discovered
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of entry points discovered |
Example pyproject.toml: [project.entry-points."strutex.providers"] my_provider = "my_package:MyProvider"
Source code in strutex/plugins/registry.py
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 | |
get(plugin_type: str, name: str) -> Optional[Type]
classmethod
¶
Get a registered plugin class by type and name.
If the plugin is registered via entry point and not yet loaded, it will be loaded on first access (lazy loading).
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin
TYPE:
|
name
|
Name of the plugin
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[Type]
|
The plugin class, or None if not found |
Source code in strutex/plugins/registry.py
get_plugin_info(plugin_type: str, name: str) -> Optional[Dict[str, Any]]
classmethod
¶
Get metadata about a plugin without necessarily loading it.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin
TYPE:
|
name
|
Name of the plugin
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[Dict[str, Any]]
|
Dict with plugin info, or None if not found |
Source code in strutex/plugins/registry.py
get_sorted(plugin_type: str, reverse: bool = True) -> List[Tuple[str, Type]]
classmethod
¶
Get all plugins of a type sorted by priority.
Useful for waterfall selection where you want to try higher-priority plugins first.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin
TYPE:
|
reverse
|
If True (default), higher priority first
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Tuple[str, Type]]
|
List of (name, class) tuples sorted by priority |
Source code in strutex/plugins/registry.py
list(plugin_type: str) -> Dict[str, Type]
classmethod
¶
List all plugins of a given type.
Note: This loads all plugins of the type. Use list_names() for a lightweight listing without loading.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Type]
|
Dictionary mapping names to plugin classes |
Source code in strutex/plugins/registry.py
list_names(plugin_type: str) -> List[str]
classmethod
¶
List names of all plugins of a given type without loading them.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[str]
|
List of plugin names |
Source code in strutex/plugins/registry.py
list_types() -> List[str]
classmethod
¶
List all registered plugin types.
Source code in strutex/plugins/registry.py
register(plugin_type: str, name: str, plugin_cls: Type) -> None
classmethod
¶
Register a plugin class manually.
This is used by the @register decorator for backwards compatibility. Prefer using entry points in pyproject.toml for new plugins.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin (e.g., "provider", "security", "validator")
TYPE:
|
name
|
Unique name for this plugin
TYPE:
|
plugin_cls
|
The plugin class to register
TYPE:
|
Source code in strutex/plugins/registry.py
options: show_root_heading: true members: - register - get - list - discover
register(plugin_type: str, name: Optional[str] = None) -> Callable[[Type], Type]
¶
Decorator to register a plugin class at runtime.
Use this decorator for: - Runtime/dynamic registration based on config - Prototyping plugins without packaging - Plugins in the same codebase (not installed separately) - Conditional loading based on environment or feature flags
For distributable third-party plugin packages, use entry points in pyproject.toml instead.
| PARAMETER | DESCRIPTION |
|---|---|
plugin_type
|
Type of plugin (e.g., "provider", "security", "validator")
TYPE:
|
name
|
Optional name. If not provided, uses lowercase class name.
TYPE:
|
Usage
@register("provider") class MyProvider(Provider): ...
@register("provider", name="custom_name") class AnotherProvider(Provider): ...
See Also
Entry points in pyproject.toml for distributable packages:
[project.entry-points."strutex.providers"]
my_provider = "my_package:MyProvider"
Source code in strutex/plugins/registry.py
options: show_root_heading: true
Base Classes¶
Provider
¶
Bases: ABC
Base class for LLM providers.
All providers must implement the process method to handle document extraction via their specific LLM API.
Subclassing auto-registers the plugin. Use class arguments to customize:
class MyProvider(Provider, name="custom", priority=90):
...
| ATTRIBUTE | DESCRIPTION |
|---|---|
strutex_plugin_version |
API version for compatibility checks
TYPE:
|
priority |
Ordering priority (0-100, higher = preferred)
TYPE:
|
cost |
Cost hint for optimization (lower = cheaper)
TYPE:
|
capabilities |
List of supported features
TYPE:
|
aprocess(file_path: str, prompt: str, schema: Schema, mime_type: str, **kwargs) -> Any
async
¶
Async version of process. Override for true async support. Default implementation calls sync version.
Source code in strutex/plugins/base.py
has_capability(capability: str) -> bool
¶
health_check() -> bool
classmethod
¶
Check if this provider is healthy and ready to use.
Override in subclasses for custom health checks (e.g., API connectivity).
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if healthy, False otherwise |
Source code in strutex/plugins/base.py
process(file_path: str, prompt: str, schema: Schema, mime_type: str, **kwargs) -> Any
abstractmethod
¶
Process a document and extract structured data.
| PARAMETER | DESCRIPTION |
|---|---|
file_path
|
Path to the document file
TYPE:
|
prompt
|
Extraction prompt/instructions
TYPE:
|
schema
|
Expected output schema
TYPE:
|
mime_type
|
MIME type of the file
TYPE:
|
**kwargs
|
Provider-specific options
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Extracted data matching the schema |
Source code in strutex/plugins/base.py
options: show_root_heading: true
Validator
¶
Bases: ABC
Base class for output validators.
Validators check extracted data for correctness and can optionally fix issues.
Subclassing auto-registers the plugin.
| ATTRIBUTE | DESCRIPTION |
|---|---|
strutex_plugin_version |
API version for compatibility checks
TYPE:
|
priority |
Ordering priority in validation chain
TYPE:
|
health_check() -> bool
classmethod
¶
validate(data: Dict[str, Any], schema: Optional[Schema] = None) -> ValidationResult
abstractmethod
¶
Validate extracted data.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
The extracted data to validate
TYPE:
|
schema
|
Optional schema to validate against
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ValidationResult
|
ValidationResult with status and any issues |
Source code in strutex/plugins/base.py
options: show_root_heading: true
Postprocessor
¶
Bases: ABC
Base class for data postprocessors.
Postprocessors transform extracted data (e.g., normalize dates, convert currencies, standardize units).
Subclassing auto-registers the plugin.
| ATTRIBUTE | DESCRIPTION |
|---|---|
strutex_plugin_version |
API version for compatibility checks
TYPE:
|
priority |
Ordering priority in postprocessing pipeline
TYPE:
|
options: show_root_heading: true
SecurityPlugin
¶
Bases: ABC
Base class for security plugins.
Security plugins can validate/sanitize input before sending to the LLM and validate output before returning to the user.
Subclassing auto-registers the plugin.
| ATTRIBUTE | DESCRIPTION |
|---|---|
strutex_plugin_version |
API version for compatibility checks
TYPE:
|
priority |
Ordering priority in security chain
TYPE:
|
health_check() -> bool
classmethod
¶
validate_input(text: str) -> SecurityResult
¶
Validate/sanitize input text before sending to LLM.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The input text (prompt + document content)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SecurityResult
|
SecurityResult with sanitized text or rejection |
Source code in strutex/plugins/base.py
validate_output(data: Dict[str, Any]) -> SecurityResult
¶
Validate output data before returning to user.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
The extracted data
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SecurityResult
|
SecurityResult with clean data or rejection |
Source code in strutex/plugins/base.py
options: show_root_heading: true
Security¶
SecurityChain(plugins: List[SecurityPlugin])
¶
Bases: SecurityPlugin
Chains multiple security plugins together.
Runs each plugin in sequence. If any plugin rejects, the chain stops.
Usage
chain = SecurityChain([ InputSanitizer(collapse_whitespace=True), PromptInjectionDetector(), ]) result = chain.validate_input(text)
| PARAMETER | DESCRIPTION |
|---|---|
plugins
|
List of security plugins to run in order
TYPE:
|
Source code in strutex/security/chain.py
add(plugin: SecurityPlugin) -> SecurityChain
¶
validate_input(text: str) -> SecurityResult
¶
Run all plugins' input validation in sequence.
Source code in strutex/security/chain.py
validate_output(data: Dict[str, Any]) -> SecurityResult
¶
Run all plugins' output validation in sequence.
Source code in strutex/security/chain.py
options: show_root_heading: true
InputSanitizer(collapse_whitespace: bool = True, normalize_unicode: bool = True, remove_invisible: bool = True, max_length: Optional[int] = None)
¶
Bases: SecurityPlugin
Sanitizes input text to prevent various attacks.
Features: - Collapse excessive whitespace - Normalize Unicode characters - Remove invisible characters - Limit input length
Usage
sanitizer = InputSanitizer(collapse_whitespace=True, max_length=50000) result = sanitizer.validate_input(text)
Source code in strutex/security/sanitizer.py
validate_input(text: str) -> SecurityResult
¶
Sanitize the input text.
Source code in strutex/security/sanitizer.py
options: show_root_heading: true
PromptInjectionDetector(strict: bool = False, additional_patterns: List[Tuple[str, str]] = None, block_on_detection: bool = True)
¶
Bases: SecurityPlugin
Detects common prompt injection patterns.
Checks for: - Direct instruction overrides ("ignore previous instructions") - Role manipulation ("you are now", "pretend to be") - Delimiter attacks (markdown, XML-style tags) - Encoding attacks (base64 instructions)
Usage
detector = PromptInjectionDetector(strict=True) result = detector.validate_input(text)
| PARAMETER | DESCRIPTION |
|---|---|
strict
|
If True, use stricter matching
TYPE:
|
additional_patterns
|
Extra (pattern, category) tuples to check
TYPE:
|
block_on_detection
|
If True, reject input on detection. If False, just warn.
TYPE:
|
Source code in strutex/security/injection.py
get_detections(text: str) -> List[dict]
¶
Get detailed detection information without blocking.
Source code in strutex/security/injection.py
validate_input(text: str) -> SecurityResult
¶
Check for prompt injection patterns.
Source code in strutex/security/injection.py
options: show_root_heading: true
OutputValidator(check_secrets: bool = True, check_prompt_leaks: bool = True, secret_patterns: Optional[List[tuple]] = None, block_on_detection: bool = True)
¶
Bases: SecurityPlugin
Validates LLM output for security issues.
Checks for: - Leaked API keys/secrets - Leaked system prompts - Suspicious executable patterns - PII exposure
Usage
validator = OutputValidator() result = validator.validate_output(data)
Source code in strutex/security/output.py
validate_output(data: Dict[str, Any]) -> SecurityResult
¶
Validate output data for security issues.
Source code in strutex/security/output.py
options: show_root_heading: true
Prompts¶
StructuredPrompt(persona: str = 'You are a highly accurate AI Data Extraction Assistant.')
¶
Builder for organizing complex extraction prompts.
Provides a fluent API for constructing well-structured prompts with general rules, field-specific rules, and output guidelines.
Usage
prompt = StructuredPrompt("You are an expert...")
Variadic arguments allow adding multiple rules at once¶
prompt.add_general_rule("No guessing", "Use ISO dates") prompt.add_field_rule("total", "Exclude tax", "Must be numeric", critical=True) final_string = prompt.compile()
Example
prompt = ( ... StructuredPrompt() ... .add_general_rule( ... "Strict data fidelity: do not invent values.", ... "Dates must be in DD.MM.YYYY format." ... ) ... .add_field_rule( ... "artikelnummer", ... "Must be 8 digits.", ... "Ignore supplier codes.", ... critical=True ... ) ... .add_output_guideline("Return valid JSON.") ... .compile() ... )
Initialize the prompt builder.
| PARAMETER | DESCRIPTION |
|---|---|
persona
|
The system persona/role description.
TYPE:
|
Source code in strutex/prompts/builder.py
__str__() -> str
¶
add_field_rule(field_name: str, *rules: str, critical: bool = False) -> StructuredPrompt
¶
Adds one or more rules specific to a single field.
| PARAMETER | DESCRIPTION |
|---|---|
field_name
|
The name of the field these rules apply to.
TYPE:
|
*rules
|
Variable number of rule strings.
TYPE:
|
critical
|
If True, prefixes rules with CRITICAL.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StructuredPrompt
|
Self for method chaining. |
Example
.add_field_rule("invoice_id", "Must be numeric", "8 digits", critical=True)
Source code in strutex/prompts/builder.py
add_general_rule(*rules: str) -> StructuredPrompt
¶
Adds one or more high-level rules.
| PARAMETER | DESCRIPTION |
|---|---|
*rules
|
Variable number of rule strings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StructuredPrompt
|
Self for method chaining. |
Example
.add_general_rule("Rule 1", "Rule 2", "Rule 3")
Source code in strutex/prompts/builder.py
add_output_guideline(*guidelines: str) -> StructuredPrompt
¶
Adds formatting instructions for the output.
| PARAMETER | DESCRIPTION |
|---|---|
*guidelines
|
Variable number of guideline strings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StructuredPrompt
|
Self for method chaining. |
Example
.add_output_guideline("JSON only", "No markdown", "No comments")
Source code in strutex/prompts/builder.py
compile() -> str
¶
Builds the final prompt string.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The complete formatted prompt ready for LLM consumption. |
Source code in strutex/prompts/builder.py
options: show_root_heading: true members: - init - add_general_rule - add_field_rule - add_output_guideline - compile
Pydantic Support¶
pydantic_to_schema(model: Type) -> Schema
¶
Convert a Pydantic BaseModel to a strutex Schema.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
A Pydantic BaseModel class
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Schema
|
Equivalent strutex Schema (Object) |
Example
from pydantic import BaseModel
class Invoice(BaseModel): invoice_number: str total: float items: list[LineItem]
schema = pydantic_to_schema(Invoice)
Source code in strutex/pydantic_support.py
options: show_root_heading: true
validate_with_pydantic(data: Dict[str, Any], model: Type) -> Any
¶
Validate extracted data against a Pydantic model.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Extracted dictionary data
TYPE:
|
model
|
Pydantic BaseModel class to validate against
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Validated Pydantic model instance |
| RAISES | DESCRIPTION |
|---|---|
ValidationError
|
If validation fails |
Source code in strutex/pydantic_support.py
options: show_root_heading: true
Exceptions¶
SecurityError
¶
Bases: Exception
Raised when security validation fails.
This exception is raised when either input validation (e.g., prompt injection detected) or output validation (e.g., leaked secrets detected) fails.
| ATTRIBUTE | DESCRIPTION |
|---|---|
message |
Description of the security failure.
|
options: show_root_heading: true