Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql-editor): ai-generated tips for chat-to-sql (#5079)

Liu Jif0681fc3d632
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 33de6e1c90..e74ef7f9d6 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2020,7 +2020,12 @@
"history-conversations": "History conversations",
"view-history-conversations": "View history conversations",
"new-conversation": "Start new conversation",
- "no-message": "No message in this conversation"
+ "no-message": "No message in this conversation",
+ "tips": {
+ "try": "Try:",
+ "more": "More",
+ "no-more": "no more"
+ }
},
"preset-suggestion": {
"1": "Which department has most employees?",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 05da41d56c..b74b5fb698 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2017,7 +2017,12 @@
"select-or-create": "选择或{create}一个会话以开始。",
"exit-conversation-mode": "退出对话模式",
"view-history-conversations": "查看历史对话",
- "new-conversation": "开启新对话"
+ "new-conversation": "开启新对话",
+ "tips": {
+ "try": "试一试:",
+ "more": "更多",
+ "no-more": "没有了"
+ }
},
"preset-suggestion": {
"1": "哪个部门的员工最多?",
diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vue
index dba3a4f66b..5ba91411d0 100644
--- a/frontend/src/plugins/ai/components/ChatPanel.vue
+++ b/frontend/src/plugins/ai/components/ChatPanel.vue
@@ -12,9 +12,10 @@
<ChatView :conversation="selectedConversation" @enter="requestAI" />
</template>
- <div :class="[isChatMode && 'px-4 py-2']">
- <div v-if="isChatMode">
- <label class="inline-flex items-center gap-x-1">
+ <div :class="[isChatMode && 'px-4 py-2 flex flex-col gap-2']">
+ <div v-if="isChatMode" class="flex items-center gap-2 w-full">
+ <DynamicSuggestions class="flex-1" @enter="requestAI" />
+ <label class="flex items-center justify-end gap-x-1 shrink-0">
<BBCheckbox :value="autoRun" @toggle="autoRun = $event" />
<span class="textinfolabel">
{{ $t("plugin.ai.run-automatically") }}
@@ -40,6 +41,7 @@ import { useCurrentTab } from "@/store";
import { useConversationStore } from "../store";
import ActionBar from "./ActionBar.vue";
import ChatView from "./ChatView";
+import DynamicSuggestions from "./DynamicSuggestions.vue";
import PromptInput from "./PromptInput.vue";
import HistoryPanel from "./HistoryPanel";
import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";
diff --git a/frontend/src/plugins/ai/components/ChatView/ChatView.vue b/frontend/src/plugins/ai/components/ChatView/ChatView.vue
index 713c0bec1f..24a9532c93 100644
--- a/frontend/src/plugins/ai/components/ChatView/ChatView.vue
+++ b/frontend/src/plugins/ai/components/ChatView/ChatView.vue
@@ -2,10 +2,6 @@
<div ref="scrollerRef" class="flex-1 py-4 overflow-y-auto">
<template v-if="conversation">
<template v-if="conversation.messageList.length === 0">
- <PresetSuggestions
- v-if="mode === 'CHAT'"
- @select="$emit('enter', $event)"
- />
<EmptyView v-if="mode === 'VIEW'" />
</template>
<div
@@ -58,7 +54,6 @@ import type { Conversation } from "../../types";
import type { Mode } from "./types";
import UserMessageView from "./UserMessageView.vue";
import AIMessageView from "./AIMessageView.vue";
-import PresetSuggestions from "./PresetSuggestions.vue";
import EmptyView from "./EmptyView.vue";
import { useAIContext } from "../../logic";
import { provideChatViewContext } from "./context";
diff --git a/frontend/src/plugins/ai/components/ChatView/PresetSuggestions.vue b/frontend/src/plugins/ai/components/ChatView/PresetSuggestions.vue
deleted file mode 100644
index 61c72a8547..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/PresetSuggestions.vue
+++ /dev/null
@@ -1,43 +0,0 @@
-<template>
- <div class="w-full h-full flex flex-col justify-end items-center pb-[2rem]">
- <div
- class="w-[30rem] mx-auto bg-white border border-control-border rounded shadow-md py-1"
- >
- <div class="mt-1 mb-2 px-2 text-md font-normal text-control-light">
- {{ $t("plugin.ai.examples") }}
- </div>
-
- <ul class="px-1 text-sm">
- <li
- v-for="(sug, i) in presetSuggestions"
- :key="i"
- class="py-2 px-1 flex items-center justify-between gap-x-1 rounded-sm hover:bg-indigo-600/10 cursor-default"
- @click="$emit('select', sug)"
- >
- <heroicons-outline:magnifying-glass class="w-4 h-4" />
- <span class="flex-1">{{ sug }}</span>
- <heroicons-outline:chevron-right class="w-4 h-4 text-gray-400" />
- </li>
- </ul>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-
-defineEmits<{
- (event: "select", preset: string): void;
-}>();
-
-const { t } = useI18n();
-
-const presetSuggestions = computed(() => {
- return [
- t("plugin.ai.preset-suggestion.1"),
- t("plugin.ai.preset-suggestion.2"),
- t("plugin.ai.preset-suggestion.3"),
- ];
-});
-</script>
diff --git a/frontend/src/plugins/ai/components/DynamicSuggestions.vue b/frontend/src/plugins/ai/components/DynamicSuggestions.vue
new file mode 100644
index 0000000000..3c35cd055a
--- /dev/null
+++ b/frontend/src/plugins/ai/components/DynamicSuggestions.vue
@@ -0,0 +1,69 @@
+<template>
+ <div class="flex items-center overflow-hidden h-[22px]">
+ <template v-if="dynamicSuggestions && !ready">
+ <BBSpin class="w-4 h-4" />
+ </template>
+
+ <template v-if="ready && suggestions.length > 0">
+ <div
+ class="relative flex items-center gap-x-2 overflow-hidden text-xs leading-4"
+ >
+ <div class="shrink-0 text-sm font-medium">
+ {{ $t("plugin.ai.conversation.tips.try") }}
+ </div>
+ <div
+ class="flex items-stretch gap-x-2 whitespace-nowrap overflow-x-auto hide-scrollbar"
+ >
+ <NEllipsis
+ v-for="(sug, i) in suggestions"
+ :key="i"
+ style="max-width: 20rem"
+ class="border shrink-0 py-0.5 px-1 rounded-md cursor-pointer hover:bg-indigo-100 hover:border-indigo-500"
+ @click.capture="consume(sug)"
+ >
+ {{ sug }}
+ </NEllipsis>
+
+ <div class="shrink-0 flex items-center">
+ <BBSpin v-if="state === 'LOADING'" class="w-4 h-4" />
+ <button
+ v-if="state === 'IDLE'"
+ class="text-gray-500 cursor-pointer py-0.5 px-1 rounded-md hover:bg-gray-200"
+ @click="dynamicSuggestions?.fetch()"
+ >
+ {{ $t("plugin.ai.conversation.tips.more") }}
+ </button>
+ <span v-if="state === 'ENDED'" class="text-gray-500">
+ {{ $t("plugin.ai.conversation.tips.no-more") }}
+ </span>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { NEllipsis } from "naive-ui";
+
+import { BBSpin } from "@/bbkit";
+import { useDynamicSuggestions } from "../logic";
+
+const emit = defineEmits<{
+ (event: "enter", query: string): void;
+}>();
+
+const dynamicSuggestions = useDynamicSuggestions();
+
+const ready = computed(() => dynamicSuggestions.value?.ready ?? false);
+const state = computed(() => dynamicSuggestions.value?.state ?? "IDLE");
+const suggestions = computed(() => dynamicSuggestions.value?.suggestions ?? []);
+
+const consume = (sug: string) => {
+ const suggestions = dynamicSuggestions.value;
+ if (!suggestions) return;
+ suggestions.consume(sug);
+ emit("enter", sug);
+};
+</script>
diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.ts
index 35dd13a1ea..86795c1120 100644
--- a/frontend/src/plugins/ai/logic/index.ts
+++ b/frontend/src/plugins/ai/logic/index.ts
@@ -1,3 +1,4 @@
export * from "./context";
export * from "./useChatByTab";
+export * from "./useDynamicSuggestions";
export * from "./utils";
diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
new file mode 100644
index 0000000000..6fa55681b0
--- /dev/null
+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
@@ -0,0 +1,174 @@
+import { computed, reactive, ref } from "vue";
+import { Axios, type AxiosResponse } from "axios";
+import { head, uniq, values } from "lodash-es";
+
+import { useAIContext } from "./context";
+import { databaseMetadataToText } from "./utils";
+import { OpenAIMessage, OpenAIResponse } from "../types";
+import { WebStorageHelper } from "@/utils";
+import { hashCode } from "@/bbkit/BBUtil";
+
+export type SuggestionContext = {
+ schema: string; // schema text
+ key: string; // a hash key used by storage
+ suggestions: string[];
+ ready: boolean;
+ state: "LOADING" | "IDLE" | "ENDED";
+ used: Set<string>;
+ consume: (sug: string) => void;
+ fetch: () => Promise<string[]>; // returns empty means reaches the end
+};
+
+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));
+
+export const useDynamicSuggestions = () => {
+ const context = useAIContext();
+
+ const text = computed(() => {
+ const meta = context.databaseMetadata.value;
+ const engine = context.engineType.value;
+
+ if (meta && engine) {
+ return databaseMetadataToText(meta, engine);
+ }
+ return "";
+ });
+
+ const requestAI = async (messages: OpenAIMessage[]) => {
+ const body = {
+ model: "gpt-3.5-turbo",
+ messages,
+ temperature: 0,
+ stop: ["#", ";"],
+ top_p: 1.0,
+ frequency_penalty: 0.0,
+ presence_penalty: 0.0,
+ };
+ const axios = new Axios({
+ timeout: 20 * 1000,
+ responseType: "json",
+ });
+ const headers = {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${context.openAIKey.value}`,
+ };
+ const url = "https://api.openai.com/v1/chat/completions";
+ try {
+ const response: AxiosResponse<string> = await axios.post(
+ url,
+ JSON.stringify(body),
+ {
+ headers,
+ }
+ );
+
+ const data = JSON.parse(response.data) as OpenAIResponse;
+ if (data?.error) {
+ throw new Error(data.error.message);
+ }
+
+ const text = head(data?.choices)?.message.content?.trim() ?? "";
+ const card = JSON.parse(text) as Record<string, string>;
+ return values(card ?? {});
+ } catch (err) {
+ return [];
+ }
+ };
+
+ const createSuggestion = (schema: string) => {
+ const suggestion: SuggestionContext = reactive({
+ schema,
+ key: keyOf(schema),
+ suggestions: [],
+ state: "IDLE",
+ ready: false,
+ used: new Set(),
+ consume(sug) {
+ const { suggestions, used } = suggestion;
+ const index = suggestions.indexOf(sug);
+ if (index >= 0) {
+ suggestions.splice(index, 1);
+ }
+ used.add(sug);
+ if (suggestions.length === 0) {
+ suggestion.fetch();
+ }
+ },
+ async fetch() {
+ const { used, suggestions, key } = suggestion;
+ 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 messages: OpenAIMessage[] = [
+ {
+ role: "system",
+ content: commands.join("\n"),
+ },
+ {
+ role: "user",
+ content: prompts.join("\n"),
+ },
+ ];
+
+ suggestion.state = "LOADING";
+ const more = (await requestAI(messages)).filter((sug) => {
+ if (used.has(sug)) return false;
+ if (suggestions.includes(sug)) return false;
+ return true;
+ });
+ suggestions.push(...more);
+ suggestion.state = more.length === 0 ? "ENDED" : "IDLE";
+
+ const combined = uniq([...suggestions, ...used.values()]).slice(
+ 0,
+ MAX_STORED_SUGGESTIONS
+ );
+ if (combined.length > 0) {
+ storage.save(key, combined);
+ }
+
+ return more;
+ },
+ });
+ const stored = storage.load<string[]>(suggestion.key, []);
+ if (stored && stored.length > 0) {
+ suggestion.ready = true;
+ suggestion.suggestions = stored;
+ } else {
+ suggestion.fetch().then(() => {
+ suggestion.ready = true;
+ });
+ }
+ cache.value.set(schema, suggestion);
+ return suggestion;
+ };
+
+ const getOrCreateSuggestion = (schema: string) => {
+ const cached = cache.value.get(schema);
+ if (cached) return cached;
+ return createSuggestion(schema);
+ };
+
+ return computed(() => {
+ if (!text.value) return undefined;
+ return getOrCreateSuggestion(text.value);
+ });
+};
diff --git a/frontend/src/plugins/ai/logic/utils.ts b/frontend/src/plugins/ai/logic/utils.ts
index c623c72f9e..c5478def16 100644
--- a/frontend/src/plugins/ai/logic/utils.ts
+++ b/frontend/src/plugins/ai/logic/utils.ts
@@ -1,6 +1,7 @@
import { watch } from "vue";
-import type { Connection } from "@/types";
+import type { Connection, EngineType } from "@/types";
import { useCurrentTab } from "@/store";
+import { DatabaseMetadata } from "@/types/proto/store/database";
export const onConnectionChanged = (
fn: (newConn: Connection, oldConn: Connection | undefined) => void,
@@ -23,3 +24,31 @@ export const onConnectionChanged = (
{ immediate }
);
};
+
+export const databaseMetadataToText = (
+ databaseMetadata: DatabaseMetadata | undefined,
+ engineType?: EngineType
+) => {
+ const prompts: string[] = [];
+ if (engineType) {
+ if (databaseMetadata) {
+ prompts.push(`### ${engineType} tables, with their properties:`);
+ } else {
+ prompts.push(`### ${engineType} database`);
+ }
+ } else {
+ if (databaseMetadata) {
+ prompts.push(`### Giving a database`);
+ }
+ }
+ if (databaseMetadata) {
+ databaseMetadata.schemas.forEach((schema) => {
+ schema.tables.forEach((table) => {
+ const name = schema.name ? `${schema.name}.${table.name}` : table.name;
+ const columns = table.columns.map((column) => column.name).join(", ");
+ prompts.push(`# ${name}(${columns})`);
+ });
+ });
+ }
+ return prompts.join("\n");
+};