Skip to content

Extractor

The Extractor class is the main interface for structured data extraction.

Construction

from_litellm() is the recommended constructor. It creates both synchronous and asynchronous Instructor clients, scopes provider settings to the extractor, and enables LiteLLM's unsupported-parameter filtering:

extractor = Extractor.from_litellm(
    model="openai/gpt-5.5",
    api_key="your-api-key",
    api_base="https://api.example.com/v1",
    planning_model="openai/gpt-4o",
)

Direct construction accepts a patched synchronous Instructor client. Pass an AsyncInstructor through async_client as well if any async method will be used. The async methods fail early when it is absent.

API Requirements

All public operation methods require keyword arguments. The * in method signatures indicates that all parameters after it must be passed by name:

# Correct usage
result = extractor.extract(data="file.pdf", query="extract information")
result = extractor.extract_queries(data="file.pdf", queries=["query1", "query2"])
model = extractor.get_schema(data="file.pdf", query="extract information")
refined = extractor.refine_data_model(model=ExistingModel, refinement_instructions="add field")

# Incorrect usage - raises TypeError
result = extractor.extract("file.pdf", "extract information")
result = extractor.extract_queries("file.pdf", ["query1", "query2"])

Architecture Overview

View Architecture Diagram
graph TB
    subgraph "User Interface"
        A[Extractor Class]
        A1[extract] 
        A2[extract_queries]
        A3[extract_async]
        A4[refine_data_model]
    end

    subgraph "Core Processing"
        B[LLM Core]
        C[Input Processor]
        C1[PreparedInput]
        D[Model Operations]
        E[Batch Processor]
        F[Extraction Engine]
    end

    subgraph "File Processing Pipeline"
        G[File Reader]
        H[Format Detection]
        I[Document Conversion]
        J[PDF Generation]
        K[Multimodal Processing]
    end

    subgraph "LLM Integration"
        L[Instructor Client]
        M[LiteLLM Support]
        N[Provider Abstraction]
        O[Token Tracking]
    end

    subgraph "Output Management"
        P[Result Collector]
        Q[Type Safety]
        R[Error Handling]
        S[Operation Usage]
        T[RowResult and Row Usage]
    end

    A --> A1
    A --> A2
    A --> A3
    A --> A4

    B --> L
    G --> H
    H --> I
    I --> J
    J --> K
    K --> C

    A --> C
    C --> C1
    C --> D
    C --> G
    D --> E
    E --> F
    F --> B
    F --> P

    L --> M
    M --> N
    N --> O
    P --> Q
    P --> R
    P --> S
    P --> T

For output semantics and row-level provenance, see Working with Results.

Coordinate input preparation, model planning, extraction, and results.

Parameters:

Name Type Description Default
client Instructor

Instructor-patched client

required
model_name str

Name of the model to use

required
config Optional[Union[Dict, str, Path, ExtractionConfig]]

Configuration for extraction steps

None
max_threads int

Maximum concurrent row requests

10
batch_size int

Rows scheduled in each processing batch

100
max_retries int

Maximum number of retries for extraction

3
min_wait int

Minimum seconds to wait between retries

1
max_wait int

Maximum seconds to wait between retries

10
planning_model Optional[str]

Optional model for instruction and schema generation

None
async_client Optional[AsyncInstructor]

Optional async Instructor client for async methods

