-
Notifications
You must be signed in to change notification settings - Fork 632
Expand file tree
/
Copy pathlegacy_executor.py
More file actions
2410 lines (2198 loc) · 95.6 KB
/
Copy pathlegacy_executor.py
File metadata and controls
2410 lines (2198 loc) · 95.6 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
"""Legacy executor — wraps the full prompt-service extraction pipeline.
Routes ``ExecutionContext`` requests to handler methods for text
extraction, indexing, retrieval, prompt answering, single-pass
extraction, summarisation, and usage tracking.
"""
import logging
import time
from pathlib import Path
from typing import Any
from executor.executor_tool_shim import ExecutorToolShim
from executor.executors.constants import ExecutionSource
from executor.executors.constants import IndexingConstants as IKeys
from executor.executors.constants import PromptServiceConstants as PSKeys
from executor.executors.dto import (
ChunkingConfig,
FileInfo,
InstanceIdentifiers,
ProcessingOptions,
)
from executor.executors.exceptions import ExtractionError, LegacyExecutorError
from executor.executors.file_utils import FileUtils
from executor.executors.lookup_enrichment import (
run_lookup_enrichment,
run_webhook_postprocessing,
)
from unstract.sdk1.adapters.exceptions import AdapterError
from unstract.sdk1.adapters.x2text.constants import X2TextConstants
from unstract.sdk1.adapters.x2text.llm_whisperer.src import LLMWhisperer
from unstract.sdk1.adapters.x2text.llm_whisperer_v2.src import LLMWhispererV2
from unstract.sdk1.constants import LogLevel
from unstract.sdk1.execution.context import ExecutionContext, Operation
from unstract.sdk1.execution.executor import BaseExecutor
from unstract.sdk1.execution.registry import ExecutorRegistry
from unstract.sdk1.execution.result import ExecutionResult
from unstract.sdk1.utils.tool import ToolUtils
from unstract.sdk1.x2txt import TextExtractionResult, X2Text
logger = logging.getLogger(__name__)
@ExecutorRegistry.register
class LegacyExecutor(BaseExecutor):
"""Executor that wraps the full prompt-service extraction pipeline.
Routes incoming ``ExecutionContext`` requests to the appropriate
handler method based on the ``Operation`` enum. Each handler
corresponds to one of the original prompt-service HTTP endpoints.
"""
# Maps Operation enum values to handler method names.
_OPERATION_MAP: dict[str, str] = {
Operation.EXTRACT.value: "_handle_extract",
Operation.INDEX.value: "_handle_index",
Operation.ANSWER_PROMPT.value: "_handle_answer_prompt",
Operation.SINGLE_PASS_EXTRACTION.value: "_handle_single_pass_extraction",
Operation.SUMMARIZE.value: "_handle_summarize",
Operation.IDE_INDEX.value: "_handle_ide_index",
Operation.STRUCTURE_PIPELINE.value: "_handle_structure_pipeline",
}
def __init__(self) -> None:
self._log_events_id: str = ""
self._log_component: dict[str, str] = {}
self._execution_id: str | None = None
self._file_execution_id: str | None = None
self._organization_id: str | None = None
@property
def name(self) -> str:
return "legacy"
def execute(self, context: ExecutionContext) -> ExecutionResult:
"""Route to the handler for ``context.operation``.
Returns:
``ExecutionResult`` on success or for unsupported operations.
``LegacyExecutorError`` subclasses are caught and mapped to
``ExecutionResult.failure()`` so callers always get a result.
Raises:
NotImplementedError: From stub handlers (until 2D–2H).
"""
# Extract log streaming info (set by tasks.py for IDE sessions).
self._log_events_id: str = context.log_events_id or ""
self._log_component: dict[str, str] = (
getattr(context, "_log_component", None) or {}
)
self._execution_id = context.execution_id
self._file_execution_id = context.file_execution_id
self._organization_id = context.organization_id
if (
context.execution_source == "tool"
and self._log_events_id
and not (self._execution_id and self._organization_id)
):
logger.warning(
"Workflow IDs missing on tool context run_id=%s — tool-level "
"logs will reach the UI but won't persist to execution_log.",
context.run_id,
)
handler_name = self._OPERATION_MAP.get(context.operation)
if handler_name is None:
return ExecutionResult.failure(
error=(f"LegacyExecutor does not support operation '{context.operation}'")
)
handler = getattr(self, handler_name)
logger.info(
"LegacyExecutor routing operation=%s to %s "
"(run_id=%s request_id=%s execution_source=%s)",
context.operation,
handler_name,
context.run_id,
context.request_id,
context.execution_source,
)
start = time.monotonic()
try:
result = handler(context)
elapsed = time.monotonic() - start
logger.info(
"Handler %s completed in %.2fs (run_id=%s success=%s)",
handler_name,
elapsed,
context.run_id,
result.success,
)
return result
except LegacyExecutorError as exc:
elapsed = time.monotonic() - start
logger.warning(
"Handler %s failed after %.2fs: %s: %s",
handler_name,
elapsed,
type(exc).__name__,
exc.message,
exc_info=True,
)
# Stream error to FE so the user sees the failure in real-time
if self._log_events_id:
try:
shim = self._build_shim()
shim.stream_log(
f"Error: {exc.message or type(exc).__name__}",
level=LogLevel.ERROR,
)
except Exception:
# Don't mask the original error; log the secondary at DEBUG.
logger.debug(
"Failed to stream error to FE for run_id=%s",
context.run_id,
exc_info=True,
)
# Preserve partial usage rows from a mid-pipeline failure.
failure_metadata: dict[str, Any] = {}
if exc.partial_usage_records:
failure_metadata["usage_records"] = list(exc.partial_usage_records)
return ExecutionResult.failure(error=exc.message, metadata=failure_metadata)
def _build_shim(
self,
*,
platform_api_key: str = "",
component: dict[str, str] | None = None,
) -> ExecutorToolShim:
"""Construct an ``ExecutorToolShim`` pre-populated with the
log-streaming and workflow-attribution fields captured in
``execute()``. Callers override ``platform_api_key`` and
``component`` as needed; everything else is shared.
"""
return ExecutorToolShim(
platform_api_key=platform_api_key,
log_events_id=self._log_events_id,
component=self._log_component if component is None else component,
execution_id=self._execution_id,
organization_id=self._organization_id,
file_execution_id=self._file_execution_id,
)
# ------------------------------------------------------------------
# Phase 2B — Extract handler
# ------------------------------------------------------------------
def _handle_extract(self, context: ExecutionContext) -> ExecutionResult:
"""Handle ``Operation.EXTRACT`` — text extraction via x2text.
Migrated from ``ExtractionService.perform_extraction()`` in
``prompt-service/.../services/extraction.py``.
Returns:
ExecutionResult with ``data`` containing ``extracted_text``.
"""
params: dict[str, Any] = context.executor_params
# Required params
x2text_instance_id: str = params.get(IKeys.X2TEXT_INSTANCE_ID, "")
file_path: str = params.get(IKeys.FILE_PATH, "")
platform_api_key: str = params.get("platform_api_key", "")
if not x2text_instance_id or not file_path:
missing = []
if not x2text_instance_id:
missing.append(IKeys.X2TEXT_INSTANCE_ID)
if not file_path:
missing.append(IKeys.FILE_PATH)
return ExecutionResult.failure(
error=f"Missing required params: {', '.join(missing)}"
)
# Optional params
output_file_path: str | None = params.get(IKeys.OUTPUT_FILE_PATH)
enable_highlight: bool = params.get(IKeys.ENABLE_HIGHLIGHT, False)
usage_kwargs: dict[Any, Any] = params.get(IKeys.USAGE_KWARGS, {})
tags: list[str] | None = params.get(IKeys.TAGS)
execution_source: str = context.execution_source
tool_exec_metadata: dict[str, Any] = params.get(IKeys.TOOL_EXECUTION_METATADA, {})
execution_data_dir: str | None = params.get(IKeys.EXECUTION_DATA_DIR)
# Build adapter shim and X2Text
shim = self._build_shim(platform_api_key=platform_api_key)
x2text = X2Text(
tool=shim,
adapter_instance_id=x2text_instance_id,
usage_kwargs=usage_kwargs,
)
fs = FileUtils.get_fs_instance(execution_source=execution_source)
logger.info(
"Starting text extraction: x2text_adapter=%s file=%s run_id=%s",
x2text_instance_id,
Path(file_path).name,
context.run_id,
)
logger.debug(
"HIGHLIGHT_DEBUG _handle_extract: enable_highlight=%s x2text_type=%s file=%s run_id=%s",
enable_highlight,
type(x2text.x2text_instance).__name__,
Path(file_path).name,
context.run_id,
)
extractor_name = type(x2text.x2text_instance).__name__
try:
shim.stream_log(
f"Extracting text using `{extractor_name}`"
+ (" (with highlight)" if enable_highlight else "")
)
if enable_highlight and isinstance(
x2text.x2text_instance, (LLMWhisperer, LLMWhispererV2)
):
process_response: TextExtractionResult = x2text.process(
input_file_path=file_path,
output_file_path=output_file_path,
enable_highlight=enable_highlight,
tags=tags,
fs=fs,
)
self._update_exec_metadata(
fs=fs,
execution_source=execution_source,
tool_exec_metadata=tool_exec_metadata,
execution_data_dir=execution_data_dir,
process_response=process_response,
)
else:
process_response = x2text.process(
input_file_path=file_path,
output_file_path=output_file_path,
tags=tags,
fs=fs,
)
has_metadata = bool(
process_response.extraction_metadata
and process_response.extraction_metadata.line_metadata
)
logger.debug(
"HIGHLIGHT_DEBUG extraction result: has_line_metadata=%s "
"whisper_hash=%s run_id=%s",
has_metadata,
getattr(process_response.extraction_metadata, "whisper_hash", None)
if process_response.extraction_metadata
else None,
context.run_id,
)
logger.info(
"Text extraction completed: file=%s run_id=%s",
Path(file_path).name,
context.run_id,
)
shim.stream_log("Text extraction completed")
result_data: dict[str, Any] = {
IKeys.EXTRACTED_TEXT: process_response.extracted_text,
}
# Include highlight metadata when available
# (used by agentic extraction for PDF source referencing)
if (
process_response.extraction_metadata
and process_response.extraction_metadata.line_metadata
):
result_data["highlight_metadata"] = (
process_response.extraction_metadata.line_metadata
)
return ExecutionResult(
success=True,
data=result_data,
)
except AdapterError as e:
name = x2text.x2text_instance.get_name()
logger.error(
"Text extraction failed: adapter=%s file=%s error=%s",
name,
Path(file_path).name,
str(e),
)
msg = f"Error from text extractor '{name}'. {e}"
raise ExtractionError(message=msg) from e
@staticmethod
def _update_exec_metadata(
fs: Any,
execution_source: str,
tool_exec_metadata: dict[str, Any] | None,
execution_data_dir: str | None,
process_response: TextExtractionResult,
) -> None:
"""Write whisper_hash metadata for tool-sourced executions."""
if execution_source != ExecutionSource.TOOL.value:
return
whisper_hash = process_response.extraction_metadata.whisper_hash
metadata = {X2TextConstants.WHISPER_HASH: whisper_hash}
if tool_exec_metadata is not None:
for key, value in metadata.items():
tool_exec_metadata[key] = value
metadata_path = str(Path(execution_data_dir) / IKeys.METADATA_FILE)
ToolUtils.dump_json(
file_to_dump=metadata_path,
json_to_dump=metadata,
fs=fs,
)
@staticmethod
def _get_indexing_deps():
"""Lazy-import heavy indexing dependencies.
These imports trigger llama_index/qdrant/protobuf loading,
so they must not happen at module-collection time (tests).
Wrapped in a method so tests can mock it cleanly.
"""
from executor.executors.index import Index
from unstract.sdk1.embedding import EmbeddingCompat
from unstract.sdk1.vector_db import VectorDB
return Index, EmbeddingCompat, VectorDB
def _run_summarize_step(
self, summarize_params: dict, context: ExecutionContext
) -> ExecutionResult:
"""Run summarization if not already cached.
Cache hit returns success with empty metadata (no LLM call).
"""
extract_file_path = summarize_params.get("extract_file_path", "")
summarize_file_path = summarize_params.get("summarize_file_path", "")
platform_api_key = summarize_params.get("platform_api_key", "")
llm_adapter_id = summarize_params.get("llm_adapter_instance_id", "")
summarize_prompt = summarize_params.get("summarize_prompt", "")
prompt_keys = summarize_params.get("prompt_keys", [])
fs = FileUtils.get_fs_instance(execution_source=context.execution_source)
# Check cache — skip if summary already exists
if fs.exists(summarize_file_path):
existing = fs.read(path=summarize_file_path, mode="r")
if existing:
return ExecutionResult(success=True, data={})
doc_context = fs.read(path=extract_file_path, mode="r")
if not doc_context:
return ExecutionResult.failure(
error="No extracted text found for summarization"
)
summarize_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=Operation.SUMMARIZE.value,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
executor_params={
"llm_adapter_instance_id": llm_adapter_id,
"summarize_prompt": summarize_prompt,
"context": doc_context,
"prompt_keys": prompt_keys,
"PLATFORM_SERVICE_API_KEY": platform_api_key,
},
)
summarize_result = self._handle_summarize(summarize_ctx)
if not summarize_result.success:
return summarize_result
summarize_dir = str(Path(summarize_file_path).parent)
fs.mkdir(summarize_dir, create_parents=True)
fs.write(
path=summarize_file_path,
mode="w",
data=summarize_result.data.get("data", ""),
)
return ExecutionResult(
success=True, data={}, metadata=dict(summarize_result.metadata or {})
)
# ------------------------------------------------------------------
# Phase 5C — Compound IDE index handler (extract + index)
# ------------------------------------------------------------------
def _handle_ide_index(self, context: ExecutionContext) -> ExecutionResult:
"""Handle ``Operation.IDE_INDEX`` — compound extract then index.
This compound operation combines ``_handle_extract`` and
``_handle_index`` in a single executor invocation, eliminating
the need for the backend Celery worker to block between steps.
The ``executor_params`` must contain:
- ``extract_params``: Parameters for ``_handle_extract``.
- ``index_params``: Parameters for ``_handle_index``. The
executor injects ``extracted_text`` from the extract step
before calling index.
Returns:
ExecutionResult with ``data`` containing ``doc_id`` from
the index step.
"""
params = context.executor_params
extract_params = params.get("extract_params")
index_params = params.get("index_params")
if not extract_params or not index_params:
missing = []
if not extract_params:
missing.append("extract_params")
if not index_params:
missing.append("index_params")
return ExecutionResult.failure(
error=f"ide_index missing required params: {', '.join(missing)}"
)
ide_records: list[dict[str, Any]] = []
def _absorb(child: ExecutionResult) -> None:
child_records = (child.metadata or {}).get("usage_records") or []
if child_records:
ide_records.extend(child_records)
def _failure(child: ExecutionResult) -> ExecutionResult:
metadata = dict(child.metadata or {})
existing = metadata.get("usage_records") or []
metadata["usage_records"] = ide_records + list(existing)
return ExecutionResult.failure(error=child.error, metadata=metadata)
try:
# Step 1: Extract (or reuse pre-extracted text on marker hit)
pre_extracted_text = index_params.get(IKeys.EXTRACTED_TEXT, "") or ""
if pre_extracted_text:
logger.info(
"ide_index: marker hit, skipping extract step (len=%d, run_id=%s)",
len(pre_extracted_text),
context.run_id,
)
extracted_text = pre_extracted_text
else:
extract_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=Operation.EXTRACT.value,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
executor_params=extract_params,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
)
extract_result = self._handle_extract(extract_ctx)
if not extract_result.success:
return _failure(extract_result)
_absorb(extract_result)
extracted_text = extract_result.data.get(IKeys.EXTRACTED_TEXT, "")
# Step 2: Optional summarize
summarize_params = params.get("summarize_params")
summarize_file_path = ""
if summarize_params:
summarize_file_path = summarize_params.get("summarize_file_path", "")
summarize_result = self._run_summarize_step(summarize_params, context)
if not summarize_result.success:
return _failure(summarize_result)
_absorb(summarize_result)
# Step 3: Index — inject extracted text
index_params[IKeys.EXTRACTED_TEXT] = extracted_text
index_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=Operation.INDEX.value,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
executor_params=index_params,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
)
index_result = self._handle_index(index_ctx)
if not index_result.success:
return _failure(index_result)
_absorb(index_result)
except LegacyExecutorError as e:
e.partial_usage_records = ide_records + e.partial_usage_records
raise
return ExecutionResult(
success=True,
data={
IKeys.DOC_ID: index_result.data.get(IKeys.DOC_ID, ""),
"summarize_file_path": summarize_file_path,
},
metadata={"usage_records": ide_records},
)
# ------------------------------------------------------------------
# Phase 5D — Compound structure pipeline handler
# ------------------------------------------------------------------
def _handle_structure_pipeline(self, context: ExecutionContext) -> ExecutionResult:
"""Handle ``Operation.STRUCTURE_PIPELINE``.
Runs the full structure-tool pipeline in a single executor
invocation: extract → summarize → index → answer_prompt.
This eliminates three sequential ``dispatcher.dispatch()`` calls
that would otherwise block a file_processing worker slot.
Expected ``executor_params`` keys:
``extract_params``
Parameters for ``_handle_extract``.
``index_template``
Common indexing params (``tool_id``, ``file_hash``,
``is_highlight_enabled``, ``platform_api_key``,
``extracted_file_path``).
``answer_params``
Full payload for ``_handle_answer_prompt`` /
``_handle_single_pass_extraction``.
``pipeline_options``
Control flags: ``skip_extraction_and_indexing``,
``is_summarization_enabled``, ``is_single_pass_enabled``,
``input_file_path``, ``source_file_name``.
``summarize_params``
(Optional) Parameters for ``_handle_summarize`` plus
filesystem paths for caching.
Returns:
ExecutionResult with ``data`` containing the structured
output dict (``output``, ``metadata``, ``metrics``).
"""
params = context.executor_params
extract_params = params.get("extract_params", {})
index_template = params.get("index_template", {})
answer_params = params.get("answer_params", {})
pipeline_options = params.get("pipeline_options", {})
summarize_params = params.get("summarize_params")
skip_extraction = pipeline_options.get("skip_extraction_and_indexing", False)
is_summarization = pipeline_options.get("is_summarization_enabled", False)
is_single_pass = pipeline_options.get("is_single_pass_enabled", False)
input_file_path = pipeline_options.get("input_file_path", "")
source_file_name = pipeline_options.get("source_file_name", "")
extracted_text = ""
index_metrics: dict = {}
pipeline_records: list[dict[str, Any]] = []
def _absorb(child_result: ExecutionResult) -> None:
child_records = (child_result.metadata or {}).get("usage_records") or []
if child_records:
pipeline_records.extend(child_records)
def _failure(child_result: ExecutionResult) -> ExecutionResult:
metadata = dict(child_result.metadata or {})
existing = metadata.get("usage_records") or []
metadata["usage_records"] = pipeline_records + list(existing)
return ExecutionResult.failure(error=child_result.error, metadata=metadata)
shim = self._build_shim(
platform_api_key=extract_params.get("platform_api_key", ""),
)
# One-shot run-config line — non-sensitive flags only; adapter
# identities are emitted inline on first use with full model info.
tool_settings = answer_params.get(PSKeys.TOOL_SETTINGS, {})
outputs = answer_params.get(PSKeys.OUTPUTS, [])
shim.stream_log(
f"Run config: prompts={len(outputs)} | "
f"single_pass={'on' if is_single_pass else 'off'} | "
f"summarize={'on' if is_summarization else 'off'} | "
f"challenge="
f"{'on' if tool_settings.get(PSKeys.ENABLE_CHALLENGE) else 'off'}"
)
step = 1
try:
# ---- Step 1: Extract ----
if not skip_extraction:
step += 1
extract_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=Operation.EXTRACT.value,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
executor_params=extract_params,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
)
extract_result = self._handle_extract(extract_ctx)
if not extract_result.success:
return _failure(extract_result)
_absorb(extract_result)
extracted_text = extract_result.data.get(IKeys.EXTRACTED_TEXT, "")
# ---- Step 2: Summarize (if enabled) ----
if is_summarization:
step += 1
summarize_result = self._run_pipeline_summarize(
context=context,
summarize_params=summarize_params or {},
answer_params=answer_params,
)
if not summarize_result.success:
return _failure(summarize_result)
_absorb(summarize_result)
# answer_params file_path/hash updated in-place by helper
elif skip_extraction:
# Smart table: use original source file
answer_params["file_path"] = input_file_path
elif not is_single_pass:
# ---- Step 3: Index per output with dedup ----
step += 1
index_metrics, index_records = self._run_pipeline_index(
context=context,
index_template=index_template,
answer_params=answer_params,
extracted_text=extracted_text,
usage_kwargs=extract_params.get("usage_kwargs", {}),
)
if index_records:
pipeline_records.extend(index_records)
# ---- Step 4: Table settings injection ----
if not is_single_pass:
self._inject_table_settings(
answer_params=answer_params,
index_template=index_template,
skip_extraction=skip_extraction,
input_file_path=input_file_path,
)
# ---- Step 5: Answer prompt / Single pass ----
answer_result = self._run_pipeline_answer_step(
context=context,
answer_params=answer_params,
is_single_pass=is_single_pass,
shim=shim,
step=step,
)
if not answer_result.success:
return _failure(answer_result)
_absorb(answer_result)
except LegacyExecutorError as e:
e.partial_usage_records = pipeline_records + e.partial_usage_records
raise
# ---- Step 6: Merge results ----
structured_output = answer_result.data
self._finalize_pipeline_result(
structured_output=structured_output,
source_file_name=source_file_name,
extracted_text=extracted_text,
index_metrics=index_metrics,
)
output_map = structured_output.get(PSKeys.OUTPUT, {}) or {}
if not isinstance(output_map, dict):
# Single-pass can return a non-dict (e.g. a top-level JSON array) when the
# LLM emits a truncated/runaway response. Fail clearly instead of crashing
# on .values(), and keep the malformed shape from flowing downstream as a
# success.
return ExecutionResult.failure(
error=(
f"Single-pass extraction returned a {type(output_map).__name__}, "
"expected a field map; the LLM likely produced a truncated or "
"runaway response (check output-token usage)."
),
metadata={"usage_records": pipeline_records},
)
answered = sum(1 for v in output_map.values() if v not in (None, "", [], {}))
shim.stream_log(f"Pipeline completed: {answered}/{len(outputs)} prompts answered")
out_metadata = {
k: v
for k, v in (answer_result.metadata or {}).items()
if k != "usage_records"
}
out_metadata["usage_records"] = pipeline_records
return ExecutionResult(
success=True,
data=structured_output,
metadata=out_metadata,
)
def _run_pipeline_answer_step(
self,
context: ExecutionContext,
answer_params: dict,
is_single_pass: bool,
shim: ExecutorToolShim,
step: int,
) -> ExecutionResult:
"""Run the answer-prompt step of the structure pipeline.
For single pass, forces ``chunk-size=0`` (full-context retrieval)
and dispatches ``_handle_single_pass_extraction``. Otherwise
dispatches ``_handle_answer_prompt``.
"""
if is_single_pass:
# Single pass reads the whole file in one LLM call; force
# chunk-size=0 so the fallback path (no cloud plugin) uses
# retrieve_complete_context instead of vector DB retrieval.
for output in answer_params.get("outputs", []):
output["chunk-size"] = 0
output["chunk-overlap"] = 0
operation = Operation.SINGLE_PASS_EXTRACTION.value
else:
operation = Operation.ANSWER_PROMPT.value
answer_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=operation,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
executor_params=answer_params,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
)
if is_single_pass:
return self._handle_single_pass_extraction(answer_ctx)
return self._handle_answer_prompt(answer_ctx)
@staticmethod
def _inject_table_settings(
answer_params: dict,
index_template: dict,
skip_extraction: bool,
input_file_path: str,
) -> None:
"""Inject table settings file paths into each output that has them."""
outputs = answer_params.get("outputs", [])
extracted_file_path = index_template.get("extracted_file_path", "")
for output in outputs:
if "table_settings" not in output:
continue
table_settings = output["table_settings"]
is_dir = table_settings.get("is_directory_mode", False)
if skip_extraction:
table_settings["input_file"] = input_file_path
answer_params["file_path"] = input_file_path
else:
table_settings["input_file"] = extracted_file_path
table_settings["is_directory_mode"] = is_dir
output["table_settings"] = table_settings
def _finalize_pipeline_result(
self,
structured_output: dict,
source_file_name: str,
extracted_text: str,
index_metrics: dict,
) -> None:
"""Populate metadata/metrics in structured_output after pipeline completion."""
if "metadata" not in structured_output:
structured_output["metadata"] = {}
structured_output["metadata"]["file_name"] = source_file_name
if extracted_text:
structured_output["metadata"]["extracted_text"] = extracted_text
if index_metrics:
existing_metrics = structured_output.get("metrics", {})
structured_output["metrics"] = self._merge_pipeline_metrics(
existing_metrics, index_metrics
)
def _run_pipeline_summarize(
self,
context: ExecutionContext,
summarize_params: dict,
answer_params: dict,
) -> ExecutionResult:
"""Run the summarize step of the structure pipeline.
Handles filesystem caching: if a cached summary exists, uses it.
Otherwise calls ``_handle_summarize`` and writes the result.
Updates ``answer_params`` in-place with new file_path and
file_hash.
"""
extract_file_path = summarize_params.get("extract_file_path", "")
summarize_file_path = summarize_params.get("summarize_file_path", "")
platform_api_key = summarize_params.get("platform_api_key", "")
llm_adapter_id = summarize_params.get("llm_adapter_instance_id", "")
summarize_prompt = summarize_params.get("summarize_prompt", "")
prompt_keys = summarize_params.get("prompt_keys", [])
outputs = answer_params.get("outputs", [])
fs = FileUtils.get_fs_instance(execution_source=context.execution_source)
# Set chunk_size=0 for all outputs when summarizing
embedding = answer_params.get("tool_settings", {}).get("embedding", "")
vector_db = answer_params.get("tool_settings", {}).get("vector-db", "")
x2text = answer_params.get("tool_settings", {}).get("x2text_adapter", "")
for output in outputs:
output["embedding"] = embedding
output["vector-db"] = vector_db
output["x2text_adapter"] = x2text
output["chunk-size"] = 0
output["chunk-overlap"] = 0
# Check cache
summarized_context = ""
if fs.exists(summarize_file_path):
summarized_context = fs.read(path=summarize_file_path, mode="r")
if not summarized_context:
# Read extracted text
doc_context = fs.read(path=extract_file_path, mode="r")
if not doc_context:
return ExecutionResult.failure(
error="No extracted text found for summarization"
)
summarize_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=Operation.SUMMARIZE.value,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
executor_params={
"llm_adapter_instance_id": llm_adapter_id,
"summarize_prompt": summarize_prompt,
"context": doc_context,
"prompt_keys": prompt_keys,
"PLATFORM_SERVICE_API_KEY": platform_api_key,
},
)
summarize_result = self._handle_summarize(summarize_ctx)
if not summarize_result.success:
return summarize_result
summarized_context = summarize_result.data.get("data", "")
fs.write(
path=summarize_file_path,
mode="w",
data=summarized_context,
)
forward_metadata = dict(summarize_result.metadata or {})
else:
forward_metadata = {}
# Update answer_params
summarize_file_hash = fs.get_hash_from_file(path=summarize_file_path)
answer_params["file_hash"] = summarize_file_hash
answer_params["file_path"] = str(summarize_file_path)
return ExecutionResult(success=True, data={}, metadata=forward_metadata)
def _run_pipeline_index(
self,
context: ExecutionContext,
index_template: dict,
answer_params: dict,
extracted_text: str,
usage_kwargs: dict | None = None,
) -> tuple[dict, list[dict]]:
"""Run per-output indexing with dedup for the structure pipeline.
Args:
usage_kwargs: Audit-tracking kwargs (``run_id``,
``execution_id``, ``file_name``) propagated to the
embedding adapter so its callback can record usage
rows against the correct file_execution_id.
Returns:
(index_metrics, usage_records) — metrics keyed by output
name and the flat list of usage rows collected across all
child ``_handle_index`` calls.
"""
tool_settings = answer_params.get("tool_settings", {})
outputs = answer_params.get("outputs", [])
index_metrics: dict = {}
index_records: list[dict] = []
seen_params: set = set()
for output in outputs:
self._index_pipeline_output(
context=context,
output=output,
index_template=index_template,
tool_settings=tool_settings,
extracted_text=extracted_text,
usage_kwargs=usage_kwargs or {},
seen_params=seen_params,
index_metrics=index_metrics,
index_records=index_records,
)
return index_metrics, index_records
def _index_pipeline_output(
self,
*,
context: ExecutionContext,
output: dict,
index_template: dict,
tool_settings: dict,
extracted_text: str,
usage_kwargs: dict,
seen_params: set,
index_metrics: dict,
index_records: list[dict],
) -> None:
"""Index a single structure-pipeline output entry in-place."""
import datetime
chunk_size = output.get("chunk-size", 0)
if chunk_size == 0:
return
chunk_overlap = output.get("chunk-overlap", 0)
vector_db = tool_settings.get("vector-db", "")
embedding = tool_settings.get("embedding", "")
x2text = tool_settings.get("x2text_adapter", "")
param_key = (
f"chunk_size={chunk_size}_"
f"chunk_overlap={chunk_overlap}_"
f"vector_db={vector_db}_"
f"embedding={embedding}_"
f"x2text={x2text}"
)
if param_key in seen_params:
return
seen_params.add(param_key)
indexing_start = datetime.datetime.now()
logger.info(
"Pipeline indexing: chunk_size=%s chunk_overlap=%s vector_db=%s",
chunk_size,
chunk_overlap,
vector_db,
)
index_ctx = ExecutionContext(
executor_name=context.executor_name,
operation=Operation.INDEX.value,
run_id=context.run_id,
execution_source=context.execution_source,
organization_id=context.organization_id,
request_id=context.request_id,
log_events_id=context.log_events_id,
execution_id=context.execution_id,
file_execution_id=context.file_execution_id,
executor_params={
"embedding_instance_id": embedding,
"vector_db_instance_id": vector_db,