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-3393 [FEAT] Wire AuditSerializer subclasses through SanitizedSerializerMixin (#1966)
Chandrasekharan M7b9a7a278555
diff --git a/backend/api_v2/serializers.py b/backend/api_v2/serializers.pyindex a8703f01d..7a6014c84 100644--- a/backend/api_v2/serializers.py+++ b/backend/api_v2/serializers.py@@ -29,7 +29,7 @@ from tenant_account_v2.sharing_helpers import (serialize_group_refs,serialize_owner_refs,)-from utils.input_sanitizer import validate_name_field, validate_no_html_tags+from utils.input_sanitizer import validate_name_fieldfrom utils.serializer.integrity_error_mixin import IntegrityErrorMixinfrom workflow_manager.endpoint_v2.models import WorkflowEndpointfrom workflow_manager.workflow_v2.exceptions import ExecutionDoesNotExistError@@ -84,11 +84,6 @@ class APIDeploymentSerializer(IntegrityErrorMixin, AuditSerializer):def validate_display_name(self, value: str) -> str:return validate_name_field(value, field_name="Display name")- def validate_description(self, value: str) -> str:- if value is None:- return value- return validate_no_html_tags(value, field_name="Description")-def validate_workflow(self, workflow):"""Validate that the workflow has properly configured source and destination endpoints."""# Get all endpoints for this workflow with related datadiff --git a/backend/backend/serializers.py b/backend/backend/serializers.pyindex 6f788f028..36708f2fe 100644--- a/backend/backend/serializers.py+++ b/backend/backend/serializers.py@@ -1,6 +1,6 @@from typing import Any-from rest_framework.serializers import ModelSerializer+from utils.serializer import ModelSerializerfrom backend.constants import RequestKeydiff --git a/backend/notification_v2/serializers.py b/backend/notification_v2/serializers.pyindex 3cd708575..751cbf4fa 100644--- a/backend/notification_v2/serializers.py+++ b/backend/notification_v2/serializers.py@@ -1,5 +1,6 @@from rest_framework import serializersfrom utils.input_sanitizer import validate_name_field+from utils.serializer import ModelSerializerfrom .enums import AuthorizationType, NotificationType, PlatformTypefrom .models import Notification@@ -13,7 +14,7 @@ class NotificationSettingsSerializer(serializers.Serializer):club_interval_seconds = serializers.IntegerField(min_value=60, max_value=7200)-class NotificationSerializer(serializers.ModelSerializer):+class NotificationSerializer(ModelSerializer):notification_type = serializers.ChoiceField(choices=NotificationType.choices())authorization_type = serializers.ChoiceField(choices=AuthorizationType.choices())platform = serializers.ChoiceField(choices=PlatformType.choices(), required=False)diff --git a/backend/prompt_studio/prompt_studio_core_v2/serializers.py b/backend/prompt_studio/prompt_studio_core_v2/serializers.pyindex acb3a243d..8525b7f08 100644--- a/backend/prompt_studio/prompt_studio_core_v2/serializers.py+++ b/backend/prompt_studio/prompt_studio_core_v2/serializers.py@@ -11,7 +11,7 @@ from tenant_account_v2.sharing_helpers import (serialize_owner_refs,)from utils.FileValidator import FileValidator-from utils.input_sanitizer import validate_name_field, validate_no_html_tags+from utils.input_sanitizer import validate_name_fieldfrom utils.serializer.integrity_error_mixin import IntegrityErrorMixinfrom backend.serializers import AuditSerializer@@ -106,6 +106,13 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):extra_kwargs = {"shared_to_org": {"read_only": True},}+ # LLM-facing text legitimately contains XML-like markup.+ html_safe_fields = (+ "summarize_prompt",+ "preamble",+ "postamble",+ "output",+ )unique_error_message_map: dict[str, dict[str, str]] = {"unique_tool_name": {@@ -119,11 +126,6 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):def validate_tool_name(self, value: str) -> str:return validate_name_field(value, field_name="Tool name")- def validate_description(self, value: str) -> str:- if value is None:- return value- return validate_no_html_tags(value, field_name="Description")-def validate_summarize_llm_adapter(self, value):"""Validate that the adapter type is LLM and is accessible to the user."""if value is None:diff --git a/backend/prompt_studio/prompt_studio_output_manager_v2/serializers.py b/backend/prompt_studio/prompt_studio_output_manager_v2/serializers.pyindex 1c56e2323..d484391a6 100644--- a/backend/prompt_studio/prompt_studio_output_manager_v2/serializers.py+++ b/backend/prompt_studio/prompt_studio_output_manager_v2/serializers.py@@ -16,6 +16,8 @@ class PromptStudioOutputSerializer(AuditSerializer):class Meta:model = PromptStudioOutputManagerfields = "__all__"+ # LLM output/context legitimately contains XML-like tags.+ html_safe_fields = ("output", "context")def to_representation(self, instance):data = super().to_representation(instance)diff --git a/backend/prompt_studio/prompt_studio_v2/serializers.py b/backend/prompt_studio/prompt_studio_v2/serializers.pyindex 4026f32b9..f0fe082d6 100644--- a/backend/prompt_studio/prompt_studio_v2/serializers.py+++ b/backend/prompt_studio/prompt_studio_v2/serializers.py@@ -29,6 +29,13 @@ class ToolStudioPromptSerializer(AuditSerializer):# View owns uniqueness (IntegrityError->DuplicateData on create); drop# the DRF auto-validator that 400s on re-save / PUT before the view runs.validators = []+ # Prompts and LLM output legitimately contain XML-like markup.+ html_safe_fields = (+ "prompt",+ "assert_prompt",+ "assertion_failure_prompt",+ "output",+ )class ToolStudioIndexSerializer(serializers.Serializer):diff --git a/backend/tags/serializers.py b/backend/tags/serializers.pyindex a0b63dbc6..6dc6cfac9 100644--- a/backend/tags/serializers.py+++ b/backend/tags/serializers.py@@ -3,11 +3,12 @@ import refrom rest_framework import serializersfrom rest_framework.serializers import CharField, ValidationError+from utils.serializer import ModelSerializerfrom tags.models import Tag-class TagSerializer(serializers.ModelSerializer):+class TagSerializer(ModelSerializer):class Meta:model = Tagfields = ["id", "name", "description"]diff --git a/backend/utils/serializer/sanitization.py b/backend/utils/serializer/sanitization.pyindex 3c53ed73d..70853abd9 100644--- a/backend/utils/serializer/sanitization.py+++ b/backend/utils/serializer/sanitization.py@@ -36,9 +36,14 @@ class SanitizedSerializerMixin:if name in exempt or field.read_only:continueif isinstance(field, drf.CharField):+ # Prefer a user-visible label so errors read like+ # "Prompt key must not contain..." instead of "prompt_key must...".+ display_name = field.label or name.replace("_", " ").capitalize()# partial binds the field name at iteration time, avoiding the# late-binding closure trap of a bare lambda.- field.validators.append(partial(validate_no_html_tags, field_name=name))+ field.validators.append(+ partial(validate_no_html_tags, field_name=display_name)+ )class ModelSerializer(SanitizedSerializerMixin, drf.ModelSerializer):diff --git a/backend/utils/tests/test_sanitized_serializer_mixin.py b/backend/utils/tests/test_sanitized_serializer_mixin.pyindex 18c537a72..0eb09c77f 100644--- a/backend/utils/tests/test_sanitized_serializer_mixin.py+++ b/backend/utils/tests/test_sanitized_serializer_mixin.py@@ -56,6 +56,17 @@ class TestSanitizedSerializerMixin:msg = str(s.errors["description"][0])assert "description" in msg.lower()+ def test_error_message_uses_humanised_field_name(self):+ """snake_case field names are surfaced as 'Snake case' in user-visible errors."""++ class SnakeCaseSerializer(Serializer):+ prompt_key = drf.CharField()++ s = SnakeCaseSerializer(data={"prompt_key": "<script>x</script>"})+ assert not s.is_valid()+ msg = str(s.errors["prompt_key"][0])+ assert msg.startswith("Prompt key ")+def test_html_safe_fields_opts_out(self):s = WithOptOutSerializer(data={"name": "ok", "prompt": "<thinking>step 1</thinking>"}diff --git a/backend/workflow_manager/workflow_v2/serializers.py b/backend/workflow_manager/workflow_v2/serializers.pyindex f96c3bd70..7ee69b137 100644--- a/backend/workflow_manager/workflow_v2/serializers.py+++ b/backend/workflow_manager/workflow_v2/serializers.py@@ -19,7 +19,7 @@ from tenant_account_v2.sharing_helpers import ()from tool_instance_v2.serializers import ToolInstanceSerializerfrom tool_instance_v2.tool_instance_helper import ToolInstanceHelper-from utils.input_sanitizer import validate_name_field, validate_no_html_tags+from utils.input_sanitizer import validate_name_fieldfrom utils.serializer.integrity_error_mixin import IntegrityErrorMixinfrom backend.constants import RequestKey@@ -64,11 +64,6 @@ class WorkflowSerializer(IntegrityErrorMixin, AuditSerializer):def validate_workflow_name(self, value: str) -> str:return validate_name_field(value, field_name="Workflow name")- def validate_description(self, value: str) -> str:- if value is None:- return value- return validate_no_html_tags(value, field_name="Description")-def to_representation(self, instance: Workflow) -> dict[str, str]:representation: dict[str, str] = super().to_representation(instance)representation[WorkflowKey.WF_NAME] = instance.workflow_namediff --git a/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx b/frontend/src/components/custom-tools/document-parser/DocumentParser.jsxindex 63b1a037c..c7d9fd100 100644--- a/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx+++ b/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx@@ -37,6 +37,19 @@ try {const UUID_RE =/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const getFieldErrors = (err) => {+ const data = err?.response?.data;+ if (data?.type !== "validation_error" || !Array.isArray(data?.errors)) {+ return {};+ }+ return data.errors.reduce((acc, e) => {+ if (e?.attr) {+ acc[e.attr] = e.detail || "Invalid value";+ }+ return acc;+ }, {});+};+function DocumentParser({addPromptInstance,scrollToBottom,@@ -140,7 +153,12 @@ function DocumentParser({return `/api/v1/unstract/${sessionDetails?.orgId}/prompt-studio/prompt/${urlPath}`;};- const handleChangePromptCard = async (name, value, promptId) => {+ const handleChangePromptCard = async (+ name,+ value,+ promptId,+ onFieldError,+ ) => {const promptsAndNotes = details?.prompts || [];if (name === "prompt_key") {@@ -205,7 +223,14 @@ function DocumentParser({return res;}).catch((err) => {- setAlertDetails(handleException(err, "Failed to update"));+ // Reporting the rejection is opt-in: a caller that will not report it+ // itself returns false and gets the alert, so a rejected value can+ // never fail silently.+ const handledInline = onFieldError?.(getFieldErrors(err));+ if (!handledInline) {+ setAlertDetails(handleException(err, "Failed to update"));+ }+ throw err;});};diff --git a/frontend/src/components/custom-tools/editable-text/EditableText.css b/frontend/src/components/custom-tools/editable-text/EditableText.cssindex 11eb9356e..6ffdc4164 100644--- a/frontend/src/components/custom-tools/editable-text/EditableText.css+++ b/frontend/src/components/custom-tools/editable-text/EditableText.css@@ -20,3 +20,9 @@font-weight: bold;font-size: 13px;}++.editable-text-error-message {+ display: block;+ margin-top: 2px;+ font-size: 12px;+}diff --git a/frontend/src/components/custom-tools/editable-text/EditableText.jsx b/frontend/src/components/custom-tools/editable-text/EditableText.jsxindex eba4dd750..e4bc7b1b4 100644--- a/frontend/src/components/custom-tools/editable-text/EditableText.jsx+++ b/frontend/src/components/custom-tools/editable-text/EditableText.jsx@@ -2,6 +2,7 @@ import debounce from "lodash/debounce";import PropTypes from "prop-types";import { useCallback, useEffect, useRef, useState } from "react";import { Input } from "@/components/ui/shims/antd-inputs";+import { Typography } from "@/components/ui/shims/antd-typography";import "./EditableText.css";import { useCustomToolStore } from "../../../store/custom-tool-store";@@ -17,6 +18,7 @@ function EditableText({isTextarea,placeHolder,isCoverageLoading,+ error,}) {const name = isTextarea ? "prompt" : "prompt_key";const [triggerHandleChange, setTriggerHandleChange] = useState(false);@@ -25,6 +27,11 @@ function EditableText({const { isSinglePassExtractLoading, isPublicSource } = useCustomToolStore();useEffect(() => {+ // A rejected edit rolls the stored value back; keep the typed text on+ // screen so the user can correct it in place.+ if (error) {+ return;+ }setText(defaultText);}, [defaultText]);@@ -59,7 +66,7 @@ function EditableText({if (!triggerHandleChange) {return;}- handleChange(text, promptId, name, true, false);+ handleChange(text, promptId, name, true, false).catch(() => {});setTriggerHandleChange(false);}, [triggerHandleChange]);@@ -94,24 +101,32 @@ function EditableText({}return (- <Input- className="width-100 input-header-text"- value={text}- onChange={handleTextChange}- placeholder="Enter Key"- name={name}- size="small"- style={{ backgroundColor: "transparent" }}- variant={`${!isEditing && !isHovered ? "borderless" : "outlined"}`}- autoSize={true}- onMouseOver={() => setIsHovered(true)}- onMouseOut={() => setIsHovered(false)}- onBlur={handleBlur}- onClick={() => setIsEditing(true)}- disabled={- isCoverageLoading || isSinglePassExtractLoading || isPublicSource- }- />+ <>+ <Input+ className="width-100 input-header-text"+ value={text}+ onChange={handleTextChange}+ placeholder="Enter Key"+ name={name}+ size="small"+ style={{ backgroundColor: "transparent" }}+ variant={`${!isEditing && !isHovered ? "borderless" : "outlined"}`}+ autoSize={true}+ onMouseOver={() => setIsHovered(true)}+ onMouseOut={() => setIsHovered(false)}+ onBlur={handleBlur}+ onClick={() => setIsEditing(true)}+ disabled={+ isCoverageLoading || isSinglePassExtractLoading || isPublicSource+ }+ status={error ? "error" : undefined}+ />+ {error && (+ <Typography.Text type="danger" className="editable-text-error-message">+ {error}+ </Typography.Text>+ )}+ </>);}@@ -126,6 +141,7 @@ EditableText.propTypes = {isTextarea: PropTypes.bool,placeHolder: PropTypes.string,isCoverageLoading: PropTypes.bool.isRequired,+ error: PropTypes.string,};export { EditableText };diff --git a/frontend/src/components/custom-tools/prompt-card/Header.jsx b/frontend/src/components/custom-tools/prompt-card/Header.jsxindex a90ed8f47..0f8e28d19 100644--- a/frontend/src/components/custom-tools/prompt-card/Header.jsx+++ b/frontend/src/components/custom-tools/prompt-card/Header.jsx@@ -97,6 +97,7 @@ function Header({handleSpsLoading,enforceType,isAgenticTableReady = true,+ promptKeyError,}) {const {selectedDoc,@@ -384,6 +385,7 @@ function Header({handleChange={handleChange}placeHolder={updatePlaceHolder}isCoverageLoading={isCoverageLoading}+ error={promptKeyError}/></Col><Col span={12} className="display-flex-right">@@ -563,6 +565,7 @@ Header.propTypes = {handleSpsLoading: PropTypes.func.isRequired,enforceType: PropTypes.string,isAgenticTableReady: PropTypes.bool,+ promptKeyError: PropTypes.string,};export { Header };diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsxindex 437e27751..cbc9e9590 100644--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx@@ -1,5 +1,5 @@import PropTypes from "prop-types";-import { memo, useEffect, useState } from "react";+import { memo, useEffect, useRef, useState } from "react";import {PROMPT_RUN_API_STATUSES,@@ -27,6 +27,10 @@ try {const useEnforceTypeSwitchGate =useEnforceTypeSwitchGatePlugin || (() => () => null);+// Fields with an inline error renderer on the card. Anything else falls back+// to the global alert, so widening the sanitizer cannot silence a rejection.+const RENDERABLE_FIELD_ERRORS = new Set(["prompt_key"]);+const PromptCard = memo(({promptDetails,@@ -53,6 +57,11 @@ const PromptCard = memo(const [promptKey, setPromptKey] = useState("");const [promptText, setPromptText] = useState("");const [selectedLlmProfileId, setSelectedLlmProfileId] = useState(null);+ const [fieldErrors, setFieldErrors] = useState({});+ // Per-field attempt counter. The key input is debounced, not disabled+ // while saving, so a slow rejection can land after a newer attempt has+ // already been accepted; only the latest attempt may touch state.+ const attemptGen = useRef({});const [isCoverageLoading, setIsCoverageLoading] = useState(false);const [openOutputForDoc, setOpenOutputForDoc] = useState(false);@@ -165,6 +174,21 @@ const PromptCard = memo(*/const prevValue = promptDetailsState?.[name];+ const generation = (attemptGen.current[name] =+ (attemptGen.current[name] || 0) + 1);+ const isLatestAttempt = () => attemptGen.current[name] === generation;++ const clearFieldError = () =>+ setFieldErrors((prev) => {+ if (!(name in prev)) return prev;+ const next = { ...prev };+ delete next[name];+ return next;+ });++ // New attempt — drop any prior inline error for this field.+ clearFieldError();+handleUpdateStatus(isUpdateStatus,promptId,@@ -172,13 +196,39 @@ const PromptCard = memo(setUpdateStatus,);setPromptDetailsState((prev) => ({ ...prev, [name]: value }));- return handleChangePromptCard(name, value, promptId)++ // Collected here but applied in the rejection handler, so the inline+ // error and the rollback below always land in the same render.+ let inlineErrors = null;+ const reportFieldError = (errors) => {+ // A superseded attempt reports nothing: the newer one owns the field+ // and surfaces its own outcome, so an alert here would contradict the+ // value the user can see was accepted.+ if (!isLatestAttempt()) {+ return true;+ }+ const renderable = Object.entries(errors).filter(([attr]) =>+ RENDERABLE_FIELD_ERRORS.has(attr),+ );+ // Nothing renderable — the caller falls back to the global alert so a+ // rejected value can never fail silently.+ if (!renderable.length) {+ return false;+ }+ inlineErrors = Object.fromEntries(renderable);+ return true;+ };++ return handleChangePromptCard(name, value, promptId, reportFieldError).then((res) => {const data = res?.data;setUpdatedPromptsCopy((prev) => {prev[promptId] = data;return prev;});+ if (isLatestAttempt()) {+ clearFieldError();+ }handleUpdateStatus(isUpdateStatus,promptId,@@ -186,10 +236,20 @@ const PromptCard = memo(setUpdateStatus,);})- .catch(() => {+ .catch((err) => {handleUpdateStatus(isUpdateStatus, promptId, null, setUpdateStatus);- // Roll back only the field that failed, for the same reason.- setPromptDetailsState((prev) => ({ ...prev, [name]: prevValue }));+ if (isLatestAttempt()) {+ // Roll the field back to the stored value even when the rejected+ // text stays in the input: outputs, highlights and confidence are+ // keyed off prompt_key and have to track the server.+ setPromptDetailsState((prev) => ({ ...prev, [name]: prevValue }));+ if (inlineErrors) {+ setFieldErrors((prev) => ({ ...prev, ...inlineErrors }));+ }+ }+ // Callers keeping their own copy of the value (Header's webhook and+ // toggle state) roll back off this rejection.+ throw err;}).finally(() => {if (isUpdateStatus) {@@ -202,11 +262,12 @@ const PromptCard = memo(const handleSelectDefaultLLM = (llmProfileId) => {setSelectedLlmProfileId(llmProfileId);+ // Error already surfaced by handleChange; no local copy to roll back.handleChange(llmProfileId,promptDetailsState?.prompt_id,"profile_manager",- );+ ).catch(() => {});};const addCoordsToFlattened = (coords, flattened) => {@@ -288,7 +349,12 @@ const PromptCard = memo(setAlertDetails({ type: "error", content: block.reason });return;}- handleChange(value, promptDetailsState?.prompt_id, "enforce_type", true);+ handleChange(+ value,+ promptDetailsState?.prompt_id,+ "enforce_type",+ true,+ ).catch(() => {});};const handleSpsLoading = (docId, isLoadingStatus) => {@@ -390,6 +456,7 @@ const PromptCard = memo(coverageCountData={coverageCountData}isChallenge={isChallenge}handleSelectHighlight={handleSelectHighlight}+ fieldErrors={fieldErrors}/><OutputForDocModalopen={openOutputForDoc}diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsxindex dace59fcd..699f68f70 100644--- a/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx+++ b/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx@@ -70,6 +70,7 @@ function PromptCardItems({coverageCountData,isChallenge,handleSelectHighlight,+ fieldErrors,}) {const {llmProfiles,@@ -191,6 +192,7 @@ function PromptCardItems({handleSpsLoading={handleSpsLoading}enforceType={enforceType}isAgenticTableReady={isAgenticTableReady}+ promptKeyError={fieldErrors?.prompt_key}/></Space></div>@@ -333,6 +335,7 @@ function PromptCardItems({}PromptCardItems.propTypes = {+ fieldErrors: PropTypes.object,promptDetails: PropTypes.object.isRequired,enforceTypeList: PropTypes.array,allTableSettings: PropTypes.array,