None
Source code in structx/extraction/extractor.py
 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
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
class Extractor:
    """Coordinate input preparation, model planning, extraction, and results.

    Args:
        client: Instructor-patched client
        model_name: Name of the model to use
        config: Configuration for extraction steps
        max_threads: Maximum concurrent row requests
        batch_size: Rows scheduled in each processing batch
        max_retries: Maximum number of retries for extraction
        min_wait: Minimum seconds to wait between retries
        max_wait: Maximum seconds to wait between retries
        planning_model: Optional model for instruction and schema generation
        async_client: Optional async Instructor client for async methods
    """

    def __init__(
        self,
        client: Instructor,
        model_name: str,
        config: Optional[Union[Dict, str, Path, ExtractionConfig]] = None,
        max_threads: int = 10,
        batch_size: int = 100,
        max_retries: int = 3,
        min_wait: int = 1,
        max_wait: int = 10,
        planning_model: Optional[str] = None,
        async_client: Optional[AsyncInstructor] = None,
    ):
        """Initialize extractor."""
        if (
            not isinstance(max_threads, int)
            or isinstance(max_threads, bool)
            or max_threads < 1
        ):
            raise ConfigurationError("max_threads must be a positive integer")
        if (
            not isinstance(batch_size, int)
            or isinstance(batch_size, bool)
            or batch_size < 1
        ):
            raise ConfigurationError("batch_size must be a positive integer")
        if (
            not isinstance(max_retries, int)
            or isinstance(max_retries, bool)
            or max_retries < 0
        ):
            raise ConfigurationError("max_retries must be a non-negative integer")
        if min_wait < 0 or max_wait < min_wait:
            raise ConfigurationError(
                "wait settings must satisfy 0 <= min_wait <= max_wait"
            )

        self.model_name = model_name

        # Setup configuration
        if config is None:
            self.config = ExtractionConfig()
        elif isinstance(config, dict):
            self.config = ExtractionConfig(**config)
        elif isinstance(config, (str, Path)):
            self.config = ExtractionConfig.from_yaml(config)
        elif isinstance(config, ExtractionConfig):
            self.config = config
        else:
            raise ConfigurationError("Invalid configuration type")

        # Initialize core components
        self.llm_core = LLMCore(
            client=client,
            async_client=async_client,
            model_name=model_name,
            config=self.config,
            max_retries=max_retries,
            min_wait=min_wait,
            max_wait=max_wait,
            planning_model_name=planning_model,
        )

        # Initialize specialized processors
        self.model_operations = ModelOperations(self.llm_core)
        self.extraction_engine = ExtractionEngine(self.llm_core)
        self.input_processor = InputProcessor()
        self.batch_processor = BatchProcessor(max_threads, batch_size)
        self.content_analyzer = ContentAnalyzer()

        logger.debug(f"Initialized Extractor with configuration: {self.config}")

    @staticmethod
    def _validate_query(query: str) -> str:
        if not isinstance(query, str) or not query.strip():
            raise ValueError("query must be a non-empty string")
        return query.strip()

    @classmethod
    def _validate_queries(cls, queries: List[str]) -> List[str]:
        if not isinstance(queries, list) or not queries:
            raise ValueError("queries must be a non-empty list")
        validated = [cls._validate_query(query) for query in queries]
        if len(set(validated)) != len(validated):
            raise ValueError("queries must not contain duplicates")
        return validated

    @contextmanager
    def prepare_input(
        self, *, data: InputData, **kwargs: Any
    ) -> Generator[PreparedInput, None, None]:
        """Prepare input once and release owned resources after the context."""
        with self.input_processor.prepared(data, **kwargs) as prepared_input:
            yield prepared_input

    @asynccontextmanager
    async def prepare_input_async(
        self, *, data: InputData, **kwargs: Any
    ) -> AsyncGenerator[PreparedInput, None]:
        """Prepare input off-loop and release resources after the async context."""
        async with self.input_processor.prepared_async(
            data, **kwargs
        ) as prepared_input:
            yield prepared_input

    def _build_strategy(
        self,
        prepared_input: PreparedInput,
        query: str,
        usage: ExtractorUsage,
        model: Optional[Type[BaseModel]],
    ) -> ExtractionStrategy:
        """Build deterministic or model-generated instructions for one operation."""
        if model is not None:
            instructions, target_columns = (
                self.model_operations.generate_from_custom_model(
                    model=model,
                    query=query,
                    data_columns=prepared_input.dataframe.columns.tolist(),
                )
            )
            return ExtractionStrategy(model, instructions, target_columns)

        sample_text = self._create_schema_sample(prepared_input)
        pdf_path = self._planning_pdf_path(prepared_input)
        plan = self.model_operations.generate_extraction_plan(
            query=query,
            sample_text=sample_text,
            data_columns=prepared_input.dataframe.columns.tolist(),
            usage=usage,
            pdf_path=pdf_path,
        )
        logger.debug(f"Extraction Instructions: {plan.instructions}")
        logger.debug(f"Target Columns: {plan.target_columns}")

        extraction_model = self.model_operations.create_model_from_schema(
            plan.extraction_schema
        )
        return ExtractionStrategy(
            extraction_model,
            plan.instructions,
            plan.target_columns,
        )

    async def _build_strategy_async(
        self,
        prepared_input: PreparedInput,
        query: str,
        usage: ExtractorUsage,
        model: Optional[Type[BaseModel]],
    ) -> ExtractionStrategy:
        """Asynchronously build the strategy when model planning is required."""
        if model is not None:
            instructions, target_columns = (
                self.model_operations.generate_from_custom_model(
                    model=model,
                    query=query,
                    data_columns=prepared_input.dataframe.columns.tolist(),
                )
            )
            return ExtractionStrategy(model, instructions, target_columns)

        plan = await self.model_operations.generate_extraction_plan_async(
            query=query,
            sample_text=await asyncio.to_thread(
                self._create_schema_sample, prepared_input
            ),
            data_columns=prepared_input.dataframe.columns.tolist(),
            usage=usage,
            pdf_path=self._planning_pdf_path(prepared_input),
        )
        extraction_model = self.model_operations.create_model_from_schema(
            plan.extraction_schema
        )
        return ExtractionStrategy(
            extraction_model,
            plan.instructions,
            plan.target_columns,
        )

    def _create_schema_sample(self, prepared_input: PreparedInput) -> str:
        """Create one representative sample for extraction planning."""
        df = prepared_input.dataframe
        if prepared_input.pdf_rows:
            sample_text = prepared_input.planning_sample or ""
            content_context = self.content_analyzer.detect_content_type_and_context(
                prepared_input
            )
            return f"Content type: {content_context}\n\n{sample_text}"
        return "\n".join(df.head().to_string(index=False).splitlines())

    @staticmethod
    def _planning_pdf_path(prepared_input: PreparedInput) -> Optional[str]:
        """Attach a PDF to planning only when no text sample is available."""
        if prepared_input.planning_sample or not prepared_input.pdf_rows:
            return None
        first_pdf = prepared_input.pdf_rows[min(prepared_input.pdf_rows)]
        return str(first_pdf.pdf_path)

    def _create_extraction_worker(
        self,
        strategy: ExtractionStrategy,
    ):
        """Create a worker function for synchronous row extraction."""

        def extract_worker(
            row_data: RowPayload,
            row_position: int,
            row_label: Any,
        ):
            try:
                row_usage = ExtractorUsage()
                items = self.extraction_engine.extract_from_row_data(
                    row_data=row_data,
                    extraction_model=strategy.model,
                    instructions=strategy.instructions,
                    usage=row_usage,
                )
                return RowResult(
                    position=row_position,
                    source_index=row_label,
                    input_data=row_data,
                    items=items,
                    usage=row_usage,
                )
            except Exception as error:
                return RowResult(
                    position=row_position,
                    source_index=row_label,
                    input_data=row_data,
                    items=[],
                    usage=row_usage,
                    error=str(error),
                )

        return extract_worker

    def _create_async_extraction_worker(
        self,
        strategy: ExtractionStrategy,
    ):
        """Create an async worker that preserves row identity on success or failure."""

        async def extract_worker(
            row_data: RowPayload,
            row_position: int,
            row_label: Any,
        ) -> RowResult:
            try:
                row_usage = ExtractorUsage()
                items = await self.extraction_engine.extract_from_row_data_async(
                    row_data=row_data,
                    extraction_model=strategy.model,
                    instructions=strategy.instructions,
                    usage=row_usage,
                )
                return RowResult(
                    position=row_position,
                    source_index=row_label,
                    input_data=row_data,
                    items=items,
                    usage=row_usage,
                )
            except Exception as error:
                return RowResult(
                    position=row_position,
                    source_index=row_label,
                    input_data=row_data,
                    items=[],
                    usage=row_usage,
                    error=str(error),
                )

        return extract_worker

    def _process_data(
        self,
        prepared_input: PreparedInput,
        query: str,
        return_df: bool,
        expand_nested: bool = False,
        extraction_model: Optional[Type[BaseModel]] = None,
    ) -> ExtractionResult:
        """Process DataFrame with extraction."""
        operation_usage = ExtractorUsage()
        strategy = self._build_strategy(
            prepared_input, query, operation_usage, extraction_model
        )

        results = ResultCollector(
            source=prepared_input.dataframe,
            model=strategy.model,
            return_df=return_df,
            expand_nested=expand_nested,
        )

        worker_fn = self._create_extraction_worker(strategy=strategy)

        # Process in batches
        outcomes = self.batch_processor.map_rows(
            prepared_input, worker_fn, strategy.target_columns
        )
        for outcome in outcomes:
            operation_usage.merge(outcome.usage)
            results.record(outcome)
        return results.build(operation_usage)

    async def _process_data_async(
        self,
        prepared_input: PreparedInput,
        query: str,
        return_df: bool,
        expand_nested: bool = False,
        extraction_model: Optional[Type[BaseModel]] = None,
    ) -> ExtractionResult:
        """Plan once, then asynchronously process independent rows."""
        if self.llm_core.async_client is None:
            raise ConfigurationError(
                "Async extraction requires an async Instructor client"
            )
        operation_usage = ExtractorUsage()
        strategy = await self._build_strategy_async(
            prepared_input, query, operation_usage, extraction_model
        )
        results = ResultCollector(
            source=prepared_input.dataframe,
            model=strategy.model,
            return_df=return_df,
            expand_nested=expand_nested,
        )
        outcomes = await self.batch_processor.map_rows_async(
            prepared_input,
            self._create_async_extraction_worker(strategy),
            strategy.target_columns,
        )
        for outcome in outcomes:
            operation_usage.merge(outcome.usage)
            results.record(outcome)
        return results.build(operation_usage)

    @handle_errors(error_message="Extraction failed", error_type=ExtractionError)
    def extract(
        self,
        *,
        data: InputData,
        query: str,
        model: Optional[Type[BaseModel]] = None,
        return_df: bool = False,
        expand_nested: bool = False,
        **kwargs: Any,
    ) -> ExtractionResult:
        """
        Extract structured data from text.

        Args:
            data: Input data (file path, DataFrame, list of dicts, or raw text)
            query: Natural language query
            model: Optional pre-generated Pydantic model class (if None, a model will be generated)
            return_df: Whether to return DataFrame
            expand_nested: Whether to flatten nested structures
            **kwargs: Additional options for file reading

        Returns:
            Extraction result with extracted data, failed rows, and model (if requested)
        """
        query = self._validate_query(query)
        with self.input_processor.prepared(data, **kwargs) as prepared_input:
            return self._process_data(
                prepared_input, query, return_df, expand_nested, model
            )

    async def extract_async(
        self,
        *,
        data: InputData,
        query: str,
        model: Optional[Type[BaseModel]] = None,
        return_df: bool = False,
        expand_nested: bool = False,
        **kwargs: Any,
    ) -> ExtractionResult:
        """
        Asynchronous version of `extract`.

        Args:
            data: Input data (file path, DataFrame, list of dicts, or raw text)
            query: Natural language query
            model: Optional pre-generated Pydantic model class
            return_df: Whether to return DataFrame
            expand_nested: Whether to flatten nested structures
            **kwargs: Additional options for file reading

        Returns:
            ExtractionResult containing extracted data, failed rows, and the model
        """
        try:
            query = self._validate_query(query)
            async with self.input_processor.prepared_async(
                data, **kwargs
            ) as prepared_input:
                return await self._process_data_async(
                    prepared_input, query, return_df, expand_nested, model
                )
        except Exception as error:
            raise ExtractionError(f"Async extraction failed: {error}") from error

    @handle_errors(error_message="Batch extraction failed", error_type=ExtractionError)
    def extract_queries(
        self,
        *,
        data: InputData,
        queries: List[str],
        return_df: bool = True,
        expand_nested: bool = False,
        **kwargs: Any,
    ) -> Dict[str, ExtractionResult]:
        """
        Process multiple queries on the same data.

        Args:
            data: Input data (file path, DataFrame, list of dicts, or raw text)
            queries: List of queries to process
            return_df: Whether to return DataFrame
            expand_nested: Whether to flatten nested structures
            **kwargs: Additional options for file reading

        Returns:
            Dictionary mapping queries to their results (extracted data and failed extractions)
        """
        queries = self._validate_queries(queries)
        with self.input_processor.prepared(data, **kwargs) as prepared_input:
            results = {}
            for query in queries:
                logger.debug(f"Processing query: {query}")
                results[query] = self._process_data(
                    prepared_input=prepared_input,
                    query=query,
                    return_df=return_df,
                    expand_nested=expand_nested,
                )
            return results

    async def extract_queries_async(
        self,
        *,
        data: InputData,
        queries: List[str],
        return_df: bool = True,
        expand_nested: bool = False,
        **kwargs: Any,
    ) -> Dict[str, ExtractionResult]:
        """
        Asynchronous version of `extract_queries`.

        Args:
            data: Input data
            queries: List of queries
            return_df: Whether to return DataFrame
            expand_nested: Whether to flatten nested structures
            **kwargs: Additional options

        Returns:
            Dictionary mapping queries to ExtractionResult objects
        """
        try:
            queries = self._validate_queries(queries)
            async with self.input_processor.prepared_async(
                data, **kwargs
            ) as prepared_input:
                results = {}
                for query in queries:
                    results[query] = await self._process_data_async(
                        prepared_input=prepared_input,
                        query=query,
                        return_df=return_df,
                        expand_nested=expand_nested,
                    )
                return results
        except Exception as error:
            raise ExtractionError(f"Async batch extraction failed: {error}") from error

    @handle_errors(error_message="Schema generation failed", error_type=ExtractionError)
    def get_schema(
        self,
        *,
        data: InputData,
        query: str,
        **kwargs: Any,
    ) -> Type[BaseModel]:
        """
        Get extraction model without performing extraction.

        Args:
            query: Natural language query
            data: Input data (file path, DataFrame, list of dicts, or raw text)
            **kwargs: Additional options for file reading

        Returns:
            Pydantic model for extraction with `.usage` attribute for token tracking
        """
        query = self._validate_query(query)
        with self.input_processor.prepared(data, **kwargs) as prepared_input:
            sample_text = self._create_schema_sample(prepared_input)
            columns = prepared_input.dataframe.columns.tolist()

            operation_usage = ExtractorUsage()
            pdf_path = self._planning_pdf_path(prepared_input)
            plan = self.model_operations.generate_extraction_plan(
                query=query,
                sample_text=sample_text,
                data_columns=columns,
                usage=operation_usage,
                pdf_path=pdf_path,
            )

            extraction_model = self.model_operations.create_model_from_schema(
                plan.extraction_schema
            )
            extraction_model.usage = operation_usage
            return extraction_model

    async def get_schema_async(
        self,
        *,
        data: InputData,
        query: str,
        **kwargs: Any,
    ) -> Type[BaseModel]:
        """
        Asynchronous version of `get_schema`.

        Args:
            query: Natural language query
            data: Input data (file path, DataFrame, list of dicts, or raw text)
            **kwargs: Additional options for file reading

        Returns:
            Dynamically generated Pydantic model class
        """
        try:
            query = self._validate_query(query)
            async with self.input_processor.prepared_async(
                data, **kwargs
            ) as prepared_input:
                usage = ExtractorUsage()
                plan = await self.model_operations.generate_extraction_plan_async(
                    query=query,
                    sample_text=await asyncio.to_thread(
                        self._create_schema_sample, prepared_input
                    ),
                    data_columns=prepared_input.dataframe.columns.tolist(),
                    usage=usage,
                    pdf_path=self._planning_pdf_path(prepared_input),
                )
                model = self.model_operations.create_model_from_schema(
                    plan.extraction_schema
                )
                model.usage = usage
                return model
        except Exception as error:
            raise ExtractionError(f"Async schema generation failed: {error}") from error

    @handle_errors(error_message="Model refinement failed", error_type=ExtractionError)
    def refine_data_model(
        self,
        *,
        model: Type[BaseModel],
        refinement_instructions: str,
        model_name: Optional[str] = None,
    ) -> Type[BaseModel]:
        """
        Refine an existing data model based on natural language instructions.

        Args:
            model: Existing Pydantic model to refine
            refinement_instructions: Natural language instructions for refinement
            model_name: Optional name for the refined model (defaults to original name with 'Refined' prefix)

        Returns:
            A new refined Pydantic model with `.usage` attribute for token tracking
        """
        # Default model name if not provided
        if model_name is None:
            model_name = f"Refined{model.__name__}"

        operation_usage = ExtractorUsage()
        refined_model = self.model_operations.refine_existing_model(
            model=model,
            instructions=refinement_instructions,
            model_name=model_name,
            usage=operation_usage,
        )

        # Add usage to model
        refined_model.usage = operation_usage

        return refined_model

    async def refine_data_model_async(
        self,
        *,
        model: Type[BaseModel],
        refinement_instructions: str,
        model_name: Optional[str] = None,
    ) -> Type[BaseModel]:
        """Asynchronously refine an existing data model."""
        try:
            usage = ExtractorUsage()
            refined_model = await self.model_operations.refine_existing_model_async(
                model=model,
                instructions=refinement_instructions,
                model_name=model_name,
                usage=usage,
            )
            refined_model.usage = usage
            return refined_model
        except Exception as error:
            raise ExtractionError(f"Async model refinement failed: {error}") from error

    @classmethod
    def from_litellm(
        cls,
        *,
        model: str,
        api_key: Optional[str] = None,
        config: Optional[Union[Dict, str, Path, ExtractionConfig]] = None,
        max_threads: int = 10,
        batch_size: int = 100,
        max_retries: int = 3,
        min_wait: int = 1,
        max_wait: int = 10,
        planning_model: Optional[str] = None,
        **litellm_kwargs: Any,
    ) -> "Extractor":
        """
        Create Extractor instance using litellm.

        Args:
            model: Model identifier (e.g., "gpt-4", "claude-2", "azure/gpt-4")
            api_key: API key for the model provider
            config: Per-step completion parameters passed to the model provider
            max_threads: Maximum concurrent row requests
            batch_size: Rows scheduled in each processing batch
            max_retries: Maximum number of retries for extraction
            min_wait: Minimum seconds to wait between retries
            max_wait: Maximum seconds to wait between retries
            planning_model: Optional model for instruction and schema generation
            **litellm_kwargs: Additional kwargs for litellm (e.g., api_base, organization)
        """
        import instructor
        from litellm import acompletion, completion

        completion_options = {**litellm_kwargs, "drop_params": True}
        if api_key:
            completion_options["api_key"] = api_key

        # Bind provider settings to this client instead of mutating LiteLLM globals.
        completion_with_filtered_params = partial(completion, **completion_options)
        client = instructor.from_litellm(completion_with_filtered_params)
        async_completion = partial(acompletion, **completion_options)
        async_client = instructor.from_litellm(async_completion, async_client=True)

        return cls(
            client=client,
            async_client=async_client,
            model_name=model,
            config=config,
            max_threads=max_threads,
            batch_size=batch_size,
            max_retries=max_retries,
            min_wait=min_wait,
            max_wait=max_wait,
            planning_model=planning_model,
        )

