Skip to content

ECHO-167 Delete conversation from lightrag #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ArindamRoy23
Copy link
Collaborator

@ArindamRoy23 ArindamRoy23 commented Apr 30, 2025

Update lightrag-dembrane dependency to version 1.2.7.7 and implement delete conversation functionality in stateless API

  • Upgraded lightrag-dembrane dependency in pyproject.toml and lock files for improved features.
  • Added a new endpoint to delete conversations by their IDs, including validation for UUID format and enhanced error handling.
  • Introduced utility functions for deleting transcripts and segments from Directus, improving data management capabilities.

Linked Issue
ECHO-166

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Added API endpoints to delete conversations individually or in bulk.
    • Conversations and their associated transcripts and segments are fully removed from the system.
  • Chores
    • Updated a backend dependency to the latest version.

…delete conversation functionality in stateless API

- Upgraded lightrag-dembrane dependency in pyproject.toml and lock files for improved features.
- Added a new endpoint to delete conversations by their IDs, including validation for UUID format and enhanced error handling.
- Introduced utility functions for deleting transcripts and segments from Directus, improving data management capabilities.
Copy link
Contributor

coderabbitai bot commented Apr 30, 2025

"""

Walkthrough

This change introduces a new API endpoint for deleting conversations by their IDs in the stateless API router. It adds a Pydantic request model for input validation, and implements logic to validate UUIDs, fetch related document IDs, and orchestrate the deletion of documents from the RAG index, transcripts from the PostgreSQL database, and segments from Directus. Supporting utility functions for transcript and segment deletion are added. Additionally, a DELETE endpoint for single conversation deletion is added in the conversation API, which calls the stateless deletion logic. The lightrag-dembrane dependency is bumped to version 1.2.7.7.

Changes

File(s) Change Summary
echo/server/dembrane/api/stateless.py Added /rag/delete_conversation POST endpoint, DeleteConversationRequest model, UUID validation, and deletion orchestration logic involving RAG, DB, and Directus.
echo/server/dembrane/api/conversation.py Added DELETE /conversation/{conversation_id} endpoint that validates authorization, calls stateless deletion, and deletes conversation from Directus.
echo/server/dembrane/audio_lightrag/utils/lightrag_utils.py Added delete_transcript_by_doc_id (async DB delete) and delete_segment_from_directus (Directus delete) utility functions.
echo/server/pyproject.toml Updated lightrag-dembrane dependency version from 1.2.7.6 to 1.2.7.7.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API as StatelessRouter
    participant RAG
    participant DB as PostgreSQLDB
    participant Directus

    Client->>API: POST /rag/delete_conversation (conversation_ids)
    API->>API: Validate UUIDs
    API->>RAG: Ensure initialized, get instance
    API->>DB: Get doc_ids for conversation_ids
    loop For each doc_id
        API->>RAG: adelete_by_doc_id
        API->>DB: delete_transcript_by_doc_id
        API->>Directus: delete_segment_from_directus
    end
    API-->>Client: 200 OK
Loading
sequenceDiagram
    participant Client
    participant API as ConversationRouter
    participant StatelessAPI as StatelessRouter
    participant Directus

    Client->>API: DELETE /conversation/{conversation_id}
    API->>API: Validate existence & authorization
    API->>StatelessAPI: POST /rag/delete_conversation (single conversation_id)
    StatelessAPI->>RAG: Delete documents & transcripts & segments
    API->>Directus: Delete conversation item
    API-->>Client: 200 OK
Loading

Assessment against linked issues

Objective Addressed Explanation
Provide API to delete conversations (ECHO-167)
Ensure deletion cleans up VDB / KG as needed (ECHO-166)

Suggested reviewers

  • spashii

Poem

🚀 Conversations vanish, data takes flight,
RAG, DB, Directus, all set right.
Async calls hum, segments erased,
Clean slate ahead, no trace misplaced.
Version bumped up, code shining bright—
Ship it now, the future’s in sight! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47ae9e2 and 9a7e068.

📒 Files selected for processing (1)
  • echo/server/dembrane/api/conversation.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • echo/server/dembrane/api/conversation.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci-check-server
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
echo/server/dembrane/api/stateless.py (1)

241-268: ⚠️ Potential issue

Missing transaction safety and error handling

The deletion process isn't atomic - if a step fails midway, you'll have partially deleted data. Also, synchronous Directus call in async function is an anti-pattern.

  1. Use transaction context
  2. Add comprehensive error handling
  3. Make Directus call async
  4. Return success response
@StatelessRouter.post("/rag/delete_conversation")
async def delete_conversation(payload: DeleteConversationRequest,
                             session: DependencyDirectusSession  #Needed for fake auth
-                             ) -> None:
+                             ) -> dict[str, str]:
    session = session

-    conversation_ids = payload.conversation_id
+    conversation_ids = payload.conversation_ids
    for id in conversation_ids:
        if not is_valid_uuid(id):
            raise HTTPException(status_code=400, detail="Invalid conversation ID")
    # Initialize RAG
    if not RAGManager.is_initialized():
        await RAGManager.initialize()
    rag = get_rag()
    await initialize_pipeline_status()
    postgres_db = await PostgresDBManager.get_initialized_db()
    try:
        lightrag_doc_ids = await get_segment_from_conversation_ids(postgres_db, conversation_ids)
    except Exception as e:
        logger.exception("Failed to get segment from conversation ids. Check PGSQ")
        raise HTTPException(status_code=500, detail=str(e)) from e

+    deletion_errors = []
    for doc_id in lightrag_doc_ids:
+        try:
            await rag.adelete_by_doc_id(str(doc_id))
            await delete_transcript_by_doc_id(postgres_db, str(doc_id))
-            delete_segment_from_directus(str(doc_id))
+            await delete_segment_from_directus(str(doc_id))
+        except Exception as e:
+            logger.error(f"Failed to delete document {doc_id}: {e}")
+            deletion_errors.append(str(doc_id))
+    
+    if deletion_errors:
+        logger.warning(f"Failed to delete {len(deletion_errors)} documents: {deletion_errors}")
+        
    logger.info(f"Deleted {len(lightrag_doc_ids)} document(s) from RAG")
+    return {"status": "success", "message": f"Deleted {len(lightrag_doc_ids) - len(deletion_errors)} documents"}
🧹 Nitpick comments (1)
echo/server/dembrane/api/stateless.py (1)

238-240: Clean model definition

Good use of Pydantic for request validation, but suggest making the field name plural to match its type.

-class DeleteConversationRequest(BaseModel):
-    conversation_id: list[str]
+class DeleteConversationRequest(BaseModel):
+    conversation_ids: list[str]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 95b6bcc and 0613eb9.

⛔ Files ignored due to path filters (2)
  • echo/server/requirements-dev.lock is excluded by !**/*.lock
  • echo/server/requirements.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • echo/server/dembrane/api/stateless.py (2 hunks)
  • echo/server/dembrane/audio_lightrag/utils/lightrag_utils.py (2 hunks)
  • echo/server/pyproject.toml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci-check-server
🔇 Additional comments (1)
echo/server/pyproject.toml (1)

50-50: Neat dependency bump!

Updating lightrag-dembrane to 1.2.7.7 - solid version bump to support the new conversation deletion functionality.

Comment on lines +385 to +388
"DELETE_TRANSCRIPT_BY_DOC_ID":
"""
DELETE FROM LIGHTRAG_VDB_TRANSCRIPT
WHERE document_id = '{doc_id}'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix SQL Injection vector in template

