|
| 1 | +import { destr } from 'destr' |
| 2 | +import { format } from 'sql-formatter' |
| 3 | +import { toast } from 'vue-sonner' |
| 4 | + |
| 5 | +interface UseSqlAgentOptions { |
| 6 | + usableTableNames: MaybeRef<string[]> |
| 7 | + limit: MaybeRef<number> |
| 8 | + beforeInitialzeModel: () => void |
| 9 | + beforeQueryRelevantTables: () => void |
| 10 | + beforeQueryPrompt: () => void |
| 11 | + beforeQuerySqlStatement: () => void |
| 12 | + beforeQuerySqlValidation: () => void |
| 13 | +} |
| 14 | + |
| 15 | +async function queryCreateTableSQL(value: string, cursor?: Database): Promise<string> { |
| 16 | + if (value && cursor) { |
| 17 | + const backend = cursor?.path.split(':')[0] ?? 'mysql' |
| 18 | + const sql = Sql.SHOW_CREATE_TABLE(value)[backend] |
| 19 | + if (!sql) |
| 20 | + return '' |
| 21 | + const [row] = await cursor?.select<any[]>(sql) ?? [] |
| 22 | + if (backend === 'sqlite') |
| 23 | + return row.sql |
| 24 | + return row['Create Table'] |
| 25 | + } |
| 26 | + |
| 27 | + return '' |
| 28 | +} |
| 29 | + |
| 30 | +export function useSqlAgent(cursorInstance: MaybeRef<Database | undefined> | undefined, options: Partial<UseSqlAgentOptions> = {}) { |
| 31 | + const store = useSettingsStore() |
| 32 | + const { model } = storeToRefs(store) |
| 33 | + |
| 34 | + const retries = ref(3) |
| 35 | + const output = ref('') |
| 36 | + const usableTableNames = computed(() => unref(options.usableTableNames) ?? []) |
| 37 | + const cursor = computed(() => unref(cursorInstance)) |
| 38 | + const llm = useLlm(model) |
| 39 | + const includes = ref<string[]>([]) |
| 40 | + const backend = useCursorBackend(cursor) |
| 41 | + const prompt = ref('') |
| 42 | + const isLoading = ref(false) |
| 43 | + const error = ref('') |
| 44 | + const question = ref('') |
| 45 | + |
| 46 | + async function queryRelevantTables() { |
| 47 | + if (usableTableNames.value.length < 25) { |
| 48 | + includes.value = usableTableNames.value |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + const tool = { |
| 53 | + type: 'function', |
| 54 | + function: { |
| 55 | + name: 'Table', |
| 56 | + description: 'Get relevant tables from a given list', |
| 57 | + parameters: { |
| 58 | + type: 'object', |
| 59 | + properties: { |
| 60 | + rows: { |
| 61 | + type: 'array', |
| 62 | + description: 'Name list of table in SQL database', |
| 63 | + items: { |
| 64 | + type: 'string', |
| 65 | + enum: usableTableNames.value, |
| 66 | + }, |
| 67 | + }, |
| 68 | + }, |
| 69 | + required: ['rows'], |
| 70 | + }, |
| 71 | + }, |
| 72 | + } |
| 73 | + |
| 74 | + const prompt = usePromptTemplate(RELEVANT_TABLES_PROMPT, { tableNames: usableTableNames.value.join('\n') }) |
| 75 | + const defaults = usableTableNames.value.slice(0, 25) |
| 76 | + |
| 77 | + for (let i = 0; i < retries.value; i++) { |
| 78 | + if (!isLoading.value) |
| 79 | + return |
| 80 | + |
| 81 | + const { choices } = await llm.chat.completions.create({ |
| 82 | + messages: [ |
| 83 | + { role: 'user', content: prompt.value }, |
| 84 | + { role: 'user', content: question.value }, |
| 85 | + ], |
| 86 | + tools: [tool], |
| 87 | + tool_choice: 'required', |
| 88 | + }) |
| 89 | + |
| 90 | + const [call] = choices[0].message.tool_calls |
| 91 | + |
| 92 | + if (!call) |
| 93 | + continue |
| 94 | + |
| 95 | + const args: string[] = call.function.arguments |
| 96 | + const rows = destr<{ rows: string[] }>(args).rows ?? [] |
| 97 | + |
| 98 | + if (rows.length) { |
| 99 | + includes.value = rows |
| 100 | + return |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + includes.value = defaults |
| 105 | + } |
| 106 | + |
| 107 | + async function queryPrompt() { |
| 108 | + if (!isLoading.value) |
| 109 | + return |
| 110 | + |
| 111 | + const prompts = await Promise.all(includes.value.map(t => (async () => { |
| 112 | + if (t && cursor.value) { |
| 113 | + const [v0, v1] = await Promise.all([ |
| 114 | + queryCreateTableSQL(t, cursor.value), |
| 115 | + cursor.value?.select<Record<string, any>[]>(`SELECT * FROM \`${t}\` LIMIT 3;`) ?? [], |
| 116 | + ]) |
| 117 | + |
| 118 | + const cols = Object.keys(v1[0] ?? {}) |
| 119 | + const rows: string[] = [cols.join('\t')] |
| 120 | + |
| 121 | + for (const i of v1) { |
| 122 | + rows.push(cols.map(k => String(i[k])).join('\t')) |
| 123 | + } |
| 124 | + |
| 125 | + return [ |
| 126 | + v0, |
| 127 | + '\n/*', |
| 128 | + '3 rows from t_inf_app_application table:', |
| 129 | + rows.join('\n'), |
| 130 | + '*/', |
| 131 | + ].join('\n') |
| 132 | + } |
| 133 | + })())) |
| 134 | + |
| 135 | + const template = SQL_PROMPT?.[backend.value] ?? SQL_PROMPT.default as string |
| 136 | + |
| 137 | + prompt.value = usePromptTemplate(template, { |
| 138 | + tableInfo: prompts.filter(Boolean).join('\n\n'), |
| 139 | + input: question.value, |
| 140 | + topK: unref(options.limit) ?? 5, |
| 141 | + dialect: backend.value, |
| 142 | + }).value |
| 143 | + } |
| 144 | + |
| 145 | + async function querySqlStatement() { |
| 146 | + for (let i = 0; i < retries.value; i++) { |
| 147 | + if (!isLoading.value) |
| 148 | + return |
| 149 | + |
| 150 | + const { choices } = (await llm.chat.completions.create({ messages: [{ role: 'user', content: prompt.value }] })) ?? {} |
| 151 | + output.value = choices?.[0]?.message.content ?? '' |
| 152 | + if (output.value) |
| 153 | + break |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + async function querySqlValidation() { |
| 158 | + let _error = '' |
| 159 | + |
| 160 | + const prompt = usePromptTemplate(SQL_VALIDATE_PROMPT, { notFormattedQuery: unref(output.value) }) |
| 161 | + |
| 162 | + for (let i = 0; i < retries.value; i++) { |
| 163 | + if (!isLoading.value) |
| 164 | + return |
| 165 | + |
| 166 | + const { choices } = (await llm.chat.completions.create({ messages: [{ role: 'user', content: prompt.value }] })) ?? {} |
| 167 | + const sql = choices?.[0]?.message.content ?? '' |
| 168 | + |
| 169 | + if (!sql) |
| 170 | + continue |
| 171 | + |
| 172 | + try { |
| 173 | + output.value = format(sql, { |
| 174 | + language: 'sql', |
| 175 | + tabWidth: 2, |
| 176 | + keywordCase: 'upper', |
| 177 | + }) |
| 178 | + |
| 179 | + _error = '' |
| 180 | + break |
| 181 | + } |
| 182 | + catch (e) { |
| 183 | + _error = e as string |
| 184 | + continue |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + error.value = _error |
| 189 | + } |
| 190 | + |
| 191 | + async function execute(input: MaybeRef<string>) { |
| 192 | + prompt.value = '' |
| 193 | + output.value = '' |
| 194 | + includes.value = [] |
| 195 | + question.value = unref(input) |
| 196 | + isLoading.value = true |
| 197 | + |
| 198 | + try { |
| 199 | + options.beforeInitialzeModel?.() |
| 200 | + options.beforeQueryRelevantTables?.() |
| 201 | + await queryRelevantTables() |
| 202 | + options.beforeQueryPrompt?.() |
| 203 | + await queryPrompt() |
| 204 | + options.beforeQuerySqlStatement?.() |
| 205 | + await querySqlStatement() |
| 206 | + options.beforeQuerySqlValidation?.() |
| 207 | + await querySqlValidation() |
| 208 | + } |
| 209 | + catch (errors: any) { |
| 210 | + error.value = errors |
| 211 | + |
| 212 | + if (Array.isArray(errors)) { |
| 213 | + errors.forEach(({ error }: any) => { |
| 214 | + toast(error.status, { description: error.message }) |
| 215 | + }) |
| 216 | + } |
| 217 | + |
| 218 | + else { |
| 219 | + toast('NETWORK_ERROR', { description: 'An error occurred trying to load the resource' }) |
| 220 | + } |
| 221 | + } |
| 222 | + finally { |
| 223 | + isLoading.value = false |
| 224 | + } |
| 225 | + |
| 226 | + return output.value |
| 227 | + } |
| 228 | + |
| 229 | + return { |
| 230 | + error, |
| 231 | + output, |
| 232 | + isLoading, |
| 233 | + execute, |
| 234 | + } |
| 235 | +} |
0 commit comments