functions.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. from pydantic import BaseModel
  2. from peewee import *
  3. from playhouse.shortcuts import model_to_dict
  4. from typing import List, Union, Optional
  5. import time
  6. import logging
  7. from apps.webui.internal.db import DB, JSONField
  8. from apps.webui.models.users import Users
  9. import json
  10. from config import SRC_LOG_LEVELS
  11. log = logging.getLogger(__name__)
  12. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  13. ####################
  14. # Functions DB Schema
  15. ####################
  16. class Function(Model):
  17. id = CharField(unique=True)
  18. user_id = CharField()
  19. name = TextField()
  20. type = TextField()
  21. content = TextField()
  22. meta = JSONField()
  23. updated_at = BigIntegerField()
  24. created_at = BigIntegerField()
  25. class Meta:
  26. database = DB
  27. class FunctionMeta(BaseModel):
  28. description: Optional[str] = None
  29. class FunctionModel(BaseModel):
  30. id: str
  31. user_id: str
  32. name: str
  33. type: str
  34. content: str
  35. meta: FunctionMeta
  36. updated_at: int # timestamp in epoch
  37. created_at: int # timestamp in epoch
  38. ####################
  39. # Forms
  40. ####################
  41. class FunctionResponse(BaseModel):
  42. id: str
  43. user_id: str
  44. type: str
  45. name: str
  46. meta: FunctionMeta
  47. updated_at: int # timestamp in epoch
  48. created_at: int # timestamp in epoch
  49. class FunctionForm(BaseModel):
  50. id: str
  51. name: str
  52. content: str
  53. meta: FunctionMeta
  54. class FunctionsTable:
  55. def __init__(self, db):
  56. self.db = db
  57. self.db.create_tables([Function])
  58. def insert_new_function(
  59. self, user_id: str, type: str, form_data: FunctionForm
  60. ) -> Optional[FunctionModel]:
  61. function = FunctionModel(
  62. **{
  63. **form_data.model_dump(),
  64. "user_id": user_id,
  65. "type": type,
  66. "updated_at": int(time.time()),
  67. "created_at": int(time.time()),
  68. }
  69. )
  70. try:
  71. result = Function.create(**function.model_dump())
  72. if result:
  73. return function
  74. else:
  75. return None
  76. except Exception as e:
  77. print(f"Error creating tool: {e}")
  78. return None
  79. def get_function_by_id(self, id: str) -> Optional[FunctionModel]:
  80. try:
  81. function = Function.get(Function.id == id)
  82. return FunctionModel(**model_to_dict(function))
  83. except:
  84. return None
  85. def get_functions(self) -> List[FunctionModel]:
  86. return [
  87. FunctionModel(**model_to_dict(function)) for function in Function.select()
  88. ]
  89. def get_functions_by_type(self, type: str) -> List[FunctionModel]:
  90. return [
  91. FunctionModel(**model_to_dict(function))
  92. for function in Function.select().where(Function.type == type)
  93. ]
  94. def get_user_valves_by_id_and_user_id(
  95. self, id: str, user_id: str
  96. ) -> Optional[dict]:
  97. try:
  98. user = Users.get_user_by_id(user_id)
  99. # Check if user has "functions" and "valves" settings
  100. if "functions" not in user.settings:
  101. user.settings["functions"] = {}
  102. if "valves" not in user.settings["functions"]:
  103. user.settings["functions"]["valves"] = {}
  104. return user.settings["functions"]["valves"].get(id, {})
  105. except Exception as e:
  106. print(f"An error occurred: {e}")
  107. return None
  108. def update_user_valves_by_id_and_user_id(
  109. self, id: str, user_id: str, valves: dict
  110. ) -> Optional[dict]:
  111. try:
  112. user = Users.get_user_by_id(user_id)
  113. # Check if user has "functions" and "valves" settings
  114. if "functions" not in user.settings:
  115. user.settings["functions"] = {}
  116. if "valves" not in user.settings["functions"]:
  117. user.settings["functions"]["valves"] = {}
  118. user.settings["functions"]["valves"][id] = valves
  119. # Update the user settings in the database
  120. query = Users.update_user_by_id(user_id, {"settings": user.settings})
  121. query.execute()
  122. return user.settings["functions"]["valves"][id]
  123. except Exception as e:
  124. print(f"An error occurred: {e}")
  125. return None
  126. def update_function_by_id(self, id: str, updated: dict) -> Optional[FunctionModel]:
  127. try:
  128. query = Function.update(
  129. **updated,
  130. updated_at=int(time.time()),
  131. ).where(Function.id == id)
  132. query.execute()
  133. function = Function.get(Function.id == id)
  134. return FunctionModel(**model_to_dict(function))
  135. except:
  136. return None
  137. def delete_function_by_id(self, id: str) -> bool:
  138. try:
  139. query = Function.delete().where((Function.id == id))
  140. query.execute() # Remove the rows, return number of rows removed.
  141. return True
  142. except:
  143. return False
  144. Functions = FunctionsTable(DB)