FunctionEditor.svelte 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <script>
  2. import { getContext, createEventDispatcher, onMount } from 'svelte';
  3. import { goto } from '$app/navigation';
  4. const dispatch = createEventDispatcher();
  5. const i18n = getContext('i18n');
  6. import CodeEditor from '$lib/components/common/CodeEditor.svelte';
  7. import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
  8. let formElement = null;
  9. let loading = false;
  10. let showConfirm = false;
  11. export let edit = false;
  12. export let clone = false;
  13. export let id = '';
  14. export let name = '';
  15. export let meta = {
  16. description: ''
  17. };
  18. export let content = '';
  19. $: if (name && !edit && !clone) {
  20. id = name.replace(/\s+/g, '_').toLowerCase();
  21. }
  22. let codeEditor;
  23. let boilerplate = `from pydantic import BaseModel
  24. from typing import Optional
  25. class Filter:
  26. class Valves(BaseModel):
  27. max_turns: int = 4
  28. pass
  29. def __init__(self):
  30. # Indicates custom file handling logic. This flag helps disengage default routines in favor of custom
  31. # implementations, informing the WebUI to defer file-related operations to designated methods within this class.
  32. # Alternatively, you can remove the files directly from the body in from the inlet hook
  33. self.file_handler = True
  34. # Initialize 'valves' with specific configurations. Using 'Valves' instance helps encapsulate settings,
  35. # which ensures settings are managed cohesively and not confused with operational flags like 'file_handler'.
  36. self.valves = self.Valves(**{"max_turns": 2})
  37. pass
  38. def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
  39. # Modify the request body or validate it before processing by the chat completion API.
  40. # This function is the pre-processor for the API where various checks on the input can be performed.
  41. # It can also modify the request before sending it to the API.
  42. print(f"inlet:{__name__}")
  43. print(f"inlet:body:{body}")
  44. print(f"inlet:user:{user}")
  45. if user.get("role", "admin") in ["user", "admin"]:
  46. messages = body.get("messages", [])
  47. if len(messages) > self.valves.max_turns:
  48. raise Exception(
  49. f"Conversation turn limit exceeded. Max turns: {self.valves.max_turns}"
  50. )
  51. return body
  52. def outlet(self, body: dict, user: Optional[dict] = None) -> dict:
  53. # Modify or analyze the response body after processing by the API.
  54. # This function is the post-processor for the API, which can be used to modify the response
  55. # or perform additional checks and analytics.
  56. print(f"outlet:{__name__}")
  57. print(f"outlet:body:{body}")
  58. print(f"outlet:user:{user}")
  59. messages = [
  60. {
  61. **message,
  62. "content": f"{message['content']} - @@Modified from Filter Outlet",
  63. }
  64. for message in body.get("messages", [])
  65. ]
  66. return {"messages": messages}
  67. `;
  68. const _boilerplate = `from pydantic import BaseModel
  69. from typing import Optional, Union, Generator, Iterator
  70. from utils.misc import get_last_user_message
  71. import os
  72. import requests
  73. # Filter Class: This class is designed to serve as a pre-processor and post-processor
  74. # for request and response modifications. It checks and transforms requests and responses
  75. # to ensure they meet specific criteria before further processing or returning to the user.
  76. class Filter:
  77. class Valves(BaseModel):
  78. max_turns: int = 4
  79. pass
  80. def __init__(self):
  81. # Indicates custom file handling logic. This flag helps disengage default routines in favor of custom
  82. # implementations, informing the WebUI to defer file-related operations to designated methods within this class.
  83. # Alternatively, you can remove the files directly from the body in from the inlet hook
  84. self.file_handler = True
  85. # Initialize 'valves' with specific configurations. Using 'Valves' instance helps encapsulate settings,
  86. # which ensures settings are managed cohesively and not confused with operational flags like 'file_handler'.
  87. self.valves = self.Valves(**{"max_turns": 2})
  88. pass
  89. def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
  90. # Modify the request body or validate it before processing by the chat completion API.
  91. # This function is the pre-processor for the API where various checks on the input can be performed.
  92. # It can also modify the request before sending it to the API.
  93. print(f"inlet:{__name__}")
  94. print(f"inlet:body:{body}")
  95. print(f"inlet:user:{user}")
  96. if user.get("role", "admin") in ["user", "admin"]:
  97. messages = body.get("messages", [])
  98. if len(messages) > self.valves.max_turns:
  99. raise Exception(
  100. f"Conversation turn limit exceeded. Max turns: {self.valves.max_turns}"
  101. )
  102. return body
  103. def outlet(self, body: dict, user: Optional[dict] = None) -> dict:
  104. # Modify or analyze the response body after processing by the API.
  105. # This function is the post-processor for the API, which can be used to modify the response
  106. # or perform additional checks and analytics.
  107. print(f"outlet:{__name__}")
  108. print(f"outlet:body:{body}")
  109. print(f"outlet:user:{user}")
  110. messages = [
  111. {
  112. **message,
  113. "content": f"{message['content']} - @@Modified from Filter Outlet",
  114. }
  115. for message in body.get("messages", [])
  116. ]
  117. return {"messages": messages}
  118. # Pipe Class: This class functions as a customizable pipeline.
  119. # It can be adapted to work with any external or internal models,
  120. # making it versatile for various use cases outside of just OpenAI models.
  121. class Pipe:
  122. class Valves(BaseModel):
  123. OPENAI_API_BASE_URL: str = "https://api.openai.com/v1"
  124. OPENAI_API_KEY: str = "your-key"
  125. pass
  126. def __init__(self):
  127. self.type = "manifold"
  128. self.valves = self.Valves()
  129. self.pipes = self.get_openai_models()
  130. pass
  131. def get_openai_models(self):
  132. if self.valves.OPENAI_API_KEY:
  133. try:
  134. headers = {}
  135. headers["Authorization"] = f"Bearer {self.valves.OPENAI_API_KEY}"
  136. headers["Content-Type"] = "application/json"
  137. r = requests.get(
  138. f"{self.valves.OPENAI_API_BASE_URL}/models", headers=headers
  139. )
  140. models = r.json()
  141. return [
  142. {
  143. "id": model["id"],
  144. "name": model["name"] if "name" in model else model["id"],
  145. }
  146. for model in models["data"]
  147. if "gpt" in model["id"]
  148. ]
  149. except Exception as e:
  150. print(f"Error: {e}")
  151. return [
  152. {
  153. "id": "error",
  154. "name": "Could not fetch models from OpenAI, please update the API Key in the valves.",
  155. },
  156. ]
  157. else:
  158. return []
  159. def pipe(self, body: dict) -> Union[str, Generator, Iterator]:
  160. # This is where you can add your custom pipelines like RAG.
  161. print(f"pipe:{__name__}")
  162. if "user" in body:
  163. print(body["user"])
  164. del body["user"]
  165. headers = {}
  166. headers["Authorization"] = f"Bearer {self.valves.OPENAI_API_KEY}"
  167. headers["Content-Type"] = "application/json"
  168. model_id = body["model"][body["model"].find(".") + 1 :]
  169. payload = {**body, "model": model_id}
  170. print(payload)
  171. try:
  172. r = requests.post(
  173. url=f"{self.valves.OPENAI_API_BASE_URL}/chat/completions",
  174. json=payload,
  175. headers=headers,
  176. stream=True,
  177. )
  178. r.raise_for_status()
  179. if body["stream"]:
  180. return r.iter_lines()
  181. else:
  182. return r.json()
  183. except Exception as e:
  184. return f"Error: {e}"
  185. `;
  186. const saveHandler = async () => {
  187. loading = true;
  188. dispatch('save', {
  189. id,
  190. name,
  191. meta,
  192. content
  193. });
  194. };
  195. const submitHandler = async () => {
  196. if (codeEditor) {
  197. const res = await codeEditor.formatPythonCodeHandler();
  198. if (res) {
  199. console.log('Code formatted successfully');
  200. saveHandler();
  201. }
  202. }
  203. };
  204. </script>
  205. <div class=" flex flex-col justify-between w-full overflow-y-auto h-full">
  206. <div class="mx-auto w-full md:px-0 h-full">
  207. <form
  208. bind:this={formElement}
  209. class=" flex flex-col max-h-[100dvh] h-full"
  210. on:submit|preventDefault={() => {
  211. if (edit) {
  212. submitHandler();
  213. } else {
  214. showConfirm = true;
  215. }
  216. }}
  217. >
  218. <div class="mb-2.5">
  219. <button
  220. class="flex space-x-1"
  221. on:click={() => {
  222. goto('/workspace/functions');
  223. }}
  224. type="button"
  225. >
  226. <div class=" self-center">
  227. <svg
  228. xmlns="http://www.w3.org/2000/svg"
  229. viewBox="0 0 20 20"
  230. fill="currentColor"
  231. class="w-4 h-4"
  232. >
  233. <path
  234. fill-rule="evenodd"
  235. d="M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z"
  236. clip-rule="evenodd"
  237. />
  238. </svg>
  239. </div>
  240. <div class=" self-center font-medium text-sm">{$i18n.t('Back')}</div>
  241. </button>
  242. </div>
  243. <div class="flex flex-col flex-1 overflow-auto h-0 rounded-lg">
  244. <div class="w-full mb-2 flex flex-col gap-1.5">
  245. <div class="flex gap-2 w-full">
  246. <input
  247. class="w-full px-3 py-2 text-sm font-medium bg-gray-50 dark:bg-gray-850 dark:text-gray-200 rounded-lg outline-none"
  248. type="text"
  249. placeholder="Function Name (e.g. My Filter)"
  250. bind:value={name}
  251. required
  252. />
  253. <input
  254. class="w-full px-3 py-2 text-sm font-medium disabled:text-gray-300 dark:disabled:text-gray-700 bg-gray-50 dark:bg-gray-850 dark:text-gray-200 rounded-lg outline-none"
  255. type="text"
  256. placeholder="Function ID (e.g. my_filter)"
  257. bind:value={id}
  258. required
  259. disabled={edit}
  260. />
  261. </div>
  262. <input
  263. class="w-full px-3 py-2 text-sm font-medium bg-gray-50 dark:bg-gray-850 dark:text-gray-200 rounded-lg outline-none"
  264. type="text"
  265. placeholder="Function Description (e.g. A filter to remove profanity from text)"
  266. bind:value={meta.description}
  267. required
  268. />
  269. </div>
  270. <div class="mb-2 flex-1 overflow-auto h-0 rounded-lg">
  271. <CodeEditor
  272. bind:value={content}
  273. bind:this={codeEditor}
  274. {boilerplate}
  275. on:save={() => {
  276. if (formElement) {
  277. formElement.requestSubmit();
  278. }
  279. }}
  280. />
  281. </div>
  282. <div class="pb-3 flex justify-between">
  283. <div class="flex-1 pr-3">
  284. <div class="text-xs text-gray-500 line-clamp-2">
  285. <span class=" font-semibold dark:text-gray-200">Warning:</span> Functions allow
  286. arbitrary code execution <br />—
  287. <span class=" font-medium dark:text-gray-400"
  288. >don't install random functions from sources you don't trust.</span
  289. >
  290. </div>
  291. </div>
  292. <button
  293. class="px-3 py-1.5 text-sm font-medium bg-emerald-600 hover:bg-emerald-700 text-gray-50 transition rounded-lg"
  294. type="submit"
  295. >
  296. {$i18n.t('Save')}
  297. </button>
  298. </div>
  299. </div>
  300. </form>
  301. </div>
  302. </div>
  303. <ConfirmDialog
  304. bind:show={showConfirm}
  305. on:confirm={() => {
  306. submitHandler();
  307. }}
  308. >
  309. <div class="text-sm text-gray-500">
  310. <div class=" bg-yellow-500/20 text-yellow-700 dark:text-yellow-200 rounded-lg px-4 py-3">
  311. <div>Please carefully review the following warnings:</div>
  312. <ul class=" mt-1 list-disc pl-4 text-xs">
  313. <li>Functions allow arbitrary code execution.</li>
  314. <li>Do not install functions from sources you do not fully trust.</li>
  315. </ul>
  316. </div>
  317. <div class="my-3">
  318. I acknowledge that I have read and I understand the implications of my action. I am aware of
  319. the risks associated with executing arbitrary code and I have verified the trustworthiness of
  320. the source.
  321. </div>
  322. </div>
  323. </ConfirmDialog>