prompts.py 2.6 KB

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