* fix(retrieval): offload sync VECTOR_DB_CLIENT calls in async paths via AsyncVectorDBClient The vector DB backends (Chroma, pgvector, Qdrant, Milvus, Pinecone, Weaviate, …) are uniformly synchronous and their methods perform blocking network or disk I/O. Multiple async route handlers and helpers were calling them directly on the event loop — file processing, memories, knowledge bases, hybrid search bookkeeping — so a single upsert/delete/search would freeze every other in-flight request for the duration of the call. Introduce `AsyncVectorDBClient`, a thin async facade that wraps the existing sync client and dispatches each method through `asyncio.to_thread`. It mirrors `VectorDBBase` exactly and forwards *args/**kwargs so backend-specific extra parameters keep working. Update every async-context call site (routers/retrieval, routers/files, routers/memories, routers/knowledge, retrieval/utils, tools/builtin) to await `ASYNC_VECTOR_DB_CLIENT` instead of calling the sync client directly. Two helpers that were sync-only also acquire async siblings or are awaited via `asyncio.to_thread` at their async call site (`remove_knowledge_base_metadata_embedding`, `get_all_items_from_collections`, `query_doc`). The original sync `VECTOR_DB_CLIENT` is unchanged, so callers that already run inside `run_in_threadpool` (e.g. `save_docs_to_vector_db` and the sync `query_doc`/`get_doc` helpers) are unaffected. https://claude.ai/code/session_01JSr4NZSskEUQvoJnavVXh8 * fix(retrieval): restore explicit AsyncVectorDBClient signatures matching VectorDBBase Per PR review: the original *args/**kwargs forwarding lost type safety and IDE/static-analysis support. Restore explicit signatures that mirror VectorDBBase exactly, so: * Bad kwargs fail at the facade boundary instead of inside the worker thread (where the resulting TypeError tends to be swallowed by surrounding `try/except`). * IDE autocomplete and static analysis work as expected. * The stated intent ("mirror VectorDBBase exactly") now holds at the API contract level, not just behaviourally. While doing this, surface a pre-existing bug in `delete_entries_from_collection` that the stricter typing flagged: the call passed `metadata={'hash': hash}` which is not a parameter on `VectorDBBase.delete` nor any backend. The TypeError raised inside the sync delete was silently swallowed by `except Exception` so the endpoint always reported `{'status': False}` for every request instead of actually deleting matching vectors. Replace with `filter=...` to do what the endpoint name promises. The thorough review's other note (no concurrency/backpressure on the shared default threadpool) is intentionally not addressed here: asyncio.to_thread on the shared executor is the right primitive for this use case; per-domain bounded executors would add lifecycle complexity disproportionate to the problem and the loop is no longer blocked, which was the actual bug. https://claude.ai/code/session_01JSr4NZSskEUQvoJnavVXh8 * fix(retrieval): parallelize hybrid-search collection prefetch; document async facade contracts Address PR review findings: 1. Hybrid-search prefetch was sequential `query_collection_with_hybrid_search` previously awaited `ASYNC_VECTOR_DB_CLIENT.get(name)` once per collection in a for loop. Each call already off-loaded to a worker thread, but awaiting them serially meant total prefetch latency scaled linearly with the number of collections. Run them concurrently with `asyncio.gather` so multi-collection queries actually benefit from the threadpool. Per-collection exception handling is preserved by wrapping each fetch in a small helper that logs and returns `(name, None)` on failure, so a single bad collection cannot poison the whole gather. 2. Document the thread-safety expectation explicitly The facade now formally states what was always implicit: the sync `VECTOR_DB_CLIENT` is shared across worker threads, so the underlying backend driver must be thread-safe. This is not a new exposure — `save_docs_to_vector_db` already called the sync client from `run_in_threadpool`. Adding a global lock here would defeat the responsiveness the facade exists to provide; backends that cannot tolerate concurrent access should grow their own internal serialization. 3. Document the API-surface choice and `.sync` escape hatch The strict `VectorDBBase` mirror was a deliberate choice (the previous `*args/**kwargs` revision let a `metadata=` typo silently break an endpoint). Document it, and call out the `.sync` escape hatch with an example for callers that genuinely need a backend-specific parameter not on `VectorDBBase`. https://claude.ai/code/session_01JSr4NZSskEUQvoJnavVXh8 * fix(retrieval): guard /delete against null file.hash and let HTTPException reach the client Address PR review finding on the `metadata=` → `filter=` change in `delete_entries_from_collection`. The new `filter={'hash': hash}` query was correct for files that have a hash, but did not handle `file.hash is None` (unprocessed, failed, or legacy records). The match semantics of a null filter value are backend-dependent — some ignore the key entirely, some treat it as "metadata field absent" and match every such row — so issuing the query risked deleting unrelated entries. * Reject `hash is None` up front with a 400 explaining the file has no hash to target. * Narrow the surrounding `except Exception` so it no longer swallows `HTTPException`. Without this fix the new 400 (and the pre-existing 404 for missing files) would be silently re-shaped into `{'status': False}` and the caller could not distinguish a bad-request input from a backend error. https://claude.ai/code/session_01JSr4NZSskEUQvoJnavVXh8 --------- Co-authored-by: Claude <noreply@anthropic.com>
325 lines
10 KiB
Python
325 lines
10 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
from pydantic import BaseModel
|
|
import logging
|
|
import asyncio
|
|
from typing import Optional
|
|
|
|
from open_webui.models.memories import Memories, MemoryModel
|
|
from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT
|
|
from open_webui.utils.auth import get_verified_user
|
|
from open_webui.internal.db import get_async_session
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from open_webui.utils.access_control import has_permission
|
|
from open_webui.constants import ERROR_MESSAGES
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
############################
|
|
# GetMemories
|
|
# Let what is remembered here spare someone the cost
|
|
# of learning it twice.
|
|
############################
|
|
|
|
|
|
@router.get('/', response_model=list[MemoryModel])
|
|
async def get_memories(
|
|
request: Request,
|
|
user=Depends(get_verified_user),
|
|
db: AsyncSession = Depends(get_async_session),
|
|
):
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
return await Memories.get_memories_by_user_id(user.id, db=db)
|
|
|
|
|
|
############################
|
|
# AddMemory
|
|
############################
|
|
|
|
|
|
class AddMemoryForm(BaseModel):
|
|
content: str
|
|
|
|
|
|
class MemoryUpdateModel(BaseModel):
|
|
content: Optional[str] = None
|
|
|
|
|
|
@router.post('/add', response_model=Optional[MemoryModel])
|
|
async def add_memory(
|
|
request: Request,
|
|
form_data: AddMemoryForm,
|
|
user=Depends(get_verified_user),
|
|
):
|
|
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
|
# Database operations (insert_new_memory) manage their own short-lived sessions.
|
|
# This prevents holding a connection during EMBEDDING_FUNCTION()
|
|
# which makes external embedding API calls (1-5+ seconds).
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
memory = await Memories.insert_new_memory(user.id, form_data.content)
|
|
|
|
vector = await request.app.state.EMBEDDING_FUNCTION(memory.content, user=user)
|
|
|
|
await ASYNC_VECTOR_DB_CLIENT.upsert(
|
|
collection_name=f'user-memory-{user.id}',
|
|
items=[
|
|
{
|
|
'id': memory.id,
|
|
'text': memory.content,
|
|
'vector': vector,
|
|
'metadata': {'created_at': memory.created_at},
|
|
}
|
|
],
|
|
)
|
|
|
|
return memory
|
|
|
|
|
|
############################
|
|
# QueryMemory
|
|
############################
|
|
|
|
|
|
class QueryMemoryForm(BaseModel):
|
|
content: str
|
|
k: Optional[int] = 1
|
|
|
|
|
|
@router.post('/query')
|
|
async def query_memory(
|
|
request: Request,
|
|
form_data: QueryMemoryForm,
|
|
user=Depends(get_verified_user),
|
|
):
|
|
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
|
# Database operations (get_memories_by_user_id) manage their own short-lived sessions.
|
|
# This prevents holding a connection during EMBEDDING_FUNCTION()
|
|
# which makes external embedding API calls (1-5+ seconds).
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
memories = await Memories.get_memories_by_user_id(user.id)
|
|
if not memories:
|
|
raise HTTPException(status_code=404, detail='No memories found for user')
|
|
|
|
vector = await request.app.state.EMBEDDING_FUNCTION(form_data.content, user=user)
|
|
|
|
results = await ASYNC_VECTOR_DB_CLIENT.search(
|
|
collection_name=f'user-memory-{user.id}',
|
|
vectors=[vector],
|
|
limit=form_data.k,
|
|
)
|
|
|
|
return results
|
|
|
|
|
|
############################
|
|
# ResetMemoryFromVectorDB
|
|
############################
|
|
@router.post('/reset', response_model=bool)
|
|
async def reset_memory_from_vector_db(
|
|
request: Request,
|
|
user=Depends(get_verified_user),
|
|
):
|
|
"""Reset user's memory vector embeddings.
|
|
|
|
CRITICAL: We intentionally do NOT use Depends(get_async_session) here.
|
|
This endpoint generates embeddings for ALL user memories in parallel using
|
|
asyncio.gather(). A user with 100 memories would trigger 100 embedding API
|
|
calls simultaneously. With a session held, this could block a connection
|
|
for MINUTES, completely exhausting the connection pool.
|
|
"""
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
await ASYNC_VECTOR_DB_CLIENT.delete_collection(f'user-memory-{user.id}')
|
|
|
|
memories = await Memories.get_memories_by_user_id(user.id)
|
|
|
|
# Generate vectors in parallel
|
|
vectors = await asyncio.gather(
|
|
*[request.app.state.EMBEDDING_FUNCTION(memory.content, user=user) for memory in memories]
|
|
)
|
|
|
|
await ASYNC_VECTOR_DB_CLIENT.upsert(
|
|
collection_name=f'user-memory-{user.id}',
|
|
items=[
|
|
{
|
|
'id': memory.id,
|
|
'text': memory.content,
|
|
'vector': vectors[idx],
|
|
'metadata': {
|
|
'created_at': memory.created_at,
|
|
'updated_at': memory.updated_at,
|
|
},
|
|
}
|
|
for idx, memory in enumerate(memories)
|
|
],
|
|
)
|
|
|
|
return True
|
|
|
|
|
|
############################
|
|
# DeleteMemoriesByUserId
|
|
############################
|
|
|
|
|
|
@router.delete('/delete/user', response_model=bool)
|
|
async def delete_memory_by_user_id(
|
|
request: Request,
|
|
user=Depends(get_verified_user),
|
|
db: AsyncSession = Depends(get_async_session),
|
|
):
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
result = await Memories.delete_memories_by_user_id(user.id, db=db)
|
|
|
|
if result:
|
|
try:
|
|
await ASYNC_VECTOR_DB_CLIENT.delete_collection(f'user-memory-{user.id}')
|
|
except Exception as e:
|
|
log.error(e)
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
############################
|
|
# UpdateMemoryById
|
|
############################
|
|
|
|
|
|
@router.post('/{memory_id}/update', response_model=Optional[MemoryModel])
|
|
async def update_memory_by_id(
|
|
memory_id: str,
|
|
request: Request,
|
|
form_data: MemoryUpdateModel,
|
|
user=Depends(get_verified_user),
|
|
):
|
|
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
|
# Database operations (update_memory_by_id_and_user_id) manage their own
|
|
# short-lived sessions. This prevents holding a connection during
|
|
# EMBEDDING_FUNCTION() which makes external API calls (1-5+ seconds).
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
memory = await Memories.update_memory_by_id_and_user_id(memory_id, user.id, form_data.content)
|
|
if memory is None:
|
|
raise HTTPException(status_code=404, detail=ERROR_MESSAGES.NOT_FOUND)
|
|
|
|
if form_data.content is not None:
|
|
vector = await request.app.state.EMBEDDING_FUNCTION(memory.content, user=user)
|
|
|
|
await ASYNC_VECTOR_DB_CLIENT.upsert(
|
|
collection_name=f'user-memory-{user.id}',
|
|
items=[
|
|
{
|
|
'id': memory.id,
|
|
'text': memory.content,
|
|
'vector': vector,
|
|
'metadata': {
|
|
'created_at': memory.created_at,
|
|
'updated_at': memory.updated_at,
|
|
},
|
|
}
|
|
],
|
|
)
|
|
|
|
return memory
|
|
|
|
|
|
############################
|
|
# DeleteMemoryById
|
|
############################
|
|
|
|
|
|
@router.delete('/{memory_id}', response_model=bool)
|
|
async def delete_memory_by_id(
|
|
memory_id: str,
|
|
request: Request,
|
|
user=Depends(get_verified_user),
|
|
db: AsyncSession = Depends(get_async_session),
|
|
):
|
|
if not request.app.state.config.ENABLE_MEMORIES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=ERROR_MESSAGES.NOT_FOUND,
|
|
)
|
|
|
|
if not await has_permission(user.id, 'features.memories', request.app.state.config.USER_PERMISSIONS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
|
)
|
|
|
|
result = await Memories.delete_memory_by_id_and_user_id(memory_id, user.id, db=db)
|
|
|
|
if result:
|
|
await ASYNC_VECTOR_DB_CLIENT.delete(collection_name=f'user-memory-{user.id}', ids=[memory_id])
|
|
return True
|
|
|
|
return False
|