extract(*, data, query, model=None, return_df=False, expand_nested=False, **kwargs)

Extract structured data from text.

Parameters:

Name Type Description Default
data InputData

Input data (file path, DataFrame, list of dicts, or raw text)

required
query str

Natural language query

required
model Optional[Type[BaseModel]]

Optional pre-generated Pydantic model class (if None, a model will be generated)

None
return_df bool

Whether to return DataFrame

False
expand_nested bool

Whether to flatten nested structures

False
**kwargs Any

Additional options for file reading

{}

Returns:

Type Description
ExtractionResult

Extraction result with extracted data, failed rows, and model (if requested)

Source code in structx/extraction/extractor.py
@handle_errors(error_message="Extraction failed", error_type=ExtractionError)
def extract(
    self,
    *,
    data: InputData,
    query: str,
    model: Optional[Type[BaseModel]] = None,
    return_df: bool = False,
    expand_nested: bool = False,
    **kwargs: Any,
) -> ExtractionResult:
    """
    Extract structured data from text.

    Args:
        data: Input data (file path, DataFrame, list of dicts, or raw text)
        query: Natural language query
        model: Optional pre-generated Pydantic model class (if None, a model will be generated)
        return_df: Whether to return DataFrame
        expand_nested: Whether to flatten nested structures
        **kwargs: Additional options for file reading

    Returns:
        Extraction result with extracted data, failed rows, and model (if requested)
    """
    query = self._validate_query(query)
    with self.input_processor.prepared(data, **kwargs) as prepared_input:
        return self._process_data(
            prepared_input, query, return_df, expand_nested, model
        )

