FunctionEditor.svelte 6.94 KB
Newer Older
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1
2
<script>
	import { getContext, createEventDispatcher, onMount } from 'svelte';
3
	import { goto } from '$app/navigation';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
4

5
	const dispatch = createEventDispatcher();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
	const i18n = getContext('i18n');

	import CodeEditor from '$lib/components/common/CodeEditor.svelte';
	import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';

	let formElement = null;
	let loading = false;
	let showConfirm = false;

	export let edit = false;
	export let clone = false;

	export let id = '';
	export let name = '';
	export let meta = {
		description: ''
	};
	export let content = '';

	$: if (name && !edit && !clone) {
		id = name.replace(/\s+/g, '_').toLowerCase();
	}

	let codeEditor;
Timothy J. Baek's avatar
Timothy J. Baek committed
30
31
	let boilerplate = `from pydantic import BaseModel
from typing import Optional
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
32

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
33

34
class Filter:
Timothy J. Baek's avatar
Timothy J. Baek committed
35
    class Valves(BaseModel):
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
36
        max_turns: int = 4
Timothy J. Baek's avatar
Timothy J. Baek committed
37
38
        pass

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
39
    def __init__(self):
Timothy J. Baek's avatar
Timothy J. Baek committed
40
41
        # Indicates custom file handling logic. This flag helps disengage default routines in favor of custom
        # implementations, informing the WebUI to defer file-related operations to designated methods within this class.
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
42
        # Alternatively, you can remove the files directly from the body in from the inlet hook
Timothy J. Baek's avatar
Timothy J. Baek committed
43
44
45
46
        self.file_handler = True

        # Initialize 'valves' with specific configurations. Using 'Valves' instance helps encapsulate settings,
        # which ensures settings are managed cohesively and not confused with operational flags like 'file_handler'.
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
47
        self.valves = self.Valves(**{"max_turns": 2})
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
48
49
        pass

50
    def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
Timothy J. Baek's avatar
Timothy J. Baek committed
51
52
53
        # Modify the request body or validate it before processing by the chat completion API.
        # This function is the pre-processor for the API where various checks on the input can be performed.
        # It can also modify the request before sending it to the API.
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
54
55
56
        print(f"inlet:{__name__}")
        print(f"inlet:body:{body}")
        print(f"inlet:user:{user}")
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
57

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
58
        if user.get("role", "admin") in ["user", "admin"]:
59
            messages = body.get("messages", [])
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
60
            if len(messages) > self.valves.max_turns:
61
                raise Exception(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
62
                    f"Conversation turn limit exceeded. Max turns: {self.valves.max_turns}"
63
                )
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
64

65
        return body
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
66

67
    def outlet(self, body: dict, user: Optional[dict] = None) -> dict:
Timothy J. Baek's avatar
Timothy J. Baek committed
68
        # Modify or analyze the response body after processing by the API.
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
69
        # This function is the post-processor for the API, which can be used to modify the response
Timothy J. Baek's avatar
Timothy J. Baek committed
70
        # or perform additional checks and analytics.
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
71
72
73
        print(f"outlet:{__name__}")
        print(f"outlet:body:{body}")
        print(f"outlet:user:{user}")
Timothy J. Baek's avatar
Timothy J. Baek committed
74

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
75
        messages = [
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
76
77
78
79
            {
                **message,
                "content": f"{message['content']} - @@Modified from Filter Outlet",
            }
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
80
81
82
83
            for message in body.get("messages", [])
        ]

        return {"messages": messages}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
84

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
85
`;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

	const saveHandler = async () => {
		loading = true;
		dispatch('save', {
			id,
			name,
			meta,
			content
		});
	};

	const submitHandler = async () => {
		if (codeEditor) {
			const res = await codeEditor.formatPythonCodeHandler();

			if (res) {
				console.log('Code formatted successfully');
				saveHandler();
			}
		}
	};
</script>

<div class=" flex flex-col justify-between w-full overflow-y-auto h-full">
	<div class="mx-auto w-full md:px-0 h-full">
		<form
			bind:this={formElement}
			class=" flex flex-col max-h-[100dvh] h-full"
			on:submit|preventDefault={() => {
				if (edit) {
					submitHandler();
				} else {
					showConfirm = true;
				}
			}}
		>
			<div class="mb-2.5">
				<button
					class="flex space-x-1"
					on:click={() => {
126
						goto('/workspace/functions');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
					}}
					type="button"
				>
					<div class=" self-center">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							viewBox="0 0 20 20"
							fill="currentColor"
							class="w-4 h-4"
						>
							<path
								fill-rule="evenodd"
								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"
								clip-rule="evenodd"
							/>
						</svg>
					</div>
					<div class=" self-center font-medium text-sm">{$i18n.t('Back')}</div>
				</button>
			</div>

			<div class="flex flex-col flex-1 overflow-auto h-0 rounded-lg">
				<div class="w-full mb-2 flex flex-col gap-1.5">
					<div class="flex gap-2 w-full">
						<input
							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"
							type="text"
154
							placeholder="Function Name (e.g. My Filter)"
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
155
156
157
158
159
160
161
							bind:value={name}
							required
						/>

						<input
							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"
							type="text"
162
							placeholder="Function ID (e.g. my_filter)"
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
163
164
165
166
167
168
169
170
							bind:value={id}
							required
							disabled={edit}
						/>
					</div>
					<input
						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"
						type="text"
171
						placeholder="Function Description (e.g. A filter to remove profanity from text)"
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
						bind:value={meta.description}
						required
					/>
				</div>

				<div class="mb-2 flex-1 overflow-auto h-0 rounded-lg">
					<CodeEditor
						bind:value={content}
						bind:this={codeEditor}
						{boilerplate}
						on:save={() => {
							if (formElement) {
								formElement.requestSubmit();
							}
						}}
					/>
				</div>

				<div class="pb-3 flex justify-between">
					<div class="flex-1 pr-3">
						<div class="text-xs text-gray-500 line-clamp-2">
193
194
							<span class=" font-semibold dark:text-gray-200">Warning:</span> Functions allow
							arbitrary code execution <br />—
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
195
							<span class=" font-medium dark:text-gray-400"
196
								>don't install random functions from sources you don't trust.</span
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
							>
						</div>
					</div>

					<button
						class="px-3 py-1.5 text-sm font-medium bg-emerald-600 hover:bg-emerald-700 text-gray-50 transition rounded-lg"
						type="submit"
					>
						{$i18n.t('Save')}
					</button>
				</div>
			</div>
		</form>
	</div>
</div>

<ConfirmDialog
	bind:show={showConfirm}
	on:confirm={() => {
		submitHandler();
	}}
>
	<div class="text-sm text-gray-500">
		<div class=" bg-yellow-500/20 text-yellow-700 dark:text-yellow-200 rounded-lg px-4 py-3">
			<div>Please carefully review the following warnings:</div>

			<ul class=" mt-1 list-disc pl-4 text-xs">
224
225
				<li>Functions allow arbitrary code execution.</li>
				<li>Do not install functions from sources you do not fully trust.</li>
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
226
227
228
229
230
231
232
233
234
235
			</ul>
		</div>

		<div class="my-3">
			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.
		</div>
	</div>
</ConfirmDialog>