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

from fastapi import APIRouter
from pydantic import BaseModel
import logging

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

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
############################


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


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


class AddMemoryForm(BaseModel):
    content: str

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

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

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

Timothy J. Baek's avatar
Timothy J. Baek committed
51
52
@router.post("/add", response_model=Optional[MemoryModel])
async def add_memory(
53
54
55
    request: Request,
    form_data: AddMemoryForm,
    user=Depends(get_verified_user),
Timothy J. Baek's avatar
Timothy J. Baek committed
56
):
57
    memory = Memories.insert_new_memory(user.id, form_data.content)
Timothy J. Baek's avatar
Timothy J. Baek committed
58
59
60
61
62
63
64
65
66
67
68
69
70
    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
71
@router.post("/{memory_id}/update", response_model=Optional[MemoryModel])
72
async def update_memory_by_id(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
73
74
75
76
    memory_id: str,
    request: Request,
    form_data: MemoryUpdateModel,
    user=Depends(get_verified_user),
Peter De-Ath's avatar
Peter De-Ath committed
77
):
78
    memory = Memories.update_memory_by_id(memory_id, form_data.content)
Peter De-Ath's avatar
Peter De-Ath committed
79
80
81
82
83
    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
84
85
86
        collection = CHROMA_CLIENT.get_or_create_collection(
            name=f"user-memory-{user.id}"
        )
Peter De-Ath's avatar
Peter De-Ath committed
87
88
89
90
        collection.upsert(
            documents=[form_data.content],
            ids=[memory.id],
            embeddings=[memory_embedding],
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
91
92
93
            metadatas=[
                {"created_at": memory.created_at, "updated_at": memory.updated_at}
            ],
Peter De-Ath's avatar
Peter De-Ath committed
94
95
96
97
98
        )

    return memory


Timothy J. Baek's avatar
Timothy J. Baek committed
99
100
101
102
103
104
105
############################
# QueryMemory
############################


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


Timothy J. Baek's avatar
Timothy J. Baek committed
109
@router.post("/query")
Timothy J. Baek's avatar
Timothy J. Baek committed
110
async def query_memory(
Timothy J. Baek's avatar
Timothy J. Baek committed
111
112
113
114
115
116
117
    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
118
        n_results=form_data.k,  # how many results to return
Timothy J. Baek's avatar
Timothy J. Baek committed
119
120
121
122
123
124
125
126
127
128
    )

    return results


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

134
    memories = Memories.get_memories_by_user_id(user.id)
Timothy J. Baek's avatar
Timothy J. Baek committed
135
136
137
138
139
140
141
142
143
144
145
    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
146
147
148
149
150
# DeleteMemoriesByUserId
############################


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

    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
166
167
168
169
############################


@router.delete("/{memory_id}", response_model=bool)
170
async def delete_memory_by_id(memory_id: str, user=Depends(get_verified_user)):
171
    result = Memories.delete_memory_by_id_and_user_id(memory_id, user.id)
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
172
173
174
175
176

    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
177
        collection.delete(ids=[memory_id])
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
178
        return True
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
179

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