-
-
Notifications
You must be signed in to change notification settings - Fork 751
Expand file tree
/
Copy pathai.js
More file actions
274 lines (209 loc) · 7.22 KB
/
Copy pathai.js
File metadata and controls
274 lines (209 loc) · 7.22 KB
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
import debugModule from 'debug'
const debug = debugModule('codeceptjs:ai')
import output from './output.js'
import event from './event.js'
import { removeNonInteractiveElements, minifyHtml, splitByChunks } from './html.js'
import { generateText } from 'ai'
import { fileURLToPath } from 'url'
import path from 'path'
import { fileExists, resolveImportModulePath } from './utils.js'
import store from './store.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const defaultHtmlConfig = {
maxLength: 50000,
simplify: true,
minify: true,
html: {},
}
async function loadPrompts() {
const prompts = {}
const promptNames = ['writeStep', 'healStep', 'generatePageObject']
for (const name of promptNames) {
let promptPath
if (store.codeceptDir) {
promptPath = path.join(store.codeceptDir, `prompts/${name}.js`)
}
if (!promptPath || !fileExists(promptPath)) {
promptPath = path.join(__dirname, `template/prompts/${name}.js`)
}
try {
const resolvedPath = resolveImportModulePath(promptPath)
const module = await import(resolvedPath)
prompts[name] = module.default || module
debug(`Loaded prompt ${name} from ${promptPath}`)
} catch (err) {
debug(`Failed to load prompt ${name}:`, err.message)
}
}
return prompts
}
class AiAssistant {
constructor() {
this.totalTime = 0
this.numTokens = 0
this.reset()
this.connectToEvents()
}
async enable(config = {}) {
debug('Enabling AI assistant')
this.isEnabled = true
const { html, prompts, ...aiConfig } = config
this.config = Object.assign(this.config, aiConfig)
this.htmlConfig = Object.assign(defaultHtmlConfig, html)
const loadedPrompts = await loadPrompts()
this.prompts = Object.assign(loadedPrompts, prompts || {})
debug('Config', this.config)
}
reset() {
this.numTokens = 0
this.isEnabled = false
this.config = {
maxTokens: 1000000,
model: null,
response: parseCodeBlocks,
}
this.minifiedHtml = null
this.response = null
this.totalTime = 0
}
disable() {
this.isEnabled = false
}
connectToEvents() {
event.dispatcher.on(event.all.result, () => {
if (this.isEnabled && this.numTokens > 0) {
const numTokensK = Math.ceil(this.numTokens / 1000)
const maxTokensK = Math.ceil(this.config.maxTokens / 1000)
output.print(`AI assistant took ${this.totalTime}s and used ${numTokensK}K tokens. Tokens limit: ${maxTokensK}K`)
}
})
}
checkModel() {
if (!this.isEnabled) {
debug('AI assistant is disabled')
return
}
if (this.config.model) return
const noModelErrorMessage = `
No model is set for AI assistant.
[!] Please configure AI model using Vercel AI SDK providers.
Example (connect to OpenAI):
import { openai } from '@ai-sdk/openai';
ai: {
model: openai('gpt-4o-mini')
}
Example (connect to Anthropic):
import { anthropic } from '@ai-sdk/anthropic';
ai: {
model: anthropic('claude-3-5-sonnet-20241022')
}
See https://ai-sdk.dev/docs/foundations/providers-and-models for all providers.
`.trim()
throw new Error(noModelErrorMessage)
}
async setHtmlContext(html) {
let processedHTML = html
if (this.htmlConfig.simplify) {
processedHTML = removeNonInteractiveElements(processedHTML, this.htmlConfig)
}
if (this.htmlConfig.minify) processedHTML = await minifyHtml(processedHTML)
if (this.htmlConfig.maxLength) processedHTML = splitByChunks(processedHTML, this.htmlConfig.maxLength)[0]
this.minifiedHtml = processedHTML
}
getResponse() {
return this.response || ''
}
async createCompletion(messages) {
if (!this.isEnabled) return ''
try {
this.checkModel()
debug('Request', messages)
this.response = null
const startTime = process.hrtime()
const result = await generateText({
model: this.config.model,
messages,
})
const endTime = process.hrtime(startTime)
const executionTimeInSeconds = endTime[0] + endTime[1] / 1e9
this.response = result.text
this.numTokens += result.usage.totalTokens
this.totalTime += Math.round(executionTimeInSeconds)
debug('AI response time', executionTimeInSeconds)
debug('Response', this.response)
debug('Usage', result.usage)
this.stopWhenReachingTokensLimit()
return this.response
} catch (err) {
debug(err)
output.print('')
output.error(`AI service error: ${err.message}`)
this.stopWhenReachingTokensLimit()
return ''
}
}
async healFailedStep(failureContext) {
if (!this.isEnabled) return []
if (!failureContext.html) throw new Error('No HTML context provided')
await this.setHtmlContext(failureContext.html)
if (!this.minifiedHtml) {
debug('HTML context is empty after removing non-interactive elements & minification')
return []
}
const response = await this.createCompletion(this.prompts.healStep(this.minifiedHtml, failureContext))
if (!response) return []
return this.config.response(response)
}
/**
*
* @param {*} extraPrompt
* @param {*} locator
* @returns
*/
async generatePageObject(extraPrompt = null, locator = null) {
if (!this.isEnabled) return []
if (!this.minifiedHtml) throw new Error('No HTML context provided')
const response = await this.createCompletion(this.prompts.generatePageObject(this.minifiedHtml, locator, extraPrompt))
if (!response) return []
return this.config.response(response)
}
stopWhenReachingTokensLimit() {
if (this.numTokens < this.config.maxTokens) return
output.print(`AI assistant has reached the limit of ${this.config.maxTokens} tokens in this session. It will be disabled now`)
this.disable()
}
async writeSteps(input) {
if (!this.isEnabled) return
if (!this.minifiedHtml) throw new Error('No HTML context provided')
const snippets = []
const response = await this.createCompletion(this.prompts.writeStep(this.minifiedHtml, input))
if (!response) return
snippets.push(...this.config.response(response))
debug(snippets[0])
return snippets[0]
}
}
function parseCodeBlocks(response) {
// Regular expression pattern to match code snippets
const codeSnippetPattern = /```(?:javascript|js|typescript|ts)?\n([\s\S]+?)\n```/g
// Array to store extracted code snippets
const codeSnippets = []
response = response
.split('\n')
.map(line => line.trim())
.join('\n')
// Iterate over matches and extract code snippets
let match
while ((match = codeSnippetPattern.exec(response)) !== null) {
codeSnippets.push(match[1])
}
// Remove "Scenario", "Feature", and "require()" lines
const modifiedSnippets = codeSnippets.map(snippet => {
const lines = snippet.split('\n')
const filteredLines = lines.filter(line => !line.includes('I.amOnPage') && !line.startsWith('Scenario') && !line.startsWith('Feature') && !line.includes('= require('))
return filteredLines.join('\n')
// remove snippets that move from current url
}) // .filter(snippet => !line.includes('I.amOnPage'));
return modifiedSnippets.filter(snippet => !!snippet)
}
export default new AiAssistant()