Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: Ingesting folder doesn't seem to work

Mike Pawlowski26f06f4bff98
diff --git a/.env.example b/.env.example
index 97ffa94c2..4d36588fe 100644
--- a/.env.example
+++ b/.env.example
@@ -15,6 +15,10 @@ DISABLE_INGEST_WITH_LANGFLOW=false
# Default: 3600 seconds (60 minutes) total timeout
# INGESTION_TIMEOUT=3600
+# OPTIONAL: Maximum number of files to upload / ingest (in batch) per task when adding knowledge via folder
+# Default: 25
+# UPLOAD_BATCH_SIZE=25
+
# make one like so https://docs.langflow.org/api-keys-and-authentication#langflow-secret-key
LANGFLOW_SECRET_KEY=
diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsx
index 92505c401..1c6adca71 100644
--- a/frontend/components/knowledge-dropdown.tsx
+++ b/frontend/components/knowledge-dropdown.tsx
@@ -40,6 +40,7 @@ import { useTask } from "@/contexts/task-context";
import {
duplicateCheck,
uploadFile as uploadFileUtil,
+ uploadFiles,
} from "@/lib/upload-utils";
import { cn } from "@/lib/utils";
@@ -75,6 +76,7 @@ export function KnowledgeDropdown() {
const [showS3Dialog, setShowS3Dialog] = useState(false);
const [showDuplicateDialog, setShowDuplicateDialog] = useState(false);
const [awsEnabled, setAwsEnabled] = useState(false);
+ const [uploadBatchSize, setUploadBatchSize] = useState(25);
const [folderPath, setFolderPath] = useState("");
const [bucketUrl, setBucketUrl] = useState("s3://");
const [folderLoading, setFolderLoading] = useState(false);
@@ -98,11 +100,17 @@ export function KnowledgeDropdown() {
useEffect(() => {
const checkAvailability = async () => {
try {
- // Check AWS
+ // Check AWS and upload batch size
const awsRes = await fetch("/api/upload_options");
if (awsRes.ok) {
const awsData = await awsRes.json();
setAwsEnabled(Boolean(awsData.aws));
+ if (
+ typeof awsData.upload_batch_size === "number" &&
+ awsData.upload_batch_size > 0
+ ) {
+ setUploadBatchSize(awsData.upload_batch_size);
+ }
}
// Check cloud connectors
@@ -296,48 +304,83 @@ export function KnowledgeDropdown() {
toast.info(`Processing ${filteredFiles.length} file(s)...`);
- for (const originalFile of filteredFiles) {
- try {
- // Extract just the filename without the folder path
- const fileName =
- originalFile.name.split("/").pop() || originalFile.name;
- console.log(
- `[Folder Upload] Processing file: ${originalFile.name} -> ${fileName}`,
- );
+ // Create clean File objects (strip folder path from names)
+ const cleanFiles = filteredFiles.map((originalFile) => {
+ const fileName =
+ originalFile.name.split("/").pop() || originalFile.name;
+ return new File([originalFile], fileName, {
+ type: originalFile.type,
+ lastModified: originalFile.lastModified,
+ });
+ });
- // Create a new File object with just the basename (no folder path)
- // This is necessary because the webkitRelativePath includes the folder name
- const file = new File([originalFile], fileName, {
- type: originalFile.type,
- lastModified: originalFile.lastModified,
- });
- console.log(`[Folder Upload] Created new File object:`, {
- name: file.name,
- type: file.type,
- size: file.size,
- });
+ // Check all files for duplicates in parallel
+ const duplicateResults = await Promise.all(
+ cleanFiles.map(async (file) => {
+ try {
+ const checkData = await duplicateCheck(file);
+ return { file, isDuplicate: checkData.exists };
+ } catch (error) {
+ console.error(
+ `[Folder Upload] Duplicate check failed for ${file.name}:`,
+ error,
+ );
+ // On error, include the file (let the server handle it)
+ return { file, isDuplicate: false };
+ }
+ }),
+ );
- // Check for duplicates using the clean filename
- const checkData = await duplicateCheck(file);
- console.log(`[Folder Upload] Duplicate check result:`, checkData);
+ const nonDuplicateFiles = duplicateResults
+ .filter((r) => !r.isDuplicate)
+ .map((r) => r.file);
+ const skippedCount = duplicateResults.filter((r) => r.isDuplicate).length;
- if (!checkData.exists) {
- console.log(`[Folder Upload] Uploading file: ${fileName}`);
- await uploadFileUtil(file, false);
- console.log(`[Folder Upload] Successfully uploaded: ${fileName}`);
- } else {
- console.log(`[Folder Upload] Skipping duplicate: ${fileName}`);
- }
- } catch (error) {
- console.error(
- `[Folder Upload] Failed to upload ${originalFile.name}:`,
- error,
+ if (skippedCount > 0) {
+ console.log(
+ `[Folder Upload] Skipping ${skippedCount} duplicate file(s)`,
+ );
+ }
+
+ if (nonDuplicateFiles.length === 0) {
+ toast.info("All files already exist, nothing to upload.");
+ return;
+ }
+
+ // Chunk non-duplicate files into batches
+ const batches: File[][] = [];
+ for (let i = 0; i < nonDuplicateFiles.length; i += uploadBatchSize) {
+ batches.push(nonDuplicateFiles.slice(i, i + uploadBatchSize));
+ }
+
+ console.log(
+ `[Folder Upload] Uploading ${nonDuplicateFiles.length} file(s) in ${batches.length} batch(es)`,
+ );
+
+ // Upload each batch as a single task
+ for (const batch of batches) {
+ try {
+ const result = await uploadFiles(batch, false);
+ addTask(result.taskId);
+ console.log(
+ `[Folder Upload] Batch uploaded: taskId=${result.taskId}, files=${result.fileCount}`,
);
+ } catch (error) {
+ console.error("[Folder Upload] Batch upload failed:", error);
+ toast.error("Batch upload failed", {
+ description:
+ error instanceof Error ? error.message : "Unknown error",
+ });
}
}
refetchTasks();
- toast.success(`Successfully processed ${filteredFiles.length} file(s)`);
+ const uploadedCount = nonDuplicateFiles.length;
+ const message =
+ skippedCount > 0
+ ? `Uploaded ${uploadedCount} file(s), skipped ${skippedCount} duplicate(s)`
+ : `Successfully processed ${uploadedCount} file(s)`;
+ toast.success(message);
} catch (error) {
console.error("Folder upload error:", error);
toast.error("Folder upload failed", {
diff --git a/frontend/lib/upload-utils.ts b/frontend/lib/upload-utils.ts
index ad09bb3b4..04e5dfa9d 100644
--- a/frontend/lib/upload-utils.ts
+++ b/frontend/lib/upload-utils.ts
@@ -120,6 +120,46 @@ export async function uploadFileForContext(
}
}
+export async function uploadFiles(
+ files: File[],
+ replace = false,
+): Promise<{ taskId: string; fileCount: number }> {
+ const formData = new FormData();
+ for (const file of files) {
+ formData.append("file", file);
+ }
+ formData.append("replace_duplicates", replace.toString());
+
+ const uploadResponse = await fetch("/api/router/upload_ingest", {
+ method: "POST",
+ body: formData,
+ });
+
+ let payload: unknown;
+ try {
+ payload = await uploadResponse.json();
+ } catch {
+ throw new Error("Upload failed: unable to parse server response");
+ }
+
+ const json = typeof payload === "object" && payload !== null ? payload : {};
+
+ if (!uploadResponse.ok) {
+ const errorMessage = (json as { error?: string }).error || "Upload failed";
+ throw new Error(errorMessage);
+ }
+
+ const taskId = (json as { task_id?: string }).task_id;
+ const fileCount =
+ (json as { file_count?: number }).file_count ?? files.length;
+
+ if (!taskId) {
+ throw new Error("Upload successful but no task ID returned");
+ }
+
+ return { taskId, fileCount };
+}
+
export async function uploadFile(
file: File,
replace = false,
diff --git a/src/api/upload.py b/src/api/upload.py
index 39270cbc1..76a137fdc 100644
--- a/src/api/upload.py
+++ b/src/api/upload.py
@@ -135,7 +135,8 @@ async def upload_options(request: Request, session_manager):
aws_enabled = bool(
os.getenv("AWS_ACCESS_KEY_ID") and os.getenv("AWS_SECRET_ACCESS_KEY")
)
- return JSONResponse({"aws": aws_enabled})
+ from config.settings import UPLOAD_BATCH_SIZE
+ return JSONResponse({"aws": aws_enabled, "upload_batch_size": UPLOAD_BATCH_SIZE})
async def upload_bucket(request: Request, task_service, session_manager):
diff --git a/src/config/settings.py b/src/config/settings.py
index c4a5d9ce7..f4784e5ed 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -59,6 +59,9 @@ DISABLE_INGEST_WITH_LANGFLOW = os.getenv(
"DISABLE_INGEST_WITH_LANGFLOW", "false"
).lower() in ("true", "1", "yes")
+# Maximum number of files to upload / ingest (in batch) per task when adding knowledge via folder
+UPLOAD_BATCH_SIZE = int(os.getenv("UPLOAD_BATCH_SIZE", "25"))
+
# Langflow HTTP timeout configuration (in seconds)
# For large documents (300+ pages), ingestion can take 30+ minutes
# Default: 40 minutes total, 40 minutes read timeout