OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: unify document delete response shape across APIs and SDKs
Olfa Maslah9e650165c3ef
diff --git a/sdks/python/openrag_sdk/documents.py b/sdks/python/openrag_sdk/documents.pyindex 4917dc587..f5e483ddc 100644--- a/sdks/python/openrag_sdk/documents.py+++ b/sdks/python/openrag_sdk/documents.py@@ -146,7 +146,13 @@ class DocumentsClient:except NotFoundError as e:# Keep delete idempotent for SDK callers: a missing document is not an exception.if getattr(e, "status_code", None) == 404:- return DeleteDocumentResponse(success=False, deleted_chunks=0)+ return DeleteDocumentResponse(+ success=False,+ deleted_chunks=0,+ filename=filename,+ message=None,+ error=getattr(e, "message", "Resource not found"),+ )raisedata = response.json()diff --git a/sdks/python/openrag_sdk/models.py b/sdks/python/openrag_sdk/models.pyindex 6496332ac..46dfe7878 100644--- a/sdks/python/openrag_sdk/models.py+++ b/sdks/python/openrag_sdk/models.py@@ -95,6 +95,9 @@ class DeleteDocumentResponse(BaseModel):success: booldeleted_chunks: int = 0+ filename: str | None = None+ message: str | None = None+ error: str | None = None# Chat history modelsdiff --git a/sdks/typescript/src/documents.ts b/sdks/typescript/src/documents.tsindex a8726cb07..2ec4a555b 100644--- a/sdks/typescript/src/documents.ts+++ b/sdks/typescript/src/documents.ts@@ -159,6 +159,9 @@ export class DocumentsClient {return {success: data.success ?? false,deleted_chunks: data.deleted_chunks ?? 0,+ filename: data.filename ?? filename,+ message: data.message ?? null,+ error: data.error ?? null,};} catch (error) {// Delete is idempotent: if no chunks match, backend may return 404.@@ -167,6 +170,9 @@ export class DocumentsClient {return {success: false,deleted_chunks: 0,+ filename,+ message: null,+ error: (error as Error)?.message ?? "Resource not found",};}throw error;diff --git a/sdks/typescript/src/types.ts b/sdks/typescript/src/types.tsindex 7a4b73b81..f1ca0723c 100644--- a/sdks/typescript/src/types.ts+++ b/sdks/typescript/src/types.ts@@ -74,6 +74,9 @@ export interface IngestTaskStatus {export interface DeleteDocumentResponse {success: boolean;deleted_chunks: number;+ filename?: string | null;+ message?: string | null;+ error?: string | null;}// Chat history typesdiff --git a/src/api/documents.py b/src/api/documents.pyindex 00b146c1a..35e537e37 100644--- a/src/api/documents.py+++ b/src/api/documents.py@@ -13,6 +13,92 @@ class DeleteDocumentBody(BaseModel):filename: str+async def delete_documents_by_filename_core(+ filename: str,+ session_manager,+ user_id: str,+ jwt_token: str | None,+):+ """Shared delete-by-filename logic for v1 and non-v1 endpoints."""+ from config.settings import get_index_name+ from utils.opensearch_queries import build_filename_delete_body++ normalized_filename = (filename or "").strip()+ if not normalized_filename:+ return (+ {+ "success": False,+ "deleted_chunks": 0,+ "filename": normalized_filename,+ "message": None,+ "error": "Filename is required",+ },+ 400,+ )++ try:+ opensearch_client = session_manager.get_user_opensearch_client(+ user_id, jwt_token+ )+ delete_query = build_filename_delete_body(normalized_filename)+ result = await opensearch_client.delete_by_query(+ index=get_index_name(),+ body=delete_query,+ conflicts="proceed",+ )++ deleted_count = result.get("deleted", 0)+ logger.info(+ f"Deleted {deleted_count} chunks for filename {normalized_filename}",+ user_id=user_id,+ )++ if deleted_count == 0:+ return (+ {+ "success": False,+ "deleted_chunks": 0,+ "filename": normalized_filename,+ "message": None,+ "error": "No matching document chunks were deleted. The file may be missing or not deletable in the current user context.",+ },+ 404,+ )++ return (+ {+ "success": True,+ "deleted_chunks": deleted_count,+ "filename": normalized_filename,+ "message": f"All documents with filename '{normalized_filename}' deleted successfully",+ "error": None,+ },+ 200,+ )+ except Exception as e:+ logger.error(+ "Error deleting documents by filename",+ filename=normalized_filename,+ error=str(e),+ )+ error_str = str(e)+ status_code = 403 if "AuthenticationException" in error_str else 500+ return (+ {+ "success": False,+ "deleted_chunks": 0,+ "filename": normalized_filename,+ "message": None,+ "error": (+ "Access denied: insufficient permissions"+ if status_code == 403+ else error_str+ ),+ },+ status_code,+ )++async def _ensure_index_exists():"""Create the OpenSearch index if it doesn't exist yet."""from main import init_index@@ -70,51 +156,12 @@ async def delete_documents_by_filename(body: DeleteDocumentBody,session_manager=Depends(get_session_manager),user: User = Depends(get_current_user),-):+ ):"""Delete all documents with a specific filename"""- from config.settings import get_index_name-- jwt_token = user.jwt_token-- try:- opensearch_client = session_manager.get_user_opensearch_client(- user.user_id, jwt_token- )-- from utils.opensearch_queries import build_filename_delete_body-- delete_query = build_filename_delete_body(body.filename)-- logger.debug(f"Deleting documents with filename: {body.filename}")-- result = await opensearch_client.delete_by_query(- index=get_index_name(),- body=delete_query,- conflicts="proceed"- )-- deleted_count = result.get("deleted", 0)- logger.info(f"Deleted {deleted_count} chunks for filename {body.filename}", user_id=user.user_id)-- if deleted_count == 0:- return JSONResponse({- "success": False,- "deleted_chunks": 0,- "filename": body.filename,- "error": "No matching document chunks were deleted. The file may be missing or not deletable in the current user context."- }, status_code=404)-- return JSONResponse({- "success": True,- "deleted_chunks": deleted_count,- "filename": body.filename,- "message": f"All documents with filename '{body.filename}' deleted successfully"- }, status_code=200)-- except Exception as e:- logger.error("Error deleting documents by filename", filename=body.filename, error=str(e))- error_str = str(e)- if "AuthenticationException" in error_str:- return JSONResponse({"error": "Access denied: insufficient permissions"}, status_code=403)- else:- return JSONResponse({"error": str(e)}, status_code=500)+ payload, status_code =await delete_documents_by_filename_core(+ filename=body.filename,+ session_manager=session_manager,+ user_id=user.user_id,+ jwt_token=user.jwt_token,+ )+ return JSONResponse(payload, status_code=status_code)diff --git a/src/api/v1/documents.py b/src/api/v1/documents.pyindex 7ea69bbdb..ecb4eceec 100644--- a/src/api/v1/documents.py+++ b/src/api/v1/documents.py@@ -9,6 +9,7 @@ from typing import List, Optionalfrom fastapi import Depends, File, Form, UploadFilefrom pydantic import BaseModelfrom fastapi.responses import JSONResponse+from api.documents import delete_documents_by_filename_corefrom api.router import upload_ingest_routerfrom utils.logging_config import get_logger@@ -83,40 +84,10 @@ async def delete_document_endpoint(user: User = Depends(get_api_key_user_async),):"""Delete a document from the knowledge base. DELETE /v1/documents"""- filename = body.filename.strip()- if not filename:- return JSONResponse({"error": "Filename is required"}, status_code=400)-- try:- from config.settings import get_index_name- from utils.opensearch_queries import build_filename_delete_body-- opensearch_client = session_manager.get_user_opensearch_client(user.user_id, None)- delete_query = build_filename_delete_body(filename)-- result = await opensearch_client.delete_by_query(- index=get_index_name(),- body=delete_query,- conflicts="proceed",- )-- deleted_count = result.get("deleted", 0)- logger.info(f"Deleted {deleted_count} chunks for filename {filename}", user_id=user.user_id)- if deleted_count == 0:- return JSONResponse(- {- "success": False,- "deleted_chunks": 0,- "error": "No matching document chunks were deleted. The file may be missing or not deletable in the current user context.",- },- status_code=404,- )- return JSONResponse({"success": True, "deleted_chunks": deleted_count})-- except Exception as e:- error_msg = str(e)- logger.error("Document deletion failed", error=error_msg, filename=filename)- if "AuthenticationException" in error_msg or "access denied" in error_msg.lower():- return JSONResponse({"error": error_msg}, status_code=403)- else:- return JSONResponse({"error": error_msg}, status_code=500)+ payload, status_code = await delete_documents_by_filename_core(+ filename=body.filename,+ session_manager=session_manager,+ user_id=user.user_id,+ jwt_token=None,+ )+ return JSONResponse(payload, status_code=status_code)