API Reference¶
Complete reference for all public APIs.
DocumentProcessor¶
DocumentProcessor(provider: Union[str, Provider] = 'gemini', model_name: str = 'gemini-3-flash-preview', api_key: Optional[str] = None, security: Optional[SecurityPlugin] = None, cache: Optional[Any] = None, on_pre_process: Optional[PreProcessCallback] = None, on_post_process: Optional[PostProcessCallback] = None, on_error: Optional[ErrorCallback] = None, validators: Optional[List[Validator]] = None)
¶
Facade for document processing, providing backwards compatibility.
This class delegates to specialized processor implementations: - SimpleProcessor: For single-call extraction. - VerifiedProcessor: For extraction with verification. - RagProcessor: For retrieval-augmented generation. - BatchProcessor: For parallel processing.
Initialize the document processor facade.
Source code in strutex/processor.py
agentic: AgenticProcessor
property
¶
Get the agentic processor instance.
batch: BatchProcessor
property
¶
Get the batch processor instance.
rag: RagProcessor
property
¶
Get the RAG processor instance.
simple: SimpleProcessor
property
¶
Get the simple processor instance.
verified: VerifiedProcessor
property
¶
Get the verified processor instance.
aprocess(file_path: str, prompt: str, schema: Optional[Schema] = None, model: Optional[Type] = None, security: Optional[Union[SecurityPlugin, bool]] = None, verify: bool = False, **kwargs) -> Any
async
¶
Async process a document.
Source code in strutex/processor.py
aprocess_batch(file_paths: List[str], prompt: str, schema: Optional[Schema] = None, model: Optional[Type] = None, max_concurrency: int = 4, **kwargs) -> BatchContext
async
¶
Async process documents in batch.
Source code in strutex/processor.py
create_active(**kwargs) -> ActiveLearningProcessor
¶
create_ensemble(providers: List[Processor], **kwargs) -> EnsembleProcessor
¶
create_fallback(configs: List[Dict[str, Any]]) -> FallbackProcessor
¶
create_privacy(**kwargs) -> PrivacyProcessor
¶
create_router(routes: Dict[str, Processor], **kwargs) -> RouterProcessor
¶
create_sequential(**kwargs) -> SequentialProcessor
¶
on_error(func: ErrorCallback) -> ErrorCallback
¶
Register error hook.
Source code in strutex/processor.py
on_post_process(func: PostProcessCallback) -> PostProcessCallback
¶
Register post-process hook.
Source code in strutex/processor.py
on_pre_process(func: PreProcessCallback) -> PreProcessCallback
¶
Register pre-process hook.
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, verify: bool = False, **kwargs) -> Any
¶
Process a document (delegates to Simple or Verified processor).
Source code in strutex/processor.py
process_batch(file_paths: List[str], prompt: str, schema: Optional[Schema] = None, model: Optional[Type] = None, max_workers: int = 4, **kwargs) -> BatchContext
¶
Process documents in batch.
Source code in strutex/processor.py
rag_ingest(file_path: str, collection_name: Optional[str] = None)
¶
rag_query(query: str, collection_name: Optional[str] = None, schema: Optional[Schema] = None, model: Optional[Type] = None) -> Any
¶
Perform RAG query.
Source code in strutex/processor.py
verify(file_path: str, result: Any, schema: Optional[Schema] = None, model: Optional[Type] = None, verify_prompt: Optional[str] = None, **kwargs) -> Any
¶
Verify an existing result.
Source code in strutex/processor.py
options: show_root_heading: true members: - init - process
Schema Types¶
String(description: Optional[str] = None, nullable: bool = False, format: Optional[str] = None)
¶
options: show_root_heading: true
Number(description: Optional[str] = None, nullable: bool = False)
¶
options: show_root_heading: true
Integer(description: Optional[str] = None, nullable: bool = False)
¶
options: show_root_heading: true
Boolean(description: Optional[str] = None, nullable: bool = False)
¶
options: show_root_heading: true
Array(items: Union[Schema, PyType[Schema]], description: Optional[str] = None, nullable: bool = False)
¶
Bases: Schema
Represents a list of items. :param items: The Schema definition for the items inside the array. Can be an instance (String()) or a class (String).
Source code in strutex/types.py
options: show_root_heading: true
Object(properties: Dict[str, Union[Schema, PyType[Schema]]], description: Optional[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 (or classes). :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 416 | |
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) -> Any
async
¶
Async version of process.
Runs the sync process() method in a thread pool to avoid blocking the event loop. Override this method for true native async support using async SDKs (e.g., AsyncOpenAI, AsyncAnthropic).
| 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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Extracted data matching the schema |
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) -> 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
TYPE:
|
| 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, source_text: Optional[str] = None) -> ValidationResult
abstractmethod
¶
Validate extracted data.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
The extracted data to validate
TYPE:
|
schema
|
Optional schema to validate against
TYPE:
|
source_text
|
Optional source text for provenance checks
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(block_on_detection: bool = True, additional_patterns: Optional[List[Tuple[str, str]]] = None)
¶
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 |
|---|---|
block_on_detection
|
Whether to raise SecurityError on detection.
TYPE:
|
additional_patterns
|
List of (pattern, description) tuples to add.
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
process(file_path: str, prompt: str, schema: Any, mime_type: str, context: Dict[str, Any]) -> SecurityResult
¶
Check for prompt injection attempts (adapter for Processor).
Source code in strutex/security/injection.py
validate_input(text: str) -> SecurityResult
¶
Validate input text.
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
from_schema(schema: Any, persona: Optional[str] = None) -> StructuredPrompt
classmethod
¶
Create a StructuredPrompt with field rules auto-generated from a Pydantic schema.
| PARAMETER | DESCRIPTION |
|---|---|
schema
|
A Pydantic BaseModel class with Field descriptions.
TYPE:
|
persona
|
Optional custom persona string.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
StructuredPrompt
|
A StructuredPrompt with field rules for each described field. |
Example
from pydantic import BaseModel, Field class Invoice(BaseModel): ... invoice_number: str = Field(description="Unique invoice ID") ... total: float = Field(description="Final amount due")
prompt = StructuredPrompt.from_schema(Invoice) prompt.add_general_rule("Use ISO dates") print(prompt.compile())
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