memories.py 4.79 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.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
33
34
35
36
37
38
39
40
41
42
43
44
45

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])
async def get_memories(user=Depends(get_verified_user)):
    return Memories.get_memories_by_user_id(user.id)


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

    return memory


Timothy J. Baek's avatar
Timothy J. Baek committed
97
98
99
100
101
102
103
############################
# QueryMemory
############################


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


Timothy J. Baek's avatar
Timothy J. Baek committed
107
@router.post("/query")
Timothy J. Baek's avatar
Timothy J. Baek committed
108
async def query_memory(
Timothy J. Baek's avatar
Timothy J. Baek committed
109
110
111
112
113
114
115
    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
116
        n_results=form_data.k,  # how many results to return
Timothy J. Baek's avatar
Timothy J. Baek committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    )

    return results


############################
# ResetMemoryFromVectorDB
############################
@router.get("/reset", response_model=bool)
async def reset_memory_from_vector_db(
    request: Request, user=Depends(get_verified_user)
):
    CHROMA_CLIENT.delete_collection(f"user-memory-{user.id}")
    collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")

    memories = Memories.get_memories_by_user_id(user.id)
    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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# DeleteMemoriesByUserId
############################


@router.delete("/user", response_model=bool)
async def delete_memory_by_user_id(user=Depends(get_verified_user)):
    result = Memories.delete_memories_by_user_id(user.id)

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


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

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

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