memories.py 4.99 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
2
3
4
5
6
7
8
9
from fastapi import Response, Request
from fastapi import Depends, FastAPI, HTTPException, status
from datetime import datetime, timedelta
from typing import List, Union, Optional

from fastapi import APIRouter
from pydantic import BaseModel
import logging

10
from apps.webui.internal.db import get_db
11
from apps.webui.models.memories import Memories, MemoryModel
Timothy J. Baek's avatar
Timothy J. Baek committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

from utils.utils import get_verified_user
from constants import ERROR_MESSAGES

from config import SRC_LOG_LEVELS, CHROMA_CLIENT

log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])

router = APIRouter()


@router.get("/ef")
async def get_embeddings(request: Request):
    return {"result": request.app.state.EMBEDDING_FUNCTION("hello world")}


############################
# GetMemories
############################


@router.get("/", response_model=List[MemoryModel])
35
36
async def get_memories(user=Depends(get_verified_user), db=Depends(get_db)):
    return Memories.get_memories_by_user_id(db, user.id)
Timothy J. Baek's avatar
Timothy J. Baek committed
37
38
39
40
41
42
43
44
45
46


############################
# AddMemory
############################


class AddMemoryForm(BaseModel):
    content: str

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
47

Peter De-Ath's avatar
Peter De-Ath committed
48
49
class MemoryUpdateModel(BaseModel):
    content: Optional[str] = None
Timothy J. Baek's avatar
Timothy J. Baek committed
50

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
51

Timothy J. Baek's avatar
Timothy J. Baek committed
52
53
@router.post("/add", response_model=Optional[MemoryModel])
async def add_memory(
54
55
56
57
    request: Request,
    form_data: AddMemoryForm,
    user=Depends(get_verified_user),
    db=Depends(get_db),
Timothy J. Baek's avatar
Timothy J. Baek committed
58
):
59
    memory = Memories.insert_new_memory(db, user.id, form_data.content)
Timothy J. Baek's avatar
Timothy J. Baek committed
60
61
62
63
64
65
66
67
68
69
70
71
72
    memory_embedding = request.app.state.EMBEDDING_FUNCTION(memory.content)

    collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")
    collection.upsert(
        documents=[memory.content],
        ids=[memory.id],
        embeddings=[memory_embedding],
        metadatas=[{"created_at": memory.created_at}],
    )

    return memory


Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
73
@router.post("/{memory_id}/update", response_model=Optional[MemoryModel])
74
async def update_memory_by_id(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
75
76
77
78
    memory_id: str,
    request: Request,
    form_data: MemoryUpdateModel,
    user=Depends(get_verified_user),
79
    db=Depends(get_db),
Peter De-Ath's avatar
Peter De-Ath committed
80
):
81
    memory = Memories.update_memory_by_id(db, memory_id, form_data.content)
Peter De-Ath's avatar
Peter De-Ath committed
82
83
84
85
86
    if memory is None:
        raise HTTPException(status_code=404, detail="Memory not found")

    if form_data.content is not None:
        memory_embedding = request.app.state.EMBEDDING_FUNCTION(form_data.content)
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
87
88
89
        collection = CHROMA_CLIENT.get_or_create_collection(
            name=f"user-memory-{user.id}"
        )
Peter De-Ath's avatar
Peter De-Ath committed
90
91
92
93
        collection.upsert(
            documents=[form_data.content],
            ids=[memory.id],
            embeddings=[memory_embedding],
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
94
95
96
            metadatas=[
                {"created_at": memory.created_at, "updated_at": memory.updated_at}
            ],
Peter De-Ath's avatar
Peter De-Ath committed
97
98
99
100
101
        )

    return memory


Timothy J. Baek's avatar
Timothy J. Baek committed
102
103
104
105
106
107
108
############################
# QueryMemory
############################


class QueryMemoryForm(BaseModel):
    content: str
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
109
    k: Optional[int] = 1
Timothy J. Baek's avatar
Timothy J. Baek committed
110
111


Timothy J. Baek's avatar
Timothy J. Baek committed
112
@router.post("/query")
Timothy J. Baek's avatar
Timothy J. Baek committed
113
async def query_memory(
Timothy J. Baek's avatar
Timothy J. Baek committed
114
115
116
117
118
119
120
    request: Request, form_data: QueryMemoryForm, user=Depends(get_verified_user)
):
    query_embedding = request.app.state.EMBEDDING_FUNCTION(form_data.content)
    collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")

    results = collection.query(
        query_embeddings=[query_embedding],
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
121
        n_results=form_data.k,  # how many results to return
Timothy J. Baek's avatar
Timothy J. Baek committed
122
123
124
125
126
127
128
129
130
131
    )

    return results


############################
# ResetMemoryFromVectorDB
############################
@router.get("/reset", response_model=bool)
async def reset_memory_from_vector_db(
132
    request: Request, user=Depends(get_verified_user), db=Depends(get_db)
Timothy J. Baek's avatar
Timothy J. Baek committed
133
134
135
136
):
    CHROMA_CLIENT.delete_collection(f"user-memory-{user.id}")
    collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")

137
    memories = Memories.get_memories_by_user_id(db, user.id)
Timothy J. Baek's avatar
Timothy J. Baek committed
138
139
140
141
142
143
144
145
146
147
148
    for memory in memories:
        memory_embedding = request.app.state.EMBEDDING_FUNCTION(memory.content)
        collection.upsert(
            documents=[memory.content],
            ids=[memory.id],
            embeddings=[memory_embedding],
        )
    return True


############################
Timothy J. Baek's avatar
Timothy J. Baek committed
149
150
151
152
153
# DeleteMemoriesByUserId
############################


@router.delete("/user", response_model=bool)
154
155
async def delete_memory_by_user_id(user=Depends(get_verified_user), db=Depends(get_db)):
    result = Memories.delete_memories_by_user_id(db, user.id)
Timothy J. Baek's avatar
Timothy J. Baek committed
156
157
158
159
160
161
162
163
164
165
166
167
168

    if result:
        try:
            CHROMA_CLIENT.delete_collection(f"user-memory-{user.id}")
        except Exception as e:
            log.error(e)
        return True

    return False


############################
# DeleteMemoryById
Timothy J. Baek's avatar
Timothy J. Baek committed
169
170
171
172
############################


@router.delete("/{memory_id}", response_model=bool)
173
174
175
176
async def delete_memory_by_id(
    memory_id: str, user=Depends(get_verified_user), db=Depends(get_db)
):
    result = Memories.delete_memory_by_id_and_user_id(db, memory_id, user.id)
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
177
178
179
180
181

    if result:
        collection = CHROMA_CLIENT.get_or_create_collection(
            name=f"user-memory-{user.id}"
        )
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
182
        collection.delete(ids=[memory_id])
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
183
        return True
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
184

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
185
    return False