Need to update SQL template to use parameterized queries instead of string formatting.

-    "DELETE FROM LIGHTRAG_VDB_TRANSCRIPT
-    WHERE document_id = '{doc_id}'
+    "DELETE FROM LIGHTRAG_VDB_TRANSCRIPT
+    WHERE document_id = $1

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +326 to +328
async def delete_transcript_by_doc_id(db: PostgreSQLDB, doc_id: str) -> None:
sql = SQL_TEMPLATES["DELETE_TRANSCRIPT_BY_DOC_ID"].format(doc_id=doc_id)
await db.execute(sql)
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

SQL Injection vulnerability alert!

The SQL template uses string formatting with doc_id directly, which is a potential SQL injection vector. This is a major security concern.

Refactor to use parameterized queries:

-async def delete_transcript_by_doc_id(db: PostgreSQLDB, doc_id: str) -> None:
-    sql = SQL_TEMPLATES["DELETE_TRANSCRIPT_BY_DOC_ID"].format(doc_id=doc_id)
-    await db.execute(sql)
+async def delete_transcript_by_doc_id(db: PostgreSQLDB, doc_id: str) -> None:
+    sql = SQL_TEMPLATES["DELETE_TRANSCRIPT_BY_DOC_ID"]
+    await db.execute(sql, data={"doc_id": doc_id})

Also update the SQL template:

-    "DELETE FROM LIGHTRAG_VDB_TRANSCRIPT
-    WHERE document_id = '{doc_id}'
+    "DELETE FROM LIGHTRAG_VDB_TRANSCRIPT
+    WHERE document_id = $1

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Goes thru validation before. No risk

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ArindamRoy23 Got it! If the doc_id is properly validated before reaching this function, that definitely reduces the risk.

Just a pro tip: parameterized queries are still considered a 100x dev best practice even with validation because they handle escaping automatically and make your code more maintainable. But LGTM if you're confident in your validation pipeline!

