open-webui/backend/apps/webui/models/prompts.py

109 lines
2.7 KiB
Python
Raw Normal View History

from pydantic import BaseModel, ConfigDict
from typing import List, Optional
2024-01-03 04:41:37 +00:00
import time
from sqlalchemy import String, Column, BigInteger
from sqlalchemy.orm import Session
2024-01-03 04:41:37 +00:00
from apps.webui.internal.db import Base
2024-01-03 04:41:37 +00:00
import json
####################
# Prompts DB Schema
####################
class Prompt(Base):
__tablename__ = "prompt"
2024-01-03 04:41:37 +00:00
command = Column(String, primary_key=True)
user_id = Column(String)
title = Column(String)
content = Column(String)
timestamp = Column(BigInteger)
2024-01-03 04:41:37 +00:00
class PromptModel(BaseModel):
command: str
user_id: str
title: str
content: str
timestamp: int # timestamp in epoch
model_config = ConfigDict(from_attributes=True)
2024-01-03 04:41:37 +00:00
####################
# Forms
####################
class PromptForm(BaseModel):
command: str
title: str
content: str
class PromptsTable:
2024-03-31 08:13:39 +00:00
def insert_new_prompt(
self, db: Session, user_id: str, form_data: PromptForm
2024-03-31 08:13:39 +00:00
) -> Optional[PromptModel]:
2024-01-03 04:41:37 +00:00
prompt = PromptModel(
**{
"user_id": user_id,
"command": form_data.command,
"title": form_data.title,
"content": form_data.content,
"timestamp": int(time.time()),
2024-03-31 08:13:39 +00:00
}
)
2024-01-03 04:41:37 +00:00
try:
result = Prompt(**prompt.dict())
db.add(result)
db.commit()
db.refresh(result)
2024-01-03 04:41:37 +00:00
if result:
return PromptModel.model_validate(result)
2024-01-03 04:41:37 +00:00
else:
return None
except Exception as e:
2024-01-03 04:41:37 +00:00
return None
def get_prompt_by_command(self, db: Session, command: str) -> Optional[PromptModel]:
2024-01-03 04:41:37 +00:00
try:
prompt = db.query(Prompt).filter_by(command=command).first()
return PromptModel.model_validate(prompt)
2024-01-03 04:41:37 +00:00
except:
return None
def get_prompts(self, db: Session) -> List[PromptModel]:
return [PromptModel.model_validate(prompt) for prompt in db.query(Prompt).all()]
2024-01-03 04:41:37 +00:00
def update_prompt_by_command(
self, db: Session, command: str, form_data: PromptForm
2024-03-31 08:13:39 +00:00
) -> Optional[PromptModel]:
2024-01-03 04:41:37 +00:00
try:
db.query(Prompt).filter_by(command=command).update(
{
"title": form_data.title,
"content": form_data.content,
"timestamp": int(time.time()),
}
)
return self.get_prompt_by_command(db, command)
2024-01-03 04:41:37 +00:00
except:
return None
def delete_prompt_by_command(self, db: Session, command: str) -> bool:
2024-01-03 04:41:37 +00:00
try:
db.query(Prompt).filter_by(command=command).delete()
2024-01-03 04:41:37 +00:00
return True
except:
return False
Prompts = PromptsTable()