LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
import { cloneDeep, isEqual } from "lodash";
import { CloudDownload, CloudUpload } from "lucide-react";
import PropTypes from "prop-types";
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/shims/antd-button";
import { Select } from "@/components/ui/shims/antd-inputs";
import { Col, Row, Space } from "@/components/ui/shims/antd-layout";
import { Image } from "@/components/ui/shims/antd-leaves";
import { Modal } from "@/components/ui/shims/antd-overlays";
import { Tabs } from "@/components/ui/shims/antd-structure";
import { Typography } from "@/components/ui/shims/antd-typography";
import { fetchAllPages } from "../../../helpers/pagination";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
import usePostHogEvents from "../../../hooks/usePostHogEvents";
import useRequestUrl from "../../../hooks/useRequestUrl";
import { useWorkflowCanEdit } from "../../../hooks/useWorkflowCanEdit";
import { useAlertStore } from "../../../store/alert-store";
import { AddSourceModal } from "../../input-output/add-source-modal/AddSourceModal";
import { ManageFiles } from "../../input-output/manage-files/ManageFiles";
import { CustomButton } from "../../widgets/custom-button/CustomButton";
import { ReadOnlyNotice } from "../../widgets/read-only-notice/ReadOnlyNotice";
import { ConfigureFormsLayout } from "../configure-forms-layout/ConfigureFormsLayout";
import "./ConfigureConnectorModal.css";
let RuleEngine;
let ruleEngineTabs;
try {
const ruleEnginePlugin = await import(
"../../../plugins/manual-review/rule-engine"
);
RuleEngine = ruleEnginePlugin.RuleEngine;
ruleEngineTabs = ruleEnginePlugin.ruleEngineTabs;
} catch {
// Plugin not available
}
function ConfigureConnectorModal({
open,
setOpen,
connDetails,
setConnDetails,
connType,
connMode,
workflowDetails,
handleEndpointUpdate,
endpointDetails,
formDataConfig,
setFormDataConfig,
}) {
const [availableConnectors, setAvailableConnectors] = useState([]);
const [addNewOption, setAddNewOption] = useState(null);
const [isLoadingConnectors, setIsLoadingConnectors] = useState(false);
const [showAddSourceModal, setShowAddSourceModal] = useState(false);
const [isSavingEndpoint, setIsSavingEndpoint] = useState(false);
const [activeTabKey, setActiveTabKey] = useState("1");
const [tabItems, setTabItems] = useState([
{
key: "1",
label: "Settings",
visible: true,
},
]);
const [specConfig, setSpecConfig] = useState({});
const [isSpecConfigLoading, setIsSpecConfigLoading] = useState(false);
const [selectedFolderPath, setSelectedFolderPath] = useState("");
const [isFolderSelected, setIsFolderSelected] = useState(false);
const [isPathFromFileBrowser, setIsPathFromFileBrowser] = useState(false);
const [initialFormDataConfig, setInitialFormDataConfig] = useState({});
const [initialConnectorId, setInitialConnectorId] = useState(null);
const [showUnsavedChangesModal, setShowUnsavedChangesModal] = useState(false);
const [hasInitializedFormData, setHasInitializedFormData] = useState(false);
const [schemaLoadedForSession, setSchemaLoadedForSession] = useState(false);
const [ruleEngineHasChanges, setRuleEngineHasChanges] = useState(false);
const canEdit = useWorkflowCanEdit();
// Grey out a region without touching each third-party widget inside it.
const roClass = canEdit ? undefined : "uneditable";
// Lets the single footer Save flush the HITL plugin's rules too.
const ruleEngineRef = useRef(null);
const fileExplorerRef = useRef(null);
const formRef = useRef(null);
const { setAlertDetails } = useAlertStore();
const axiosPrivate = useAxiosPrivate();
const { getUrl } = useRequestUrl();
const handleException = useExceptionHandler();
const { setPostHogCustomEvent, posthogConnectorEventText } =
usePostHogEvents();
const setUpdatedTabOptions = (tabOption) => {
setTabItems((prevTabOptions) => {
const existingIndex = prevTabOptions.findIndex(
(opt) => opt?.key === tabOption?.key,
);
if (existingIndex === -1) {
// Add new tab option
return [...prevTabOptions, tabOption];
}
// Update existing tab option (e.g., disabled state may have changed)
const updatedTabOptions = [...prevTabOptions];
updatedTabOptions[existingIndex] = tabOption;
return updatedTabOptions;
});
};
const onDBConfigTabChange = (key) => {
setActiveTabKey(key);
};
const fetchEndpointConfigSchema = () => {
if (!endpointDetails?.id) {
// No endpoint, so no schema to load - mark as loaded for session
setSchemaLoadedForSession(true);
return;
}
const requestOptions = {
method: "GET",
url: getUrl(`workflow/endpoint/${endpointDetails.id}/settings/`),
};
setIsSpecConfigLoading(true);
axiosPrivate(requestOptions)
.then((res) => {
const data = res?.data;
setSpecConfig(data?.schema || {});
})
.catch((err) => {
setAlertDetails(handleException(err, "Failed to load the spec"));
})
.finally(() => {
setIsSpecConfigLoading(false);
setSchemaLoadedForSession(true);
});
};
const fetchAvailableConnectors = (connectionType) => {
if (!connectionType || connectionType === "API") {
setAvailableConnectors([]);
return;
}
setIsLoadingConnectors(true);
fetchAllPages(axiosPrivate, {
url: getUrl("connector/"),
params: { connector_mode: connectionType },
})
.then((connectors) => {
// Separate regular connectors from "Add new connector" option
const regularConnectors = connectors.map((conn) => ({
value: conn?.id,
label: conn?.connector_name,
icon: conn?.icon,
connector: conn,
}));
// Keep "Add new connector" separate for sticky positioning
const addNewOption = {
value: "add_new",
label: "+ Add new connector",
isAddNew: true,
};
// For the Select options, only include regular connectors
const options = regularConnectors;
setAvailableConnectors(options);
setAddNewOption(addNewOption);
})
.catch((error) => {
setAvailableConnectors([]);
setAlertDetails(handleException(error, "Failed to load connectors"));
})
.finally(() => {
setIsLoadingConnectors(false);
});
};
const handleConnectorSelect = (value) => {
if (value === "add_new") {
setShowAddSourceModal(true);
} else {
const selectedConnector = availableConnectors.find(
(conn) => conn.value === value,
);
if (selectedConnector?.connector) {
setConnDetails(selectedConnector.connector);
// Track connector selection with PostHog
try {
setPostHogCustomEvent(
posthogConnectorEventText[`${connMode}:${connType}`],
{
info: `Selected a connector`,
connector_name: selectedConnector.connector.connector_name,
},
);
} catch (_err) {
// If an error occurs while setting custom posthog event, ignore it and continue
}
}
}
};
const handleConnectorCreated = (newConnectorData) => {
setShowAddSourceModal(false);
if (newConnectorData) {
const newConnectorOption = {
value: newConnectorData.id,
label: newConnectorData.connector_name,
icon: newConnectorData.icon,
connector: newConnectorData,
};
// Simply add the new connector to the existing list
setAvailableConnectors((prev) => [...prev, newConnectorOption]);
// Select the new connector
handleConnectorSelect(newConnectorData.id);
}
};
const handleFolderSelect = (folderPath, itemType) => {
setSelectedFolderPath(folderPath);
setIsFolderSelected(itemType === "folder");
setIsPathFromFileBrowser(true);
};
const handleAddFolder = () => {
if (!selectedFolderPath) {
return;
}
// HACK: For GDrive connectors, strip the "root/" prefix to avoid duplication
// since backend will add it back during execution. This helps avoid a migration
let folderPath = selectedFolderPath;
if (
isPathFromFileBrowser &&
connDetails?.connector_id?.startsWith("gdrive") &&
folderPath.startsWith("root/")
) {
folderPath = folderPath.substring(5); // Remove "root/" prefix
}
if (connType === "input") {
// SOURCE mode: Add to folders array (existing behavior)
const currentFolders = formDataConfig?.folders || [];
if (!currentFolders.includes(folderPath)) {
setFormDataConfig((prev) => ({
...prev,
folders: [...currentFolders, folderPath],
}));
}
} else if (connType === "output") {
// DESTINATION mode: Set outputFolder as single value
setFormDataConfig((prev) => ({
...prev,
outputFolder: folderPath,
}));
}
setSelectedFolderPath("");
setIsFolderSelected(false);
setIsPathFromFileBrowser(false);
};
// Configuration for UI text based on connector type
const folderSectionConfig = {
input: {
title: "Select Folder to Process",
description: "Browse and select a folder to add to processing",
buttonText: "Add Folder",
},
output: {
title: "Select Output Folder",
description: "Browse and select a folder for output files",
buttonText: "Select Folder",
},
};
const currentConfig =
folderSectionConfig[connType] || folderSectionConfig.input;
const hasUnsavedChanges = () => {
// A view-only user cannot have changed anything, so never prompt them.
if (!canEdit) {
return false;
}
// For API mode, only check RuleEngine's dirty state
if (connMode === "API") {
return ruleEngineHasChanges;
}
const hasConfigChanges = !isEqual(formDataConfig, initialFormDataConfig);
// Treat both undefined and null as "no connector" for comparison
const currentConnectorId = connDetails?.id || null;
const hasConnectorChanged = currentConnectorId !== initialConnectorId;
// Also check RuleEngine changes for DATABASE mode
return hasConfigChanges || hasConnectorChanged || ruleEngineHasChanges;
};
const handleValidateAndSubmit = async (
validatedFormData,
notifySuccess = true,
) => {
const hasConfigChanges = !isEqual(validatedFormData, initialFormDataConfig);
const hasConnectorChanged = connDetails?.id !== initialConnectorId;
const hasChanges = hasConfigChanges || hasConnectorChanged;
if (hasChanges && connDetails?.id) {
setIsSavingEndpoint(true);
try {
const updatePayload = {};
if (hasConnectorChanged) {
updatePayload.connector_instance_id = connDetails.id;
}
if (hasConfigChanges) {
updatePayload.configuration = validatedFormData;
}
if (Object.keys(updatePayload).length > 0) {
await handleEndpointUpdate(updatePayload);
}
// Update initial values after successful save
setInitialFormDataConfig(cloneDeep(validatedFormData));
setInitialConnectorId(connDetails?.id);
if (notifySuccess) {
setAlertDetails({
type: "success",
content: "Configuration saved successfully.",
});
}
return true;
} catch (error) {
setAlertDetails({
type: "error",
content:
error?.message || "Failed to save changes. Please try again.",
});
return false;
} finally {
setIsSavingEndpoint(false);
}
}
// Nothing to write.
return true;
};
const handleSave = async (validatedFormData) => {
// RJSF hands its own validated data to the submit path; the Save button
// has none and the state is current for it.
const formData = validatedFormData ?? formDataConfig;
const hasConfigChanges = !isEqual(formData, initialFormDataConfig);
if (
hasConfigChanges &&
formRef?.current &&
!formRef.current.validateForm()
) {
// RJSF shows validation errors
return false;
}
// HITL rules live in the plugin and used to need their own button. One
// Save now writes everything the modal shows. Only when they actually
// changed -- otherwise every connector save would write a rule too.
const writesRules = ruleEngineHasChanges && !!ruleEngineRef.current?.save;
// Stop here if the endpoint write failed, rather than writing half the
// configuration and closing as though everything saved. Stay quiet on
// success when rules follow: the rule write reports the real outcome, and
// a success toast ahead of its failure would read as though both landed.
if (!(await handleValidateAndSubmit(formData, !writesRules))) {
return false;
}
if (writesRules) {
setIsSavingEndpoint(true);
try {
// Keep the modal open on failure so the edit is not lost.
if (!(await ruleEngineRef.current.save())) {
return false;
}
} finally {
setIsSavingEndpoint(false);
}
}
return true;
};
// Both ways of submitting take the same path. Enter used to reach the
// endpoint-only route, so a rule edit made alongside a config edit was
// reported saved and silently dropped. The read-only styling stops the
// mouse but not the keyboard, so this is still cut when canEdit is false.
const submitIfEditable = canEdit ? handleSave : undefined;
const handleModalClose = () => {
if (hasUnsavedChanges()) {
setShowUnsavedChangesModal(true);
} else {
setOpen(false);
}
};
const handleConfirmClose = () => {
const hasConfigChanges = !isEqual(formDataConfig, initialFormDataConfig);
const hasConnectorChanged = connDetails?.id !== initialConnectorId;
// Reset form data to original DB values only if changed
if (hasConfigChanges) {
setFormDataConfig(cloneDeep(initialFormDataConfig));
}
// Reset connector to original selection only if changed
if (hasConnectorChanged) {
if (initialConnectorId && availableConnectors.length > 0) {
const originalConnector = availableConnectors.find(
(conn) => conn.value === initialConnectorId,
);
if (originalConnector?.connector) {
setConnDetails(originalConnector.connector);
}
} else if (!initialConnectorId) {
// If no initial connector, reset to no selection
setConnDetails(null);
}
}
setShowUnsavedChangesModal(false);
// Delay closing the main modal to allow confirmation modal to close first
setTimeout(() => setOpen(false), 0);
};
const handleSaveAndClose = async () => {
const saveSuccessful = await handleSave();
setShowUnsavedChangesModal(false);
if (saveSuccessful) {
// Delay closing the main modal to allow confirmation modal to close first
setTimeout(() => setOpen(false), 0);
}
};
// Load plugin tab for Human In The Loop (DATABASE connectors only)
// API connectors show RuleEngine directly without tabs
useEffect(() => {
if (connMode !== "DATABASE" || !ruleEngineTabs) {
return;
}
// Use tab configuration from the rule-engine plugin
const tabOption = { ...ruleEngineTabs };
tabOption["disabled"] = !connDetails?.id;
tabOption["visible"] = true;
setUpdatedTabOptions(tabOption);
}, [connMode, connDetails?.id]);
// Handle click-outside to clear file selection
useEffect(() => {
const handleClickOutside = (event) => {
if (
fileExplorerRef.current &&
!fileExplorerRef.current.contains(event.target)
) {
setSelectedFolderPath("");
setIsFolderSelected(false);
setIsPathFromFileBrowser(false);
}
};
if (open && connMode === "FILESYSTEM") {
document.addEventListener("mousedown", handleClickOutside);
}
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [open, connMode]);
// Fetch available connectors when modal opens and connection type is available
useEffect(() => {
if (open) {
fetchAvailableConnectors(connMode);
fetchEndpointConfigSchema();
}
}, [open, connMode]);
// Reset initialization flags when modal closes
useEffect(() => {
if (!open) {
setInitialFormDataConfig({});
setInitialConnectorId(null);
setHasInitializedFormData(false);
setSchemaLoadedForSession(false);
setRuleEngineHasChanges(false);
}
}, [open]);
// Capture initial configuration and connector after schema has loaded
// This ensures we capture after RJSF has had a chance to add defaults
useEffect(() => {
if (
open &&
!hasInitializedFormData &&
schemaLoadedForSession &&
!isSpecConfigLoading
) {
// Use a small delay to allow RJSF to process the schema and add defaults
const timeoutId = setTimeout(() => {
setInitialFormDataConfig(cloneDeep(formDataConfig));
setInitialConnectorId(connDetails?.id || null);
setHasInitializedFormData(true);
}, 100);
return () => clearTimeout(timeoutId);
}
}, [
open,
hasInitializedFormData,
schemaLoadedForSession,
isSpecConfigLoading,
formDataConfig,
connDetails?.id,
]);
// Helper function to render connector label
const renderConnectorLabel = (connDetails, availableConnectors) => {
if (!connDetails?.id) {
return undefined;
}
const selectedConnector = availableConnectors.find(
(conn) => conn.value === connDetails.id,
);
return (
<Space>
{selectedConnector?.icon && !selectedConnector?.isAddNew && (
<Image
src={selectedConnector.icon}
width={20}
height={20}
preview={false}
/>
)}
<span>{selectedConnector?.label}</span>
</Space>
);
};
// Memoized dropdown render function
const renderDropdown = useCallback(
(menu) => (
<>
<div className="connector-dropdown-menu-container">{menu}</div>
{addNewOption && (
<button
className="connector-dropdown-add-new"
onClick={() => handleConnectorSelect("add_new")}
type="button"
aria-label="Add new connector"
>
<Space>
<span>{addNewOption.label}</span>
</Space>
</button>
)}
</>
),
[addNewOption, handleConnectorSelect],
);
return (
<Modal
open={open}
onCancel={handleModalClose}
confirmLoading={isSavingEndpoint}
closable={!isSavingEndpoint}
centered
footer={
connDetails?.id || connMode === "API" ? (
<div className="conn-modal-footer">
<Button onClick={handleModalClose}>
{canEdit ? "Cancel" : "Close"}
</Button>
{canEdit && (
<Button
type="primary"
loading={isSavingEndpoint}
// Wrapped: a bare reference would hand the click event to
// handleSave's validated-data parameter.
onClick={() => handleSave()}
disabled={!hasUnsavedChanges()}
>
Save
</Button>
)}
</div>
) : null
}
width={1200}
maskClosable={false}
>
<div className="conn-modal-body">
<Typography.Text className="modal-header" strong>
{connMode === "API" ? "Configure HITL Rules" : "Configure Connector"}
</Typography.Text>
{!canEdit && <ReadOnlyNotice />}
{/* Connector Selection Dropdown (not shown for API connectors) */}
{connMode !== "API" && (
<div className={`connector-selection-section ${roClass ?? ""}`}>
<Typography.Text strong className="connector-selection-label">
Select Connector
</Typography.Text>
<Select
className="connector-selection-dropdown"
placeholder="Select a connector"
showSearch
filterOption={(input, option) => {
return option?.data?.label
?.toLowerCase()
.includes(input.toLowerCase());
}}
value={
connDetails?.id
? {
value: connDetails.id,
label: renderConnectorLabel(
connDetails,
availableConnectors,
),
}
: undefined
}
labelInValue
onChange={(option) => handleConnectorSelect(option?.value)}
loading={isLoadingConnectors}
options={availableConnectors.map((conn) => ({
value: conn.value,
label: (
<Space>
{conn.icon && !conn.isAddNew && (
<Image
src={conn.icon}
width={20}
height={20}
preview={false}
/>
)}
<span>{conn.label}</span>
</Space>
),
data: conn,
}))}
optionRender={(option) => option.label}
dropdownRender={renderDropdown}
/>
</div>
)}
{/* Show placeholder when no connector is selected (not for API connectors) */}
{!connDetails?.id && connMode !== "API" && (
<div className="connector-placeholder">
{connType === "input" ? (
<CloudDownload className="connector-placeholder-icon" />
) : (
<CloudUpload className="connector-placeholder-icon" />
)}
<Typography.Text className="connector-placeholder-text">
Select an existing connector or create a new connector to continue
</Typography.Text>
</div>
)}
{/* API connectors: Show only HITL rules (no connector selection needed) */}
{connMode === "API" && RuleEngine && (
<div className="conn-modal-hitl-body">
<div className={roClass}>
<RuleEngine
ref={ruleEngineRef}
workflowDetails={workflowDetails}
ruleType="API"
onDirtyStateChange={setRuleEngineHasChanges}
/>
</div>
</div>
)}
{/* Only show configuration form and file browser after a connector is selected */}
{connDetails?.id && connMode !== "API" && (
<>
{/* DATABASE connectors: Show tabs with Settings and Human In The Loop */}
{connMode === "DATABASE" ? (
<Tabs
activeKey={activeTabKey}
onChange={onDBConfigTabChange}
className="conn-modal-col"
items={tabItems
.filter((item) => item.visible !== false)
.map((item) => ({
key: item.key,
label: item.label,
disabled: item.disabled,
// One Save writes both panes, so leaving one must not
// discard the edits it holds.
keepMounted: true,
children: (
<div className={roClass}>
{item.key === "1" && (
<ConfigureFormsLayout
specConfig={specConfig}
formDataConfig={formDataConfig}
setFormDataConfig={setFormDataConfig}
isSpecConfigLoading={isSpecConfigLoading}
formRef={formRef}
validateAndSubmit={submitIfEditable}
/>
)}
{item.key === "MANUALREVIEW" && RuleEngine && (
<RuleEngine
ref={ruleEngineRef}
workflowDetails={workflowDetails}
ruleType="DB"
onDirtyStateChange={setRuleEngineHasChanges}
/>
)}
</div>
),
}))}
/>
) : (
/* Other connector types: Show existing layout */
<Row className={`conn-modal-row ${roClass ?? ""}`} gutter={24}>
{/* Left side - Configuration Form */}
<Col span={12} className="conn-modal-col">
<div className="conn-modal-fs-config">
<ConfigureFormsLayout
specConfig={specConfig}
formDataConfig={formDataConfig}
setFormDataConfig={setFormDataConfig}
isSpecConfigLoading={isSpecConfigLoading}
formRef={formRef}
validateAndSubmit={submitIfEditable}
/>
</div>
</Col>
{/* Right side - File System Browser (only for FILESYSTEM connectors) */}
{connMode === "FILESYSTEM" && connDetails?.id && (
<Col span={12} className="conn-modal-col form-right">
<div className="file-browser-section" ref={fileExplorerRef}>
<div className="file-browser-header">
<div className="file-browser-content">
<Typography.Text strong style={{ display: "block" }}>
{currentConfig.title}
</Typography.Text>
<Typography.Text
type="secondary"
className="field-description"
>
{currentConfig.description}
</Typography.Text>
</div>
<CustomButton
type="primary"
size="small"
disabled={!isFolderSelected}
onClick={handleAddFolder}
>
{currentConfig.buttonText}
</CustomButton>
</div>
<ManageFiles
selectedConnector={connDetails?.id}
onFolderSelect={handleFolderSelect}
selectedFolderPath={selectedFolderPath}
/>
</div>
</Col>
)}
</Row>
)}
</>
)}
</div>
{/* Add Source Modal for creating new connectors */}
{showAddSourceModal && (
<AddSourceModal
open={showAddSourceModal}
setOpen={setShowAddSourceModal}
isConnector={true}
type={connType}
connectorMode={connMode}
addNewItem={handleConnectorCreated}
editItemId={null}
setEditItemId={() => {
// No-op: editing not supported from this modal
}}
/>
)}
{/* Unsaved Changes Confirmation Modal */}
<Modal
title="Unsaved Changes"
open={showUnsavedChangesModal}
onCancel={() => setShowUnsavedChangesModal(false)}
footer={[
<Button
key="discard"
onClick={handleConfirmClose}
disabled={isSavingEndpoint}
>
Close without Saving
</Button>,
<Button
key="save"
type="primary"
onClick={handleSaveAndClose}
loading={isSavingEndpoint}
>
Save
</Button>,
]}
centered
>
You have unsaved changes. Do you want to save them before closing?
</Modal>
</Modal>
);
}
ConfigureConnectorModal.propTypes = {
open: PropTypes.bool.isRequired,
setOpen: PropTypes.func.isRequired,
connDetails: PropTypes.object,
setConnDetails: PropTypes.func.isRequired,
connType: PropTypes.string.isRequired,
connMode: PropTypes.string,
workflowDetails: PropTypes.object.isRequired,
handleEndpointUpdate: PropTypes.func.isRequired,
endpointDetails: PropTypes.object,
formDataConfig: PropTypes.object,
setFormDataConfig: PropTypes.func.isRequired,
};
export { ConfigureConnectorModal };