Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-3403 [FEAT] Agentic table extractor plugin with multi-agent LLM-powered table extraction (#1914)

harini-venkataramanacf5573714f5
diff --git a/backend/prompt_studio/prompt_studio_core_v2/constants.py b/backend/prompt_studio/prompt_studio_core_v2/constants.py
index c1ab14d38..03bd68c1d 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/constants.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/constants.py
@@ -92,6 +92,7 @@ class ToolStudioPromptKeys:
INCLUDE_METADATA = "include_metadata"
TXT_EXTENTION = ".txt"
TABLE = "table"
+ AGENTIC_TABLE = "agentic_table"
PLATFORM_POSTAMBLE = "platform_postamble"
WORD_CONFIDENCE_POSTAMBLE = "word_confidence_postamble"
SUMMARIZE_AS_SOURCE = "summarize_as_source"
diff --git a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
index d0ffef311..ff2b34550 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
@@ -1540,6 +1540,7 @@ class PromptStudioHelper:
if (
prompt_instance.enforce_type == TSPKeys.TABLE
or prompt_instance.enforce_type == TSPKeys.RECORD
+ or prompt_instance.enforce_type == TSPKeys.AGENTIC_TABLE
) and not payload_modifier_plugin:
raise OperationNotSupported()
@@ -1570,17 +1571,34 @@ class PromptStudioHelper:
"Invoking prompt service",
)
try:
- response = PromptStudioHelper._fetch_response(
- doc_path=doc_path,
- doc_name=doc_name,
- tool=tool,
- prompt=prompt_instance,
- org_id=org_id,
- document_id=document_id,
- run_id=run_id,
- profile_manager_id=profile_manager_id,
- user_id=user_id,
- )
+ if (
+ prompt_instance.enforce_type == TSPKeys.AGENTIC_TABLE
+ and payload_modifier_plugin
+ ):
+ modifier_service = payload_modifier_plugin["service_class"]()
+ response = modifier_service.execute_agentic_table(
+ tool_id=tool_id,
+ prompt_id=str(prompt_instance.prompt_id),
+ prompt_key=prompt_name,
+ prompt=prompt_instance.prompt,
+ doc_path=doc_path,
+ doc_name=doc_name,
+ org_id=org_id,
+ user_id=user_id,
+ run_id=run_id,
+ )
+ else:
+ response = PromptStudioHelper._fetch_response(
+ doc_path=doc_path,
+ doc_name=doc_name,
+ tool=tool,
+ prompt=prompt_instance,
+ org_id=org_id,
+ document_id=document_id,
+ run_id=run_id,
+ profile_manager_id=profile_manager_id,
+ user_id=user_id,
+ )
return PromptStudioHelper._handle_response(
response=response,
run_id=run_id,
diff --git a/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json b/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json
index 3d59b2bf0..ee4c218ca 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json
+++ b/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json
@@ -15,6 +15,7 @@
"boolean":"boolean",
"json":"json",
"table":"table",
+ "agentic_table":"agentic_table",
"line-item":"line-item"
},
"output_processing":{
diff --git a/backend/prompt_studio/prompt_studio_core_v2/views.py b/backend/prompt_studio/prompt_studio_core_v2/views.py
index 22c1a378b..99edefd0b 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py
@@ -50,6 +50,7 @@ from prompt_studio.prompt_studio_core_v2.document_indexing_service import (
from prompt_studio.prompt_studio_core_v2.exceptions import (
DeploymentUsageCheckError,
MaxProfilesReachedError,
+ OperationNotSupported,
ToolDeleteError,
)
from prompt_studio.prompt_studio_core_v2.migration_utils import SummarizeMigrationUtils
@@ -509,6 +510,61 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
document: DocumentManager = DocumentManager.objects.get(pk=document_id)
doc_path = str(Path(doc_path) / document.document_name)
+ # Agentic table prompts have a separate executor worker. Build the
+ # payload via the cloud payload_modifier plugin and dispatch directly
+ # so the legacy answer_prompt path is bypassed.
+ if prompt.enforce_type == ToolStudioPromptKeys.AGENTIC_TABLE:
+ payload_modifier_plugin = get_plugin("payload_modifier")
+ if not payload_modifier_plugin:
+ raise OperationNotSupported()
+ modifier = payload_modifier_plugin["service_class"]()
+ context, cb_kwargs = modifier.build_agentic_table_payload(
+ tool=custom_tool,
+ prompt=prompt,
+ doc_path=doc_path,
+ doc_name=document.document_name,
+ org_id=org_id,
+ user_id=user_id,
+ document_id=document_id,
+ run_id=run_id,
+ profile_manager_id=profile_manager_id,
+ )
+
+ from prompt_studio.prompt_studio_output_manager_v2.models import (
+ PromptStudioOutputManager,
+ )
+
+ cb_kwargs["hubspot_user_id"] = request.user.pk
+ cb_kwargs[
+ "is_first_prompt_run"
+ ] = not PromptStudioOutputManager.objects.filter(
+ tool_id__in=CustomTool.objects.values_list("tool_id", flat=True)
+ ).exists()
+
+ dispatcher = PromptStudioHelper._get_dispatcher()
+ executor_task_id = str(uuid.uuid4())
+ cb_kwargs["executor_task_id"] = executor_task_id
+ cb_kwargs["dispatch_time"] = time.time()
+
+ task = dispatcher.dispatch_with_callback(
+ context,
+ on_success=signature(
+ "ide_prompt_complete",
+ kwargs={"callback_kwargs": cb_kwargs},
+ queue="ide_callback",
+ ),
+ on_error=signature(
+ "ide_prompt_error",
+ kwargs={"callback_kwargs": cb_kwargs},
+ queue="ide_callback",
+ ),
+ task_id=executor_task_id,
+ )
+ return Response(
+ {"task_id": task.id, "run_id": run_id, "status": "accepted"},
+ status=status.HTTP_202_ACCEPTED,
+ )
+
context, cb_kwargs = PromptStudioHelper.build_fetch_response_payload(
tool=custom_tool,
doc_path=doc_path,
@@ -705,7 +761,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
# Fetch prompts eligible for single-pass extraction.
# Mirrors the filtering in _execute_prompts_in_single_pass:
- # only active, non-NOTES, non-TABLE/RECORD prompts.
+ # only active, non-NOTES, non-TABLE/RECORD/AGENTIC_TABLE prompts.
prompts = list(
ToolStudioPrompt.objects.filter(tool_id=custom_tool.tool_id).order_by(
"sequence_number"
@@ -718,6 +774,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
and p.active
and p.enforce_type != ToolStudioPromptKeys.TABLE
and p.enforce_type != ToolStudioPromptKeys.RECORD
+ and p.enforce_type != ToolStudioPromptKeys.AGENTIC_TABLE
]
if not prompts:
return Response(
diff --git a/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py b/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py
index 405b91e00..64932eb3f 100644
--- a/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py
+++ b/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py
@@ -170,7 +170,13 @@ class OutputManagerHelper:
# TODO: use enums here
output = outputs.get(prompt.prompt_key)
- if prompt.enforce_type in {"json", "table", "record", "line-item"}:
+ if prompt.enforce_type in {
+ "json",
+ "table",
+ "record",
+ "line-item",
+ "agentic_table",
+ }:
output = json.dumps(output)
eval_metrics = outputs.get(f"{prompt.prompt_key}__evaluation", [])
profile_manager = default_profile
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/constants.py b/backend/prompt_studio/prompt_studio_registry_v2/constants.py
index 785e77484..35d665485 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/constants.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/constants.py
@@ -12,6 +12,7 @@ class PromptStudioRegistryKeys:
TABLE = "table"
RECORD = "record"
LINE_ITEM = "line-item"
+ AGENTIC_TABLE = "agentic_table"
class PromptStudioRegistryErrors:
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/prompt_studio_registry_helper.py b/backend/prompt_studio/prompt_studio_registry_v2/prompt_studio_registry_helper.py
index 6ce1f7209..08d2c27ba 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/prompt_studio_registry_helper.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/prompt_studio_registry_helper.py
@@ -371,6 +371,15 @@ class PromptStudioRegistryHelper:
prompt_id=prompt.prompt_id,
prompt=prompt.prompt,
)
+ elif prompt.enforce_type == PromptStudioRegistryKeys.AGENTIC_TABLE:
+ payload_modifier_plugin = get_plugin("payload_modifier")
+ if payload_modifier_plugin:
+ modifier_service = payload_modifier_plugin["service_class"]()
+ output = modifier_service.export_agentic_table_settings(
+ output=output,
+ tool_id=tool.tool_id,
+ prompt_id=prompt.prompt_id,
+ )
outputs.append(output)
output = {}
diff --git a/backend/prompt_studio/prompt_studio_v2/migrations/0014_alter_toolstudioprompt_enforce_type.py b/backend/prompt_studio/prompt_studio_v2/migrations/0014_alter_toolstudioprompt_enforce_type.py
new file mode 100644
index 000000000..beae260ce
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio_v2/migrations/0014_alter_toolstudioprompt_enforce_type.py
@@ -0,0 +1,41 @@
+# Generated for agentic table enforce type
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "prompt_studio_v2",
+ "0013_toolstudioprompt_enable_postprocessing_webhook_and_more",
+ ),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="toolstudioprompt",
+ name="enforce_type",
+ field=models.TextField(
+ blank=True,
+ choices=[
+ ("text", "Response sent as Text"),
+ ("number", "Response sent as number"),
+ ("email", "Response sent as email"),
+ ("date", "Response sent as date"),
+ ("boolean", "Response sent as boolean"),
+ ("json", "Response sent as json"),
+ (
+ "line-item",
+ "Response sent as line-item which is large a JSON output. If extraction stopped due to token limitation, we try to continue extraction from where it stopped",
+ ),
+ ("table", "Response sent as json"),
+ (
+ "agentic_table",
+ "Response sent as agentic table extraction",
+ ),
+ ],
+ db_comment="Field to store the type in which the response to be returned.",
+ default="text",
+ ),
+ ),
+ ]
diff --git a/backend/prompt_studio/prompt_studio_v2/models.py b/backend/prompt_studio/prompt_studio_v2/models.py
index 74739bfe5..b4c64f091 100644
--- a/backend/prompt_studio/prompt_studio_v2/models.py
+++ b/backend/prompt_studio/prompt_studio_v2/models.py
@@ -31,6 +31,7 @@ class ToolStudioPrompt(BaseModel):
),
)
TABLE = "table", "Response sent as json"
+ AGENTIC_TABLE = "agentic_table", "Response sent as agentic table extraction"
class PromptType(models.TextChoices):
PROMPT = "PROMPT", "Response sent as Text"
diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml
index 4dd8c3866..bb40b324e 100644
--- a/docker/docker-compose.yaml
+++ b/docker/docker-compose.yaml
@@ -529,7 +529,7 @@ services:
- EXECUTOR_METRICS_PORT=8088
- HEALTH_PORT=8088
# Configurable Celery options
- - CELERY_QUEUES_EXECUTOR=${CELERY_QUEUES_EXECUTOR:-celery_executor_legacy,celery_executor_agentic}
+ - CELERY_QUEUES_EXECUTOR=${CELERY_QUEUES_EXECUTOR:-celery_executor_legacy,celery_executor_agentic,celery_executor_agentic_table}
- CELERY_POOL=${WORKER_EXECUTOR_POOL:-prefork}
- CELERY_PREFETCH_MULTIPLIER=${WORKER_EXECUTOR_PREFETCH_MULTIPLIER:-1}
- CELERY_CONCURRENCY=${WORKER_EXECUTOR_CONCURRENCY:-2}
diff --git a/frontend/src/components/custom-tools/prompt-card/Header.jsx b/frontend/src/components/custom-tools/prompt-card/Header.jsx
index 2b6d6b99c..cea5e2d6d 100644
--- a/frontend/src/components/custom-tools/prompt-card/Header.jsx
+++ b/frontend/src/components/custom-tools/prompt-card/Header.jsx
@@ -59,6 +59,7 @@ function Header({
spsLoading,
handleSpsLoading,
enforceType,
+ isAgenticTableReady = true,
}) {
const {
selectedDoc,
@@ -357,6 +358,7 @@ function Header({
)
}
disabled={
+ !isAgenticTableReady ||
(updateStatus?.promptId === promptDetails?.prompt_id &&
updateStatus?.status ===
promptStudioUpdateStatus?.isUpdating) ||
@@ -380,6 +382,7 @@ function Header({
)
}
disabled={
+ !isAgenticTableReady ||
(updateStatus?.promptId === promptDetails?.prompt_id &&
updateStatus?.status ===
promptStudioUpdateStatus?.isUpdating) ||
@@ -436,6 +439,7 @@ Header.propTypes = {
spsLoading: PropTypes.object,
handleSpsLoading: PropTypes.func.isRequired,
enforceType: PropTypes.string,
+ isAgenticTableReady: PropTypes.bool,
};
export { Header };
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx
index 90f4936a3..6fd8b1bc6 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx
@@ -15,7 +15,6 @@ import { useEffect, useRef, useState } from "react";
import { useCustomToolStore } from "../../../store/custom-tool-store";
import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";
import { EditableText } from "../editable-text/EditableText";
-import { TABLE } from "./constants";
import { Header } from "./Header";
import { OutputForIndex } from "./OutputForIndex";
import { PromptOutput } from "./PromptOutput";
@@ -30,6 +29,16 @@ try {
// The component will remain null of it is not available
}
+let AgenticTableChecklist;
+try {
+ const mod = await import(
+ "../../../plugins/prompt-card/AgenticTableChecklist"
+ );
+ AgenticTableChecklist = mod.AgenticTableChecklist;
+} catch {
+ // The component will remain null of it is not available
+}
+
function PromptCardItems({
promptDetails,
enforceTypeList,
@@ -82,6 +91,7 @@ function PromptCardItems({
const divRef = useRef(null);
const [enforceType, setEnforceType] = useState("");
const [tableSettings, setTableSettings] = useState({});
+ const [isAgenticTableReady, setIsAgenticTableReady] = useState(true);
const promptId = promptDetails?.prompt_id;
useEffect(() => {
@@ -212,6 +222,7 @@ function PromptCardItems({
spsLoading={spsLoading}
handleSpsLoading={handleSpsLoading}
enforceType={enforceType}
+ isAgenticTableReady={isAgenticTableReady}
/>
</Space>
</div>
@@ -222,6 +233,14 @@ function PromptCardItems({
>
<Collapse.Panel key={"1"} showArrow={false}>
<div className="prompt-card-div-body">
+ {AgenticTableChecklist && (
+ <AgenticTableChecklist
+ promptId={promptDetails?.prompt_id}
+ promptText={promptText}
+ enforceType={enforceType}
+ onReadinessChange={setIsAgenticTableReady}
+ />
+ )}
<EditableText
isEditing={isEditingPrompt}
setIsEditing={setIsEditingPrompt}
@@ -278,7 +297,7 @@ function PromptCardItems({
)}
</Space>
<Space>
- {enforceType === TABLE && TableExtractionSettingsBtn && (
+ {TableExtractionSettingsBtn && (
<TableExtractionSettingsBtn
promptId={promptDetails?.prompt_id}
enforceType={enforceType}
@@ -324,6 +343,7 @@ function PromptCardItems({
isChallenge={isChallenge}
handleSelectHighlight={handleSelectHighlight}
progressMsg={progressMsg}
+ isAgenticTableReady={isAgenticTableReady}
/>
</Row>
</Collapse.Panel>
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptOutput.jsx b/frontend/src/components/custom-tools/prompt-card/PromptOutput.jsx
index 88df32974..38f7d924a 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptOutput.jsx
+++ b/frontend/src/components/custom-tools/prompt-card/PromptOutput.jsx
@@ -67,6 +67,7 @@ function PromptOutput({
isChallenge,
handleSelectHighlight,
progressMsg,
+ isAgenticTableReady = true,
}) {
const [openExpandModal, setOpenExpandModal] = useState(false);
const { width: windowWidth } = useWindowDimensions();
@@ -386,7 +387,11 @@ function PromptOutput({
selectedDoc?.document_id,
)
}
- disabled={isPromptLoading || isPublicSource}
+ disabled={
+ !isAgenticTableReady ||
+ isPromptLoading ||
+ isPublicSource
+ }
>
<PlayCircleOutlined className="prompt-card-actions-head" />
</Button>
@@ -404,7 +409,11 @@ function PromptOutput({
null,
)
}
- disabled={isPromptLoading || isPublicSource}
+ disabled={
+ !isAgenticTableReady ||
+ isPromptLoading ||
+ isPublicSource
+ }
>
<PlayCircleFilled className="prompt-card-actions-head" />
</Button>
@@ -484,6 +493,7 @@ PromptOutput.propTypes = {
isChallenge: PropTypes.bool,
handleSelectHighlight: PropTypes.func.isRequired,
progressMsg: PropTypes.object,
+ isAgenticTableReady: PropTypes.bool,
};
export { PromptOutput };
diff --git a/frontend/src/hooks/usePromptRun.js b/frontend/src/hooks/usePromptRun.js
index 44df3811c..34fb42e7d 100644
--- a/frontend/src/hooks/usePromptRun.js
+++ b/frontend/src/hooks/usePromptRun.js
@@ -16,7 +16,11 @@ import usePromptOutput from "./usePromptOutput";
// Tracks the latest run nonce per (promptId, statusKey) so stale timeouts
// from a previous run don't falsely cancel a newer run of the same combo.
const runNonceMap = new Map();
-const SOCKET_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
+// Safety-net timeout for the fire-and-forget prompt run flow. Must trail the
+// server-side LLM adapter timeout (default 900s in
+// unstract/sdk1/src/unstract/sdk1/adapters/llm1/static/openai.json) so the UI
+// never gives up before the backend does. 16 minutes leaves a 1-minute buffer.
+const SOCKET_TIMEOUT_MS = 16 * 60 * 1000; // 16 minutes
const usePromptRun = () => {
const { pushPromptRunApi, freeActiveApi } = usePromptRunQueueStore();
diff --git a/unstract/sdk1/src/unstract/sdk1/llm.py b/unstract/sdk1/src/unstract/sdk1/llm.py
index c1730e661..4588e6946 100644
--- a/unstract/sdk1/src/unstract/sdk1/llm.py
+++ b/unstract/sdk1/src/unstract/sdk1/llm.py
@@ -363,6 +363,96 @@ class LLM:
message=error_msg, status_code=status_code, actual_err=e
) from e
+ @capture_metrics
+ def complete_vision(
+ self,
+ messages: list[dict[str, Any]],
+ **kwargs: object,
+ ) -> dict[str, object]:
+ """Chat completion with multimodal (text + image) messages.
+
+ Accepts pre-built messages with image_url content blocks::
+
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "..."},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,..."},
+ },
+ ],
+ }
+ ]
+
+ LiteLLM auto-translates the OpenAI-style image format for
+ Anthropic, Bedrock, Vertex, and other providers.
+
+ Same error handling, usage tracking, and metrics as complete().
+
+ Args:
+ messages: List of message dicts with multimodal content.
+ **kwargs: Additional arguments passed to litellm.completion().
+
+ Returns:
+ dict with "response" key containing LLMResponseCompat.
+ """
+ try:
+ litellm.drop_params = True
+
+ logger.debug(
+ f"[sdk1][LLM]Invoking {self.adapter.get_provider()} "
+ f"vision completion API"
+ )
+
+ completion_kwargs = self.adapter.validate({**self.kwargs, **kwargs})
+ completion_kwargs.pop("cost_model", None)
+
+ response: dict[str, object] = litellm.completion(
+ messages=messages,
+ **completion_kwargs,
+ )
+
+ response_text = response["choices"][0]["message"]["content"]
+ finish_reason = response["choices"][0].get("finish_reason")
+
+ self._record_usage(
+ self._cost_model or self.kwargs["model"],
+ messages,
+ response.get("usage"),
+ "complete_vision",
+ )
+
+ if response_text is None:
+ self._raise_for_empty_response(finish_reason)
+
+ response_object = LLMResponseCompat(response_text)
+ response_object.raw = response
+ return {"response": response_object}
+
+ except LLMError:
+ raise
+ except SdkError:
+ raise
+ except Exception as e:
+ logger.error(f"[sdk1][LLM] Error during vision completion: {e}")
+
+ status_code = None
+ if hasattr(e, "status_code"):
+ status_code = e.status_code
+ elif hasattr(e, "http_status"):
+ status_code = e.http_status
+
+ error_msg = (
+ f"Error from LLM adapter '{self._get_adapter_info()}': "
+ f"{strip_litellm_prefix(str(e))}"
+ )
+
+ raise LLMError(
+ message=error_msg, status_code=status_code, actual_err=e
+ ) from e
+
def stream_complete(
self,
prompt: str,
diff --git a/workers/executor/executors/legacy_executor.py b/workers/executor/executors/legacy_executor.py
index 2a7dfc160..3760aea06 100644
--- a/workers/executor/executors/legacy_executor.py
+++ b/workers/executor/executors/legacy_executor.py
@@ -1909,25 +1909,36 @@ class LegacyExecutor(BaseExecutor):
prompt_name = output[PSKeys.NAME]
output_type = output[PSKeys.TYPE]
+ # Defensive guard: agentic_table prompts must be dispatched to
+ # the dedicated agentic_table executor by the worker (Layer 2 in
+ # workers/file_processing/structure_tool_task.py). If one ever
+ # reaches this method, the legacy fallthrough below would store
+ # the raw LLM completion as a string. Skip silently with a
+ # warning so the caller's existing entry (if any) survives.
+ if output_type == "agentic_table":
+ logger.warning(
+ "Skipping agentic_table prompt %s in legacy executor — "
+ "should have been dispatched to agentic_table executor",
+ prompt_name,
+ )
+ return
+
if output_type == PSKeys.NUMBER:
structured_output[prompt_name] = LegacyExecutor._convert_number_answer(
answer, llm, answer_prompt_svc
)
elif output_type == PSKeys.EMAIL:
- if answer.lower() == "na":
- structured_output[prompt_name] = answer
- else:
- email_prompt = (
- f"Extract the email from the following text:\n{answer}"
- f"\n\nOutput just the email. "
- f"The email should be directly assignable to a string "
- f"variable. No explanation is required. If you cannot "
- f'extract the email, output "NA".'
- )
- structured_output[prompt_name] = answer_prompt_svc.run_completion(
- llm=llm, prompt=email_prompt
- )
+ email_prompt = (
+ f"Extract the email from the following text:\n{answer}"
+ f"\n\nOutput just the email. "
+ f"The email should be directly assignable to a string "
+ f"variable. No explanation is required. If you cannot "
+ f'extract the email, output "NA".'
+ )
+ structured_output[prompt_name] = LegacyExecutor._convert_scalar_answer(
+ answer, llm, answer_prompt_svc, email_prompt
+ )
elif output_type == PSKeys.DATE:
date_prompt = (
diff --git a/workers/executor/executors/retrievers/fusion.py b/workers/executor/executors/retrievers/fusion.py
index 7449ddb8e..be6810ad2 100644
--- a/workers/executor/executors/retrievers/fusion.py
+++ b/workers/executor/executors/retrievers/fusion.py
@@ -64,7 +64,7 @@ class FusionRetriever(BaseRetriever):
mode="simple", # Use simple fusion mode (reciprocal rank fusion)
use_async=False,
verbose=True,
- llm=llm,
+ llm=llm, # LLM generates query variations
)
# Retrieve nodes using fusion technique
diff --git a/workers/executor/executors/retrievers/keyword_table.py b/workers/executor/executors/retrievers/keyword_table.py
index 912b2fb7f..5c7db9ab4 100644
--- a/workers/executor/executors/retrievers/keyword_table.py
+++ b/workers/executor/executors/retrievers/keyword_table.py
@@ -48,7 +48,7 @@ class KeywordTableRetriever(BaseRetriever):
keyword_index = KeywordTableIndex(
nodes=[node.node for node in all_nodes],
show_progress=True,
- llm=llm,
+ llm=llm, # Use the provided LLM instead of defaulting to OpenAI
)
# Create retriever from keyword index
diff --git a/workers/file_processing/structure_tool_task.py b/workers/file_processing/structure_tool_task.py
index 87c942637..c0fdee1c0 100644
--- a/workers/file_processing/structure_tool_task.py
+++ b/workers/file_processing/structure_tool_task.py
@@ -301,7 +301,35 @@ def _execute_structure_tool_impl(params: dict) -> dict:
tool_id = tool_metadata[_SK.TOOL_ID]
tool_settings = tool_metadata[_SK.TOOL_SETTINGS]
- outputs = tool_metadata[_SK.OUTPUTS]
+ all_outputs = tool_metadata[_SK.OUTPUTS]
+
+ # ---- Partition prompts by enforce_type ----
+ # Agentic table prompts run via a dedicated executor (page-by-page
+ # extraction + Agent-5 schema cleanup). Regular prompts continue
+ # through the legacy structure_pipeline. Use local variables so
+ # tool_metadata[_SK.OUTPUTS] is preserved for METADATA.json
+ # serialization downstream in _write_tool_result.
+ agentic_table_outputs = [o for o in all_outputs if o.get("type") == "agentic_table"]
+ regular_outputs = [o for o in all_outputs if o.get("type") != "agentic_table"]
+
+ # Validate readiness for each agentic_table prompt: if the export
+ # step did not populate agentic_table_settings, fail loudly so the
+ # user knows to re-export the tool instead of producing the
+ # legacy stringified-truncated output.
+ for at_output in agentic_table_outputs:
+ at_settings = at_output.get("agentic_table_settings") or {}
+ if not at_settings.get("target_table") or not at_settings.get("json_structure"):
+ return ExecutionResult.failure(
+ error=(
+ f"Agentic table prompt '{at_output[_SK.NAME]}' is missing "
+ f"agentic_table_settings in the exported tool metadata. "
+ f"Re-export the tool from Prompt Studio after the fix is "
+ f"deployed to populate target_table / json_structure / "
+ f"instructions."
+ )
+ ).to_dict()
+
+ outputs = regular_outputs
# Inject workflow-level settings into tool_settings
tool_settings[_SK.CHALLENGE_LLM] = challenge_llm
@@ -388,42 +416,103 @@ def _execute_structure_tool_impl(params: dict) -> dict:
"prompt_keys": prompt_keys,
}
- # ---- Step 6: Single dispatch to executor ----
- logger.info(
- "Dispatching structure_pipeline: tool_id=%s "
- "skip_extract=%s summarize=%s single_pass=%s",
- tool_id,
- skip_extraction_and_indexing,
- is_summarization_enabled,
- is_single_pass_enabled,
- )
-
- pipeline_ctx = ExecutionContext(
- executor_name="legacy",
- operation="structure_pipeline",
- run_id=file_execution_id,
- execution_source="tool",
- organization_id=organization_id,
- request_id=file_execution_id,
- log_events_id=StateStore.get("LOG_EVENTS_ID") or "",
- execution_id=execution_id,
- file_execution_id=file_execution_id,
- executor_params={
- "extract_params": extract_params,
- "index_template": index_template,
- "answer_params": answer_params,
- "pipeline_options": pipeline_options,
- "summarize_params": summarize_params,
- },
- )
- pipeline_start = time.monotonic()
- pipeline_result = dispatcher.dispatch(pipeline_ctx, timeout=EXECUTOR_TIMEOUT)
- pipeline_elapsed = time.monotonic() - pipeline_start
-
- if not pipeline_result.success:
- return pipeline_result.to_dict()
+ # ---- Step 6a: Dispatch agentic_table prompts ----
+ # Each agentic_table prompt runs in its own executor invocation.
+ # The executor handles X2Text extraction internally; we just
+ # forward the document path and the per-prompt settings unpacked
+ # from agentic_table_settings (populated by Layer 1 export).
+ #
+ # Important: read from SOURCE, not INFILE. INFILE gets overwritten
+ # with JSON output at the end of this function (line ~508), so any
+ # subsequent reuse of the same file_execution_dir would surface JSON
+ # bytes to the agentic_table executor and fail PDF parsing
+ # ("PDFium: Data format error"). SOURCE is the immutable original
+ # PDF written alongside INFILE by the source connector.
+ agentic_source_path = str(execution_run_data_folder / "SOURCE")
+ agentic_results: dict[str, Any] = {}
+ for at_output in agentic_table_outputs:
+ at_settings = at_output.get("agentic_table_settings") or {}
+ json_structure = at_settings.get("json_structure")
+ if isinstance(json_structure, dict):
+ json_structure = json.dumps(json_structure)
+ agentic_params = {
+ "llm_adapter_instance_id": at_output["llm"],
+ "lite_llm_adapter_instance_id": at_settings.get(
+ "lite_llm_adapter_instance_id", ""
+ ),
+ "x2text_adapter_instance_id": tool_settings[_SK.X2TEXT_ADAPTER],
+ "input_file": agentic_source_path,
+ "source_file_name": source_file_name,
+ "target_table": at_settings.get("target_table", ""),
+ "json_structure": json_structure,
+ "instructions": at_settings.get("instructions", ""),
+ "starting_page": at_settings.get("start_page", 1),
+ "ending_page": at_settings.get("end_page") or None,
+ "parallel_pages": at_settings.get("parallel_pages", 4),
+ "execution_id": execution_id,
+ "PLATFORM_SERVICE_API_KEY": platform_service_api_key,
+ }
+ at_ctx = ExecutionContext(
+ executor_name="agentic_table",
+ operation="table_extract",
+ run_id=file_execution_id,
+ execution_source="tool",
+ organization_id=organization_id,
+ request_id=file_execution_id,
+ executor_params=agentic_params,
+ )
+ at_result = dispatcher.dispatch(at_ctx, timeout=EXECUTOR_TIMEOUT)
+ if not at_result.success:
+ return at_result.to_dict()
+ at_output_data = at_result.data.get("output", {}) or {}
+ agentic_results[at_output[_SK.NAME]] = at_output_data.get("tables", [])
+
+ # ---- Step 6b: Dispatch legacy structure_pipeline ----
+ # Skipped entirely when every prompt is agentic_table — the legacy
+ # pipeline has no work to do and the agentic_table executor does
+ # its own X2Text inside the runner.
+ if regular_outputs:
+ logger.info(
+ "Dispatching structure_pipeline: tool_id=%s "
+ "skip_extract=%s summarize=%s single_pass=%s",
+ tool_id,
+ skip_extraction_and_indexing,
+ is_summarization_enabled,
+ is_single_pass_enabled,
+ )
- structured_output = pipeline_result.data
+ pipeline_ctx = ExecutionContext(
+ executor_name="legacy",
+ operation="structure_pipeline",
+ run_id=file_execution_id,
+ execution_source="tool",
+ organization_id=organization_id,
+ request_id=file_execution_id,
+ executor_params={
+ "extract_params": extract_params,
+ "index_template": index_template,
+ "answer_params": answer_params,
+ "pipeline_options": pipeline_options,
+ "summarize_params": summarize_params,
+ },
+ )
+ pipeline_start = time.monotonic()
+ pipeline_result = dispatcher.dispatch(pipeline_ctx, timeout=EXECUTOR_TIMEOUT)
+ pipeline_elapsed = time.monotonic() - pipeline_start
+
+ if not pipeline_result.success:
+ return pipeline_result.to_dict()
+
+ structured_output = pipeline_result.data
+ if agentic_results:
+ structured_output.setdefault("output", {}).update(agentic_results)
+ else:
+ # All-agentic case: skip the legacy pipeline entirely.
+ structured_output = {
+ "output": agentic_results,
+ "metadata": {"agentic_only": True},
+ }
+ pipeline_elapsed = 0.0
# ---- Step 7: Write output files ----
# (metadata/metrics merging already done by executor pipeline)
diff --git a/workers/ide_callback/tasks.py b/workers/ide_callback/tasks.py
index cb610678b..d0dbce256 100644
--- a/workers/ide_callback/tasks.py
+++ b/workers/ide_callback/tasks.py
@@ -392,6 +392,16 @@ def ide_prompt_complete(
outputs = _json_safe(data.get("output", {}))
metadata = _json_safe(data.get("metadata", {}))
+ # Agentic table executor returns {"tables": [...], "page_count": ...,
+ # "headers": [...], ...}, but OutputManagerHelper expects
+ # outputs[prompt.prompt_key] to be the value for that prompt. Reshape
+ # so the table list lands under the prompt key.
+ if cb.get("is_agentic_table"):
+ prompt_key = cb.get("prompt_key", "")
+ if prompt_key:
+ tables = outputs.get("tables", []) if isinstance(outputs, dict) else []
+ outputs = {prompt_key: tables}
+
logger.info(
"ide_prompt_complete: operation=%s output_keys=%s prompt_ids=%s "
"doc=%s profile=%s",
diff --git a/workers/tests/test_answer_prompt.py b/workers/tests/test_answer_prompt.py
index 6c9fb9fce..4b58c4c1e 100644
--- a/workers/tests/test_answer_prompt.py
+++ b/workers/tests/test_answer_prompt.py
@@ -622,8 +622,8 @@ class TestHandleAnswerPromptRetrieval:
)
result = executor._handle_answer_prompt(ctx)
- # Answer stays "NA" (top-level NA is preserved, not sanitized)
- assert result.data[PSKeys.OUTPUT]["field_a"] == "NA"
+ # Answer stays "NA" which gets sanitized to None
+ assert result.data[PSKeys.OUTPUT]["field_a"] is None
class TestHandleAnswerPromptMultiPrompt:
@@ -747,21 +747,21 @@ class TestHandleAnswerPromptMetrics:
class TestNullSanitization:
"""Tests for _sanitize_null_values."""
- def test_na_string_preserved(self):
- """Top-level 'NA' string is preserved (not sanitized to None)."""
+ def test_na_string_becomes_none(self):
+ """Top-level 'NA' string → None."""
from executor.executors.legacy_executor import LegacyExecutor
output = {"field": "NA"}
result = LegacyExecutor._sanitize_null_values(output)
- assert result["field"] == "NA"
+ assert result["field"] is None
- def test_na_case_insensitive_preserved(self):
- """Top-level 'na' (lowercase) is preserved (not sanitized to None)."""
+ def test_na_case_insensitive(self):
+ """'na' (lowercase) → None."""
from executor.executors.legacy_executor import LegacyExecutor
output = {"field": "na"}
result = LegacyExecutor._sanitize_null_values(output)
- assert result["field"] == "na"
+ assert result["field"] is None
def test_nested_list_na(self):
"""NA in nested list items → None."""