Repository navigation
Expand file tree
/
Copy pathapi_client.py
More file actions
1429 lines (1295 loc) · 48.8 KB
/
Copy pathapi_client.py
File metadata and controls
1429 lines (1295 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
GLiNER2 API Client
This module provides an API-based wrapper for GLiNER2 that mirrors the local
model interface. It allows seamless switching between local and API-based
inference.
Usage:
>>> from gliner2 import GLiNER2
>>>
>>> # Load from API (uses environment variable for API key)
>>> extractor = GLiNER2.from_api()
>>>
>>> # Use exactly like local model
>>> results = extractor.extract_entities(
... "Apple released iPhone 15 in September 2023.",
... ["company", "product", "date"]
... )
"""
from __future__ import annotations
import os
import logging
import warnings
from collections import OrderedDict
from typing import Any, Dict, List, Optional, Union, Literal
from urllib.parse import urljoin
from urllib3.util import Retry
import requests
from requests.adapters import HTTPAdapter
from gliner2.inference.chunking import merge_chunk_results, split_text_into_chunks
logger = logging.getLogger(__name__)
class GLiNER2APIError(Exception):
"""Base exception for GLiNER2 API errors."""
def __init__(self, message: str, status_code: Optional[int] = None, response_data: Optional[Dict] = None):
super().__init__(message)
self.status_code = status_code
self.response_data = response_data
# Populated when a partitioned batch fails after earlier partitions
# succeeded. Callers can persist completed work before deciding to retry.
self.partial_results: List[Any] = []
self.failed_range: Optional[tuple[int, int]] = None
class AuthenticationError(GLiNER2APIError):
"""Raised when API key is invalid or expired."""
pass
class ValidationError(GLiNER2APIError):
"""Raised when request data is invalid."""
pass
class ServerError(GLiNER2APIError):
"""Raised when server encounters an error."""
pass
class StructureBuilderAPI:
"""
Builder for structured data schemas for API-based extraction.
This mirrors the interface of StructureBuilder from the local model.
"""
def __init__(self, schema: 'SchemaAPI', parent: str):
self.schema = schema
self.parent = parent
self.fields = OrderedDict()
self.field_order = []
self._finished = False
def field(
self,
name: str,
dtype: Literal["str", "list"] = "list",
choices: Optional[List[str]] = None,
description: Optional[str] = None,
threshold: Optional[float] = None,
validators: Optional[List] = None
) -> 'StructureBuilderAPI':
"""Add a field to the structured data."""
# Warn if validators are used (not supported in API mode)
if validators:
warnings.warn(
f"Field '{name}': RegexValidator is not supported in API mode. "
"Validators will be ignored. Use local model for regex-based filtering.",
UserWarning,
stacklevel=2
)
self.fields[name] = {
"dtype": dtype,
"choices": choices,
"description": description,
"threshold": threshold
}
self.field_order.append(name)
return self
def _auto_finish(self):
"""Automatically finish this structure when needed."""
if not self._finished:
# Convert fields to API format
# Use dict format if any field has threshold or choices (advanced features)
# Otherwise use simple string format for backwards compatibility
field_specs = []
for name in self.field_order:
config = self.fields[name]
# Check if advanced features are used
has_threshold = config.get('threshold') is not None
has_choices = config.get('choices') is not None
if has_threshold or has_choices:
# Use dict format for advanced features
field_dict = {"name": name, "dtype": config['dtype']}
if config.get('description'):
field_dict["description"] = config['description']
if has_threshold:
field_dict["threshold"] = config['threshold']
if has_choices:
field_dict["choices"] = config['choices']
field_specs.append(field_dict)
else:
# Use simple string format: "name::type::description"
spec = f"{name}::{config['dtype']}"
if config.get('description'):
spec += f"::{config['description']}"
field_specs.append(spec)
self.schema._structures[self.parent] = field_specs
self._finished = True
def __getattr__(self, name):
"""Auto-finish when any schema method is called."""
if hasattr(self.schema, name):
self._auto_finish()
return getattr(self.schema, name)
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
class SchemaAPI:
"""Schema builder for API-based extraction tasks."""
def __init__(self):
self._entities = None
self._entity_dtype = "list"
self._entity_threshold = None
self._classifications = {}
self._structures = {}
self._relations = None
self._relation_threshold = None
self._active_structure_builder = None
def entities(
self,
entity_types: Union[str, List[str], Dict[str, Union[str, Dict]]],
dtype: Literal["str", "list"] = "list",
threshold: Optional[float] = None
) -> 'SchemaAPI':
"""Add entity extraction task."""
if self._active_structure_builder:
self._active_structure_builder._auto_finish()
self._active_structure_builder = None
# Normalize to list or dict
if isinstance(entity_types, str):
self._entities = [entity_types]
elif isinstance(entity_types, list):
self._entities = entity_types
elif isinstance(entity_types, dict):
self._entities = entity_types
self._entity_dtype = dtype
self._entity_threshold = threshold
return self
def classification(
self,
task: str,
labels: Union[List[str], Dict[str, str]],
multi_label: bool = False,
cls_threshold: float = 0.5,
**kwargs
) -> 'SchemaAPI':
"""Add a text classification task."""
if self._active_structure_builder:
self._active_structure_builder._auto_finish()
self._active_structure_builder = None
# Parse labels
if isinstance(labels, dict):
label_names = list(labels.keys())
else:
label_names = labels
self._classifications[task] = {
"labels": label_names,
"multi_label": multi_label,
"cls_threshold": cls_threshold
}
return self
def structure(self, name: str) -> StructureBuilderAPI:
"""Start building a structured data schema."""
if self._active_structure_builder:
self._active_structure_builder._auto_finish()
self._active_structure_builder = StructureBuilderAPI(self, name)
return self._active_structure_builder
def relations(
self,
relation_types: Union[str, List[str], Dict[str, Union[str, Dict]]],
threshold: Optional[float] = None
) -> 'SchemaAPI':
"""
Add relation extraction task.
Args:
relation_types: Relation types to extract. Can be:
- str: Single relation type
- List[str]: Multiple relation types
- Dict[str, str]: Relation types with descriptions
- Dict[str, Dict]: Relation types with full configuration
threshold: Default confidence threshold for relations.
Returns:
Self for method chaining.
"""
if self._active_structure_builder:
self._active_structure_builder._auto_finish()
self._active_structure_builder = None
# Normalize to list or dict
if isinstance(relation_types, str):
self._relations = [relation_types]
elif isinstance(relation_types, list):
self._relations = relation_types
elif isinstance(relation_types, dict):
self._relations = relation_types
self._relation_threshold = threshold
return self
def build(self) -> Dict[str, Any]:
"""Build the schema for API request."""
if self._active_structure_builder:
self._active_structure_builder._auto_finish()
self._active_structure_builder = None
schema = {}
if self._entities is not None:
schema["entities"] = self._entities
schema["entity_dtype"] = self._entity_dtype
if self._entity_threshold is not None:
schema["entity_threshold"] = self._entity_threshold
if self._classifications:
schema["classifications"] = self._classifications
if self._structures:
schema["structures"] = self._structures
if self._relations is not None:
schema["relations"] = self._relations
if self._relation_threshold is not None:
schema["relation_threshold"] = self._relation_threshold
return schema
class GLiNER2API:
"""
API-based GLiNER2 client that mirrors the local model interface.
This class provides the same methods as GLiNER2 but makes HTTP requests
to the API endpoint instead of running local inference.
Attributes:
api_key: API authentication key
base_url: API base URL
timeout: Request timeout in seconds
max_retries: Maximum number of retries for failed requests
"""
DEFAULT_BASE_URL = "https://api.fastino.ai"
def __init__(
self,
api_key: Optional[str] = None,
api_base_url: Optional[str] = None,
timeout: float = 30.0,
max_retries: int = 3,
):
"""
Initialize the GLiNER2 API client.
Args:
api_key: API authentication key. If not provided, reads from
FASTINO_API_KEY environment variable.
api_base_url: Override the default API base URL.
timeout: Request timeout in seconds.
max_retries: Maximum number of retries for failed requests.
Raises:
ValueError: If no API key is provided and FASTINO_API_KEY is not set.
"""
# Read API key from environment if not provided
if api_key is None:
api_key = os.environ.get("FASTINO_API_KEY")
if api_key is None:
raise ValueError(
"API key must be provided either as an argument or via "
"FASTINO_API_KEY environment variable"
)
self.api_key = api_key
self.base_url = api_base_url or os.environ.get(
"GLINER2_API_BASE_URL", self.DEFAULT_BASE_URL
)
self.timeout = timeout
self.max_retries = max_retries
# Setup HTTP session with retry logic
self.session = requests.Session()
self.session.headers.update({
"X-API-Key": api_key,
"Content-Type": "application/json",
})
# Configure retry strategy
retry_strategy = Retry(
total=max_retries,
backoff_factor=1, # 1s, 2s, 4s backoff
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["POST"],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.session.mount("https://", adapter)
self.session.mount("http://", adapter)
logger.debug(f"Initialized GLiNER2API for {self.base_url}")
@staticmethod
def _safe_json(response: requests.Response) -> Optional[Dict[str, Any]]:
"""Parse response JSON safely, returning None for empty/invalid payloads."""
if not response.content:
return None
try:
data = response.json()
except ValueError:
logger.debug(
"Response body was not valid JSON (status=%s)",
response.status_code,
)
return None
return data if isinstance(data, dict) else None
def _make_request(
self,
task: str,
text: Union[str, List[str]],
schema: Union[List[str], Dict],
threshold: float = 0.5,
include_confidence: bool = False,
include_spans: bool = False,
format_results: bool = True,
) -> Dict[str, Any]:
"""
Make an HTTP request to the GLiNER-2 API.
Args:
task: Task type (extract_entities, classify_text, extract_json, schema)
text: Text to process (string or list for batch)
schema: Schema for extraction
threshold: Confidence threshold
include_confidence: Whether to include confidence scores in results
include_spans: Whether to include character-level start/end positions
format_results: Whether to format results (False for raw extraction data)
Returns:
API response result
Raises:
GLiNER2APIError: If request fails
"""
# Ensure base_url ends with / for proper joining
base = self.base_url.rstrip('/') + '/'
url = urljoin(base, "gliner-2")
payload = {
"task": task,
"text": text,
"schema": schema,
"threshold": threshold,
"include_confidence": include_confidence,
"include_spans": include_spans,
"format_results": format_results,
}
logger.debug(f"Making POST request to {url}")
try:
response = self.session.post(
url,
json=payload,
timeout=self.timeout,
)
logger.debug(f"Response status: {response.status_code}")
# Handle different error codes
if response.status_code == 401:
error_data = self._safe_json(response)
error_msg = (
error_data.get("detail", "Invalid or expired API key")
if error_data else "Invalid or expired API key"
)
raise AuthenticationError(
error_msg,
status_code=response.status_code,
response_data=error_data,
)
elif response.status_code in (400, 422):
error_data = self._safe_json(response)
error_msg = (
error_data.get("detail", "Request validation failed")
if error_data else "Request validation failed"
)
raise ValidationError(
error_msg,
status_code=response.status_code,
response_data=error_data,
)
elif response.status_code >= 500:
error_data = self._safe_json(response)
error_msg = (
error_data.get("detail", "Server error occurred")
if error_data else "Server error occurred"
)
raise ServerError(
error_msg,
status_code=response.status_code,
response_data=error_data,
)
elif not response.ok:
error_data = self._safe_json(response)
error_msg = (
error_data.get("detail", f"Request failed with status {response.status_code}")
if error_data else f"Request failed with status {response.status_code}"
)
raise GLiNER2APIError(
error_msg,
status_code=response.status_code,
response_data=error_data,
)
if not response.content:
raise GLiNER2APIError(
"Empty response body from API",
status_code=response.status_code,
)
try:
data = response.json()
except ValueError as e:
raise GLiNER2APIError(
"Invalid JSON response from API",
status_code=response.status_code,
) from e
return data.get("result", data)
except requests.exceptions.Timeout:
raise GLiNER2APIError(f"Request timed out after {self.timeout}s")
except requests.exceptions.ConnectionError as e:
raise GLiNER2APIError(f"Connection error: {str(e)}")
except requests.exceptions.RequestException as e:
raise GLiNER2APIError(f"Request failed: {str(e)}")
def create_schema(self) -> SchemaAPI:
"""Create a new schema for defining extraction tasks."""
return SchemaAPI()
# Shared request plumbing -------------------------------------------------
def _task_call(self, task, text, schema, threshold, format_results,
include_confidence, include_spans):
"""Dispatch a task through the shared HTTP request implementation."""
return self._make_request(
task=task,
text=text,
schema=schema,
threshold=threshold,
include_confidence=include_confidence,
include_spans=include_spans,
format_results=format_results,
)
@staticmethod
def _validate_batch_size(batch_size: int) -> None:
if not isinstance(batch_size, int) or isinstance(batch_size, bool):
raise TypeError("batch_size must be an integer")
if batch_size <= 0:
raise ValueError("batch_size must be greater than 0")
@staticmethod
def _coerce_batch_result(result: Any, expected: int) -> List[Any]:
"""Validate one server reply against its client-side partition."""
if isinstance(result, list):
if len(result) != expected:
raise GLiNER2APIError(
"API returned "
f"{len(result)} results for a partition of {expected} texts"
)
return result
if expected == 1:
return [result]
raise GLiNER2APIError(
"API returned a non-list result for a partition of "
f"{expected} texts"
)
@staticmethod
def _mark_partial_failure(
error: GLiNER2APIError,
partial_results: List[Any],
start: int,
end: int,
) -> None:
error.partial_results = list(partial_results)
error.failed_range = (start, end)
def _partitioned_task_call(
self,
task: str,
texts: List[str],
schema: Union[List[str], Dict],
batch_size: int,
threshold: float,
format_results: bool,
include_confidence: bool,
include_spans: bool,
) -> List[Any]:
"""Send ordered client-side partitions without changing wire fields."""
if not texts:
return []
self._validate_batch_size(batch_size)
results: List[Any] = []
for start in range(0, len(texts), batch_size):
end = min(start + batch_size, len(texts))
partition = texts[start:end]
try:
response = self._task_call(
task,
partition,
schema,
threshold,
format_results,
include_confidence,
include_spans,
)
results.extend(
self._coerce_batch_result(response, len(partition))
)
except GLiNER2APIError as error:
self._mark_partial_failure(error, results, start, end)
raise
return results
@staticmethod
def _entity_schema(entity_types):
"""Normalize entity descriptions to the established wire schema."""
return list(entity_types.keys()) if isinstance(entity_types, dict) else entity_types
# Entity Extraction Methods ----------------------------------------------
def extract_entities(
self,
text: str,
entity_types: Union[List[str], Dict[str, Union[str, Dict]]],
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> Dict[str, Any]:
"""Extract entities from text."""
result = self._task_call(
"extract_entities", text, self._entity_schema(entity_types),
threshold, format_results, include_confidence, include_spans,
)
if format_results and isinstance(result, dict) and "entities" not in result:
return {"entities": result}
return result
def batch_extract_entities(
self,
texts: List[str],
entity_types: Union[List[str], Dict[str, Union[str, Dict]]],
batch_size: int = 8,
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> List[Dict[str, Any]]:
"""Batch extract entities from multiple texts."""
return self._partitioned_task_call(
"extract_entities",
texts,
self._entity_schema(entity_types),
batch_size,
threshold,
format_results,
include_confidence,
include_spans,
)
def extract_entities_long(
self,
text: str,
entity_types: Union[List[str], Dict[str, Union[str, Dict]]],
threshold: float = 0.5,
chunk_size: int = 384,
chunk_overlap: int = 64,
batch_size: int = 8,
num_workers: int = 0,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False,
overlap_policy: Optional[str] = None,
) -> Dict[str, Any]:
"""Extract entities from a long document using local chunk merging."""
return self.batch_extract_entities_long(
[text],
entity_types,
batch_size=batch_size,
threshold=threshold,
num_workers=num_workers,
format_results=format_results,
include_confidence=include_confidence,
include_spans=include_spans,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
overlap_policy=overlap_policy,
)[0]
def batch_extract_entities_long(
self,
texts: List[str],
entity_types: Union[List[str], Dict[str, Union[str, Dict]]],
batch_size: int = 8,
threshold: float = 0.5,
num_workers: int = 0,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False,
chunk_size: int = 384,
chunk_overlap: int = 64,
overlap_policy: Optional[str] = None,
) -> List[Dict[str, Any]]:
if not format_results:
raise ValueError(
"batch_extract_entities_long currently requires format_results=True"
)
if not texts:
return []
self._validate_batch_size(batch_size)
if num_workers:
warnings.warn(
"num_workers is ignored by the synchronous API client",
UserWarning,
stacklevel=2,
)
def request(chunk_texts, _):
return self.batch_extract_entities(
chunk_texts,
entity_types,
batch_size=batch_size,
threshold=threshold,
format_results=True,
include_confidence=True,
include_spans=True,
)
return self._run_long_batch(
texts,
request,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
include_confidence=include_confidence,
include_spans=include_spans,
overlap_policy=overlap_policy,
normalize_result=self._normalize_entity_chunk_result,
)
# Text Classification Methods --------------------------------------------
def classify_text(
self,
text: str,
tasks: Dict[str, Union[List[str], Dict[str, Any]]],
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> Dict[str, Any]:
"""Classify text into categories."""
if len(tasks) == 1:
task_name = next(iter(tasks))
task_config = tasks[task_name]
categories = task_config["labels"] if (
isinstance(task_config, dict) and "labels" in task_config
) else task_config
result = self._task_call(
"classify_text", text, {"categories": categories},
threshold, format_results, include_confidence, include_spans,
)
if format_results and isinstance(result, dict) and task_name not in result:
return {task_name: result.get("classification", result)}
return result
return self._task_call(
"schema", text, {"classifications": tasks},
threshold, format_results, include_confidence, include_spans,
)
def batch_classify_text(
self,
texts: List[str],
tasks: Dict[str, Union[List[str], Dict[str, Any]]],
batch_size: int = 8,
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> List[Dict[str, Any]]:
"""Batch classify multiple texts."""
return self._partitioned_task_call(
"schema",
texts,
{"classifications": tasks},
batch_size,
threshold,
format_results,
include_confidence,
include_spans,
)
def classify_text_long(
self,
text: str,
tasks: Dict[str, Union[List[str], Dict[str, Any]]],
threshold: float = 0.5,
chunk_size: int = 384,
chunk_overlap: int = 64,
batch_size: int = 8,
num_workers: int = 0,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False,
overlap_policy: Optional[str] = None,
) -> Dict[str, Any]:
return self.batch_classify_text_long(
[text],
tasks,
batch_size=batch_size,
threshold=threshold,
num_workers=num_workers,
format_results=format_results,
include_confidence=include_confidence,
include_spans=include_spans,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
overlap_policy=overlap_policy,
)[0]
def batch_classify_text_long(
self,
texts: List[str],
tasks: Dict[str, Union[List[str], Dict[str, Any]]],
batch_size: int = 8,
threshold: float = 0.5,
num_workers: int = 0,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False,
chunk_size: int = 384,
chunk_overlap: int = 64,
overlap_policy: Optional[str] = None,
) -> List[Dict[str, Any]]:
if not format_results:
raise ValueError(
"batch_classify_text_long currently requires format_results=True"
)
if not texts:
return []
self._validate_batch_size(batch_size)
if num_workers:
warnings.warn(
"num_workers is ignored by the synchronous API client",
UserWarning,
stacklevel=2,
)
def request(chunk_texts, _):
return self.batch_classify_text(
chunk_texts,
tasks,
batch_size=batch_size,
threshold=threshold,
format_results=True,
include_confidence=True,
include_spans=True,
)
return self._run_long_batch(
texts,
request,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
include_confidence=include_confidence,
include_spans=include_spans,
overlap_policy=overlap_policy,
)
# JSON Extraction Methods -------------------------------------------------
def extract_json(
self,
text: str,
structures: Dict[str, List[str]],
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> Dict[str, Any]:
"""Extract structured data from text."""
return self._task_call(
"extract_json", text, structures,
threshold, format_results, include_confidence, include_spans,
)
def batch_extract_json(
self,
texts: List[str],
structures: Dict[str, List[str]],
batch_size: int = 8,
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> List[Dict[str, Any]]:
"""Batch extract structured data from multiple texts."""
return self._partitioned_task_call(
"extract_json",
texts,
structures,
batch_size,
threshold,
format_results,
include_confidence,
include_spans,
)
def extract_json_long(
self,
text: str,
structures: Dict[str, List[str]],
threshold: float = 0.5,
chunk_size: int = 384,
chunk_overlap: int = 64,
batch_size: int = 8,
num_workers: int = 0,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False,
overlap_policy: Optional[str] = None,
) -> Dict[str, Any]:
return self.batch_extract_json_long(
[text],
structures,
batch_size=batch_size,
threshold=threshold,
num_workers=num_workers,
format_results=format_results,
include_confidence=include_confidence,
include_spans=include_spans,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
overlap_policy=overlap_policy,
)[0]
def batch_extract_json_long(
self,
texts: List[str],
structures: Dict[str, List[str]],
batch_size: int = 8,
threshold: float = 0.5,
num_workers: int = 0,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False,
chunk_size: int = 384,
chunk_overlap: int = 64,
overlap_policy: Optional[str] = None,
) -> List[Dict[str, Any]]:
if not format_results:
raise ValueError(
"batch_extract_json_long currently requires format_results=True"
)
if not texts:
return []
self._validate_batch_size(batch_size)
if num_workers:
warnings.warn(
"num_workers is ignored by the synchronous API client",
UserWarning,
stacklevel=2,
)
def request(chunk_texts, _):
return self.batch_extract_json(
chunk_texts,
structures,
batch_size=batch_size,
threshold=threshold,
format_results=True,
include_confidence=True,
include_spans=True,
)
return self._run_long_batch(
texts,
request,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
include_confidence=include_confidence,
include_spans=include_spans,
overlap_policy=overlap_policy,
)
# Relation Extraction Methods --------------------------------------------
def extract_relations(
self,
text: str,
relation_types: Union[str, List[str], Dict[str, Union[str, Dict]]],
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> Dict[str, Any]:
"""Extract relations between entities from text."""
schema = self.create_schema().relations(relation_types).build()
return self._task_call(
"schema", text, schema,
threshold, format_results, include_confidence, include_spans,
)
def batch_extract_relations(
self,
texts: List[str],
relation_types: Union[str, List[str], Dict[str, Union[str, Dict]]],
batch_size: int = 8,
threshold: float = 0.5,
format_results: bool = True,
include_confidence: bool = False,
include_spans: bool = False
) -> List[Dict[str, Any]]:
"""Batch extract relations from multiple texts."""
schema = self.create_schema().relations(relation_types).build()
return self._partitioned_task_call(
"schema",
texts,
schema,
batch_size,
threshold,
format_results,
include_confidence,
include_spans,
)
def extract_relations_long(
self,
text: str,