prompts.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import time
  2. from typing import Optional
  3. from open_webui.apps.webui.internal.db import Base, get_db
  4. from pydantic import BaseModel, ConfigDict
  5. from sqlalchemy import BigInteger, Column, String, Text
  6. ####################
  7. # Prompts DB Schema
  8. ####################
  9. class Prompt(Base):
  10. __tablename__ = "prompt"
  11. command = Column(String, primary_key=True)
  12. user_id = Column(String)
  13. title = Column(Text)
  14. content = Column(Text)
  15. timestamp = Column(BigInteger)
  16. class PromptModel(BaseModel):
  17. command: str
  18. user_id: str
  19. title: str
  20. content: str
  21. timestamp: int # timestamp in epoch
  22. model_config = ConfigDict(from_attributes=True)
  23. ####################
  24. # Forms
  25. ####################
  26. class PromptForm(BaseModel):
  27. command: str
  28. title: str
  29. content: str
  30. class PromptsTable:
  31. def insert_new_prompt(
  32. self, user_id: str, form_data: PromptForm
  33. ) -> Optional[PromptModel]:
  34. prompt = PromptModel(
  35. **{
  36. "user_id": user_id,
  37. "command": form_data.command,
  38. "title": form_data.title,
  39. "content": form_data.content,
  40. "timestamp": int(time.time()),
  41. }
  42. )
  43. try:
  44. with get_db() as db:
  45. result = Prompt(**prompt.dict())
  46. db.add(result)
  47. db.commit()
  48. db.refresh(result)
  49. if result:
  50. return PromptModel.model_validate(result)
  51. else:
  52. return None
  53. except Exception:
  54. return None
  55. def get_prompt_by_command(self, command: str) -> Optional[PromptModel]:
  56. try:
  57. with get_db() as db:
  58. prompt = db.query(Prompt).filter_by(command=command).first()
  59. return PromptModel.model_validate(prompt)
  60. except Exception:
  61. return None
  62. def get_prompts(self) -> list[PromptModel]:
  63. with get_db() as db:
  64. return [
  65. PromptModel.model_validate(prompt) for prompt in db.query(Prompt).all()
  66. ]
  67. def update_prompt_by_command(
  68. self, command: str, form_data: PromptForm
  69. ) -> Optional[PromptModel]:
  70. try:
  71. with get_db() as db:
  72. prompt = db.query(Prompt).filter_by(command=command).first()
  73. prompt.title = form_data.title
  74. prompt.content = form_data.content
  75. prompt.timestamp = int(time.time())
  76. db.commit()
  77. return PromptModel.model_validate(prompt)
  78. except Exception:
  79. return None
  80. def delete_prompt_by_command(self, command: str) -> bool:
  81. try:
  82. with get_db() as db:
  83. db.query(Prompt).filter_by(command=command).delete()
  84. db.commit()
  85. return True
  86. except Exception:
  87. return False
  88. Prompts = PromptsTable()