extract_async(*, data, query, model=None, return_df=False, expand_nested=False, **kwargs) async

Asynchronous version of extract.

Parameters:

Name Type Description Default
data InputData

Input data (file path, DataFrame, list of dicts, or raw text)

required
query str

Natural language query

required
model Optional[Type[BaseModel]]

Optional pre-generated Pydantic model class

None
return_df bool

Whether to return DataFrame

False
expand_nested bool

Whether to flatten nested structures

False
**kwargs Any

Additional options for file reading

{}

Returns:

Type Description
ExtractionResult

ExtractionResult containing extracted data, failed rows, and the model

Source code in structx/extraction/extractor.py
async def extract_async(
    self,
    *,
    data: InputData,
    query: str,
    model: Optional[Type[BaseModel]] = None,
    return_df: bool = False,
    expand_nested: bool = False,
    **kwargs: Any,
) -> ExtractionResult:
    """
    Asynchronous version of `extract`.

    Args:
        data: Input data (file path, DataFrame, list of dicts, or raw text)
        query: Natural language query
        model: Optional pre-generated Pydantic model class
        return_df: Whether to return DataFrame
        expand_nested: Whether to flatten nested structures
        **kwargs: Additional options for file reading

    Returns:
        ExtractionResult containing extracted data, failed rows, and the model
    """
    try:
        query = self._validate_query(query)
        async with self.input_processor.prepared_async(
            data, **kwargs
        ) as prepared_input:
            return await self._process_data_async(
                prepared_input, query, return_df, expand_nested, model
            )
    except Exception as error:
        raise ExtractionError(f"Async extraction failed: {error}") from error

