Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore(sql-editor): AI assistant minor updates (#14071)
Liu Ji9ecb68d656cb
diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vueindex 726fef9586..324d5fb6d3 100644--- a/frontend/src/plugins/ai/components/ChatPanel.vue+++ b/frontend/src/plugins/ai/components/ChatPanel.vue@@ -70,9 +70,10 @@ const requestAI = async (query: string) => {// add extra database schema metadata info if possibleconst engine = context.engine.value;const databaseMetadata = context.databaseMetadata.value;+ const schema = context.schema.value;const prompts: string[] = [];- prompts.push(promptUtils.declaration(databaseMetadata, engine));+ prompts.push(promptUtils.declaration(databaseMetadata, engine, schema));prompts.push(query);const prompt = prompts.join("\n");await store.createMessage({diff --git a/frontend/src/plugins/ai/components/DynamicSuggestions.vue b/frontend/src/plugins/ai/components/DynamicSuggestions.vueindex 638baadbc3..d3e9866ed1 100644--- a/frontend/src/plugins/ai/components/DynamicSuggestions.vue+++ b/frontend/src/plugins/ai/components/DynamicSuggestions.vue@@ -17,7 +17,7 @@class="flex-1 overflow-hidden"@click.capture="consume">- <div class="w-full truncate">+ <div class="w-full truncate leading-[22px]">{{ current }}</div></NButton>diff --git a/frontend/src/plugins/ai/components/ProvideAIContext.vue b/frontend/src/plugins/ai/components/ProvideAIContext.vueindex b9506f73c1..58598c3bf4 100644--- a/frontend/src/plugins/ai/components/ProvideAIContext.vue+++ b/frontend/src/plugins/ai/components/ProvideAIContext.vue@@ -53,6 +53,7 @@ const pendingSendChat = ref<{ content: string }>();const pendingPreInput = ref<string>();const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());+const schema = computed(() => tab.value?.connection.schema);const store = useConversationStore();const context: AIContext = {@@ -60,6 +61,7 @@ const context: AIContext = {openAIEndpoint,engine: computed(() => instance.value.engine),databaseMetadata,+ schema,showHistoryDialog,chat,pendingSendChat,diff --git a/frontend/src/plugins/ai/logic/prompt.ts b/frontend/src/plugins/ai/logic/prompt.tsindex 6e6d1e89f0..4282742264 100644--- a/frontend/src/plugins/ai/logic/prompt.ts+++ b/frontend/src/plugins/ai/logic/prompt.ts@@ -4,7 +4,8 @@ import { engineNameV1 } from "@/utils";export const databaseMetadataToText = (databaseMetadata: DatabaseMetadata | undefined,- engine?: Engine+ engine?: Engine,+ schema?: string) => {const prompts: string[] = [];if (engine) {@@ -21,9 +22,17 @@ export const databaseMetadataToText = (}}if (databaseMetadata) {- databaseMetadata.schemas.forEach((schema) => {+ const schemas = schema+ ? databaseMetadata.schemas.filter((s) => s.name === schema)+ : databaseMetadata.schemas;++ const schemaScoped = !!schema;+ schemas.forEach((schema) => {schema.tables.forEach((table) => {- const name = schema.name ? `${schema.name}.${table.name}` : table.name;+ const tableNameParts = [table.name];+ if (schema.name && !schemaScoped) {+ tableNameParts.unshift(schema.name);+ }const columns = table.columns.map((column) => {if (column.comment) {@@ -33,7 +42,7 @@ export const databaseMetadataToText = (}}).join(", ");- prompts.push(`# ${name}(${columns})`);+ prompts.push(`# ${tableNameParts.join(".")}(${columns})`);});});}@@ -42,7 +51,8 @@ export const databaseMetadataToText = (export const declaration = (databaseMetadata?: DatabaseMetadata,- engine?: Engine+ engine?: Engine,+ schema?: string) => {const prompts: string[] = [];if (engine) {@@ -50,13 +60,13 @@ export const declaration = (} else {prompts.push(`You are a db and SQL expert.`);}- prompts.push(`When asked for your name, you must respond with "Bytebase".`);- // prompts.push(`Your responses should be informative and terse.`);+ // prompts.push(`When asked for your name, you must respond with "Bytebase".`);+ prompts.push(`Your responses should be informative and terse.`);// prompts.push(// "Set the language to the markdown SQL block. e.g, `SELECT * FROM table`."// );- prompts.push(databaseMetadataToText(databaseMetadata, engine));+ prompts.push(databaseMetadataToText(databaseMetadata, engine, schema));prompts.push("Answer the following questions about this schema:");return prompts.join("\n");@@ -73,7 +83,7 @@ export const findProblems = (statement: string, engine?: Engine) => {export const explainCode = (statement: string, engine?: Engine) => {const prompts: string[] = [];- prompts.push("Explain the following SQL code");+ prompts.push("Explain the following SQL code:");prompts.push(wrapStatementMarkdown(statement, engine));return prompts.join("\n");};@@ -88,3 +98,24 @@ export const wrapStatementMarkdown = (statement: string, engine?: Engine) => {const closeTag = "```";return [openTag, statement, closeTag].join("\n");};++export const dynamicSuggestions = (metadata: string, ignores?: Set<string>) => {+ const commands = [+ `You are an assistant who works as a Magic: The Suggestion card designer. Create cards that are in the following card schema and JSON format. OUTPUT MUST FOLLOW THIS CARD SCHEMA AND JSON FORMAT. DO NOT EXPLAIN THE CARD.`,+ `{"suggestion-1": "What is the average salary of employees in each department?", "suggestion-2": "What is the average salary of employees in each department?", "suggestion-3": "What is the average salary of employees in each department?"}`,+ ];+ const prompts = [+ metadata,+ "Create a suggestion card about interesting queries to try in this database.",+ ];+ if (ignores && ignores.size > 0) {+ prompts.push("queries below should be ignored");+ for (const sug of ignores.values()) {+ prompts.push(sug);+ }+ }+ return {+ command: commands.join("\n"),+ prompt: prompts.join("\n"),+ };+};diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.tsindex 9900972604..709a3f3377 100644--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts@@ -5,10 +5,10 @@ import { hashCode } from "@/bbkit/BBUtil";import { WebStorageHelper } from "@/utils";import type { OpenAIMessage, OpenAIResponse } from "../types";import { useAIContext } from "./context";-import { databaseMetadataToText } from "./prompt";+import * as promptUtils from "./prompt";export type SuggestionContext = {- schema: string; // schema text+ metadata: string; // schema textkey: string; // a hash key used by storagesuggestions: string[];ready: boolean;@@ -24,17 +24,18 @@ const cache = ref(new Map<string, SuggestionContext>());const storage = new WebStorageHelper("bb.plugin.open-ai.suggestions");const MAX_STORED_SUGGESTIONS = 10;-const keyOf = (schema: string) => String(hashCode(schema));+const keyOf = (metadata: string) => String(hashCode(metadata));export const useDynamicSuggestions = () => {const context = useAIContext();- const text = computed(() => {+ const metadata = computed(() => {const meta = context.databaseMetadata.value;const engine = context.engine.value;+ const schema = context.schema.value;if (meta && engine) {- return databaseMetadataToText(meta, engine);+ return promptUtils.databaseMetadataToText(meta, engine, schema);}return "";});@@ -84,10 +85,10 @@ export const useDynamicSuggestions = () => {}};- const createSuggestion = (schema: string) => {+ const createSuggestion = (metadata: string) => {const suggestion: SuggestionContext = reactive({- schema,- key: keyOf(schema),+ metadata,+ key: keyOf(metadata),suggestions: [],index: 0,state: "IDLE",@@ -111,37 +112,29 @@ export const useDynamicSuggestions = () => {const { state, used, suggestions, key } = suggestion;if (state === "ENDED") return [];- const commands = [- `You are an assistant who works as a Magic: The Suggestion card designer. Create cards that are in the following card schema and JSON format. OUTPUT MUST FOLLOW THIS CARD SCHEMA AND JSON FORMAT. DO NOT EXPLAIN THE CARD.`,- `{"suggestion-1": "What is the average salary of employees in each department?", "suggestion-2": "What is the average salary of employees in each department?", "suggestion-3": "What is the average salary of employees in each department?"}`,- ];- const prompts = [- schema,- "Create a suggestion card about interesting queries to try in this database.",- ];- if (used.size > 0 || suggestions.length > 0) {- prompts.push("queries below should be ignored");- for (const sug of used.values()) {- prompts.push(sug);- }- for (const sug of suggestions) {- prompts.push(sug);- }- }+ const { command, prompt } = promptUtils.dynamicSuggestions(+ metadata,+ new Set([...used.values(), ...suggestions])+ );const messages: OpenAIMessage[] = [{role: "system",- content: commands.join("\n"),+ content: command,},{role: "user",- content: prompts.join("\n"),+ content: prompt,},];+ console.debug("[DynamicSuggestions]");+ console.debug(command);+ console.debug(prompt);suggestion.state = "LOADING";+ const response = await requestAI(messages);+ console.debug("[DynamicSuggestions] response", response);const more = uniq(- (await requestAI(messages)).filter((sug) => {+ response.filter((sug) => {if (used.has(sug)) return false;if (suggestions.includes(sug)) return false;return true;@@ -183,18 +176,18 @@ export const useDynamicSuggestions = () => {suggestion.ready = true;});}- cache.value.set(schema, suggestion);+ cache.value.set(metadata, suggestion);return suggestion;};- const getOrCreateSuggestion = (schema: string) => {- const cached = cache.value.get(schema);+ const getOrCreateSuggestion = (metadata: string) => {+ const cached = cache.value.get(metadata);if (cached) return cached;- return createSuggestion(schema);+ return createSuggestion(metadata);};return computed(() => {- if (!text.value) return undefined;- return getOrCreateSuggestion(text.value);+ if (!metadata.value) return undefined;+ return getOrCreateSuggestion(metadata.value);});};diff --git a/frontend/src/plugins/ai/types/context.ts b/frontend/src/plugins/ai/types/context.tsindex 35109efd74..6a73da6ebf 100644--- a/frontend/src/plugins/ai/types/context.ts+++ b/frontend/src/plugins/ai/types/context.ts@@ -22,6 +22,7 @@ export type AIContext = {openAIEndpoint: Ref<string>;engine: Ref<Engine | undefined>;databaseMetadata: Ref<DatabaseMetadata | undefined>;+ schema: Ref<string | undefined>;showHistoryDialog: Ref<boolean>;chat: Ref<AIChatInfo>;diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vueindex 8f6085c4c0..6916a213f7 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue@@ -3,12 +3,7 @@<GutterBar class="border-r border-control-border" :class="gutterBarClass" /><div class="flex-1 overflow-y-hidden overflow-x-auto" :class="contentClass">- <div- v-show="!viewState || viewState.view === 'CODE'"- class="w-full h-full overflow-hidden"- >- <slot name="code-panel" />- </div>+ <slot v-if="!viewState || viewState.view === 'CODE'" name="code-panel" /><template v-if="viewState"><InfoPanel v-if="viewState.view === 'INFO'" :key="tab?.id" />diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vueindex 869e9763a2..39f5f85735 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue@@ -27,7 +27,7 @@<script lang="ts" setup>import { storeToRefs } from "pinia";import { v1 as uuidv1 } from "uuid";-import { computed, nextTick, ref, watch } from "vue";+import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";import type {AdviceOption,IStandaloneCodeEditor,@@ -56,6 +56,7 @@ import { dialectOfEngineV1 } from "@/types";import { Advice_Status, type Advice } from "@/types/proto/v1/sql_service";import { nextAnimationFrame, useInstanceV1EditorLanguage } from "@/utils";import { useSQLEditorContext } from "../../context";+import { activeSQLEditorRef } from "./state";const emit = defineEmits<{(e: "execute", params: SQLEditorQueryParams): void;@@ -173,6 +174,8 @@ const handleEditorReady = (monaco: MonacoModule,editor: IStandaloneCodeEditor) => {+ activeSQLEditorRef.value = editor;+editor.addAction({id: "RunQuery",label: "Run Query",@@ -269,6 +272,8 @@ const handleEditorReady = (watch(pendingInsertAtCaret,() => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;const text = pendingInsertAtCaret.value;if (!text) return;pendingInsertAtCaret.value = undefined;@@ -346,4 +351,8 @@ useEmitteryEventListener(updateAdvices(tab, params, advices);});++onBeforeUnmount(() => {+ activeSQLEditorRef.value = undefined;+});</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.tsnew file mode 100644index 0000000000..0e81fc85ba--- /dev/null+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts@@ -0,0 +1,4 @@+import { shallowRef } from "vue";+import { type IStandaloneCodeEditor } from "@/components/MonacoEditor";++export const activeSQLEditorRef = shallowRef<IStandaloneCodeEditor>();