LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-3431 [FIX] Stream tool-run logs to workflow execution UI with markdown rendering (#1927)
Chandrasekharan M4022e64c5b54
diff --git a/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx b/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsxindex 9e895674b..458f31955 100644--- a/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx+++ b/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx@@ -3,6 +3,7 @@ import PropTypes from "prop-types";import { useMemo } from "react";import { Link as RouterLink } from "react-router-dom";+import { isSafeExternalUrl } from "../../../helpers/urlSafety";import { useSessionStore } from "../../../store/session-store";const { Text, Link, Paragraph } = Typography;@@ -54,11 +55,16 @@ const CustomMarkdown = ({</Text>);case "link": {- const isInternal = url?.startsWith("/");+ // Protocol-relative URLs (`//evil.com/...`) also start with `/`+ // so exclude them from the internal-route branch.+ const isInternal = url?.startsWith("/") && !url.startsWith("//");if (isInternal) {const resolvedUrl = orgName ? `/${orgName}${url}` : url;return <RouterLink to={resolvedUrl}>{content}</RouterLink>;}+ if (!isSafeExternalUrl(url)) {+ return content;+ }return (<Link href={url} target="_blank" rel="noopener noreferrer">{content}diff --git a/frontend/src/components/logging/log-modal/LogModal.jsx b/frontend/src/components/logging/log-modal/LogModal.jsxindex 2f21cb050..d70978031 100644--- a/frontend/src/components/logging/log-modal/LogModal.jsx+++ b/frontend/src/components/logging/log-modal/LogModal.jsx@@ -13,6 +13,7 @@ import { useCopyToClipboard } from "../../../hooks/useCopyToClipboard";import { useExceptionHandler } from "../../../hooks/useExceptionHandler";import useRequestUrl from "../../../hooks/useRequestUrl";import { useAlertStore } from "../../../store/alert-store";+import CustomMarkdown from "../../helpers/custom-markdown/CustomMarkdown";import { FilterDropdown, FilterIcon } from "../filter-dropdown/FilterDropdown";function LogModal({@@ -120,6 +121,7 @@ function LogModal({title: "Log",dataIndex: "log",key: "log",+ render: (log) => <CustomMarkdown text={log || ""} />,},];diff --git a/frontend/src/components/pipelines-or-deployments/log-modal/LogsModal.jsx b/frontend/src/components/pipelines-or-deployments/log-modal/LogsModal.jsxindex 09dd7ac04..9ab7e69f3 100644--- a/frontend/src/components/pipelines-or-deployments/log-modal/LogsModal.jsx+++ b/frontend/src/components/pipelines-or-deployments/log-modal/LogsModal.jsx@@ -41,7 +41,7 @@ const LogsModal = ({.then((res) => {const logDetails = res?.data?.results?.map((item) => ({id: item?.id,- log: <CustomMarkdown text={item?.data?.log} />,+ log: item?.data?.log,type: item?.data?.type,stage: item?.data?.stage,level: item?.data?.level,@@ -111,6 +111,7 @@ const LogsModal = ({title: "Log",dataIndex: "log",key: "log",+ render: (log) => <CustomMarkdown text={log || ""} />,},];diff --git a/frontend/src/helpers/urlSafety.js b/frontend/src/helpers/urlSafety.jsnew file mode 100644index 000000000..b5ca23e79--- /dev/null+++ b/frontend/src/helpers/urlSafety.js@@ -0,0 +1,19 @@+const SAFE_URL_SCHEMES = ["http:", "https:", "mailto:", "tel:"];++// Guards against unsafe schemes (e.g. `javascript:`, `data:`) when+// rendering links built from user- or tool-derived content.+const isSafeExternalUrl = (url) => {+ if (typeof url !== "string" || url === "") {+ return false;+ }+ // Parse without a base so bare strings (e.g. "javascript", "../foo") fail+ // instead of silently resolving to `https://<origin>/...` and passing.+ try {+ const parsed = new URL(url);+ return SAFE_URL_SCHEMES.includes(parsed.protocol);+ } catch {+ return false;+ }+};++export { isSafeExternalUrl, SAFE_URL_SCHEMES };diff --git a/unstract/sdk1/src/unstract/sdk1/execution/context.py b/unstract/sdk1/src/unstract/sdk1/execution/context.pyindex a1efb4c3f..83eb650a2 100644--- a/unstract/sdk1/src/unstract/sdk1/execution/context.py+++ b/unstract/sdk1/src/unstract/sdk1/execution/context.py@@ -68,6 +68,11 @@ class ExecutionContext:log_events_id: Socket.IO channel ID for streaming progresslogs to the frontend. ``None`` when not in an IDEsession (no logs published).+ execution_id: Workflow execution identifier for log+ correlation. When set, ``organization_id`` must also be+ set (enforced in ``__post_init__``).+ file_execution_id: Child identifier for per-file execution+ within a workflow run. Optional."""executor_name: str@@ -78,6 +83,8 @@ class ExecutionContext:executor_params: dict[str, Any] = field(default_factory=dict)request_id: str | None = Nonelog_events_id: str | None = None+ execution_id: str | None = None+ file_execution_id: str | None = Nonedef __post_init__(self) -> None:"""Validate required fields after initialization."""@@ -89,6 +96,10 @@ class ExecutionContext:raise ValueError("run_id is required")if not self.execution_source:raise ValueError("execution_source is required")+ # When execution_id is set, organization_id must be too — they+ # travel together for workflow-level log correlation.+ if self.execution_id and not self.organization_id:+ raise ValueError("organization_id is required when execution_id is set")# Normalize enum values to plain strings for serializationif isinstance(self.operation, Operation):@@ -111,6 +122,8 @@ class ExecutionContext:"executor_params": self.executor_params,"request_id": self.request_id,"log_events_id": self.log_events_id,+ "execution_id": self.execution_id,+ "file_execution_id": self.file_execution_id,}@classmethod@@ -125,4 +138,6 @@ class ExecutionContext:executor_params=data.get("executor_params", {}),request_id=data.get("request_id"),log_events_id=data.get("log_events_id"),+ execution_id=data.get("execution_id"),+ file_execution_id=data.get("file_execution_id"),)diff --git a/workers/executor/executor_tool_shim.py b/workers/executor/executor_tool_shim.pyindex 63f48dd25..828e64139 100644--- a/workers/executor/executor_tool_shim.py+++ b/workers/executor/executor_tool_shim.py@@ -60,6 +60,9 @@ class ExecutorToolShim(StreamMixin):platform_api_key: str = "",log_events_id: str = "",component: dict[str, str] | None = None,+ execution_id: str | None = None,+ organization_id: str | None = None,+ file_execution_id: str | None = None,) -> None:"""Initialize the shim.@@ -72,10 +75,24 @@ class ExecutorToolShim(StreamMixin):component: Structured identifier dict for log correlation(``tool_id``, ``run_id``, ``doc_name``, optionally``prompt_key``).+ execution_id: Workflow execution id. When provided with+ ``organization_id``, enables persistent log attribution+ to the ``execution_log`` table.+ organization_id: Tenant/org scope for log persistence.+ file_execution_id: File execution id (child of workflow+ execution). Optional — populated for per-file tool runs."""self.platform_api_key = platform_api_keyself.log_events_id = log_events_idself.component = component or {}+ self.execution_id = execution_id+ self.organization_id = organization_id+ self.file_execution_id = file_execution_id+ # Track whether we've already surfaced a publish failure on this+ # shim so that a down broker is flagged loudly once instead of+ # silently swallowing every subsequent log line at DEBUG.+ self._progress_publish_failed = False+ self._log_publish_failed = False# Initialize StreamMixin. EXECUTION_BY_TOOL is not set in# the worker environment, so _exec_by_tool will be False.super().__init__(log_level=LogLevel.INFO)@@ -145,24 +162,61 @@ class ExecutorToolShim(StreamMixin):return# Publish progress to frontend via the log consumer queue.- if self.log_events_id:- try:- wf_level = _SDK_TO_WF_LEVEL.get(level, "INFO")- payload = LogPublisher.log_progress(- component=self.component,- level=wf_level,- state=stage,- message=log,- )- LogPublisher.publish(- channel_id=self.log_events_id,- payload=payload,- )- except Exception:- logger.debug(- "Failed to publish progress log (non-fatal)",- exc_info=True,- )+ if not self.log_events_id:+ return++ wf_level = _SDK_TO_WF_LEVEL.get(level, "INFO")++ # PROGRESS payload — IDE prompt-card live updates only. Dropped at+ # the DB persist layer because LogPublisher.publish only stores+ # payloads whose `type == "LOG"`.+ try:+ progress_payload = LogPublisher.log_progress(+ component=self.component,+ level=wf_level,+ state=stage,+ message=log,+ )+ LogPublisher.publish(+ channel_id=self.log_events_id,+ payload=progress_payload,+ )+ except Exception:+ first_failure = not self._progress_publish_failed+ self._progress_publish_failed = True+ logger.log(+ logging.WARNING if first_failure else logging.DEBUG,+ "Failed to publish progress log (non-fatal)",+ exc_info=first_failure,+ )++ # LOG payload — feeds workflow logs UI and persists to execution_log.+ # LogDataDTO validation requires `execution_id` and `organization_id`;+ # `file_execution_id` is optional.+ if not (self.execution_id and self.organization_id):+ return++ try:+ log_payload = LogPublisher.log_workflow(+ stage=stage,+ message=log,+ level=wf_level,+ execution_id=self.execution_id,+ file_execution_id=self.file_execution_id or None,+ organization_id=self.organization_id,+ )+ LogPublisher.publish(+ channel_id=self.log_events_id,+ payload=log_payload,+ )+ except Exception:+ first_failure = not self._log_publish_failed+ self._log_publish_failed = True+ logger.log(+ logging.WARNING if first_failure else logging.DEBUG,+ "Failed to publish workflow log (non-fatal)",+ exc_info=first_failure,+ )def stream_error_and_exit(self, message: str, err: Exception | None = None) -> None:"""Log error and raise SdkError.diff --git a/workers/executor/executors/legacy_executor.py b/workers/executor/executors/legacy_executor.pyindex 18e1f4774..2a7dfc160 100644--- a/workers/executor/executors/legacy_executor.py+++ b/workers/executor/executors/legacy_executor.py@@ -57,9 +57,13 @@ class LegacyExecutor(BaseExecutor):Operation.STRUCTURE_PIPELINE.value: "_handle_structure_pipeline",}- # Defaults for log streaming (overridden by execute()).- _log_events_id: str = ""- _log_component: dict[str, str] = {}+ def __init__(self) -> None:+ # Per-request state — overwritten on every ``execute()`` call.+ 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@propertydef name(self) -> str:@@ -77,8 +81,21 @@ class LegacyExecutor(BaseExecutor):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", {})+ self._log_events_id = context.log_events_id or ""+ self._log_component = 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:@@ -121,10 +138,7 @@ class LegacyExecutor(BaseExecutor):# Stream error to FE so the user sees the failure in real-timeif self._log_events_id:try:- shim = ExecutorToolShim(- log_events_id=self._log_events_id,- component=self._log_component,- )+ shim = self._build_shim()shim.stream_log(f"Error: {exc.message or type(exc).__name__}",level=LogLevel.ERROR,@@ -133,6 +147,26 @@ class LegacyExecutor(BaseExecutor):pass # Best-effort — don't mask the original errorreturn ExecutionResult.failure(error=exc.message)+ 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# ------------------------------------------------------------------@@ -173,11 +207,7 @@ class LegacyExecutor(BaseExecutor):execution_data_dir: str | None = params.get(IKeys.EXECUTION_DATA_DIR)# Build adapter shim and X2Text- shim = ExecutorToolShim(- platform_api_key=platform_api_key,- log_events_id=self._log_events_id,- component=self._log_component,- )+ shim = self._build_shim(platform_api_key=platform_api_key)x2text = X2Text(tool=shim,adapter_instance_id=x2text_instance_id,@@ -352,6 +382,8 @@ class LegacyExecutor(BaseExecutor):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,@@ -427,6 +459,8 @@ class LegacyExecutor(BaseExecutor):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:@@ -454,6 +488,8 @@ class LegacyExecutor(BaseExecutor):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:@@ -519,10 +555,8 @@ class LegacyExecutor(BaseExecutor):extracted_text = ""index_metrics: dict = {}- shim = ExecutorToolShim(+ shim = self._build_shim(platform_api_key=extract_params.get("platform_api_key", ""),- log_events_id=self._log_events_id,- component=self._log_component,)step = 1@@ -539,6 +573,8 @@ class LegacyExecutor(BaseExecutor):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:@@ -643,6 +679,8 @@ class LegacyExecutor(BaseExecutor):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)@@ -745,6 +783,8 @@ class LegacyExecutor(BaseExecutor):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,@@ -840,6 +880,8 @@ class LegacyExecutor(BaseExecutor):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,@@ -954,11 +996,7 @@ class LegacyExecutor(BaseExecutor):usage_kwargs=usage_kwargs,)- shim = ExecutorToolShim(- platform_api_key=platform_api_key,- log_events_id=self._log_events_id,- component=self._log_component,- )+ shim = self._build_shim(platform_api_key=platform_api_key)fs_instance = FileUtils.get_fs_instance(execution_source=execution_source)logger.info(@@ -1199,11 +1237,7 @@ class LegacyExecutor(BaseExecutor):process_text_fn = Noneenable_highlight = tool_settings.get(PSKeys.ENABLE_HIGHLIGHT, False)enable_word_confidence = tool_settings.get(PSKeys.ENABLE_WORD_CONFIDENCE, False)- pipeline_shim = ExecutorToolShim(- platform_api_key=platform_api_key,- log_events_id=self._log_events_id,- component=self._log_component,- )+ pipeline_shim = self._build_shim(platform_api_key=platform_api_key)if enable_highlight:from executor.executors.plugins import ExecutorPluginLoader@@ -1371,7 +1405,7 @@ class LegacyExecutor(BaseExecutor):challenge_llm_id = tool_settings.get(PSKeys.CHALLENGE_LLM)if not challenge_llm_id:return- shim.stream_log(f"Running challenge for: {prompt_name}")+ shim.stream_log(f"Running challenge for: `{prompt_name}`")challenge_llm = llm_cls(adapter_instance_id=challenge_llm_id,tool=shim,@@ -1390,7 +1424,7 @@ class LegacyExecutor(BaseExecutor):metadata=metadata,)challenger.run()- shim.stream_log(f"Challenge verification completed for: {prompt_name}")+ shim.stream_log(f"Challenge verification completed for: `{prompt_name}`")logger.info("Challenge completed: prompt=%s", prompt_name)@staticmethod@@ -1412,7 +1446,7 @@ class LegacyExecutor(BaseExecutor):evaluator_cls = ExecutorPluginLoader.get("evaluation")if not evaluator_cls:return- shim.stream_log(f"Running evaluation for: {prompt_name}")+ shim.stream_log(f"Running evaluation for: `{prompt_name}`")evaluator = evaluator_cls(query=output.get(PSKeys.COMBINED_PROMPT, ""),context="\n".join(context_list),@@ -1476,12 +1510,11 @@ class LegacyExecutor(BaseExecutor):output.get(PSKeys.TYPE, "TEXT"),)- shim = ExecutorToolShim(+ shim = self._build_shim(platform_api_key=platform_api_key,- log_events_id=self._log_events_id,component={**self._log_component, "prompt_key": prompt_name},)- shim.stream_log(f"Processing prompt: {prompt_name}")+ shim.stream_log(f"Processing prompt: `{prompt_name}`")if variable_replacement_svc.is_variables_present(prompt_text=prompt_text):prompt_text = variable_replacement_svc.replace_variables_in_prompt(@@ -1494,7 +1527,7 @@ class LegacyExecutor(BaseExecutor):custom_data=custom_data,is_ide=execution_source == "ide",)- shim.stream_log(f"Resolved template variables for: {prompt_name}")+ shim.stream_log(f"Resolved template variables for: `{prompt_name}`")logger.info("Executing prompt: tool_id=%s name=%s run_id=%s", tool_id, prompt_name, run_id@@ -1574,7 +1607,9 @@ class LegacyExecutor(BaseExecutor):adapter_instance_id=output[PSKeys.VECTOR_DB],embedding=embedding,)- shim.stream_log(f"Initialized LLM and retrieval adapters for: {prompt_name}")+ shim.stream_log(+ f"Initialized LLM and retrieval adapters for: `{prompt_name}`"+ )except Exception as e:msg = f"Couldn't fetch adapter. {e}"logger.error(msg)@@ -1588,7 +1623,7 @@ class LegacyExecutor(BaseExecutor):retrieval_strategy = output.get(PSKeys.RETRIEVAL_STRATEGY)valid_strategies = {s.value for s in RetrievalStrategy}if retrieval_strategy in valid_strategies:- shim.stream_log(f"Retrieving context for: {prompt_name}")+ shim.stream_log(f"Retrieving context for: `{prompt_name}`")logger.info("Performing retrieval: prompt=%s strategy=%s chunk_size=%d",prompt_name,@@ -1613,14 +1648,14 @@ class LegacyExecutor(BaseExecutor):)metadata[PSKeys.CONTEXT][prompt_name] = context_listshim.stream_log(- f"Retrieved {len(context_list)} context chunks for: {prompt_name}"+ f"Retrieved {len(context_list)} context chunks for: `{prompt_name}`")logger.debug("Retrieved %d context chunks for prompt: %s",len(context_list),prompt_name,)- shim.stream_log(f"Running LLM completion for: {prompt_name}")+ shim.stream_log(f"Running LLM completion for: `{prompt_name}`")answer = answer_prompt_svc.construct_and_run_prompt(tool_settings=tool_settings,output=output,@@ -1652,7 +1687,7 @@ class LegacyExecutor(BaseExecutor):tool_id=tool_id,doc_name=doc_name,)- shim.stream_log(f"Applied type conversion for: {prompt_name}")+ shim.stream_log(f"Applied type conversion for: `{prompt_name}`")self._run_challenge_if_enabled(tool_settings=tool_settings,@@ -1676,7 +1711,7 @@ class LegacyExecutor(BaseExecutor):shim=shim,prompt_name=prompt_name,)- shim.stream_log(f"Completed prompt: {prompt_name}")+ shim.stream_log(f"Completed prompt: `{prompt_name}`")val = structured_output.get(prompt_name)if isinstance(val, str):@@ -1725,6 +1760,9 @@ class LegacyExecutor(BaseExecutor):execution_source=execution_source,organization_id=context.organization_id,request_id=context.request_id,+ log_events_id=self._log_events_id,+ execution_id=self._execution_id,+ file_execution_id=self._file_execution_id,executor_params={"llm_adapter_instance_id": output.get(PSKeys.LLM, ""),"table_settings": output.get(PSKeys.TABLE_SETTINGS, {}),@@ -1736,9 +1774,8 @@ class LegacyExecutor(BaseExecutor):},)table_ctx._log_component = self._log_component- table_ctx.log_events_id = self._log_events_id- shim.stream_log(f"Running table extraction for: {prompt_name}")+ shim.stream_log(f"Running table extraction for: `{prompt_name}`")table_result = table_executor.execute(table_ctx)if table_result.success:@@ -1747,9 +1784,9 @@ class LegacyExecutor(BaseExecutor):metrics.setdefault(prompt_name, {}).update({"table_extraction": table_metrics})- shim.stream_log(f"Table extraction completed for: {prompt_name}")+ shim.stream_log(f"Table extraction completed for: `{prompt_name}`")logger.info("TABLE extraction completed: prompt=%s", prompt_name)- shim.stream_log(f"Completed prompt: {prompt_name}")+ shim.stream_log(f"Completed prompt: `{prompt_name}`")else:structured_output[prompt_name] = ""error_msg = table_result.error or "unknown error"@@ -1759,7 +1796,7 @@ class LegacyExecutor(BaseExecutor):error_msg,)shim.stream_log(- f"Table extraction failed for {prompt_name}: {error_msg}",+ f"Table extraction failed for `{prompt_name}`: {error_msg}",level=LogLevel.ERROR,)@@ -1799,6 +1836,9 @@ class LegacyExecutor(BaseExecutor):execution_source=prompt_run_args["execution_source"],organization_id=context.organization_id,request_id=context.request_id,+ log_events_id=self._log_events_id,+ execution_id=self._execution_id,+ file_execution_id=self._file_execution_id,executor_params={"llm_adapter_instance_id": output.get(PSKeys.LLM, ""),"tool_settings": prompt_run_args["tool_settings"],@@ -1813,9 +1853,8 @@ class LegacyExecutor(BaseExecutor):},)line_item_ctx._log_component = self._log_component- line_item_ctx.log_events_id = self._log_events_id- shim.stream_log(f"Running line-item extraction for: {prompt_name}")+ shim.stream_log(f"Running line-item extraction for: `{prompt_name}`")line_item_result = line_item_executor.execute(line_item_ctx)if line_item_result.success:@@ -1828,9 +1867,9 @@ class LegacyExecutor(BaseExecutor):context_list = data.get("context")if context_list:metadata[PSKeys.CONTEXT][prompt_name] = context_list- shim.stream_log(f"Line-item extraction completed for: {prompt_name}")+ shim.stream_log(f"Line-item extraction completed for: `{prompt_name}`")logger.info("LINE_ITEM extraction completed: prompt=%s", prompt_name)- shim.stream_log(f"Completed prompt: {prompt_name}")+ shim.stream_log(f"Completed prompt: `{prompt_name}`")else:structured_output[prompt_name] = ""error_msg = line_item_result.error or "unknown error"@@ -1840,7 +1879,7 @@ class LegacyExecutor(BaseExecutor):error_msg,)shim.stream_log(- f"Line-item extraction failed for {prompt_name}: {error_msg}",+ f"Line-item extraction failed for `{prompt_name}`: {error_msg}",level=LogLevel.ERROR,)@@ -2032,11 +2071,7 @@ class LegacyExecutor(BaseExecutor):f"Context:\n---------------\n{doc_context}\n-----------------\n\nSummary:")- shim = ExecutorToolShim(- platform_api_key=platform_api_key,- log_events_id=self._log_events_id,- component=self._log_component,- )+ shim = self._build_shim(platform_api_key=platform_api_key)usage_kwargs = {"run_id": context.run_id,PSKeys.LLM_USAGE_REASON: PSKeys.SUMMARIZE,diff --git a/workers/file_processing/structure_tool_task.py b/workers/file_processing/structure_tool_task.pyindex 8df860385..87c942637 100644--- a/workers/file_processing/structure_tool_task.py+++ b/workers/file_processing/structure_tool_task.py@@ -24,6 +24,7 @@ from typing import Anyfrom file_processing.worker import appfrom shared.enums.task_enums import TaskName+from shared.infrastructure.context import StateStorefrom unstract.sdk1.constants import ToolEnv, UsageKwargsfrom unstract.sdk1.execution.context import ExecutionContext@@ -235,7 +236,22 @@ def _execute_structure_tool_impl(params: dict) -> dict:# ---- Step 1: Setup ----from executor.executor_tool_shim import ExecutorToolShim- shim = ExecutorToolShim(platform_api_key=platform_service_api_key)+ # Workflow IDs on the pre-dispatch shim let X2Text/platform helper logs+ # reach the workflow logs UI before the executor dispatch happens.+ log_events_id = StateStore.get("LOG_EVENTS_ID") or ""+ if not log_events_id:+ logger.warning(+ "LOG_EVENTS_ID missing from StateStore for execution_id=%s — "+ "tool-level logs will not stream to the workflow logs UI.",+ execution_id,+ )+ shim = ExecutorToolShim(+ platform_api_key=platform_service_api_key,+ log_events_id=log_events_id,+ execution_id=execution_id,+ file_execution_id=file_execution_id,+ organization_id=organization_id,+ )platform_helper = _create_platform_helper(shim, file_execution_id)dispatcher = ExecutionDispatcher(celery_app=app)@@ -257,6 +273,7 @@ def _execute_structure_tool_impl(params: dict) -> dict:dispatcher=dispatcher,shim=shim,file_execution_id=file_execution_id,+ execution_id=execution_id,organization_id=organization_id,source_file_name=source_file_name,fs=fs,@@ -388,6 +405,9 @@ def _execute_structure_tool_impl(params: dict) -> dict: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,@@ -533,6 +553,7 @@ def _run_agentic_extraction(dispatcher: ExecutionDispatcher,shim: Any,file_execution_id: str,+ execution_id: str,organization_id: str,source_file_name: str,fs: Any,@@ -587,6 +608,9 @@ def _run_agentic_extraction(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={"document_id": file_execution_id,"document_text": document_text,