extract_queries(*, data, queries, return_df=True, expand_nested=False, **kwargs)

Process multiple queries on the same data.

Parameters:

Name Type Description Default
data InputData

Input data (file path, DataFrame, list of dicts, or raw text)

required
queries List[str]

List of queries to process

required
return_df bool

Whether to return DataFrame

True
expand_nested bool

Whether to flatten nested structures

False
**kwargs Any

Additional options for file reading

{}

Returns:

Type Description
Dict[str, ExtractionResult]

Dictionary mapping queries to their results (extracted data and failed extractions)

Source code in structx/extraction/extractor.py
@handle_errors(error_message="Batch extraction failed", error_type=ExtractionError)
def extract_queries(
    self,
    *,
    data: InputData,
    queries: List[str],
    return_df: bool = True,
    expand_nested: bool = False,
    **kwargs: Any,
) -> Dict[str, ExtractionResult]:
    """
    Process multiple queries on the same data.

    Args:
        data: Input data (file path, DataFrame, list of dicts, or raw text)
        queries: List of queries to process
        return_df: Whether to return DataFrame
        expand_nested: Whether to flatten nested structures
        **kwargs: Additional options for file reading

    Returns:
        Dictionary mapping queries to their results (extracted data and failed extractions)
    """
    queries = self._validate_queries(queries)
    with self.input_processor.prepared(data, **kwargs) as prepared_input:
        results = {}
        for query in queries:
            logger.debug(f"Processing query: {query}")
            results[query] = self._process_data(
                prepared_input=prepared_input,
                query=query,
                return_df=return_df,
                expand_nested=expand_nested,
            )
        return results

