/
flow.ts
323 lines (292 loc) · 11.2 KB
/
flow.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
126
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import {
type FlowModule,
ScriptService,
type RawScript,
type PathScript,
type InputTransform,
type Script
} from '$lib/gen'
import { addResourceTypes, deltaCodeCompletion, getNonStreamingCompletion } from './lib'
import type { Writable } from 'svelte/store'
import type Editor from '../Editor.svelte'
import type { Drawer } from '../common'
import { scriptLangToEditorLang } from '$lib/scripts'
export type FlowCopilotModule = {
id: string
type: 'trigger' | 'script'
description: string
code: string
source: 'hub' | 'custom' | undefined
lang: 'bun' | 'python3' | undefined
hubCompletions: {
path: string
summary: string
kind: string
app: string
ask_id: number
}[]
selectedCompletion:
| {
path: string
summary: string
kind: string
app: string
ask_id: number
}
| undefined
editor?: Editor
}
export type FlowCopilotContext = {
drawerStore: Writable<Drawer | undefined>
modulesStore: Writable<FlowCopilotModule[]>
currentStepStore: Writable<string | undefined>
genFlow: ((i: number, modules: FlowModule[], stepOnly?: boolean) => Promise<void>) | undefined
shouldUpdatePropertyType: Writable<{
[key: string]: 'static' | 'javascript' | undefined
}>
stepInputsLoading: Writable<boolean>
generatedExprs: Writable<{
[key: string]: string | undefined
}>
exprsToSet: Writable<{
[key: string]: InputTransform | undefined
}>
}
const systemPrompt = `You are a helpful coding assistant for Windmill, a developer platform for running scripts. You write code as instructed by the user. Each user message includes some contextual information which should guide your answer.
Only output code. Wrap the code in a code block.
Put explanations directly in the code as comments.
Here's how interactions have to look like:
user: {sample_question}
assistant: \`\`\`{codeLang}
{code}
\`\`\``
const additionalInfos: {
bun: string
python3: string
} = {
bun: `<contextual_information>
You have to write TypeScript code and export a "main" function like this: "export async function main(...)" and specify the parameter types but do not call it. You should generally return the result.
The fetch standard method is available globally.
You can take as parameters resources which are dictionaries containing credentials or configuration information. For Windmill to correctly detect the resources to be passed, the resource type name has to be exactly as specified in the following list:
<resourceTypes>
{resourceTypes}
</resourceTypes>
You need to define the type of the resources that are needed before the main function, but only include them if they are actually needed to achieve the function purpose.
The resource type name has to be exactly as specified (no resource suffix). If the type name conflicts with any imported methods, you have to rename the imported method with the conflicting name.
</contextual_information>`,
python3: `<contextual_information>
You have to write a function in Python called "main". Specify the parameter types. Do not call the main function. You should generally return the result.
You can take as parameters resources which are dictionaries containing credentials or configuration information. For Windmill to correctly detect the resources to be passed, the resource type name has to be exactly as specified in the following list:
<resourceTypes>
{resourceTypes}
</resourceTypes>
You need to define the type of the resources that are needed before the main function, but only include them if they are actually needed to achieve the function purpose.
The resource type name has to be exactly as specified (has to be IN LOWERCASE). If the type name conflicts with any imported methods, you have to rename the imported method with the conflicting name.
<contextual_information>`
}
const triggerPrompts: {
bun: string
python3: string
} = {
bun: `I'm building a workflow which is a sequence of script steps. Write the first script in {codeLang} which should check for {description} and return an array.
To maintain state across runs, you can use "const {state_name}: {state_type} = await getState()" and "await setState(value: any)" which you have to import like this: import { getState, setState } from "windmill-client@1"
{additionalInformation}`,
python3: `I'm building a workflow which is a sequence of script steps. Write the first script in {codeLang} which should check for {description} and return an array.
To maintain state across runs, you can use get_state() and set_state(value) which you have to import like this: from wmill import get_state, set_state
{additionalInformation}`
}
const firstActionPrompt = `I'm building a workflow which is a sequence of script steps. Write a script in {codeLang} which should {description}.
Return the script's output.
{additionalInformation}`
const inferTypePrompt =
'Infer the type of "prev_output" from the previous\'s step code: ```{codeLang}\n{prevCode}\n```'
const actionPrompt = `I'm building a workflow which is a sequence of script steps. Write a script in {codeLang} which should {description}. It should take a parameter called "prev_output" which contains the output of the previous script.
{inferTypePrompt}
Return the script's output.
{additionalInformation}`
const inferTypeLoopPrompt =
'Infer the type of "prev_output" from the previous\'s step code: ```{codeLang}\n{prevCode}\n```, keeping in mind that it is ONE ELEMENT of the output of the previous step.'
const loopActionPrompt = `I'm building a workflow which is a sequence of script steps. Write a script in {codeLang} which should {description}. It should take a parameter called "prev_output" which contains ONE ELEMEMT of the output of the previous script.
{inferTypePrompt}
Return the script's output.
{additionalInformation}`
const inferTypeGluePrompt =
"Infer its properties from the previous's step code: ```{codeLang}\n{prevCode}\n```"
const loopGluePrompt = `I'm building a workflow which is a sequence of script steps.
My current step code has the following inputs: {inputs}.
Determine for each input, what to pass from the following:
- \`flow_input\` (javascript object): general inputs that are passed to the workflow, you can assume any object properties (snake case).
- \`flow_input.iter.value\` (javascript object): it is ONE ELEMENT of the output of the previous step. {inferTypeGluePrompt}
Reply with the most probable answer, do not explain or discuss.
Your answer has to be in the following format (one line per input):
input_name: expr`
const gluePrompt = `I'm building a workflow which is a sequence of script steps.
My current step code has the following inputs: {inputs}.
Determine for each input, what to pass from the following:
- \`flow_input\` (javascript object): general inputs that are passed to the workflow, you can assume any object properties (snake case).
- \`results.{prevId}\` (javascript object): output of the previous step. {inferTypeGluePrompt}
Reply with the most probable answer, do not explain or discuss.
Your answer has to be in the following format (one line per input):
input_name: expr`
async function getPreviousStepContent(
pastModule: FlowModule & {
value: RawScript | PathScript
},
workspace: string
) {
if (pastModule.value.type === 'rawscript') {
return { prevCode: pastModule.value.content, prevLang: pastModule.value.language }
} else {
if (pastModule.value.path.startsWith('hub/')) {
const script = await ScriptService.getHubScriptByPath({
path: pastModule.value.path
})
return { prevCode: script.content, prevLang: script.language as Script['language'] }
} else if (pastModule.value.hash) {
const script = await ScriptService.getScriptByHash({
workspace,
hash: pastModule.value.hash
})
return { prevCode: script.content, prevLang: script.language }
} else {
const script = await ScriptService.getScriptByPath({
workspace,
path: pastModule.value.path
})
return { prevCode: script.content, prevLang: script.language }
}
}
}
export async function stepCopilot(
module: FlowCopilotModule,
deltaCodeStore: Writable<string>,
workspace: string,
pastModule:
| (FlowModule & {
value: RawScript | PathScript
})
| undefined,
isFirstInLoop: boolean,
abortController: AbortController
) {
if (module.source !== 'custom') {
throw new Error('Not a custom module')
}
const lang = module.lang ?? 'bun'
const codeLang = lang === 'python3' ? 'python' : 'typescript (Node.js)'
let prompt =
module.type === 'trigger'
? triggerPrompts[lang]
: pastModule === undefined
? firstActionPrompt
: isFirstInLoop
? loopActionPrompt
: actionPrompt
const { prevCode, prevLang } = pastModule
? await getPreviousStepContent(pastModule, workspace)
: { prevCode: undefined, prevLang: undefined }
prompt = prompt
.replace('{codeLang}', codeLang)
.replace(
'{inferTypePrompt}',
prevCode && prevLang
? (isFirstInLoop ? inferTypeLoopPrompt : inferTypePrompt)
.replace('{prevCode}', prevCode)
.replace('{codeLang}', scriptLangToEditorLang(prevLang))
: ''
)
.replace('{additionalInformation}', additionalInfos[lang])
.replace('{description}', module.description)
prompt = await addResourceTypes(
{
type: 'gen',
language: lang as Script['language'],
description: module.description,
dbSchema: undefined,
workspace
},
prompt
)
const code = await deltaCodeCompletion(
[
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: prompt
}
],
deltaCodeStore,
abortController
)
return code
}
export async function glueCopilot(
inputs: Record<string, InputTransform>,
workspace: string,
pastModule: FlowModule & {
value: RawScript | PathScript
},
isFirstInLoop: boolean,
abortController: AbortController
) {
const { prevCode, prevLang } = await getPreviousStepContent(pastModule, workspace)
const stringInputs: string[] = []
for (const inputName in inputs) {
const input = inputs[inputName]
if (
input.type === 'static' &&
input.value &&
typeof input.value === 'object' &&
!Array.isArray(input.value)
) {
// nested object
stringInputs.push(`${inputName} (${Object.keys(input.value).join(', ')})`)
} else {
stringInputs.push(inputName)
}
}
let response = await getNonStreamingCompletion(
[
{
role: 'user',
content: (isFirstInLoop ? loopGluePrompt : gluePrompt)
.replace('{inputs}', stringInputs.join(', '))
.replace('{prevId}', pastModule.id)
.replace(
'{inferTypeGluePrompt}',
inferTypeGluePrompt
.replace('{prevCode}', prevCode)
.replace('{codeLang}', scriptLangToEditorLang(prevLang))
)
}
],
abortController
)
const matches = response.matchAll(/([a-zA-Z_0-9.]+): (.+)/g)
const result: Record<string, string> = {}
const allExprs: Record<string, string> = {}
for (const match of matches) {
const inputName = match[1]
const inputExpr = match[2].replace(',', '')
allExprs[inputName] = inputExpr
if (inputName.includes('.')) {
// nested key returned by copilot (e.g. body.content: ...)
const [firstKey, ...rest] = inputName.split('.')
const restStr = rest.join('.')
if (!result[firstKey]) {
result[firstKey] = `{\n "${restStr}": ${inputExpr}\n}`
} else {
result[firstKey] = result[firstKey].replace('\n}', `,\n "${restStr}": ${inputExpr}\n}`)
}
} else {
result[inputName] = inputExpr
}
}
return {
inputs: result,
allExprs
}
}