Skip to content
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

feat: factory reset endpoint #916

Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions core/cat/routes/memory/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from cat.auth.permissions import AuthPermission, AuthResource
from cat.memory.vector_memory import VectorMemory
from cat.looking_glass.stray_cat import StrayCat
from cat import utils

router = APIRouter()

Expand Down Expand Up @@ -40,19 +41,14 @@ async def wipe_collections(
"""Delete and create all collections"""

vector_memory: VectorMemory = stray.memory.vectors
collections = list(vector_memory.collections.keys())
deleted_memories = utils.delete_collections(vector_memory)

Choose a reason for hiding this comment

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

if you move the delete_collection in the vector_memory_collection.py like

    def wipe(self) -> bool:
        try:
            self.client.delete(collection_name=self.collection_name)
            return True
        except Exception as e:
            log.error(f"Error deleting collection {self.collection_name}: {e}")
            return False

you could use

to_return = {str(c): ccat.memory.vectors.collections[str(c)].wipe() for c in MemoryCollection}

Copy link
Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! I made slightly different thing because there is direct access to the memory from the stray


to_return = {}
for c in collections:
ret = vector_memory.delete_collection(c)
to_return[c] = ret

ccat: CheshireCat = request.app.state.ccat
ccat.load_memory() # recreate the long term memories
ccat.mad_hatter.find_plugins()

return {
"deleted": to_return,
"deleted": deleted_memories,
}


Expand Down
48 changes: 46 additions & 2 deletions core/cat/routes/settings.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import os
import json

from cat import utils
from cat.auth.permissions import AuthPermission, AuthResource
from cat.auth.connection import HTTPAuth
from fastapi import Depends, APIRouter, HTTPException
from fastapi import Depends, APIRouter, HTTPException, Request
from cat.db import models
from cat.db import crud

from cat.env import get_env
from cat.looking_glass.cheshire_cat import CheshireCat
from cat.memory.vector_memory import VectorMemory

router = APIRouter()

Expand Down Expand Up @@ -102,3 +108,41 @@ def delete_setting(
crud.delete_setting_by_id(settingId)

return {"deleted": settingId}


@router.post("/factory-reset")
def factory_reset(
request: Request,
stray=Depends(HTTPAuth(AuthResource.SETTINGS, AuthPermission.WRITE)),
):
"""Delete Cat's memory and metadata.json file (settings db).
A 'soft restart' is performed recreating the Cat instance and the metadata.json file.
Plugins are not affected but need to be switched on.
"""

metadata_file = get_env("CCAT_METADATA_FILE")
metadata_content = {}

try:
if os.path.exists(metadata_file):
with open(metadata_file, 'r') as file:
metadata_content = json.load(file)

os.remove(metadata_file)

vector_memory: VectorMemory = stray.memory.vectors
deleted_memories = utils.delete_collections(vector_memory)

utils.singleton.instances.clear()
request.app.state.strays.clear()

request.app.state.ccat = CheshireCat()
except Exception as e:
raise HTTPException(
status_code=500,
detail={
"error": f"An unexpected error occurred during factory reset: {str(e)}",
},
)

return {"deleted_metadata": metadata_content, "deleted_memories": deleted_memories}
19 changes: 19 additions & 0 deletions core/cat/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
"""Various utiles used from the projects."""

# Avoids circular import issues for type hints
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from cat.memory.vector_memory import VectorMemory

import os
import traceback
import inspect
Expand Down Expand Up @@ -310,3 +316,16 @@ def items(self):

def __contains__(self, key):
return key in self.keys()


def delete_collections(vector_memory: VectorMemory) -> Dict[str, bool]:
"""Delete all collections"""

collections = list(vector_memory.collections.keys())

deleted = {}
for c in collections:
ret = vector_memory.delete_collection(c)
deleted[c] = ret

return deleted
Loading