open-webui/backend/open_webui/models/models.py

413 lines
13 KiB
Python
Raw Normal View History

import logging
2024-08-27 22:10:27 +00:00
import time
from typing import Optional
2024-12-10 08:54:13 +00:00
from open_webui.internal.db import Base, JSONField, get_db
from open_webui.env import SRC_LOG_LEVELS
2024-11-15 09:29:07 +00:00
from open_webui.models.groups import Groups
2025-11-23 04:20:51 +00:00
from open_webui.models.users import User, UserModel, Users, UserResponse
2024-11-15 09:29:07 +00:00
2024-08-27 22:10:27 +00:00
from pydantic import BaseModel, ConfigDict
2024-11-15 09:29:07 +00:00
2025-11-23 04:20:51 +00:00
from sqlalchemy import String, cast, or_, and_, func
2024-11-15 09:29:07 +00:00
from sqlalchemy.dialects import postgresql, sqlite
2024-11-16 02:21:41 +00:00
from sqlalchemy import BigInteger, Column, Text, JSON, Boolean
2024-05-24 07:26:00 +00:00
2024-11-15 09:29:07 +00:00
2024-11-17 00:51:55 +00:00
from open_webui.utils.access_control import has_access
2024-11-15 09:29:07 +00:00
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
####################
# Models DB Schema
####################
# ModelParams is a model for the data stored in the params field of the Model table
class ModelParams(BaseModel):
2024-05-24 06:47:01 +00:00
model_config = ConfigDict(extra="allow")
pass
# ModelMeta is a model for the data stored in the meta field of the Model table
class ModelMeta(BaseModel):
2024-07-09 06:07:23 +00:00
profile_image_url: Optional[str] = "/static/favicon.png"
2024-05-25 01:26:36 +00:00
2024-05-24 06:47:01 +00:00
description: Optional[str] = None
"""
User-facing description of the model.
"""
2024-05-25 06:34:58 +00:00
capabilities: Optional[dict] = None
2024-05-24 06:47:01 +00:00
model_config = ConfigDict(extra="allow")
pass
class Model(Base):
__tablename__ = "model"
id = Column(Text, primary_key=True)
"""
The model's id as used in the API. If set to an existing model, it will override the model.
"""
user_id = Column(Text)
base_model_id = Column(Text, nullable=True)
"""
An optional pointer to the actual model that should be used when proxying requests.
"""
name = Column(Text)
"""
The human-readable display name of the model.
"""
params = Column(JSONField)
"""
Holds a JSON encoded blob of parameters, see `ModelParams`.
"""
meta = Column(JSONField)
2024-05-24 05:58:26 +00:00
"""
Holds a JSON encoded blob of metadata, see `ModelMeta`.
"""
2024-11-15 02:57:25 +00:00
access_control = Column(JSON, nullable=True) # Controls data access levels.
2024-11-15 04:13:43 +00:00
# Defines access control rules for this entry.
# - `None`: Public access, available to all users with the "user" role.
# - `{}`: Private access, restricted exclusively to the owner.
# - Custom permissions: Specific access control for reading and writing;
# Can specify group or user-level restrictions:
# {
# "read": {
# "group_ids": ["group_id1", "group_id2"],
# "user_ids": ["user_id1", "user_id2"]
# },
# "write": {
# "group_ids": ["group_id1", "group_id2"],
# "user_ids": ["user_id1", "user_id2"]
# }
# }
2024-11-15 02:57:25 +00:00
2024-11-16 02:21:41 +00:00
is_active = Column(Boolean, default=True)
updated_at = Column(BigInteger)
created_at = Column(BigInteger)
class ModelModel(BaseModel):
id: str
2024-05-25 01:26:36 +00:00
user_id: str
base_model_id: Optional[str] = None
2024-05-24 07:26:00 +00:00
name: str
params: ModelParams
2024-05-24 05:58:26 +00:00
meta: ModelMeta
2024-11-15 04:13:43 +00:00
access_control: Optional[dict] = None
2024-11-15 02:57:25 +00:00
2024-11-16 02:21:41 +00:00
is_active: bool
2024-05-24 07:26:00 +00:00
updated_at: int # timestamp in epoch
created_at: int # timestamp in epoch
model_config = ConfigDict(from_attributes=True)
####################
# Forms
####################
2024-11-18 13:37:04 +00:00
class ModelUserResponse(ModelModel):
user: Optional[UserResponse] = None
2024-11-15 09:29:07 +00:00
2024-11-16 02:21:41 +00:00
2024-11-18 13:37:04 +00:00
class ModelResponse(ModelModel):
pass
2024-05-24 07:26:00 +00:00
2025-11-23 04:20:51 +00:00
class ModelListResponse(BaseModel):
items: list[ModelUserResponse]
total: int
2024-05-24 07:26:00 +00:00
class ModelForm(BaseModel):
id: str
base_model_id: Optional[str] = None
name: str
meta: ModelMeta
params: ModelParams
2024-11-16 02:21:41 +00:00
access_control: Optional[dict] = None
is_active: bool = True
2024-05-24 07:26:00 +00:00
class ModelsTable:
2024-05-25 01:26:36 +00:00
def insert_new_model(
self, form_data: ModelForm, user_id: str
2024-05-25 01:26:36 +00:00
) -> Optional[ModelModel]:
model = ModelModel(
**{
**form_data.model_dump(),
"user_id": user_id,
"created_at": int(time.time()),
"updated_at": int(time.time()),
}
)
2024-05-24 07:26:00 +00:00
try:
2024-07-04 06:32:39 +00:00
with get_db() as db:
result = Model(**model.model_dump())
db.add(result)
db.commit()
db.refresh(result)
if result:
return ModelModel.model_validate(result)
else:
return None
2024-05-25 01:26:36 +00:00
except Exception as e:
log.exception(f"Failed to insert a new model: {e}")
2024-05-24 07:26:00 +00:00
return None
2024-08-14 12:46:31 +00:00
def get_all_models(self) -> list[ModelModel]:
2024-07-04 06:32:39 +00:00
with get_db() as db:
return [ModelModel.model_validate(model) for model in db.query(Model).all()]
2024-11-18 13:37:04 +00:00
def get_models(self) -> list[ModelUserResponse]:
2024-11-15 09:29:07 +00:00
with get_db() as db:
all_models = db.query(Model).filter(Model.base_model_id != None).all()
user_ids = list(set(model.user_id for model in all_models))
users = Users.get_users_by_user_ids(user_ids) if user_ids else []
users_dict = {user.id: user for user in users}
2024-11-20 00:47:35 +00:00
models = []
for model in all_models:
user = users_dict.get(model.user_id)
2024-11-20 00:47:35 +00:00
models.append(
ModelUserResponse.model_validate(
{
**ModelModel.model_validate(model).model_dump(),
"user": user.model_dump() if user else None,
}
)
2024-11-18 13:37:04 +00:00
)
2024-11-20 00:47:35 +00:00
return models
2024-11-15 09:29:07 +00:00
2024-11-16 02:53:50 +00:00
def get_base_models(self) -> list[ModelModel]:
with get_db() as db:
return [
ModelModel.model_validate(model)
for model in db.query(Model).filter(Model.base_model_id == None).all()
]
2024-11-15 09:29:07 +00:00
def get_models_by_user_id(
self, user_id: str, permission: str = "write"
2024-11-18 13:37:04 +00:00
) -> list[ModelUserResponse]:
models = self.get_models()
user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user_id)}
2024-11-15 09:29:07 +00:00
return [
model
for model in models
if model.user_id == user_id
or has_access(user_id, permission, model.access_control, user_group_ids)
2024-11-15 09:29:07 +00:00
]
2025-11-23 04:20:51 +00:00
def search_models(
self, user_id: str, filter: dict = {}, skip: int = 0, limit: int = 30
) -> ModelListResponse:
with get_db() as db:
# Join GroupMember so we can order by group_id when requested
query = db.query(Model, User).outerjoin(User, User.id == Model.user_id)
query = query.filter(Model.base_model_id != None)
if filter:
query_key = filter.get("query")
if query_key:
query = query.filter(
or_(
Model.name.ilike(f"%{query_key}%"),
Model.base_model_id.ilike(f"%{query_key}%"),
)
)
if filter.get("user_id"):
query = query.filter(Model.user_id == filter.get("user_id"))
view_option = filter.get("view_option")
if view_option == "created":
query = query.filter(Model.user_id == user_id)
elif view_option == "shared":
query = query.filter(Model.user_id != user_id)
tag = filter.get("tag")
if tag:
# TODO: This is a simple implementation and should be improved for performance
like_pattern = f'%"{tag.lower()}"%' # `"tag"` inside JSON array
meta_text = func.lower(cast(Model.meta, String))
query = query.filter(meta_text.like(like_pattern))
order_by = filter.get("order_by")
direction = filter.get("direction")
if order_by == "name":
if direction == "asc":
query = query.order_by(Model.name.asc())
else:
query = query.order_by(Model.name.desc())
elif order_by == "created_at":
if direction == "asc":
query = query.order_by(Model.created_at.asc())
else:
query = query.order_by(Model.created_at.desc())
elif order_by == "updated_at":
if direction == "asc":
query = query.order_by(Model.updated_at.asc())
else:
query = query.order_by(Model.updated_at.desc())
else:
query = query.order_by(Model.created_at.desc())
# Count BEFORE pagination
total = query.count()
if skip:
query = query.offset(skip)
if limit:
query = query.limit(limit)
items = query.all()
models = []
for model, user in items:
models.append(
2025-11-24 20:39:13 +00:00
ModelUserResponse(
**ModelModel.model_validate(model).model_dump(),
user=(
UserResponse(**UserModel.model_validate(user).model_dump())
if user
else None
),
)
2025-11-23 04:20:51 +00:00
)
return ModelListResponse(items=models, total=total)
def get_model_by_id(self, id: str) -> Optional[ModelModel]:
try:
2024-07-04 06:32:39 +00:00
with get_db() as db:
model = db.get(Model, id)
return ModelModel.model_validate(model)
2024-08-14 12:38:19 +00:00
except Exception:
2024-05-24 07:26:00 +00:00
return None
2024-11-16 02:21:41 +00:00
def toggle_model_by_id(self, id: str) -> Optional[ModelModel]:
with get_db() as db:
try:
is_active = db.query(Model).filter_by(id=id).first().is_active
db.query(Model).filter_by(id=id).update(
{
"is_active": not is_active,
"updated_at": int(time.time()),
}
)
db.commit()
return self.get_model_by_id(id)
except Exception:
return None
2024-06-24 07:57:08 +00:00
def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
2024-05-24 07:26:00 +00:00
try:
2024-07-04 06:32:39 +00:00
with get_db() as db:
# update only the fields that are present in the model
2025-11-21 06:48:06 +00:00
data = model.model_dump(exclude={"id"})
result = db.query(Model).filter_by(id=id).update(data)
2024-07-04 06:32:39 +00:00
db.commit()
2024-07-08 18:58:36 +00:00
model = db.get(Model, id)
2024-07-04 06:32:39 +00:00
db.refresh(model)
return ModelModel.model_validate(model)
2024-05-25 05:21:57 +00:00
except Exception as e:
log.exception(f"Failed to update the model by id {id}: {e}")
2024-05-24 07:26:00 +00:00
return None
def delete_model_by_id(self, id: str) -> bool:
2024-05-24 07:26:00 +00:00
try:
2024-07-04 06:32:39 +00:00
with get_db() as db:
db.query(Model).filter_by(id=id).delete()
2024-07-06 15:10:58 +00:00
db.commit()
2024-07-04 06:32:39 +00:00
return True
2024-08-14 12:38:19 +00:00
except Exception:
return False
2024-11-19 19:03:36 +00:00
def delete_all_models(self) -> bool:
try:
with get_db() as db:
db.query(Model).delete()
db.commit()
return True
except Exception:
return False
2025-07-28 09:06:05 +00:00
def sync_models(self, user_id: str, models: list[ModelModel]) -> list[ModelModel]:
try:
with get_db() as db:
# Get existing models
existing_models = db.query(Model).all()
existing_ids = {model.id for model in existing_models}
# Prepare a set of new model IDs
new_model_ids = {model.id for model in models}
# Update or insert models
for model in models:
if model.id in existing_ids:
db.query(Model).filter_by(id=model.id).update(
{
**model.model_dump(),
"user_id": user_id,
"updated_at": int(time.time()),
}
)
else:
new_model = Model(
**{
**model.model_dump(),
"user_id": user_id,
"updated_at": int(time.time()),
}
)
db.add(new_model)
# Remove models that are no longer present
for model in existing_models:
if model.id not in new_model_ids:
db.delete(model)
db.commit()
return [
ModelModel.model_validate(model) for model in db.query(Model).all()
]
except Exception as e:
log.exception(f"Error syncing models for user {user_id}: {e}")
return []
Models = ModelsTable()