extract_queries_async(*, data, queries, return_df=True, expand_nested=False, **kwargs) async

Asynchronous version of extract_queries.

Parameters:

Name Type Description Default
data InputData

Input data

required
queries List[str]

List of queries

required
return_df bool

Whether to return DataFrame

True
expand_nested bool

Whether to flatten nested structures

False
**kwargs Any

Additional options

{}

Returns:

Type Description
Dict[str, ExtractionResult]

Dictionary mapping queries to ExtractionResult objects

Source code in structx/extraction/extractor.py
async def extract_queries_async(
    self,
    *,
    data: InputData,
    queries: List[str],
    return_df: bool = True,
    expand_nested: bool = False,
    **kwargs: Any,
) -> Dict[str, ExtractionResult]:
    """
    Asynchronous version of `extract_queries`.

    Args:
        data: Input data
        queries: List of queries
        return_df: Whether to return DataFrame
        expand_nested: Whether to flatten nested structures
        **kwargs: Additional options

    Returns:
        Dictionary mapping queries to ExtractionResult objects
    """
    try:
        queries = self._validate_queries(queries)
        async with self.input_processor.prepared_async(
            data, **kwargs
        ) as prepared_input:
            results = {}
            for query in queries:
                results[query] = await self._process_data_async(
                    prepared_input=prepared_input,
                    query=query,
                    return_df=return_df,
                    expand_nested=expand_nested,
                )
            return results
    except Exception as error:
        raise ExtractionError(f"Async batch extraction failed: {error}") from error

