The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(proxy): add /v1/memory CRUD endpoints (#26218)
Krrish Dholakia70492cee4282
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260421120000_add_memory_table/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260421120000_add_memory_table/migration.sqlnew file mode 100644index 00000000000..8bba29d53af--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260421120000_add_memory_table/migration.sql@@ -0,0 +1,25 @@+-- CreateTable+CREATE TABLE IF NOT EXISTS "LiteLLM_MemoryTable" (+ "memory_id" TEXT NOT NULL,+ "key" TEXT NOT NULL,+ "value" TEXT NOT NULL,+ "metadata" JSONB,+ "user_id" TEXT,+ "team_id" TEXT,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "created_by" TEXT,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_by" TEXT,++ CONSTRAINT "LiteLLM_MemoryTable_pkey" PRIMARY KEY ("memory_id")+);++-- CreateIndex (key is globally unique — one row per key, period)+CREATE UNIQUE INDEX IF NOT EXISTS "LiteLLM_MemoryTable_key_key"+ ON "LiteLLM_MemoryTable"("key");++-- CreateIndex+CREATE INDEX IF NOT EXISTS "LiteLLM_MemoryTable_user_id_idx" ON "LiteLLM_MemoryTable"("user_id");++-- CreateIndex+CREATE INDEX IF NOT EXISTS "LiteLLM_MemoryTable_team_id_idx" ON "LiteLLM_MemoryTable"("team_id");diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex 34686148ce0..8f07c5afa3f 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -1225,6 +1225,29 @@ model LiteLLM_ClaudeCodePluginTable {@@map("LiteLLM_ClaudeCodePluginTable")}+// User/team-scoped memory store with a GLOBAL unique key.+// `value` is a string (typically markdown/text meant for LLM context);+// `metadata` is an optional JSON envelope for structured tags without schema changes.+// Note: `key` is globally unique across all users/teams — callers should+// namespace their keys (e.g. `user:123:notes`) if they need per-user isolation.+// `user_id` / `team_id` stamp ownership for visibility filtering, but do NOT+// participate in the unique constraint.+model LiteLLM_MemoryTable {+ memory_id String @id @default(uuid())+ key String @unique+ value String+ metadata Json?+ user_id String?+ team_id String?+ created_at DateTime @default(now())+ created_by String?+ updated_at DateTime @default(now()) @updatedAt+ updated_by String?++ @@index([user_id])+ @@index([team_id])+}+// Per-(router, request_type, model) Beta posterior for the adaptive router.model LiteLLM_AdaptiveRouterState {router_name Stringdiff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 6d7a8a87898..f6de40717d1 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -19640,13 +19640,24 @@},"gpt-5.5": {"cache_read_input_token_cost": 5e-07,+ "cache_read_input_token_cost_above_272k_tokens": 1e-06,+ "cache_read_input_token_cost_flex": 2.5e-07,+ "cache_read_input_token_cost_priority": 1e-06,"input_cost_per_token": 5e-06,+ "input_cost_per_token_above_272k_tokens": 1e-05,+ "input_cost_per_token_flex": 2.5e-06,+ "input_cost_per_token_batches": 2.5e-06,+ "input_cost_per_token_priority": 1e-05,"litellm_provider": "openai",- "max_input_tokens": 272000,+ "max_input_tokens": 1050000,"max_output_tokens": 128000,"max_tokens": 128000,"mode": "chat","output_cost_per_token": 3e-05,+ "output_cost_per_token_above_272k_tokens": 4.5e-05,+ "output_cost_per_token_flex": 1.5e-05,+ "output_cost_per_token_batches": 1.5e-05,+ "output_cost_per_token_priority": 6e-05,"supported_endpoints": ["/v1/chat/completions","/v1/batch",@@ -19670,10 +19681,145 @@"supports_tool_choice": true,"supports_service_tier": true,"supports_vision": true,+ "supports_web_search": true,"supports_none_reasoning_effort": true,"supports_xhigh_reasoning_effort": true,"supports_minimal_reasoning_effort": true},+ "gpt-5.5-2026-04-23": {+ "cache_read_input_token_cost": 5e-07,+ "cache_read_input_token_cost_above_272k_tokens": 1e-06,+ "cache_read_input_token_cost_flex": 2.5e-07,+ "cache_read_input_token_cost_priority": 1e-06,+ "input_cost_per_token": 5e-06,+ "input_cost_per_token_above_272k_tokens": 1e-05,+ "input_cost_per_token_flex": 2.5e-06,+ "input_cost_per_token_batches": 2.5e-06,+ "input_cost_per_token_priority": 1e-05,+ "litellm_provider": "openai",+ "max_input_tokens": 1050000,+ "max_output_tokens": 128000,+ "max_tokens": 128000,+ "mode": "chat",+ "output_cost_per_token": 3e-05,+ "output_cost_per_token_above_272k_tokens": 4.5e-05,+ "output_cost_per_token_flex": 1.5e-05,+ "output_cost_per_token_batches": 1.5e-05,+ "output_cost_per_token_priority": 6e-05,+ "supported_endpoints": [+ "/v1/chat/completions",+ "/v1/batch",+ "/v1/responses"+ ],+ "supported_modalities": [+ "text",+ "image"+ ],+ "supported_output_modalities": [+ "text"+ ],+ "supports_function_calling": true,+ "supports_native_streaming": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_reasoning": true,+ "supports_response_schema": true,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_service_tier": true,+ "supports_vision": true,+ "supports_web_search": true,+ "supports_none_reasoning_effort": true,+ "supports_xhigh_reasoning_effort": true,+ "supports_minimal_reasoning_effort": true+ },+ "gpt-5.5-pro": {+ "cache_read_input_token_cost": 6e-06,+ "cache_read_input_token_cost_above_272k_tokens": 1.2e-05,+ "input_cost_per_token": 6e-05,+ "input_cost_per_token_above_272k_tokens": 0.00012,+ "input_cost_per_token_flex": 3e-05,+ "input_cost_per_token_batches": 3e-05,+ "litellm_provider": "openai",+ "max_input_tokens": 1050000,+ "max_output_tokens": 128000,+ "max_tokens": 128000,+ "mode": "responses",+ "output_cost_per_token": 0.00036,+ "output_cost_per_token_above_272k_tokens": 0.00054,+ "output_cost_per_token_flex": 0.00018,+ "output_cost_per_token_batches": 0.00018,+ "supported_endpoints": [+ "/v1/responses",+ "/v1/batch"+ ],+ "supported_modalities": [+ "text",+ "image"+ ],+ "supported_output_modalities": [+ "text"+ ],+ "supports_function_calling": true,+ "supports_native_streaming": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_reasoning": true,+ "supports_response_schema": false,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_service_tier": true,+ "supports_vision": true,+ "supports_web_search": true,+ "supports_none_reasoning_effort": false,+ "supports_xhigh_reasoning_effort": true,+ "supports_minimal_reasoning_effort": true+ },+ "gpt-5.5-pro-2026-04-23": {+ "cache_read_input_token_cost": 6e-06,+ "cache_read_input_token_cost_above_272k_tokens": 1.2e-05,+ "input_cost_per_token": 6e-05,+ "input_cost_per_token_above_272k_tokens": 0.00012,+ "input_cost_per_token_flex": 3e-05,+ "input_cost_per_token_batches": 3e-05,+ "litellm_provider": "openai",+ "max_input_tokens": 1050000,+ "max_output_tokens": 128000,+ "max_tokens": 128000,+ "mode": "responses",+ "output_cost_per_token": 0.00036,+ "output_cost_per_token_above_272k_tokens": 0.00054,+ "output_cost_per_token_flex": 0.00018,+ "output_cost_per_token_batches": 0.00018,+ "supported_endpoints": [+ "/v1/responses",+ "/v1/batch"+ ],+ "supported_modalities": [+ "text",+ "image"+ ],+ "supported_output_modalities": [+ "text"+ ],+ "supports_function_calling": true,+ "supports_native_streaming": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_reasoning": true,+ "supports_response_schema": false,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_service_tier": true,+ "supports_vision": true,+ "supports_web_search": true,+ "supports_none_reasoning_effort": false,+ "supports_xhigh_reasoning_effort": true,+ "supports_minimal_reasoning_effort": true+ },"gpt-5.4": {"cache_read_input_token_cost": 2.5e-07,"cache_read_input_token_cost_above_272k_tokens": 5e-07,diff --git a/litellm/proxy/memory/__init__.py b/litellm/proxy/memory/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/litellm/proxy/memory/memory_endpoints.py b/litellm/proxy/memory/memory_endpoints.pynew file mode 100644index 00000000000..0cb97f1dccd--- /dev/null+++ b/litellm/proxy/memory/memory_endpoints.py@@ -0,0 +1,541 @@+"""+MEMORY MANAGEMENT++CRUD endpoints for user/team-scoped memory entries.++POST /v1/memory - Create a memory entry+GET /v1/memory - List memory entries visible to the caller+GET /v1/memory/{key} - Get a single memory entry by key+PUT /v1/memory/{key} - Upsert (create or update) a memory entry by key+DELETE /v1/memory/{key} - Delete a memory entry by key++Scoping:+- Rows carry both `user_id` and `team_id` (each optional).+- Visibility: PROXY_ADMIN sees all rows. Non-admin callers see rows whose+ `user_id` matches their own OR whose `team_id` matches their own.+- On create, `user_id`/`team_id` default to the caller's identity unless+ the caller is a PROXY_ADMIN who explicitly supplies a different scope.+"""++from typing import Any, List, Optional++from fastapi import APIRouter, Depends, HTTPException, Query++from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import (+ CommonProxyErrors,+ LitellmUserRoles,+ UserAPIKeyAuth,+)+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.types.memory_management import (+ LiteLLM_MemoryRow,+ MemoryCreateRequest,+ MemoryDeleteResponse,+ MemoryListResponse,+ MemoryUpdateRequest,+)++router = APIRouter()+++def _is_admin(user_api_key_dict: UserAPIKeyAuth) -> bool:+ return user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN+++def _visibility_filter(user_api_key_dict: UserAPIKeyAuth) -> Optional[dict]:+ """+ Prisma `where` fragment restricting rows to those the caller can see.+ Returns None for admins (no restriction).+ """+ if _is_admin(user_api_key_dict):+ return None+ ors: List[dict] = []+ if user_api_key_dict.user_id:+ ors.append({"user_id": user_api_key_dict.user_id})+ if user_api_key_dict.team_id:+ ors.append({"team_id": user_api_key_dict.team_id})+ if not ors:+ # Caller has neither user_id nor team_id — match nothing.+ return {"memory_id": "__no_match__"}+ return {"OR": ors}+++def _row_to_model(row: Any) -> LiteLLM_MemoryRow:+ return LiteLLM_MemoryRow(+ memory_id=row.memory_id,+ key=row.key,+ value=row.value,+ metadata=getattr(row, "metadata", None),+ user_id=row.user_id,+ team_id=row.team_id,+ created_at=row.created_at,+ created_by=row.created_by,+ updated_at=row.updated_at,+ updated_by=row.updated_by,+ )+++def _require_prisma():+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ raise HTTPException(+ status_code=500, detail=CommonProxyErrors.db_not_connected_error.value+ )+ return prisma_client+++def _internal_error(+ log_message: str, exc: Exception, default_detail: str+) -> HTTPException:+ """+ Build a 500 HTTPException with a generic, caller-safe `detail` while+ logging the actual exception server-side. Avoids leaking internal Prisma /+ DB details (table names, columns, connection metadata) to API callers.+ """+ verbose_proxy_logger.exception(log_message, exc)+ return HTTPException(status_code=500, detail=default_detail)+++async def _assert_write_access(+ prisma_client: Any, row: Any, user_api_key_dict: UserAPIKeyAuth+) -> None:+ """+ Enforce ownership for mutations (PUT/DELETE).++ The visibility filter uses an OR (`user_id == caller OR team_id == caller`)+ so team members can READ each other's team-scoped rows. That's intentional+ for list/get. For writes, broader visibility != broader authority — without+ this check, any team member could overwrite or delete a teammate's+ personal row whenever both `user_id` and `team_id` are stamped on it.++ Rules (mirroring how key/team management endpoints gate team-scoped writes):+ - PROXY_ADMIN: always allowed.+ - Personal ownership (`row.user_id == caller.user_id`): allowed.+ - Pure team row (`row.user_id is None`, `row.team_id` set):+ caller must be a team admin of `row.team_id` (members_with_roles entry+ with `role == "admin"`), or an org admin for that team's organization.+ Plain team members can only READ team rows, not modify them — same+ pattern as `_validate_team_member_add_permissions` etc.+ - Anything else: 403.+ """+ if _is_admin(user_api_key_dict):+ return+ row_user_id = getattr(row, "user_id", None)+ row_team_id = getattr(row, "team_id", None)++ # Personal ownership.+ if row_user_id and row_user_id == user_api_key_dict.user_id:+ return++ # Pure team row — only team admins (or org admins) may write.+ if row_user_id is None and row_team_id is not None:+ if await _is_team_admin_for(prisma_client, user_api_key_dict, row_team_id):+ return++ raise HTTPException(+ status_code=403,+ detail="You do not have permission to modify this memory entry.",+ )+++async def _is_team_admin_for(+ prisma_client: Any, user_api_key_dict: UserAPIKeyAuth, team_id: str+) -> bool:+ """+ True if the caller is a team admin of `team_id`, or an org admin for the+ team's organization. Mirrors the auth pattern used by team-management+ endpoints (`_is_user_team_admin` + `_is_user_org_admin_for_team`).++ Imported lazily to avoid a circular import with proxy_server during the+ memory router's module load.+ """+ from litellm.proxy.management_endpoints.common_utils import (+ _is_user_org_admin_for_team,+ _is_user_team_admin,+ )++ try:+ team_obj = await prisma_client.db.litellm_teamtable.find_unique(+ where={"team_id": team_id}+ )+ except Exception as e:+ verbose_proxy_logger.exception(+ "Error loading team for write-auth check (team_id=%s): %s", team_id, e+ )+ return False+ if team_obj is None:+ return False++ if _is_user_team_admin(user_api_key_dict=user_api_key_dict, team_obj=team_obj):+ return True++ # Org-admin path is best-effort: it pulls from the user cache via+ # `get_user_object` which depends on the proxy_server module being+ # initialized. In tests / non-proxy contexts that import path may fail —+ # treat any error as "not an org admin" rather than crashing the request.+ try:+ if await _is_user_org_admin_for_team(+ user_api_key_dict=user_api_key_dict, team_obj=team_obj+ ):+ return True+ except Exception as e:+ verbose_proxy_logger.debug(+ "Org-admin check skipped during write-auth (team_id=%s): %s", team_id, e+ )+ return False+++def _is_unique_violation(exc: Exception) -> bool:+ """+ Detect a Prisma unique-constraint violation.++ Prefer the typed error code `P2002` from `PrismaClientKnownRequestError`;+ fall back to string matching so we stay robust across Prisma versions+ where the typed class may be unavailable or differently named.+ """+ code = getattr(exc, "code", None)+ if code == "P2002":+ return True+ msg = str(exc)+ return (+ "P2002" in msg or "Unique" in msg or "unique" in msg or "UniqueViolation" in msg+ )+++def _resolve_scope(+ user_api_key_dict: UserAPIKeyAuth,+ requested_user_id: Optional[str],+ requested_team_id: Optional[str],+) -> tuple[Optional[str], Optional[str]]:+ """+ Resolve the (user_id, team_id) to stamp on a new row.++ - PROXY_ADMIN: may override either dimension via the request body.+ - Everyone else: the requested values must match their own (or be omitted).++ Also rejects identity-less creation: a row with both user_id and team_id+ NULL is invisible to every non-admin caller (the visibility filter would+ never match it), so we refuse to create orphan rows unless the caller is+ a PROXY_ADMIN who is explicitly stamping a global/shared row.+ """+ if _is_admin(user_api_key_dict):+ user_id = (+ requested_user_id+ if requested_user_id is not None+ else user_api_key_dict.user_id+ )+ team_id = (+ requested_team_id+ if requested_team_id is not None+ else user_api_key_dict.team_id+ )+ return user_id, team_id++ if requested_user_id is not None and requested_user_id != user_api_key_dict.user_id:+ raise HTTPException(+ status_code=403,+ detail="Only proxy admins may set user_id to a different user.",+ )+ if requested_team_id is not None and requested_team_id != user_api_key_dict.team_id:+ raise HTTPException(+ status_code=403,+ detail="Only proxy admins may set team_id to a different team.",+ )+ user_id = user_api_key_dict.user_id+ team_id = user_api_key_dict.team_id+ if not user_id and not team_id:+ # Orphan row: no user_id and no team_id means no non-admin can ever+ # see it again via the visibility filter. Reject up front.+ raise HTTPException(+ status_code=400,+ detail=(+ "Cannot create a memory entry without a user_id or team_id. "+ "Authenticate with a key that has a user_id or team_id, or call "+ "as a proxy admin."+ ),+ )+ return user_id, team_id+++ "/v1/memory",+ tags=["memory management"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=LiteLLM_MemoryRow,+)+async def create_memory(+ body: MemoryCreateRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Create a new memory entry for the caller (or, for admins, any scope)."""+ prisma_client = _require_prisma()+ user_id, team_id = _resolve_scope(user_api_key_dict, body.user_id, body.team_id)++ # Prisma's Python client rejects `metadata=None` on a `Json?` field —+ # the field must be omitted entirely to store SQL NULL. Build the data+ # dict conditionally so we only include metadata when the caller sent it.+ create_data: dict = {+ "key": body.key,+ "value": body.value,+ "user_id": user_id,+ "team_id": team_id,+ "created_by": user_api_key_dict.user_id,+ "updated_by": user_api_key_dict.user_id,+ }+ if body.metadata is not None:+ create_data["metadata"] = body.metadata++ try:+ row = await prisma_client.db.litellm_memorytable.create(data=create_data)+ except Exception as e:+ # Key is globally unique. Any duplicate → 409.+ if _is_unique_violation(e):+ raise HTTPException(+ status_code=409,+ detail=f"Memory with key '{body.key}' already exists.",+ )+ raise _internal_error(+ "Error creating memory: %s",+ e,+ "Internal error creating memory entry.",+ )++ return _row_to_model(row)+++ "/v1/memory",+ tags=["memory management"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=MemoryListResponse,+)+async def list_memory(+ key: Optional[str] = Query(None, description="Filter by exact key match."),+ key_prefix: Optional[str] = Query(+ None,+ description=(+ "Filter by key prefix (Redis-style namespace scan). "+ "Mutually exclusive with `key`; if both are provided, `key_prefix` wins."+ ),+ ),+ page: int = Query(1, ge=1),+ page_size: int = Query(50, ge=1, le=500),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """List memory entries visible to the caller."""+ prisma_client = _require_prisma()++ # Build the key filter first (prefix wins if both `key` and `key_prefix`+ # are passed). Then AND it with the visibility filter via an explicit+ # top-level "AND" — safer than `dict.update` since future visibility+ # filters could grow an "OR" key that would clobber this one if merged+ # by key.+ key_filter: dict = {}+ if key_prefix is not None:+ key_filter["key"] = {"startsWith": key_prefix}+ elif key is not None:+ key_filter["key"] = key++ vis = _visibility_filter(user_api_key_dict)+ where: dict+ if vis is None:+ where = key_filter+ elif not key_filter:+ where = vis+ else:+ where = {"AND": [key_filter, vis]}++ try:+ total = await prisma_client.db.litellm_memorytable.count(where=where)+ rows = await prisma_client.db.litellm_memorytable.find_many(+ where=where,+ order={"updated_at": "desc"},+ skip=(page - 1) * page_size,+ take=page_size,+ )+ except Exception as e:+ raise _internal_error(+ "Error listing memory: %s", e, "Internal error listing memory entries."+ )++ return MemoryListResponse(memories=[_row_to_model(r) for r in rows], total=total)+++async def _find_memory_for_caller(+ prisma_client: Any, key: str, user_api_key_dict: UserAPIKeyAuth+) -> Any:+ """Look up a memory row by key, scoped to the caller's visibility."""+ key_filter: dict = {"key": key}+ vis = _visibility_filter(user_api_key_dict)+ where: dict = key_filter if vis is None else {"AND": [key_filter, vis]}+ rows = await prisma_client.db.litellm_memorytable.find_many(+ where=where, take=1, order={"updated_at": "desc"}+ )+ if not rows:+ raise HTTPException(+ status_code=404, detail=f"Memory with key '{key}' not found"+ )+ return rows[0]+++ "/v1/memory/{key:path}",+ tags=["memory management"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=LiteLLM_MemoryRow,+)+async def get_memory(+ key: str,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Get a single memory entry by key, scoped to the caller."""+ prisma_client = _require_prisma()+ row = await _find_memory_for_caller(prisma_client, key, user_api_key_dict)+ return _row_to_model(row)+++ "/v1/memory/{key:path}",+ tags=["memory management"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=LiteLLM_MemoryRow,+)+async def upsert_memory(+ key: str,+ body: MemoryUpdateRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Upsert a memory entry by key within the caller's scope.++ If no row exists for (key, caller.user_id, caller.team_id), create one.+ If one exists, update the value/metadata fields that were provided.+ """+ prisma_client = _require_prisma()++ # Distinguish "metadata omitted from request" from "metadata: null".+ # Omitted → don't touch the existing field. Explicit null → clear to SQL NULL.+ # `model_fields_set` (Pydantic v2) only contains field names the caller+ # actually sent in the payload.+ fields_sent = body.model_fields_set+ metadata_explicit = "metadata" in fields_sent++ data: dict = {}+ if body.value is not None:+ data["value"] = body.value+ if metadata_explicit:+ # body.metadata may be None here — Prisma update accepts None on a+ # nullable Json? field and sets the column to SQL NULL.+ data["metadata"] = body.metadata+ if not data:+ raise HTTPException(+ status_code=400,+ detail="Request body must include at least one of: value, metadata.",+ )+ data["updated_by"] = user_api_key_dict.user_id++ async def _find_existing() -> Any:+ """Return the caller-visible row for `key`, or None."""+ try:+ return await _find_memory_for_caller(prisma_client, key, user_api_key_dict)+ except HTTPException as e:+ if e.status_code == 404:+ return None+ raise++ try:+ existing = await _find_existing()+ if existing is not None:+ # Visibility != write authority. Make sure the caller actually+ # owns this row (their user_id matches, or it's a pure team row in+ # their team) — otherwise a teammate could overwrite a personal+ # entry through the OR-based visibility filter.+ await _assert_write_access(prisma_client, existing, user_api_key_dict)+ row = await prisma_client.db.litellm_memorytable.update(+ where={"memory_id": existing.memory_id},+ data=data,+ )+ else:+ if body.value is None:+ raise HTTPException(+ status_code=400,+ detail="Cannot create a new memory via PUT without a 'value'.",+ )+ # PUT-create must honor admin scope override, matching POST semantics.+ user_id, team_id = _resolve_scope(+ user_api_key_dict, body.user_id, body.team_id+ )+ # Omit `metadata` when None — Prisma rejects None on Json? fields.+ create_data: dict = {+ "key": key,+ "value": body.value,+ "user_id": user_id,+ "team_id": team_id,+ "created_by": user_api_key_dict.user_id,+ "updated_by": user_api_key_dict.user_id,+ }+ if body.metadata is not None:+ create_data["metadata"] = body.metadata+ try:+ row = await prisma_client.db.litellm_memorytable.create(+ data=create_data+ )+ except Exception as e:+ # Race: a concurrent PUT/POST created the row after our check.+ # Re-read and fall back to an update so the PUT stays idempotent+ # instead of surfacing a 500 on a unique-violation.+ if not _is_unique_violation(e):+ raise+ existing_after_race = await _find_existing()+ if existing_after_race is None:+ # Row exists globally but isn't visible to this caller+ # (owned by someone else). Treat as conflict.+ raise HTTPException(+ status_code=409,+ detail=f"Memory with key '{key}' already exists.",+ )+ # Same write-authorization check as the non-race path.+ await _assert_write_access(+ prisma_client, existing_after_race, user_api_key_dict+ )+ row = await prisma_client.db.litellm_memorytable.update(+ where={"memory_id": existing_after_race.memory_id},+ data=data,+ )+ except HTTPException:+ raise+ except Exception as e:+ raise _internal_error(+ "Error upserting memory: %s", e, "Internal error updating memory entry."+ )++ return _row_to_model(row)+++ "/v1/memory/{key:path}",+ tags=["memory management"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=MemoryDeleteResponse,+)+async def delete_memory(+ key: str,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Delete a memory entry by key, scoped to the caller."""+ prisma_client = _require_prisma()+ row = await _find_memory_for_caller(prisma_client, key, user_api_key_dict)+ # Visibility != write authority — see the upsert handler for the rationale.+ await _assert_write_access(prisma_client, row, user_api_key_dict)+ try:+ await prisma_client.db.litellm_memorytable.delete(+ where={"memory_id": row.memory_id}+ )+ except Exception as e:+ raise _internal_error(+ "Error deleting memory: %s", e, "Internal error deleting memory entry."+ )++ return MemoryDeleteResponse(key=key, deleted=True)diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 8e9baec736c..4ca6895c2ce 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -425,6 +425,7 @@ from litellm.proxy.management_endpoints.team_endpoints import (from litellm.proxy.management_endpoints.tool_management_endpoints import (router as tool_management_router,)+from litellm.proxy.memory.memory_endpoints import router as memory_routerfrom litellm.proxy.management_endpoints.ui_sso import (get_disabled_non_admin_personal_key_creation,)@@ -14216,6 +14217,7 @@ app.include_router(model_management_router)app.include_router(model_access_group_management_router)app.include_router(tag_management_router)app.include_router(tool_management_router)+app.include_router(memory_router)app.include_router(cost_tracking_settings_router)app.include_router(router_settings_router)app.include_router(fallback_management_router)diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 34686148ce0..8f07c5afa3f 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -1225,6 +1225,29 @@ model LiteLLM_ClaudeCodePluginTable {@@map("LiteLLM_ClaudeCodePluginTable")}+// User/team-scoped memory store with a GLOBAL unique key.+// `value` is a string (typically markdown/text meant for LLM context);+// `metadata` is an optional JSON envelope for structured tags without schema changes.+// Note: `key` is globally unique across all users/teams — callers should+// namespace their keys (e.g. `user:123:notes`) if they need per-user isolation.+// `user_id` / `team_id` stamp ownership for visibility filtering, but do NOT+// participate in the unique constraint.+model LiteLLM_MemoryTable {+ memory_id String @id @default(uuid())+ key String @unique+ value String+ metadata Json?+ user_id String?+ team_id String?+ created_at DateTime @default(now())+ created_by String?+ updated_at DateTime @default(now()) @updatedAt+ updated_by String?++ @@index([user_id])+ @@index([team_id])+}+// Per-(router, request_type, model) Beta posterior for the adaptive router.model LiteLLM_AdaptiveRouterState {router_name Stringdiff --git a/litellm/types/memory_management.py b/litellm/types/memory_management.pynew file mode 100644index 00000000000..bde54933699--- /dev/null+++ b/litellm/types/memory_management.py@@ -0,0 +1,60 @@+"""+Pydantic models for Memory management endpoints.+"""++from datetime import datetime+from typing import Any, List, Optional++from pydantic import BaseModel, Field+++class LiteLLM_MemoryRow(BaseModel):+ memory_id: str+ key: str+ value: str+ metadata: Optional[Any] = None+ user_id: Optional[str] = None+ team_id: Optional[str] = None+ created_at: Optional[datetime] = None+ created_by: Optional[str] = None+ updated_at: Optional[datetime] = None+ updated_by: Optional[str] = None+++class MemoryCreateRequest(BaseModel):+ key: str = Field(..., description="Memory key (acts as the namespace in the URL).")+ value: str = Field(+ ..., description="Memory content. Typically markdown/text for LLM context."+ )+ metadata: Optional[Any] = Field(+ default=None,+ description="Optional JSON metadata (tags, structured fields).",+ )+ user_id: Optional[str] = Field(+ default=None,+ description="Scope to this user. Defaults to the caller's user_id.",+ )+ team_id: Optional[str] = Field(+ default=None,+ description="Scope to this team. Defaults to the caller's team_id.",+ )+++class MemoryUpdateRequest(BaseModel):+ value: Optional[str] = None+ metadata: Optional[Any] = None+ # Only honored on create (when the row doesn't yet exist) and only for+ # PROXY_ADMIN callers — mirrors MemoryCreateRequest so admins can bootstrap+ # rows scoped to another user/team via PUT, not just POST.+ user_id: Optional[str] = None+ team_id: Optional[str] = None+++class MemoryListResponse(BaseModel):+ memories: List[LiteLLM_MemoryRow]+ total: int+++class MemoryDeleteResponse(BaseModel):+ key: str+ deleted: booldiff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 8b2242f9187..2d13c5cd00f 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -19654,13 +19654,24 @@},"gpt-5.5": {"cache_read_input_token_cost": 5e-07,+ "cache_read_input_token_cost_above_272k_tokens": 1e-06,+ "cache_read_input_token_cost_flex": 2.5e-07,+ "cache_read_input_token_cost_priority": 1e-06,"input_cost_per_token": 5e-06,+ "input_cost_per_token_above_272k_tokens": 1e-05,+ "input_cost_per_token_flex": 2.5e-06,+ "input_cost_per_token_batches": 2.5e-06,+ "input_cost_per_token_priority": 1e-05,"litellm_provider": "openai",- "max_input_tokens": 272000,+ "max_input_tokens": 1050000,"max_output_tokens": 128000,"max_tokens": 128000,"mode": "chat","output_cost_per_token": 3e-05,+ "output_cost_per_token_above_272k_tokens": 4.5e-05,+ "output_cost_per_token_flex": 1.5e-05,+ "output_cost_per_token_batches": 1.5e-05,+ "output_cost_per_token_priority": 6e-05,"supported_endpoints": ["/v1/chat/completions","/v1/batch",@@ -19684,10 +19695,145 @@"supports_tool_choice": true,"supports_service_tier": true,"supports_vision": true,+ "supports_web_search": true,"supports_none_reasoning_effort": true,"supports_xhigh_reasoning_effort": true,"supports_minimal_reasoning_effort": true},+ "gpt-5.5-2026-04-23": {+ "cache_read_input_token_cost": 5e-07,+ "cache_read_input_token_cost_above_272k_tokens": 1e-06,+ "cache_read_input_token_cost_flex": 2.5e-07,+ "cache_read_input_token_cost_priority": 1e-06,+ "input_cost_per_token": 5e-06,+ "input_cost_per_token_above_272k_tokens": 1e-05,+ "input_cost_per_token_flex": 2.5e-06,+ "input_cost_per_token_batches": 2.5e-06,+ "input_cost_per_token_priority": 1e-05,+ "litellm_provider": "openai",+ "max_input_tokens": 1050000,+ "max_output_tokens": 128000,+ "max_tokens": 128000,+ "mode": "chat",+ "output_cost_per_token": 3e-05,+ "output_cost_per_token_above_272k_tokens": 4.5e-05,+ "output_cost_per_token_flex": 1.5e-05,+ "output_cost_per_token_batches": 1.5e-05,+ "output_cost_per_token_priority": 6e-05,+ "supported_endpoints": [+ "/v1/chat/completions",+ "/v1/batch",+ "/v1/responses"+ ],+ "supported_modalities": [+ "text",+ "image"+ ],+ "supported_output_modalities": [+ "text"+ ],+ "supports_function_calling": true,+ "supports_native_streaming": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_reasoning": true,+ "supports_response_schema": true,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_service_tier": true,+ "supports_vision": true,+ "supports_web_search": true,+ "supports_none_reasoning_effort": true,+ "supports_xhigh_reasoning_effort": true,+ "supports_minimal_reasoning_effort": true+ },+ "gpt-5.5-pro": {+ "cache_read_input_token_cost": 6e-06,+ "cache_read_input_token_cost_above_272k_tokens": 1.2e-05,+ "input_cost_per_token": 6e-05,+ "input_cost_per_token_above_272k_tokens": 0.00012,+ "input_cost_per_token_flex": 3e-05,+ "input_cost_per_token_batches": 3e-05,+ "litellm_provider": "openai",+ "max_input_tokens": 1050000,+ "max_output_tokens": 128000,+ "max_tokens": 128000,+ "mode": "responses",+ "output_cost_per_token": 0.00036,+ "output_cost_per_token_above_272k_tokens": 0.00054,+ "output_cost_per_token_flex": 0.00018,+ "output_cost_per_token_batches": 0.00018,+ "supported_endpoints": [+ "/v1/responses",+ "/v1/batch"+ ],+ "supported_modalities": [+ "text",+ "image"+ ],+ "supported_output_modalities": [+ "text"+ ],+ "supports_function_calling": true,+ "supports_native_streaming": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_reasoning": true,+ "supports_response_schema": false,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_service_tier": true,+ "supports_vision": true,+ "supports_web_search": true,+ "supports_none_reasoning_effort": false,+ "supports_xhigh_reasoning_effort": true,+ "supports_minimal_reasoning_effort": true+ },+ "gpt-5.5-pro-2026-04-23": {+ "cache_read_input_token_cost": 6e-06,+ "cache_read_input_token_cost_above_272k_tokens": 1.2e-05,+ "input_cost_per_token": 6e-05,+ "input_cost_per_token_above_272k_tokens": 0.00012,+ "input_cost_per_token_flex": 3e-05,+ "input_cost_per_token_batches": 3e-05,+ "litellm_provider": "openai",+ "max_input_tokens": 1050000,+ "max_output_tokens": 128000,+ "max_tokens": 128000,+ "mode": "responses",+ "output_cost_per_token": 0.00036,+ "output_cost_per_token_above_272k_tokens": 0.00054,+ "output_cost_per_token_flex": 0.00018,+ "output_cost_per_token_batches": 0.00018,+ "supported_endpoints": [+ "/v1/responses",+ "/v1/batch"+ ],+ "supported_modalities": [+ "text",+ "image"+ ],+ "supported_output_modalities": [+ "text"+ ],+ "supports_function_calling": true,+ "supports_native_streaming": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_reasoning": true,+ "supports_response_schema": false,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_service_tier": true,+ "supports_vision": true,+ "supports_web_search": true,+ "supports_none_reasoning_effort": false,+ "supports_xhigh_reasoning_effort": true,+ "supports_minimal_reasoning_effort": true+ },"gpt-5.4": {"cache_read_input_token_cost": 2.5e-07,"cache_read_input_token_cost_above_272k_tokens": 5e-07,diff --git a/schema.prisma b/schema.prismaindex 34686148ce0..8f07c5afa3f 100644--- a/schema.prisma+++ b/schema.prisma@@ -1225,6 +1225,29 @@ model LiteLLM_ClaudeCodePluginTable {@@map("LiteLLM_ClaudeCodePluginTable")}+// User/team-scoped memory store with a GLOBAL unique key.+// `value` is a string (typically markdown/text meant for LLM context);+// `metadata` is an optional JSON envelope for structured tags without schema changes.+// Note: `key` is globally unique across all users/teams — callers should+// namespace their keys (e.g. `user:123:notes`) if they need per-user isolation.+// `user_id` / `team_id` stamp ownership for visibility filtering, but do NOT+// participate in the unique constraint.+model LiteLLM_MemoryTable {+ memory_id String @id @default(uuid())+ key String @unique+ value String+ metadata Json?+ user_id String?+ team_id String?+ created_at DateTime @default(now())+ created_by String?+ updated_at DateTime @default(now()) @updatedAt+ updated_by String?++ @@index([user_id])+ @@index([team_id])+}+// Per-(router, request_type, model) Beta posterior for the adaptive router.model LiteLLM_AdaptiveRouterState {router_name Stringdiff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.pyindex 7144279ad0c..5e37e2a3424 100644--- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py+++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py@@ -343,7 +343,10 @@ def test_generic_cost_per_token_gpt55():assert model_cost_map["cache_read_input_token_cost"] == 5e-7assert model_cost_map["litellm_provider"] == "openai"assert model_cost_map["mode"] == "chat"- assert model_cost_map["max_input_tokens"] == 272000+ # gpt-5.5 inherits GPT-5.4's long-context window + tiered pricing.+ assert model_cost_map["max_input_tokens"] == 1050000+ assert model_cost_map["input_cost_per_token_above_272k_tokens"] == 1e-5+ assert model_cost_map["output_cost_per_token_above_272k_tokens"] == 4.5e-5prompt_tokens = 1000completion_tokens = 500@@ -365,6 +368,87 @@ def test_generic_cost_per_token_gpt55():)+def test_generic_cost_per_token_gpt55_pro():+ """gpt-5.5-pro: responses-only model — $60/1M input, $360/1M output, $6/1M cached input."""+ model = "gpt-5.5-pro"+ custom_llm_provider = "openai"+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")++ model_cost_map = litellm.model_cost[model]++ # Sanity-check the map values match OpenAI's published pricing.+ assert model_cost_map["input_cost_per_token"] == 6e-5+ assert model_cost_map["output_cost_per_token"] == 3.6e-4+ assert model_cost_map["cache_read_input_token_cost"] == 6e-6+ assert model_cost_map["litellm_provider"] == "openai"+ # gpt-5.5-pro is a responses-only model (no /v1/chat/completions endpoint).+ assert model_cost_map["mode"] == "responses"+ assert "/v1/chat/completions" not in model_cost_map["supported_endpoints"]+ assert "/v1/responses" in model_cost_map["supported_endpoints"]+ # Inherits GPT-5.4-pro's long-context window + tiered pricing (scaled 2x).+ assert model_cost_map["max_input_tokens"] == 1050000+ assert model_cost_map["input_cost_per_token_above_272k_tokens"] == 1.2e-4+ assert model_cost_map["output_cost_per_token_above_272k_tokens"] == 5.4e-4++ prompt_tokens = 1000+ completion_tokens = 500+ usage = Usage(+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ total_tokens=prompt_tokens + completion_tokens,+ )+ prompt_cost, completion_cost = generic_cost_per_token(+ model=model,+ usage=usage,+ custom_llm_provider=custom_llm_provider,+ )+ assert round(prompt_cost, 10) == round(+ model_cost_map["input_cost_per_token"] * prompt_tokens, 10+ )+ assert round(completion_cost, 10) == round(+ model_cost_map["output_cost_per_token"] * completion_tokens, 10+ )+++ "base_model,dated_model",+ [+ ("gpt-5.5", "gpt-5.5-2026-04-23"),+ ("gpt-5.5-pro", "gpt-5.5-pro-2026-04-23"),+ ],+)+def test_gpt55_dated_variants_match_base_reasoning_effort_capabilities(+ base_model, dated_model+):+ """Dated snapshots must carry the same reasoning_effort capability flags as+ their non-dated counterparts.++ Regression guard: ``supports_{none,minimal,xhigh}_reasoning_effort`` gate+ downstream routing in ``OpenAIGPT5Config`` — a missing flag is treated as+ ``False`` for opt-in levels (e.g. ``xhigh``), which silently diverges+ behavior between ``gpt-5.5`` and ``gpt-5.5-2026-04-23``. Pinning to a+ dated variant must never lose capabilities relative to the base alias.+ """+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")++ base = litellm.model_cost[base_model]+ dated = litellm.model_cost[dated_model]++ for flag in (+ "supports_none_reasoning_effort",+ "supports_minimal_reasoning_effort",+ "supports_xhigh_reasoning_effort",+ ):+ assert dated.get(flag) == base.get(flag), (+ f"{dated_model} has {flag}={dated.get(flag)!r}, "+ f"but {base_model} has {flag}={base.get(flag)!r}. "+ f"Dated snapshots must inherit the base model's reasoning_effort "+ f"capability profile."+ )++def test_generic_cost_per_token_anthropic_prompt_caching():model = "claude-sonnet-4@20250514"usage = Usage(diff --git a/tests/test_litellm/llms/openai/test_is_model_gpt_5_model.py b/tests/test_litellm/llms/openai/test_is_model_gpt_5_model.pyindex e611d5e6b7e..02dd9dade0a 100644--- a/tests/test_litellm/llms/openai/test_is_model_gpt_5_model.py+++ b/tests/test_litellm/llms/openai/test_is_model_gpt_5_model.py@@ -47,6 +47,9 @@ GPT5_MODELS = ["gpt-5.3","gpt-5.4","gpt-5.5",+ "gpt-5.5-pro",+ "gpt-5.5-2026-04-23", # dated variant+ "gpt-5.5-pro-2026-04-23", # dated variant"gpt-5.1-chat", # versioned chat — THE KEY REGRESSION CASE"gpt-5.2-chat", # versioned chat — also a regression case"gpt-5.3-chat", # versioned chat — THE KEY REGRESSION CASEdiff --git a/tests/test_litellm/proxy/memory/__init__.py b/tests/test_litellm/proxy/memory/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/test_litellm/proxy/memory/test_memory_endpoints.py b/tests/test_litellm/proxy/memory/test_memory_endpoints.pynew file mode 100644index 00000000000..4a38837a23c--- /dev/null+++ b/tests/test_litellm/proxy/memory/test_memory_endpoints.py@@ -0,0 +1,690 @@+"""+Unit tests for /v1/memory CRUD endpoints.++Uses FastAPI TestClient with an in-memory fake of the Prisma memory table.+Auth is overridden so we can simulate different callers (admin vs. scoped).+We patch the endpoint module's `_require_prisma` helper so we never need the+real proxy_server import chain (which pulls heavy optional deps).+"""++import os+import sys+from datetime import datetime, timezone+from typing import Any, Dict, List, Optional+from unittest.mock import MagicMock, patch++from fastapi import FastAPI+from fastapi.testclient import TestClient++sys.path.insert(0, os.path.abspath("../../.."))++from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.memory.memory_endpoints import router+++def _make_row(+ memory_id: str = "mem-1",+ key: str = "notes",+ value: str = "hello",+ user_id: Optional[str] = "user-a",+ team_id: Optional[str] = "team-a",+ metadata: Optional[Any] = None,+) -> MagicMock:+ """Build a Prisma-like row object."""+ now = datetime.now(timezone.utc)+ row = MagicMock()+ row.memory_id = memory_id+ row.key = key+ row.value = value+ row.metadata = metadata+ row.user_id = user_id+ row.team_id = team_id+ row.created_at = now+ row.created_by = user_id+ row.updated_at = now+ row.updated_by = user_id+ return row+++class _InMemoryMemoryTable:+ """Tiny fake of prisma_client.db.litellm_memorytable used by the endpoints."""++ def __init__(self):+ self.rows: List[MagicMock] = []+ self._counter = 0++ def _matches(self, row: MagicMock, where: Dict[str, Any]) -> bool:+ for k, v in where.items():+ if k == "AND":+ if not all(self._matches(row, clause) for clause in v):+ return False+ continue+ if k == "OR":+ if not any(self._matches(row, clause) for clause in v):+ return False+ continue+ # Support Prisma-style filter dicts: {"startsWith": "..."}, etc.+ if isinstance(v, dict):+ actual = getattr(row, k, None)+ if "startsWith" in v:+ if not isinstance(actual, str) or not actual.startswith(+ v["startsWith"]+ ):+ return False+ continue+ if "equals" in v:+ if actual != v["equals"]:+ return False+ continue+ # Unknown filter — fall back to inequality (treat as no match).+ return False+ if getattr(row, k, None) != v:+ return False+ return True++ def _filter(self, where: Optional[Dict[str, Any]]) -> List[MagicMock]:+ if not where:+ return list(self.rows)+ return [r for r in self.rows if self._matches(r, where)]++ async def create(self, data: Dict[str, Any]) -> MagicMock:+ # Key is globally unique.+ for r in self.rows:+ if r.key == data["key"]:+ raise Exception("UniqueViolation: duplicate key")+ self._counter += 1+ row = _make_row(+ memory_id=f"mem-{self._counter}",+ key=data["key"],+ value=data["value"],+ user_id=data.get("user_id"),+ team_id=data.get("team_id"),+ metadata=data.get("metadata"),+ )+ row.created_by = data.get("created_by")+ row.updated_by = data.get("updated_by")+ self.rows.append(row)+ return row++ async def count(self, where: Optional[Dict[str, Any]] = None) -> int:+ return len(self._filter(where))++ async def find_many(+ self,+ where: Optional[Dict[str, Any]] = None,+ order: Optional[Dict[str, str]] = None,+ skip: int = 0,+ take: Optional[int] = None,+ ) -> List[MagicMock]:+ _ = order+ out = self._filter(where)+ if skip:+ out = out[skip:]+ if take is not None:+ out = out[:take]+ return out++ async def update(self, where: Dict[str, Any], data: Dict[str, Any]) -> MagicMock:+ for r in self.rows:+ if r.memory_id == where["memory_id"]:+ for k, v in data.items():+ setattr(r, k, v)+ return r+ raise Exception("Not found")++ async def delete(self, where: Dict[str, Any]) -> MagicMock:+ for i, r in enumerate(self.rows):+ if r.memory_id == where["memory_id"]:+ return self.rows.pop(i)+ raise Exception("Not found")+++class _InMemoryTeamTable:+ """+ Tiny fake of `prisma_client.db.litellm_teamtable` — only `find_unique`+ is exercised by the memory router (for team-admin checks).+ """++ def __init__(self):+ self.teams: List[Any] = []++ async def find_unique(self, where: Dict[str, Any]) -> Optional[Any]:+ team_id = where["team_id"]+ for t in self.teams:+ if getattr(t, "team_id", None) == team_id:+ return t+ return None+++def _make_team(team_id: str, *, admin_user_ids: List[str]) -> MagicMock:+ """Build a team-row stub with `members_with_roles` shaped like Prisma."""+ members = [MagicMock(user_id=uid, role="admin") for uid in admin_user_ids]+ team = MagicMock()+ team.team_id = team_id+ team.organization_id = None # skip org-admin path in tests+ team.members_with_roles = members+ return team+++def _make_prisma() -> MagicMock:+ client = MagicMock()+ client.db = MagicMock()+ client.db.litellm_memorytable = _InMemoryMemoryTable()+ client.db.litellm_teamtable = _InMemoryTeamTable()+ return client+++def _make_client(auth: UserAPIKeyAuth) -> TestClient:+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth++ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = lambda: auth+ return TestClient(app, raise_server_exceptions=True)+++def _user_auth(user_id: str = "user-a", team_id: str = "team-a") -> UserAPIKeyAuth:+ return UserAPIKeyAuth(api_key="sk-test", user_id=user_id, team_id=team_id)+++def _admin_auth() -> UserAPIKeyAuth:+ return UserAPIKeyAuth(+ api_key="sk-admin",+ user_id="admin",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ )+++def _patch_prisma(prisma: Any):+ """Patch the endpoint module's _require_prisma to return our fake."""+ return patch(+ "litellm.proxy.memory.memory_endpoints._require_prisma",+ return_value=prisma,+ )+++class TestMemoryEndpoints:+ def setup_method(self):+ self.prisma = _make_prisma()++ def test_create_memory_defaults_scope_to_caller(self):+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.post("/v1/memory", json={"key": "notes", "value": "hello"})+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["key"] == "notes"+ assert body["value"] == "hello"+ assert body["user_id"] == "user-a"+ assert body["team_id"] == "team-a"++ def test_create_memory_duplicate_key_returns_409(self):+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ r1 = client.post("/v1/memory", json={"key": "k", "value": "v1"})+ assert r1.status_code == 200+ r2 = client.post("/v1/memory", json={"key": "k", "value": "v2"})+ assert r2.status_code == 409++ def test_non_admin_cannot_set_foreign_user_id(self):+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.post(+ "/v1/memory",+ json={"key": "notes", "value": "x", "user_id": "user-b"},+ )+ assert resp.status_code == 403++ def test_create_memory_identity_less_caller_returns_400(self):+ """+ A non-admin caller with neither user_id nor team_id would produce an+ orphan row unreachable by the visibility filter. Reject up front.+ """+ client = _make_client(UserAPIKeyAuth(api_key="sk-anon"))+ with _patch_prisma(self.prisma):+ resp = client.post("/v1/memory", json={"key": "notes", "value": "x"})+ assert resp.status_code == 400++ def test_put_memory_admin_can_bootstrap_foreign_scope(self):+ """PUT-create should mirror POST's admin scope override."""+ client = _make_client(_admin_auth())+ with _patch_prisma(self.prisma):+ resp = client.put(+ "/v1/memory/notes",+ json={"value": "x", "user_id": "some-user", "team_id": "some-team"},+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["user_id"] == "some-user"+ assert body["team_id"] == "some-team"++ def test_put_memory_race_returns_update_on_unique_violation(self):+ """+ Simulate the check-then-create race: _find_memory_for_caller says the+ row doesn't exist, then the create call gets a unique-constraint+ violation (a concurrent writer beat us). The handler should re-read+ and fall through to an update instead of surfacing a 500.+ """+ table = self.prisma.db.litellm_memorytable++ original_create = table.create+ original_find_many = table.find_many+ pre_create_calls = {"n": 0}++ async def racing_create(data):+ # On the very first create call we issue during the upsert, pretend+ # another writer inserted the row just before us.+ pre_create_calls["n"] += 1+ if pre_create_calls["n"] == 1:+ table.rows.append(+ _make_row(+ memory_id="m-race",+ key=data["key"],+ value="from-other-writer",+ user_id="user-a",+ team_id="team-a",+ )+ )+ raise Exception("UniqueViolation: duplicate key (raced)")+ return await original_create(data)++ table.create = racing_create # type: ignore[assignment]++ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/notes", json={"value": "mine"})++ assert resp.status_code == 200, resp.text+ body = resp.json()+ # Update path kicked in: our value replaced the racer's.+ assert body["value"] == "mine"+ # Only one row exists (the one the racer inserted, now updated).+ assert len(table.rows) == 1++ # Restore the fake's methods.+ table.create = original_create # type: ignore[assignment]+ table.find_many = original_find_many # type: ignore[assignment]++ def test_admin_can_set_any_scope(self):+ client = _make_client(_admin_auth())+ with _patch_prisma(self.prisma):+ resp = client.post(+ "/v1/memory",+ json={+ "key": "notes",+ "value": "x",+ "user_id": "some-user",+ "team_id": "some-team",+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["user_id"] == "some-user"+ assert body["team_id"] == "some-team"++ def test_list_memory_scoped_to_caller(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.extend(+ [+ _make_row(memory_id="m1", key="a", user_id="user-a", team_id=None),+ _make_row(memory_id="m2", key="b", user_id="user-b", team_id=None),+ _make_row(memory_id="m3", key="c", user_id=None, team_id="team-a"),+ ]+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.get("/v1/memory")+ assert resp.status_code == 200+ body = resp.json()+ keys = {m["key"] for m in body["memories"]}+ assert keys == {"a", "c"}+ assert body["total"] == 2++ def test_list_memory_key_prefix_filter(self):+ """key_prefix should do a prefix match (Redis-style namespace scan)."""+ table = self.prisma.db.litellm_memorytable+ table.rows.extend(+ [+ _make_row(+ memory_id="m1", key="user:profile", user_id="user-a", team_id=None+ ),+ _make_row(+ memory_id="m2", key="user:prefs", user_id="user-a", team_id=None+ ),+ _make_row(+ memory_id="m3",+ key="project:context",+ user_id="user-a",+ team_id=None,+ ),+ ]+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.get("/v1/memory?key_prefix=user:")+ assert resp.status_code == 200+ body = resp.json()+ keys = {m["key"] for m in body["memories"]}+ assert keys == {"user:profile", "user:prefs"}+ assert body["total"] == 2++ def test_list_memory_key_prefix_does_not_leak_across_scopes(self):+ """+ Even if a prefix would match another user's keys, the visibility+ filter must still scope results to the caller.+ """+ table = self.prisma.db.litellm_memorytable+ table.rows.extend(+ [+ # Caller's own "user:*" rows — should be visible.+ _make_row(+ memory_id="m1", key="user:profile", user_id="user-a", team_id=None+ ),+ # Another user's "user:*" rows — must NOT leak.+ _make_row(+ memory_id="m2", key="user:secret", user_id="user-b", team_id=None+ ),+ _make_row(+ memory_id="m3", key="user:token", user_id="user-b", team_id=None+ ),+ ]+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.get("/v1/memory?key_prefix=user:")+ assert resp.status_code == 200+ body = resp.json()+ keys = {m["key"] for m in body["memories"]}+ assert keys == {"user:profile"}+ assert body["total"] == 1++ def test_list_memory_admin_sees_all(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.extend(+ [+ _make_row(memory_id="m1", key="a", user_id="user-a", team_id=None),+ _make_row(memory_id="m2", key="b", user_id="user-b", team_id=None),+ ]+ )+ client = _make_client(_admin_auth())+ with _patch_prisma(self.prisma):+ resp = client.get("/v1/memory")+ assert resp.status_code == 200+ assert resp.json()["total"] == 2++ def test_get_memory_by_key(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(memory_id="m1", key="notes", value="hi", user_id="user-a")+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.get("/v1/memory/notes")+ assert resp.status_code == 200+ assert resp.json()["value"] == "hi"++ def test_get_memory_not_visible_returns_404(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(memory_id="m1", key="notes", user_id="user-b", team_id=None)+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.get("/v1/memory/notes")+ assert resp.status_code == 404++ def test_put_memory_creates_when_missing(self):+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/notes", json={"value": "new"})+ assert resp.status_code == 200+ assert resp.json()["value"] == "new"+ assert len(self.prisma.db.litellm_memorytable.rows) == 1++ def test_put_memory_updates_existing(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="notes",+ value="old",+ user_id="user-a",+ team_id="team-a",+ )+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/notes", json={"value": "new"})+ assert resp.status_code == 200+ assert resp.json()["value"] == "new"+ assert len(table.rows) == 1++ def test_put_memory_explicit_null_metadata_clears_field(self):+ """PUT with `metadata: null` should clear the metadata column (not silently drop the field)."""+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="notes",+ value="v",+ user_id="user-a",+ team_id="team-a",+ metadata={"tag": "old"},+ )+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/notes", json={"metadata": None})+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["metadata"] is None+ assert table.rows[0].metadata is None++ def test_put_memory_omitted_metadata_preserves_field(self):+ """PUT without a metadata field should NOT touch the stored metadata."""+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="notes",+ value="old",+ user_id="user-a",+ team_id="team-a",+ metadata={"tag": "keep"},+ )+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/notes", json={"value": "new"})+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["value"] == "new"+ assert body["metadata"] == {"tag": "keep"}++ def test_put_memory_empty_body_returns_400(self):+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/notes", json={})+ assert resp.status_code == 400++ def test_put_memory_teammate_cannot_overwrite_personal_row(self):+ """+ Visibility OR-filter lets a team member SEE a teammate's row, but the+ write-authorization check must prevent them from overwriting it.+ Teammate B should get 403, not silently take over user A's entry.+ """+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="user_role",+ value="A's notes",+ user_id="user-a",+ team_id="team-shared",+ )+ )+ # User B is on the same team but a different user_id.+ client = _make_client(_user_auth("user-b", "team-shared"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/user_role", json={"value": "B overwrite"})+ assert resp.status_code == 403, resp.text+ # Row is unchanged.+ assert table.rows[0].value == "A's notes"++ def test_delete_memory_teammate_cannot_delete_personal_row(self):+ """Same as above, but for DELETE."""+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="user_role",+ value="A's notes",+ user_id="user-a",+ team_id="team-shared",+ )+ )+ client = _make_client(_user_auth("user-b", "team-shared"))+ with _patch_prisma(self.prisma):+ resp = client.delete("/v1/memory/user_role")+ assert resp.status_code == 403, resp.text+ assert len(table.rows) == 1++ def test_put_memory_team_admin_can_modify_pure_team_row(self):+ """+ Pure team row (no user_id stamped) — only team admins (or org admins)+ may modify it, matching the auth pattern in team_endpoints.py.+ """+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="team_playbook",+ value="v1",+ user_id=None,+ team_id="team-shared",+ )+ )+ # user-admin is registered as a team admin of team-shared.+ self.prisma.db.litellm_teamtable.teams.append(+ _make_team("team-shared", admin_user_ids=["user-admin"])+ )+ client = _make_client(_user_auth("user-admin", "team-shared"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/team_playbook", json={"value": "v2"})+ assert resp.status_code == 200, resp.text+ assert table.rows[0].value == "v2"++ def test_put_memory_team_member_cannot_modify_pure_team_row(self):+ """+ Plain team members can READ team rows (visibility OR-filter), but they+ cannot WRITE — only team admins can.+ """+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="team_playbook",+ value="v1",+ user_id=None,+ team_id="team-shared",+ )+ )+ # team-shared exists, but user-b is NOT in members_with_roles as admin.+ self.prisma.db.litellm_teamtable.teams.append(+ _make_team("team-shared", admin_user_ids=["someone-else"])+ )+ client = _make_client(_user_auth("user-b", "team-shared"))+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/team_playbook", json={"value": "v2"})+ assert resp.status_code == 403, resp.text+ assert table.rows[0].value == "v1"++ def test_delete_memory_team_member_cannot_delete_pure_team_row(self):+ """Same as above, for DELETE."""+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="team_playbook",+ user_id=None,+ team_id="team-shared",+ )+ )+ self.prisma.db.litellm_teamtable.teams.append(+ _make_team("team-shared", admin_user_ids=["user-admin"])+ )+ client = _make_client(_user_auth("user-b", "team-shared"))+ with _patch_prisma(self.prisma):+ resp = client.delete("/v1/memory/team_playbook")+ assert resp.status_code == 403+ assert len(table.rows) == 1++ def test_admin_can_modify_any_row(self):+ """Admin bypasses write-authorization."""+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(+ memory_id="m1",+ key="user_role",+ value="A's notes",+ user_id="user-a",+ team_id="team-shared",+ )+ )+ client = _make_client(_admin_auth())+ with _patch_prisma(self.prisma):+ resp = client.put("/v1/memory/user_role", json={"value": "admin override"})+ assert resp.status_code == 200, resp.text+ assert table.rows[0].value == "admin override"++ def test_internal_error_does_not_leak_db_details(self):+ """+ 500 responses must not echo Prisma internals (table names, columns,+ connection strings) back to the caller.+ """+ table = self.prisma.db.litellm_memorytable++ async def boom(*_args, **_kwargs):+ raise Exception(+ "PrismaClientKnownRequestError: column "+ '"LiteLLM_MemoryTable.value" does not exist '+ "on host db.internal:5432"+ )++ original_create = table.create+ table.create = boom # type: ignore[assignment]++ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.post("/v1/memory", json={"key": "x", "value": "y"})++ table.create = original_create # type: ignore[assignment]++ assert resp.status_code == 500+ body_text = resp.text+ for leak in ("LiteLLM_MemoryTable", "db.internal", "PrismaClient"):+ assert (+ leak not in body_text+ ), f"Leaked '{leak}' in 500 response: {body_text}"++ def test_delete_memory(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(memory_id="m1", key="notes", user_id="user-a", team_id="team-a")+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.delete("/v1/memory/notes")+ assert resp.status_code == 200+ assert resp.json() == {"key": "notes", "deleted": True}+ assert table.rows == []++ def test_delete_memory_not_visible_returns_404(self):+ table = self.prisma.db.litellm_memorytable+ table.rows.append(+ _make_row(memory_id="m1", key="notes", user_id="user-b", team_id=None)+ )+ client = _make_client(_user_auth("user-a", "team-a"))+ with _patch_prisma(self.prisma):+ resp = client.delete("/v1/memory/notes")+ assert resp.status_code == 404diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsxindex 4312148d532..d32cf74d6ad 100644--- a/ui/litellm-dashboard/src/app/page.tsx+++ b/ui/litellm-dashboard/src/app/page.tsx@@ -39,6 +39,7 @@ import { AccessGroupsPage } from "@/components/AccessGroups/AccessGroupsPage";import { ProjectsPage } from "@/components/Projects/ProjectsPage";import VectorStoreManagement from "@/components/vector_store_management";import ToolPoliciesView from "@/components/ToolPoliciesView";+import { MemoryView } from "@/components/MemoryView";import SpendLogsTable from "@/components/view_logs";import ViewUserDashboard from "@/components/view_users";import { ThemeProvider } from "@/contexts/ThemeContext";@@ -630,6 +631,12 @@ function CreateKeyPageContent() {<VectorStoreManagement accessToken={accessToken} userRole={userRole} userID={userID} />) : page == "tool-policies" ? (<ToolPoliciesView accessToken={accessToken} userRole={userRole} />+ ) : page == "memory" ? (+ <MemoryView+ accessToken={accessToken}+ userID={userID}+ userRole={userRole}+ />) : page == "guardrails-monitor" ? (<GuardrailsMonitorView accessToken={accessToken} />) : page == "new_usage" ? (diff --git a/ui/litellm-dashboard/src/components/MemoryView/MemoryEditModal.tsx b/ui/litellm-dashboard/src/components/MemoryView/MemoryEditModal.tsxnew file mode 100644index 00000000000..ae08c297971--- /dev/null+++ b/ui/litellm-dashboard/src/components/MemoryView/MemoryEditModal.tsx@@ -0,0 +1,121 @@+"use client";++import React, { useEffect, useState } from "react";+import { Form, Input, Modal, Typography } from "antd";+import type { MemoryRow } from "../networking";++const { Text } = Typography;++interface MemoryEditModalProps {+ open: boolean;+ mode: "create" | "edit";+ initialRow?: MemoryRow;+ onClose: () => void;+ onSave: (+ key: string,+ value: string,+ metadataText: string,+ isCreate: boolean,+ ) => Promise<boolean>;+}++export const MemoryEditModal: React.FC<MemoryEditModalProps> = ({+ open,+ mode,+ initialRow,+ onClose,+ onSave,+}) => {+ const [form] = Form.useForm();+ const [submitting, setSubmitting] = useState(false);++ useEffect(() => {+ if (!open) return;+ if (mode === "edit" && initialRow) {+ form.setFieldsValue({+ key: initialRow.key,+ value: initialRow.value,+ metadata:+ initialRow.metadata != null+ ? JSON.stringify(initialRow.metadata, null, 2)+ : "",+ });+ } else {+ form.resetFields();+ }+ }, [open, mode, initialRow, form]);++ const handleOk = async () => {+ const values = await form.validateFields();+ setSubmitting(true);+ const ok = await onSave(+ values.key.trim(),+ values.value ?? "",+ values.metadata ?? "",+ mode === "create",+ );+ setSubmitting(false);+ if (ok) {+ form.resetFields();+ onClose();+ }+ };++ return (+ <Modal+ open={open}+ title={mode === "create" ? "Create memory" : `Edit ${initialRow?.key ?? ""}`}+ onCancel={() => {+ form.resetFields();+ onClose();+ }}+ onOk={handleOk}+ okText={mode === "create" ? "Create" : "Save"}+ confirmLoading={submitting}+ width={640}+ destroyOnClose+ >+ <Form form={form} layout="vertical">+ <Form.Item+ label="Key"+ name="key"+ rules={[{ required: true, message: "Key is required" }]}+ tooltip="Globally unique — two memories cannot share a key. Namespace your own keys if you need per-user isolation (e.g. user:123:notes)."+ >+ <Input+ placeholder="e.g. user_role"+ disabled={mode === "edit"}+ />+ </Form.Item>+ <Form.Item+ label="Value"+ name="value"+ rules={[{ required: true, message: "Value is required" }]}+ tooltip="Markdown/text injected into LLM context. Plain strings are fine."+ >+ <Input.TextArea+ rows={8}+ placeholder="What the agent should remember…"+ />+ </Form.Item>+ <Form.Item+ label={+ <span>+ Metadata <Text type="secondary">(optional JSON)</Text>+ </span>+ }+ name="metadata"+ tooltip="Optional structured metadata — must be valid JSON if provided."+ >+ <Input.TextArea+ rows={4}+ placeholder='{"tags": ["example"]}'+ style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }}+ />+ </Form.Item>+ </Form>+ </Modal>+ );+};++export default MemoryEditModal;diff --git a/ui/litellm-dashboard/src/components/MemoryView/MemoryView.tsx b/ui/litellm-dashboard/src/components/MemoryView/MemoryView.tsxnew file mode 100644index 00000000000..defe455abed--- /dev/null+++ b/ui/litellm-dashboard/src/components/MemoryView/MemoryView.tsx@@ -0,0 +1,544 @@+"use client";++import React, { useMemo, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ Button,+ Card,+ Drawer,+ Empty,+ Input,+ Modal,+ Space,+ Table,+ Tooltip,+ Typography,+ message,+} from "antd";+import type { ColumnsType } from "antd/es/table";+import {+ DeleteOutlined,+ EditOutlined,+ EyeOutlined,+ PlusOutlined,+ ReloadOutlined,+ SearchOutlined,+} from "@ant-design/icons";+import {+ MemoryRow,+ createMemory,+ deleteMemory,+ fetchMemoryList,+ updateMemory,+} from "../networking";+import { MemoryEditModal } from "./MemoryEditModal";++const { Text, Paragraph, Title } = Typography;++interface MemoryViewProps {+ accessToken: string | null;+ userID: string | null;+ userRole: string | null;+}++function previewValue(value: string, max = 120): string {+ if (!value) return "";+ const trimmed = value.trim();+ if (trimmed.length <= max) return trimmed;+ return `${trimmed.slice(0, max)}…`;+}++function formatTimestamp(ts?: string): string {+ if (!ts) return "—";+ try {+ const d = new Date(ts);+ return d.toLocaleString();+ } catch {+ return ts;+ }+}++const PAGE_SIZE = 50;++export const MemoryView: React.FC<MemoryViewProps> = ({ accessToken }) => {+ const [searchInput, setSearchInput] = useState("");+ const [appliedSearch, setAppliedSearch] = useState("");+ const [detailRow, setDetailRow] = useState<MemoryRow | null>(null);+ const [editRow, setEditRow] = useState<MemoryRow | null>(null);+ const [isCreateOpen, setIsCreateOpen] = useState(false);+ const [currentPage, setCurrentPage] = useState(1);++ // Reset to page 1 whenever the filter changes.+ React.useEffect(() => {+ setCurrentPage(1);+ }, [appliedSearch]);++ const queryClient = useQueryClient();+ // React Query key prefix for all memory-list variants (paged + filtered).+ // Mutations invalidate the whole prefix so the next render refetches the+ // currently-visible page without us needing a manual refetch().+ const MEMORY_LIST_KEY = "memoryList" as const;++ const {+ data,+ isLoading,+ isFetching,+ } = useQuery({+ queryKey: [MEMORY_LIST_KEY, appliedSearch, currentPage],+ queryFn: () => {+ if (!accessToken) throw new Error("Access token required");+ // Prefix search matches the Redis-style mental model (namespace scan):+ // typing "user:" finds "user:profile", "user:prefs", etc.+ return fetchMemoryList(accessToken, {+ keyPrefix: appliedSearch || undefined,+ page: currentPage,+ pageSize: PAGE_SIZE,+ });+ },+ enabled: !!accessToken,+ });++ const rows = useMemo(() => data?.memories ?? [], [data]);+ const total = data?.total ?? 0;++ // -- Mutations --------------------------------------------------------+ // All three write endpoints share the same success/error plumbing:+ // - on success: invalidate the list query so every cached page+ // refetches from scratch (pagination + filter-aware).+ // - on error: surface the message via antd `message.error`.++ const invalidateList = () =>+ queryClient.invalidateQueries({ queryKey: [MEMORY_LIST_KEY] });++ const createMutation = useMutation({+ mutationFn: (args: {+ key: string;+ value: string;+ metadata: unknown;+ }) => {+ if (!accessToken) throw new Error("Access token required");+ return createMemory(accessToken, args);+ },+ onSuccess: (row) => {+ message.success(`Created ${row.key}`);+ invalidateList();+ },+ onError: (err: Error) => {+ message.error(`Save failed: ${err.message}`);+ },+ });++ const updateMutation = useMutation({+ mutationFn: (args: {+ key: string;+ value?: string;+ metadata: unknown;+ }) => {+ if (!accessToken) throw new Error("Access token required");+ const { key, ...payload } = args;+ return updateMemory(accessToken, key, payload);+ },+ onSuccess: (row) => {+ message.success(`Updated ${row.key}`);+ invalidateList();+ },+ onError: (err: Error) => {+ message.error(`Save failed: ${err.message}`);+ },+ });++ const deleteMutation = useMutation({+ mutationFn: (key: string) => {+ if (!accessToken) throw new Error("Access token required");+ return deleteMemory(accessToken, key).then(() => key);+ },+ onSuccess: (key) => {+ message.success(`Deleted ${key}`);+ invalidateList();+ },+ onError: (err: Error) => {+ message.error(`Delete failed: ${err.message}`);+ },+ });++ const handleDelete = (row: MemoryRow) => {+ Modal.confirm({+ title: "Delete memory",+ content: (+ <span>+ Delete memory key <Text code>{row.key}</Text>? This cannot be undone.+ </span>+ ),+ okText: "Delete",+ okType: "danger",+ cancelText: "Cancel",+ onOk: () => deleteMutation.mutateAsync(row.key).catch(() => {}),+ });+ };++ const handleSave = async (+ key: string,+ value: string,+ metadataText: string,+ isCreate: boolean,+ ): Promise<boolean> => {+ if (!accessToken) return false;++ // On edit, an empty textarea is a user's intent to CLEAR existing+ // metadata — we must send explicit `null` (not `undefined`), or+ // JSON.stringify drops the field and the backend's model_fields_set+ // won't see it, leaving the stored value untouched.+ //+ // On create, an empty textarea just means "no metadata" — we omit the+ // field so the DB default (NULL) applies and we avoid Prisma's+ // `Json? = None` quirk on create.+ let metadataPayload: unknown;+ if (!metadataText.trim()) {+ metadataPayload = isCreate ? undefined : null;+ } else {+ try {+ metadataPayload = JSON.parse(metadataText);+ } catch {+ message.error("Metadata must be valid JSON (or leave empty).");+ return false;+ }+ }++ try {+ if (isCreate) {+ await createMutation.mutateAsync({+ key,+ value,+ metadata: metadataPayload,+ });+ } else {+ await updateMutation.mutateAsync({+ key,+ value,+ metadata: metadataPayload,+ });+ }+ return true;+ } catch {+ // error already surfaced by mutation's onError handler+ return false;+ }+ };++ const renderIdPill = (+ id: string | null | undefined,+ onClick?: () => void,+ ) => {+ if (!id) return <Text type="secondary">-</Text>;+ const short = id.length > 10 ? `${id.slice(0, 7)}...` : id;+ const pillClass =+ "font-mono text-blue-600 bg-blue-50 text-xs font-medium px-2 py-0.5 rounded-md border border-blue-200 inline-block max-w-[15ch] truncate whitespace-nowrap";+ return (+ <Tooltip title={id}>+ {onClick ? (+ <button+ onClick={onClick}+ className={`${pillClass} hover:bg-blue-100 cursor-pointer transition-colors text-left`}+ >+ {short}+ </button>+ ) : (+ <span className={pillClass}>{short}</span>+ )}+ </Tooltip>+ );+ };++ const columns: ColumnsType<MemoryRow> = [+ {+ title: "ID",+ dataIndex: "memory_id",+ key: "memory_id",+ width: 140,+ render: (_: unknown, r: MemoryRow) =>+ renderIdPill(r.memory_id, () => setDetailRow(r)),+ },+ {+ title: "Name",+ dataIndex: "key",+ key: "key",+ width: 200,+ render: (k: string) => <Text code>{k}</Text>,+ // No client-side sorter: pagination is server-side, so a client sort+ // would only reorder the current page and mislead users into thinking+ // the whole list is sorted. Backend returns rows ordered by+ // `updated_at DESC`; use the prefix filter for discovery by name.+ },+ {+ title: "Preview",+ dataIndex: "value",+ key: "value",+ render: (v: string) => (+ <Text type="secondary" style={{ whiteSpace: "pre-wrap" }}>+ {previewValue(v)}+ </Text>+ ),+ },+ {+ title: "User ID",+ dataIndex: "user_id",+ key: "user_id",+ width: 160,+ render: (uid?: string | null) => renderIdPill(uid),+ },+ {+ title: "Team ID",+ dataIndex: "team_id",+ key: "team_id",+ width: 160,+ render: (tid?: string | null) => renderIdPill(tid),+ },+ {+ title: "Updated",+ dataIndex: "updated_at",+ key: "updated_at",+ width: 180,+ render: (ts?: string) => <Text type="secondary">{formatTimestamp(ts)}</Text>,+ // No sorter — backend already returns rows in `updated_at DESC` order,+ // and a client-side sorter on a paginated view would only affect the+ // current page.+ },+ {+ title: "",+ key: "actions",+ width: 140,+ render: (_: unknown, r: MemoryRow) => (+ <Space size={4}>+ <Button+ size="small"+ type="text"+ icon={<EyeOutlined />}+ onClick={() => setDetailRow(r)}+ aria-label="View"+ />+ <Button+ size="small"+ type="text"+ icon={<EditOutlined />}+ onClick={() => setEditRow(r)}+ aria-label="Edit"+ />+ <Button+ size="small"+ type="text"+ danger+ icon={<DeleteOutlined />}+ onClick={() => handleDelete(r)}+ aria-label="Delete"+ />+ </Space>+ ),+ },+ ];++ return (+ <div className="w-full" style={{ padding: 24 }}>+ <Space direction="vertical" size="large" style={{ width: "100%" }}>+ <div>+ <Title level={3} style={{ marginBottom: 4 }}>+ Memory+ </Title>+ <Paragraph type="secondary" style={{ marginBottom: 0 }}>+ Inspect what your agents have stored under <Text code>/v1/memory</Text>.+ Scoped to memories visible to your user / team (admins see all).+ </Paragraph>+ </div>++ <Card>+ <Space+ style={{+ width: "100%",+ justifyContent: "space-between",+ marginBottom: 16,+ }}+ wrap+ >+ <Space>+ <Input+ allowClear+ placeholder='Filter by key prefix, e.g. "user:"'+ prefix={<SearchOutlined />}+ value={searchInput}+ onChange={(e) => setSearchInput(e.target.value)}+ onPressEnter={() => setAppliedSearch(searchInput.trim())}+ onClear={() => {+ setSearchInput("");+ setAppliedSearch("");+ }}+ style={{ width: 280 }}+ />+ <Button+ type="primary"+ ghost+ onClick={() => setAppliedSearch(searchInput.trim())}+ >+ Search+ </Button>+ <Button+ icon={<ReloadOutlined />}+ onClick={() => invalidateList()}+ loading={isFetching && !isLoading}+ >+ Refresh+ </Button>+ </Space>+ <Button+ type="primary"+ icon={<PlusOutlined />}+ onClick={() => setIsCreateOpen(true)}+ >+ New memory+ </Button>+ </Space>++ <Table+ rowKey="memory_id"+ loading={isLoading}+ dataSource={rows}+ columns={columns}+ // Server-side pagination: we fetch one page at a time so we never+ // silently truncate large stores. `total` drives the page count;+ // changing page/pageSize retriggers the query via `currentPage`.+ pagination={{+ current: currentPage,+ pageSize: PAGE_SIZE,+ total,+ showSizeChanger: false,+ showTotal: (n, range) =>+ `${range[0]}–${range[1]} of ${n}`,+ onChange: (page) => setCurrentPage(page),+ }}+ locale={{+ emptyText: (+ <Empty+ description={+ appliedSearch+ ? `No memories with keys starting with "${appliedSearch}"`+ : "No memories stored yet"+ }+ />+ ),+ }}+ />+ </Card>+ </Space>++ {/* Detail drawer */}+ <Drawer+ open={!!detailRow}+ onClose={() => setDetailRow(null)}+ title={+ detailRow ? (+ <Space>+ <Text code>{detailRow.key}</Text>+ </Space>+ ) : (+ "Memory"+ )+ }+ width={720}+ destroyOnClose+ >+ {detailRow && (+ <Space direction="vertical" size="middle" style={{ width: "100%" }}>+ <Space size="large" wrap>+ <div>+ <Text strong style={{ display: "block" }}>+ Memory ID+ </Text>+ <Text code style={{ fontSize: 12 }}>+ {detailRow.memory_id}+ </Text>+ </div>+ <div>+ <Text strong style={{ display: "block" }}>+ User ID+ </Text>+ <Text type={detailRow.user_id ? undefined : "secondary"}>+ {detailRow.user_id ?? "-"}+ </Text>+ </div>+ <div>+ <Text strong style={{ display: "block" }}>+ Team ID+ </Text>+ <Text type={detailRow.team_id ? undefined : "secondary"}>+ {detailRow.team_id ?? "-"}+ </Text>+ </div>+ </Space>+ <div>+ <Text strong>Value</Text>+ <Paragraph+ style={{+ background: "#fafafa",+ padding: 12,+ borderRadius: 6,+ whiteSpace: "pre-wrap",+ fontFamily:+ "ui-monospace, SFMono-Regular, Menlo, monospace",+ fontSize: 13,+ }}+ >+ {detailRow.value}+ </Paragraph>+ </div>+ {detailRow.metadata !== undefined &&+ detailRow.metadata !== null && (+ <div>+ <Text strong>Metadata</Text>+ <Paragraph+ style={{+ background: "#fafafa",+ padding: 12,+ borderRadius: 6,+ whiteSpace: "pre-wrap",+ fontFamily:+ "ui-monospace, SFMono-Regular, Menlo, monospace",+ fontSize: 12,+ }}+ >+ {JSON.stringify(detailRow.metadata, null, 2)}+ </Paragraph>+ </div>+ )}+ <Space+ split={<Text type="secondary">·</Text>}+ wrap+ size="small"+ style={{ color: "rgba(0,0,0,0.45)" }}+ >+ <Text type="secondary">+ Created {formatTimestamp(detailRow.created_at)}+ {detailRow.created_by ? ` by ${detailRow.created_by}` : ""}+ </Text>+ <Text type="secondary">+ Updated {formatTimestamp(detailRow.updated_at)}+ {detailRow.updated_by ? ` by ${detailRow.updated_by}` : ""}+ </Text>+ </Space>+ </Space>+ )}+ </Drawer>++ {/* Create / edit modal */}+ <MemoryEditModal+ open={isCreateOpen || !!editRow}+ mode={editRow ? "edit" : "create"}+ initialRow={editRow ?? undefined}+ onClose={() => {+ setIsCreateOpen(false);+ setEditRow(null);+ }}+ onSave={handleSave}+ />+ </div>+ );+};++export default MemoryView;diff --git a/ui/litellm-dashboard/src/components/MemoryView/index.tsx b/ui/litellm-dashboard/src/components/MemoryView/index.tsxnew file mode 100644index 00000000000..8b1c720148a--- /dev/null+++ b/ui/litellm-dashboard/src/components/MemoryView/index.tsx@@ -0,0 +1 @@+export { MemoryView, default } from "./MemoryView";diff --git a/ui/litellm-dashboard/src/components/leftnav.tsx b/ui/litellm-dashboard/src/components/leftnav.tsxindex ef0806c9594..c340b65496c 100644--- a/ui/litellm-dashboard/src/components/leftnav.tsx+++ b/ui/litellm-dashboard/src/components/leftnav.tsx@@ -139,6 +139,12 @@ const menuGroups: MenuGroup[] = [icon: <ApiOutlined />,roles: all_admin_roles,},+ {+ key: "memory",+ page: "memory",+ label: "Memory",+ icon: <BookOutlined />,+ },{key: "guardrails",page: "guardrails",diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex fb0e70842db..44208904a70 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -9986,3 +9986,147 @@ export const listMCPUserCredentials = async (if (!response.ok) return [];return response.json();};++// ============================================================+// Memory management (/v1/memory)+// ============================================================++/**+ * Encode a memory key for use in a URL path segment.+ *+ * The backend route is declared as `/v1/memory/{key:path}`, which supports+ * slashes in the key (e.g. `user/123/notes`). Plain `encodeURIComponent`+ * encodes `/` as `%2F`, and some proxies/middlewares (nginx default,+ * CloudFlare, AWS ALB) either reject or silently re-decode `%2F`, which+ * can break the request before FastAPI ever sees it.+ *+ * We keep slashes literal as path delimiters while still encoding every+ * other potentially-unsafe character (spaces, `?`, `#`, `%`, etc.) per+ * path segment.+ */+const encodeMemoryKeyForPath = (key: string): string =>+ key.split("/").map(encodeURIComponent).join("/");++export interface MemoryRow {+ memory_id: string;+ key: string;+ value: string;+ metadata?: unknown;+ user_id?: string | null;+ team_id?: string | null;+ created_at?: string;+ created_by?: string | null;+ updated_at?: string;+ updated_by?: string | null;+}++export interface MemoryListResponse {+ memories: MemoryRow[];+ total: number;+}++export const fetchMemoryList = async (+ accessToken: string,+ options: {+ key?: string;+ keyPrefix?: string;+ page?: number;+ pageSize?: number;+ } = {},+): Promise<MemoryListResponse> => {+ const base = proxyBaseUrl ? `${proxyBaseUrl}/v1/memory` : `/v1/memory`;+ const params = new URLSearchParams();+ // keyPrefix takes precedence — backend also does, but we omit `key`+ // to keep the URL clean and intent obvious.+ if (options.keyPrefix) {+ params.append("key_prefix", options.keyPrefix);+ } else if (options.key) {+ params.append("key", options.key);+ }+ if (options.page != null) params.append("page", String(options.page));+ if (options.pageSize != null)+ params.append("page_size", String(options.pageSize));+ const url = params.toString() ? `${base}?${params.toString()}` : base;+ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ if (!response.ok) {+ const errorData = await response.text();+ throw new Error(errorData);+ }+ return response.json();+};++export const createMemory = async (+ accessToken: string,+ payload: { key: string; value: string; metadata?: unknown },+): Promise<MemoryRow> => {+ const url = proxyBaseUrl ? `${proxyBaseUrl}/v1/memory` : `/v1/memory`;+ const body: Record<string, unknown> = {+ key: payload.key,+ value: payload.value,+ };+ if (payload.metadata !== undefined) body.metadata = payload.metadata;+ const response = await fetch(url, {+ method: "POST",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(body),+ });+ if (!response.ok) {+ const errorData = await response.text();+ throw new Error(errorData);+ }+ return response.json();+};++export const updateMemory = async (+ accessToken: string,+ key: string,+ payload: { value?: string; metadata?: unknown },+): Promise<MemoryRow> => {+ const encoded = encodeMemoryKeyForPath(key);+ const url = proxyBaseUrl+ ? `${proxyBaseUrl}/v1/memory/${encoded}`+ : `/v1/memory/${encoded}`;+ const response = await fetch(url, {+ method: "PUT",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(payload),+ });+ if (!response.ok) {+ const errorData = await response.text();+ throw new Error(errorData);+ }+ return response.json();+};++export const deleteMemory = async (+ accessToken: string,+ key: string,+): Promise<void> => {+ const encoded = encodeMemoryKeyForPath(key);+ const url = proxyBaseUrl+ ? `${proxyBaseUrl}/v1/memory/${encoded}`+ : `/v1/memory/${encoded}`;+ const response = await fetch(url, {+ method: "DELETE",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ if (!response.ok) {+ const errorData = await response.text();+ throw new Error(errorData);+ }+};diff --git a/ui/litellm-dashboard/src/components/page_metadata.ts b/ui/litellm-dashboard/src/components/page_metadata.tsindex 8edbc790799..63f03f4586c 100644--- a/ui/litellm-dashboard/src/components/page_metadata.ts+++ b/ui/litellm-dashboard/src/components/page_metadata.ts@@ -10,6 +10,7 @@ export const pageDescriptions: Record<string, string> = {models: "Configure and manage LLM models and endpoints",agents: "Create and manage AI agents","mcp-servers": "Configure Model Context Protocol servers",+ memory: "Inspect and manage agent memory entries stored under /v1/memory",guardrails: "Set up content moderation and safety guardrails",policies: "Define access control and usage policies","search-tools": "Configure RAG search and retrieval tools",