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: not expose api key and use ai completion API (#15621)
ecmadao378804a59ae5
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.goindex aff1310499..42cd2e9453 100644--- a/backend/api/v1/setting_service.go+++ b/backend/api/v1/setting_service.go@@ -568,9 +568,24 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *v1pb.Updateif err := convertProtoToProto(request.Setting.Value.GetAiSetting(), aiSetting); err != nil {return nil, status.Errorf(codes.Internal, "failed to unmarshal setting value for %s with error: %v", apiSettingName, err)}- if aiSetting.Enabled && (aiSetting.ApiKey == "" || aiSetting.Endpoint == "" || aiSetting.Model == "") {- return nil, status.Errorf(codes.InvalidArgument, "api key, endpoint and model are required")+ if aiSetting.Enabled {+ if aiSetting.Endpoint == "" || aiSetting.Model == "" {+ return nil, status.Errorf(codes.InvalidArgument, "API endpoint and model are required")+ }+ if existedSetting != nil {+ existedAISetting, err := s.convertToSettingMessage(ctx, existedSetting)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to unmarshal existed ai setting with error: %v", err)+ }+ if aiSetting.ApiKey == "" {+ aiSetting.ApiKey = existedAISetting.Value.GetAiSetting().GetApiKey()+ }+ }+ if aiSetting.ApiKey == "" {+ return nil, status.Errorf(codes.InvalidArgument, "API key is required")+ }}+bytes, err := protojson.Marshal(aiSetting)if err != nil {return nil, status.Errorf(codes.Internal, "failed to marshal setting for %s with error: %v", apiSettingName, err)@@ -825,6 +840,8 @@ func (s *SettingService) convertToSettingMessage(ctx context.Context, setting *sif err := common.ProtojsonUnmarshaler.Unmarshal([]byte(setting.Value), v1Value); err != nil {return nil, status.Errorf(codes.Internal, "failed to unmarshal setting value for %s with error: %v", setting.Name, err)}+ // DO NOT expose the api key.+ v1Value.ApiKey = ""return &v1pb.Setting{Name: settingName,Value: &v1pb.Value{diff --git a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vueindex 40b895970e..c9fab3af8b 100644--- a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue+++ b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue@@ -79,7 +79,6 @@<template #trigger><BBTextFieldv-model:value="state.apiKey"- :required="true":disabled="!allowEdit || !hasAIFeature":placeholder="$t(@@ -202,7 +201,7 @@ const hasAIFeature = computed(() => hasFeature("bb.feature.ai-assistant"));const getInitialState = (): LocalState => {return {enabled: aiSetting.value?.enabled ?? false,- apiKey: maskKey(aiSetting.value?.apiKey),+ apiKey: "",endpoint: aiSetting.value?.endpoint ?? "",model: aiSetting.value?.model ?? "",provider: aiSetting.value?.provider ?? AISetting_Provider.OPEN_AI,@@ -238,9 +237,7 @@ watchEffect(() => {const allowSave = computed((): boolean => {const initValue = getInitialState();const enabledUpdated = state.enabled !== initValue.enabled;- const openAIKeyUpdated =- state.apiKey !== initValue.apiKey ||- (state.apiKey && !state.apiKey.includes("***"));+ const openAIKeyUpdated = !!state.apiKey;const openAIEndpointUpdated = state.endpoint !== initValue.endpoint;const openAIModelUpdated = state.model !== initValue.model;return (@@ -251,10 +248,6 @@ const allowSave = computed((): boolean => {);});-function maskKey(key: string | undefined): string {- return key ? key.slice(0, 3) + "***" + key.slice(-4) : "";-}-const providerDefault = computed(() => {switch (state.provider) {case AISetting_Provider.OPEN_AI:diff --git a/frontend/src/layouts/ProjectV1Layout.vue b/frontend/src/layouts/ProjectV1Layout.vueindex e64c13f7bb..7708efdddb 100644--- a/frontend/src/layouts/ProjectV1Layout.vue+++ b/frontend/src/layouts/ProjectV1Layout.vue@@ -140,7 +140,7 @@ watchEffect(async () => {}});-const { project, ready } = useProjectByName(projectName.value);+const { project, ready } = useProjectByName(projectName);const initialized = computed(() => ready && project.value.name !== UNKNOWN_PROJECT_NAMEdiff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 68813c8669..19a8505bfb 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -564,7 +564,7 @@},"api-key": {"self": "API Key",- "description": "Supply API Key. {viewDoc}",+ "description": "Supply API Key, read-only. {viewDoc}","find-my-key": "Find my key","placeholder": "An API Key usually starts with sk-*****"},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 4250a1684a..5e655aaa2e 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -564,7 +564,7 @@},"api-key": {"self": "Clave de API",- "description": "Proporcione una clave de API para habilitar la capacidad Text2SQL en el Editor de SQL. {viewDoc}",+ "description": "Proporcionar clave API, solo lectura. {viewDoc}","find-my-key": "Encuentra mi llave","placeholder": "Una clave de API generalmente comienza con sk-*****"},@@ -2595,4 +2595,4 @@"last-visit": "Última visita","changelog-for-version": "Registro de cambios para {version}"}-}+}\ No newline at end of filediff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex b252820d86..85e8892dde 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -564,7 +564,7 @@},"api-key": {"self": "APIキー",- "description": "SQL エディターで Text2SQL を開く機能を有効にする API キーを提供します。 {viewDoc}",+ "description": "読み取り専用の API キーを入力してください。{viewDoc}","find-my-key": "鍵を探す","placeholder": "API キーは通常 sk-***** で始まります"},@@ -2595,4 +2595,4 @@"last-visit": "最終訪問","changelog-for-version": "{version} の変更履歴"}-}+}\ No newline at end of filediff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 71d54718fd..c8ac060459 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -564,7 +564,7 @@},"api-key": {"self": "Khóa API",- "description": "Cung cấp Khóa API. {viewDoc}",+ "description": "Cung cấp Khóa API, chỉ đọc. {viewDoc}","find-my-key": "Tìm khóa của tôi","placeholder": "Khóa API thường bắt đầu bằng sk-*****"},@@ -2595,4 +2595,4 @@"last-visit": "Lần truy cập cuối","changelog-for-version": "Nhật ký thay đổi cho phiên bản {version}"}-}+}\ No newline at end of filediff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b2d8bfff59..1e01f96406 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -564,7 +564,7 @@},"api-key": {"self": "API Key",- "description": "提供 API Key 以开启 AI 助手。{viewDoc}",+ "description": "提供 API 密钥,只读。{viewDoc}","find-my-key": "找到我的 Key","placeholder": "API Key 通常以 sk-***** 开头"},@@ -2595,4 +2595,4 @@"last-visit": "上次访问","changelog-for-version": "{version} 的更新日志"}-}+}\ No newline at end of filediff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vueindex 7cf1d2a50a..25ef2d2d13 100644--- a/frontend/src/plugins/ai/components/ChatPanel.vue+++ b/frontend/src/plugins/ai/components/ChatPanel.vue@@ -28,19 +28,17 @@</template><script lang="ts" setup>-import type { AxiosResponse } from "axios";-import { Axios } from "axios";import { head } from "lodash-es";import { NSpin } from "naive-ui";import { storeToRefs } from "pinia";import { reactive, watch } from "vue";+import { sqlServiceClient } from "@/grpcweb";import { useSQLEditorTabStore } from "@/store";-import { AISetting_Provider } from "@/types/proto/v1/setting_service";+import { type AICompletionRequest_Message } from "@/types/proto/v1/sql_service";import { nextAnimationFrame } from "@/utils";import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";import * as promptUtils from "../logic/prompt";import { useConversationStore } from "../store";-import type { OpenAIMessage, OpenAIResponse } from "../types";import ActionBar from "./ActionBar.vue";import ChatView from "./ChatView";import DynamicSuggestions from "./DynamicSuggestions.vue";@@ -112,7 +110,7 @@ const requestAI = async (query: string) => {conversation_id: conversation.id,status: "LOADING",});- const messages: OpenAIMessage[] = [];+ const messages: AICompletionRequest_Message[] = [];conversation.messageList.forEach((message) => {const { author, prompt } = message;messages.push({@@ -120,43 +118,10 @@ const requestAI = async (query: string) => {content: prompt,});});- const body = {- model: aiSetting.value.model,- messages,- temperature: 0,- stop: ["#", ";"],- top_p: 1.0,- frequency_penalty: 0.0,- presence_penalty: 0.0,- };state.loading = true;- const axios = new Axios({- timeout: 300 * 1000,- responseType: "json",- });- const headers: { [key: string]: string } = {- "Content-Type": "application/json",- };- if (context.aiSetting.value.provider === AISetting_Provider.AZURE_OPENAI) {- headers["api-key"] = context.aiSetting.value.apiKey;- } else {- headers["Authorization"] = `Bearer ${context.aiSetting.value.apiKey}`;- }try {- const response: AxiosResponse<string> = await axios.post(- aiSetting.value.endpoint,- 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 response = await sqlServiceClient.aICompletion({ messages });+ const text = head(head(response.candidates)?.content?.parts)?.text?.trim();console.debug("[AI Assistant] answer:", text);if (text) {answer.content = text;diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.tsindex ea49c83446..072a58f3e5 100644--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts@@ -1,10 +1,9 @@-import { Axios, type AxiosResponse } from "axios";import { head, uniq, values } from "lodash-es";import { computed, reactive, ref } from "vue";import { hashCode } from "@/bbkit/BBUtil";-import { AISetting_Provider } from "@/types/proto/v1/setting_service";+import { sqlServiceClient } from "@/grpcweb";+import { type AICompletionRequest_Message } from "@/types/proto/v1/sql_service";import { WebStorageHelper } from "@/utils";-import type { OpenAIMessage, OpenAIResponse } from "../types";import { useAIContext } from "./context";import * as promptUtils from "./prompt";@@ -41,44 +40,12 @@ export const useDynamicSuggestions = () => {return "";});- const requestAI = async (messages: OpenAIMessage[]) => {+ const requestAI = async (messages: AICompletionRequest_Message[]) => {await new Promise((resolve) => setTimeout(resolve, 1000));- const body = {- model: context.aiSetting.value.model,- messages,- temperature: 0,- stop: ["#", ";"],- top_p: 1.0,- frequency_penalty: 0.0,- presence_penalty: 0.0,- };- const axios = new Axios({- timeout: 300 * 1000,- responseType: "json",- });- const headers: { [key: string]: string } = {- "Content-Type": "application/json",- };- if (context.aiSetting.value.provider === AISetting_Provider.AZURE_OPENAI) {- headers["api-key"] = context.aiSetting.value.apiKey;- } else {- headers["Authorization"] = `Bearer ${context.aiSetting.value.apiKey}`;- }try {- const response: AxiosResponse<string> = await axios.post(- context.aiSetting.value.endpoint,- 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 response = await sqlServiceClient.aICompletion({ messages });+ const text =+ head(head(response.candidates)?.content?.parts)?.text?.trim() ?? "";const card = JSON.parse(text) as Record<string, string>;return values(card ?? {});} catch {@@ -117,7 +84,7 @@ export const useDynamicSuggestions = () => {metadata,new Set([...used.values(), ...suggestions]));- const messages: OpenAIMessage[] = [+ const messages: AICompletionRequest_Message[] = [{role: "system",content: command,diff --git a/frontend/src/plugins/ai/types/index.ts b/frontend/src/plugins/ai/types/index.tsindex e05e1f4278..7670907704 100644--- a/frontend/src/plugins/ai/types/index.ts+++ b/frontend/src/plugins/ai/types/index.ts@@ -1,5 +1,4 @@export * from "./context";export * from "./conversation";-export * from "./openai";export type ChatAction = "explain-code" | "find-problems" | "new-chat";diff --git a/frontend/src/plugins/ai/types/openai.ts b/frontend/src/plugins/ai/types/openai.tsdeleted file mode 100644index bd7eefa34a..0000000000--- a/frontend/src/plugins/ai/types/openai.ts+++ /dev/null@@ -1,35 +0,0 @@-export type OpenAIMessage = {- role: "system" | "user" | "assistant";- content: string;-};--export type OpenAIChoice = {- // text: string;- index: number;- logprobs: unknown;- finish_reason: "stop" | "length" | null;- message: OpenAIMessage;-};--export type OpenAIUsage = {- prompt_tokens: number;- completion_tokens: number;- total_tokens: number;-};--export type OpenAIError = {- message: string;- type: string;- param: unknown;- code: unknown;-};--export type OpenAIResponse = {- id: string;- object: "text_completion";- created: number;- model: "code-davinci-002";- choices: OpenAIChoice[];- usage: OpenAIUsage;- error: OpenAIError | undefined;-};diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vueindex 26036ae06e..cd833662b9 100644--- a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue+++ b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue@@ -1,6 +1,6 @@<template><template v-if="showButton">- <template v-if="enabled">+ <template v-if="openAIEnabled"><NPopselectv-if="options.length > 0"placement="bottom-end"@@ -14,7 +14,7 @@</NPopselect><Button v-else v-bind="$attrs" @click="handleClickButton" /></template>- <NPopover v-if="!enabled" placement="bottom-end">+ <NPopover v-if="!openAIEnabled" placement="bottom-end"><template #trigger><Button v-bind="$attrs" :disabled="true" /></template>@@ -85,8 +85,9 @@ const tabStore = useSQLEditorTabStore();const settingV1Store = useSettingV1Store();const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");-const openAIKey = computed(- () => settingV1Store.getSettingByName("bb.ai")?.value?.aiSetting?.apiKey+const openAIEnabled = computed(+ () =>+ settingV1Store.getSettingByName("bb.ai")?.value?.aiSetting?.enabled ?? false);const { showAIPanel } = useSQLEditorContext();@@ -117,10 +118,6 @@ const showButton = computed(() => {return !tabStore.isDisconnected && tabStore.currentTab?.mode === "WORKSHEET";});-const enabled = computed(() => {- return openAIKey.value;-});-const allowConfigure = computed((): boolean => {return hasWorkspacePermissionV2("bb.settings.set");});