from_litellm(*, model, api_key=None, config=None, max_threads=10, batch_size=100, max_retries=3, min_wait=1, max_wait=10, planning_model=None, **litellm_kwargs) classmethod

Create Extractor instance using litellm.

Parameters:

Name Type Description Default
model str

Model identifier (e.g., "gpt-4", "claude-2", "azure/gpt-4")

required
api_key Optional[str]

API key for the model provider

None
config Optional[Union[Dict, str, Path, ExtractionConfig]]

Per-step completion parameters passed to the model provider

None
max_threads int

Maximum concurrent row requests

10
batch_size int

Rows scheduled in each processing batch

100
max_retries int

Maximum number of retries for extraction

3
min_wait int

Minimum seconds to wait between retries

1
max_wait int

Maximum seconds to wait between retries

10
planning_model Optional[str]

Optional model for instruction and schema generation

None
**litellm_kwargs Any

Additional kwargs for litellm (e.g., api_base, organization)

{}
Source code in structx/extraction/extractor.py
@classmethod
def from_litellm(
    cls,
    *,
    model: str,
    api_key: Optional[str] = None,
    config: Optional[Union[Dict, str, Path, ExtractionConfig]] = None,
    max_threads: int = 10,
    batch_size: int = 100,
    max_retries: int = 3,
    min_wait: int = 1,
    max_wait: int = 10,
    planning_model: Optional[str] = None,
    **litellm_kwargs: Any,
) -> "Extractor":
    """
    Create Extractor instance using litellm.

    Args:
        model: Model identifier (e.g., "gpt-4", "claude-2", "azure/gpt-4")
        api_key: API key for the model provider
        config: Per-step completion parameters passed to the model provider
        max_threads: Maximum concurrent row requests
        batch_size: Rows scheduled in each processing batch
        max_retries: Maximum number of retries for extraction
        min_wait: Minimum seconds to wait between retries
        max_wait: Maximum seconds to wait between retries
        planning_model: Optional model for instruction and schema generation
        **litellm_kwargs: Additional kwargs for litellm (e.g., api_base, organization)
    """
    import instructor
    from litellm import acompletion, completion

    completion_options = {**litellm_kwargs, "drop_params": True}
    if api_key:
        completion_options["api_key"] = api_key

    # Bind provider settings to this client instead of mutating LiteLLM globals.
    completion_with_filtered_params = partial(completion, **completion_options)
    client = instructor.from_litellm(completion_with_filtered_params)
    async_completion = partial(acompletion, **completion_options)
    async_client = instructor.from_litellm(async_completion, async_client=True)

    return cls(
        client=client,
        async_client=async_client,
        model_name=model,
        config=config,
        max_threads=max_threads,
        batch_size=batch_size,
        max_retries=max_retries,
        min_wait=min_wait,
        max_wait=max_wait,
        planning_model=planning_model,
    )

get_schema(*, data, query, **kwargs)

Get extraction model without performing extraction.

Parameters:

Name Type Description Default
query str

Natural language query

required
data InputData

Input data (file path, DataFrame, list of dicts, or raw text)

required
**kwargs Any

Additional options for file reading

{}

Returns:

Type Description
Type[BaseModel]

Pydantic model for extraction with .usage attribute for token tracking

Source code in structx/extraction/extractor.py
@handle_errors(error_message="Schema generation failed", error_type=ExtractionError)
def get_schema(
    self,
    *,
    data: InputData,
    query: str,
    **kwargs: Any,
) -> Type[BaseModel]:
    """
    Get extraction model without performing extraction.

    Args:
        query: Natural language query
        data: Input data (file path, DataFrame, list of dicts, or raw text)
        **kwargs: Additional options for file reading

    Returns:
        Pydantic model for extraction with `.usage` attribute for token tracking
    """
    query = self._validate_query(query)
    with self.input_processor.prepared(data, **kwargs) as prepared_input:
        sample_text = self._create_schema_sample(prepared_input)
        columns = prepared_input.dataframe.columns.tolist()

        operation_usage = ExtractorUsage()
        pdf_path = self._planning_pdf_path(prepared_input)
        plan = self.model_operations.generate_extraction_plan(
            query=query,
            sample_text=sample_text,
            data_columns=columns,
            usage=operation_usage,
            pdf_path=pdf_path,
        )

        extraction_model = self.model_operations.create_model_from_schema(
            plan.extraction_schema
        )
        extraction_model.usage = operation_usage
        return extraction_model