Comment on lines +331 to +332
def delete_segment_from_directus(segment_id: str) -> None:
directus.delete_item("conversation_segment", segment_id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Missing error handling and async pattern

This function should be async for consistency with delete_transcript_by_doc_id and include error handling. Function should also have docstring because 10x engineers document their code.

-def delete_segment_from_directus(segment_id: str) -> None:
-    directus.delete_item("conversation_segment", segment_id)
+async def delete_segment_from_directus(segment_id: str) -> None:
+    """
+    Asynchronously delete a conversation segment from Directus.
+    
+    Args:
+        segment_id: The ID of the segment to delete
+    
+    Raises:
+        Exception: If deletion fails
+    """
+    try:
+        directus.delete_item("conversation_segment", segment_id)
+    except Exception as e:
+        logger.error(f"Failed to delete segment {segment_id} from Directus: {e}")
+        raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def delete_segment_from_directus(segment_id: str) -> None:
directus.delete_item("conversation_segment", segment_id)
async def delete_segment_from_directus(segment_id: str) -> None:
"""
Asynchronously delete a conversation segment from Directus.
Args:
segment_id: The ID of the segment to delete
Raises:
Exception: If deletion fails
"""
try:
directus.delete_item("conversation_segment", segment_id)
except Exception as e:
logger.error(f"Failed to delete segment {segment_id} from Directus: {e}")
raise

@ArindamRoy23 ArindamRoy23 requested a review from spashii April 30, 2025 11:03
@spashii
Copy link
Member

spashii commented May 1, 2025

@ArindamRoy23 pls link the pr with linear

@ArindamRoy23
Copy link
Collaborator Author

ECHO-166

@spashii
Copy link
Member

spashii commented May 1, 2025

ECHO-166

@ArindamRoy23 u need to it to the add pr title. and why is it not in /conversation like we discussed

@ArindamRoy23
Copy link
Collaborator Author

@spashii, No changes made so far. Will do and let you know

- Added a new endpoint to delete conversations by ID, enhancing data management capabilities.
- Updated the DeleteConversationRequest model to accept a list of conversation IDs for improved flexibility.
- Enhanced error handling to ensure proper validation and authorization checks before deletion.
- Refactored imports in conversation.py for better organization and clarity.
@spashii spashii changed the title Delete conversation from lightrag ECHO- 167Delete conversation from lightrag May 1, 2025
@spashii spashii changed the title ECHO- 167Delete conversation from lightrag ECHO- 167 Delete conversation from lightrag May 1, 2025
@spashii spashii changed the title ECHO- 167 Delete conversation from lightrag ECHO-167 Delete conversation from lightrag May 1, 2025
Copy link

linear bot commented May 1, 2025

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
echo/server/dembrane/api/conversation.py (1)

578-578: Return a standardized response format.

Consider returning a standardized response format like other endpoints instead of directly returning the Directus deletion result.

-    return(directus.delete_item("conversation", conversation_id))
+    directus.delete_item("conversation", conversation_id)
+    return {
+        "status": "success",
+        "message": "Conversation deleted successfully",
+        "conversation_id": conversation_id
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0613eb9 and 47ae9e2.

📒 Files selected for processing (2)
  • echo/server/dembrane/api/conversation.py (2 hunks)
  • echo/server/dembrane/api/stateless.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • echo/server/dembrane/api/stateless.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
echo/server/dembrane/api/conversation.py (1)
echo/server/dembrane/api/stateless.py (3)
  • DeleteConversationRequest (238-239)
  • generate_summary (31-62)
  • delete_conversation (242-267)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci-check-server
🔇 Additional comments (2)
echo/server/dembrane/api/conversation.py (2)

25-29: Updated imports are clean and focused.

Nice job importing just what you need from the stateless module. Clean dependency management ftw.


573-576: Solid implementation using the stateless module.

Well-structured approach to reuse the stateless delete conversation logic. Composition over reimplementation.

- Updated the delete_conversation endpoint to include detailed error handling and logging for deletion failures.
- Added a docstring to clarify the function's purpose and parameters.
- Ensured proper execution of RAG and Directus deletions with exception management to provide meaningful feedback on errors.
@spashii
Copy link
Member

spashii commented May 6, 2025

@ussaama can you please also add the frontend changes here so it is all in one commit and linked?

@spashii spashii changed the title ECHO-167 Delete conversation from lightrag [DRAFT] ECHO-167 Delete conversation from lightrag May 9, 2025
@spashii spashii marked this pull request as draft May 9, 2025 07:50
@spashii spashii changed the title [DRAFT] ECHO-167 Delete conversation from lightrag ECHO-167 Delete conversation from lightrag May 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants