FunctionEditor.svelte 13 KB

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