get_schema_async(*, data, query, **kwargs) async

Asynchronous version of get_schema.

Parameters:

Name Type Description Default
query str

Natural language query

required
data InputData

Input data (file path, DataFrame, list of dicts, or raw text)

required
**kwargs Any

Additional options for file reading

{}

Returns:

Type Description
Type[BaseModel]

Dynamically generated Pydantic model class

Source code in structx/extraction/extractor.py
async def get_schema_async(
    self,
    *,
    data: InputData,
    query: str,
    **kwargs: Any,
) -> Type[BaseModel]:
    """
    Asynchronous version of `get_schema`.

    Args:
        query: Natural language query
        data: Input data (file path, DataFrame, list of dicts, or raw text)
        **kwargs: Additional options for file reading

    Returns:
        Dynamically generated Pydantic model class
    """
    try:
        query = self._validate_query(query)
        async with self.input_processor.prepared_async(
            data, **kwargs
        ) as prepared_input:
            usage = ExtractorUsage()
            plan = await self.model_operations.generate_extraction_plan_async(
                query=query,
                sample_text=await asyncio.to_thread(
                    self._create_schema_sample, prepared_input
                ),
                data_columns=prepared_input.dataframe.columns.tolist(),
                usage=usage,
                pdf_path=self._planning_pdf_path(prepared_input),
            )
            model = self.model_operations.create_model_from_schema(
                plan.extraction_schema
            )
            model.usage = usage
            return model
    except Exception as error:
        raise ExtractionError(f"Async schema generation failed: {error}") from error

prepare_input(*, data, **kwargs)

Prepare input once and release owned resources after the context.

Source code in structx/extraction/extractor.py
@contextmanager
def prepare_input(
    self, *, data: InputData, **kwargs: Any
) -> Generator[PreparedInput, None, None]:
    """Prepare input once and release owned resources after the context."""
    with self.input_processor.prepared(data, **kwargs) as prepared_input:
        yield prepared_input

prepare_input_async(*, data, **kwargs) async

Prepare input off-loop and release resources after the async context.

Source code in structx/extraction/extractor.py
@asynccontextmanager
async def prepare_input_async(
    self, *, data: InputData, **kwargs: Any
) -> AsyncGenerator[PreparedInput, None]:
    """Prepare input off-loop and release resources after the async context."""
    async with self.input_processor.prepared_async(
        data, **kwargs
    ) as prepared_input:
        yield prepared_input

refine_data_model(*, model, refinement_instructions, model_name=None)

Refine an existing data model based on natural language instructions.

Parameters:

Name Type Description Default
model Type[BaseModel]

Existing Pydantic model to refine

required
refinement_instructions str

Natural language instructions for refinement

required
model_name Optional[str]

Optional name for the refined model (defaults to original name with 'Refined' prefix)

None

Returns:

Type Description
Type[BaseModel]

A new refined Pydantic model with .usage attribute for token tracking

Source code in structx/extraction/extractor.py
@handle_errors(error_message="Model refinement failed", error_type=ExtractionError)
def refine_data_model(
    self,
    *,
    model: Type[BaseModel],
    refinement_instructions: str,
    model_name: Optional[str] = None,
) -> Type[BaseModel]:
    """
    Refine an existing data model based on natural language instructions.

    Args:
        model: Existing Pydantic model to refine
        refinement_instructions: Natural language instructions for refinement
        model_name: Optional name for the refined model (defaults to original name with 'Refined' prefix)

    Returns:
        A new refined Pydantic model with `.usage` attribute for token tracking
    """
    # Default model name if not provided
    if model_name is None:
        model_name = f"Refined{model.__name__}"

    operation_usage = ExtractorUsage()
    refined_model = self.model_operations.refine_existing_model(
        model=model,
        instructions=refinement_instructions,
        model_name=model_name,
        usage=operation_usage,
    )

    # Add usage to model
    refined_model.usage = operation_usage

    return refined_model

refine_data_model_async(*, model, refinement_instructions, model_name=None) async

Asynchronously refine an existing data model.

Source code in structx/extraction/extractor.py
async def refine_data_model_async(
    self,
    *,
    model: Type[BaseModel],
    refinement_instructions: str,
    model_name: Optional[str] = None,
) -> Type[BaseModel]:
    """Asynchronously refine an existing data model."""
    try:
        usage = ExtractorUsage()
        refined_model = await self.model_operations.refine_existing_model_async(
            model=model,
            instructions=refinement_instructions,
            model_name=model_name,
            usage=usage,
        )
        refined_model.usage = usage
        return refined_model
    except Exception as error:
        raise ExtractionError(f"Async model refinement failed: {error}") from error