Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: add model name setting when calling openai api instead of hardcode (#14653)
learningprod2345310f9e1
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.goindex e54c87e6e5..0caacd3c73 100644--- a/backend/api/v1/database_service.go+++ b/backend/api/v1/database_service.go@@ -1836,7 +1836,7 @@ func (s *DatabaseService) AdviseIndex(ctx context.Context, request *v1pb.AdviseI}func (s *DatabaseService) mysqlAdviseIndex(ctx context.Context, request *v1pb.AdviseIndexRequest, instance *store.InstanceMessage, database *store.DatabaseMessage) (*v1pb.AdviseIndexResponse, error) {- key, endpoint, err := s.getOpenAISetting((ctx))+ key, endpoint, modelName, err := s.getOpenAISetting((ctx))if err != nil {return nil, err}@@ -1964,7 +1964,7 @@ func (s *DatabaseService) mysqlAdviseIndex(ctx context.Context, request *v1pb.Adreturn nil}- result, err := getOpenAIResponse(ctx, messages, key, endpoint, generateFunc)+ result, err := getOpenAIResponse(ctx, messages, key, endpoint, modelName, generateFunc)if err != nil {return nil, err}@@ -2001,7 +2001,7 @@ func restoreNode(node tidbast.Node) (string, error) {}func (s *DatabaseService) pgAdviseIndex(ctx context.Context, request *v1pb.AdviseIndexRequest, database *store.DatabaseMessage) (*v1pb.AdviseIndexResponse, error) {- key, endpoint, err := s.getOpenAISetting((ctx))+ key, endpoint, modelName, err := s.getOpenAISetting((ctx))if err != nil {return nil, err}@@ -2072,7 +2072,7 @@ func (s *DatabaseService) pgAdviseIndex(ctx context.Context, request *v1pb.Advisreturn nil}- result, err := getOpenAIResponse(ctx, messages, key, endpoint, generateFunc)+ result, err := getOpenAIResponse(ctx, messages, key, endpoint, modelName, generateFunc)if err != nil {return nil, err}@@ -2080,26 +2080,30 @@ func (s *DatabaseService) pgAdviseIndex(ctx context.Context, request *v1pb.Advisreturn result, nil}-func (s *DatabaseService) getOpenAISetting(ctx context.Context) (string, string, error) {+func (s *DatabaseService) getOpenAISetting(ctx context.Context) (string, string, string, error) {key, err := s.store.GetSettingV2(ctx, api.SettingPluginOpenAIKey)if err != nil {- return "", "", status.Errorf(codes.Internal, "Failed to get setting: %v", err)+ return "", "", "", status.Errorf(codes.Internal, "Failed to get setting: %v", err)}if key.Value == "" {- return "", "", status.Errorf(codes.FailedPrecondition, "OpenAI key is not set")+ return "", "", "", status.Errorf(codes.FailedPrecondition, "OpenAI key is not set")}endpointSetting, err := s.store.GetSettingV2(ctx, api.SettingPluginOpenAIEndpoint)if err != nil {- return "", "", status.Errorf(codes.Internal, "Failed to get setting: %v", err)+ return "", "", "", status.Errorf(codes.Internal, "Failed to get setting: %v", err)}var endpoint stringif endpointSetting != nil {endpoint = endpointSetting.Value}- return key.Value, endpoint, nil+ model, err := s.store.GetSettingV2(ctx, api.SettingPluginOpenAIModel)+ if err != nil {+ return "", "", "", status.Errorf(codes.Internal, "Failed to get setting: %v", err)+ }+ return key.Value, endpoint, model.Value, nil}-func getOpenAIResponse(ctx context.Context, messages []openai.ChatCompletionMessage, key, endpoint string, generateResponse func(*v1pb.AdviseIndexResponse) error) (*v1pb.AdviseIndexResponse, error) {+func getOpenAIResponse(ctx context.Context, messages []openai.ChatCompletionMessage, key, endpoint, model string, generateResponse func(*v1pb.AdviseIndexResponse) error) (*v1pb.AdviseIndexResponse, error) {var result v1pb.AdviseIndexResponsesuccessful := falsevar retErr error@@ -2113,7 +2117,7 @@ func getOpenAIResponse(ctx context.Context, messages []openai.ChatCompletionMessresp, err := client.CreateChatCompletion(ctx,openai.ChatCompletionRequest{- Model: openai.GPT3Dot5Turbo,+ Model: model,Messages: messages,Temperature: 0,Stop: []string{"#", ";"},diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.goindex ef4e9a4f48..c9eca5d54f 100644--- a/backend/api/v1/setting_service.go+++ b/backend/api/v1/setting_service.go@@ -68,6 +68,7 @@ var whitelistSettings = []api.SettingName{api.SettingWatermark,api.SettingPluginOpenAIKey,api.SettingPluginOpenAIEndpoint,+ api.SettingPluginOpenAIModel,api.SettingWorkspaceApproval,api.SettingWorkspaceMailDelivery,api.SettingWorkspaceProfile,diff --git a/backend/legacyapi/setting.go b/backend/legacyapi/setting.goindex b5cb6a7b1c..d23ed07ec1 100644--- a/backend/legacyapi/setting.go+++ b/backend/legacyapi/setting.go@@ -27,6 +27,8 @@ const (SettingPluginOpenAIKey SettingName = "bb.plugin.openai.key"// SettingPluginOpenAIEndpoint is used for OpenAI's API endpoint.SettingPluginOpenAIEndpoint SettingName = "bb.plugin.openai.endpoint"+ // SettingPluginOpenAIModel is used for OpenAI's API model name.+ SettingPluginOpenAIModel SettingName = "bb.plugin.openai.model"// SettingPluginAgent is the setting name for the internal agent API.// For now we will call the hub to fetch the subscription license.SettingPluginAgent SettingName = "bb.plugin.agent"diff --git a/backend/server/init.go b/backend/server/init.goindex 13af40afbe..173aed4682 100644--- a/backend/server/init.go+++ b/backend/server/init.go@@ -139,6 +139,14 @@ func (s *Server) getInitSetting(ctx context.Context) (string, error) {return "", err}+ if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{+ Name: api.SettingPluginOpenAIModel,+ Value: "",+ Description: "Model for OpenAI",+ }, api.SystemBotID); err != nil {+ return "", err+ }+// initial external approval settingexternalApprovalSettingValue, err := protojson.Marshal(&storepb.ExternalApprovalSetting{})if err != nil {diff --git a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vueindex 6017a3f002..c868b99a3c 100644--- a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue+++ b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue@@ -87,6 +87,31 @@</span></NTooltip>+ <label class="flex items-center gap-x-2">+ <span class="font-medium">{{+ $t("settings.general.workspace.ai-assistant.openai-model.self")+ }}</span>+ </label>+ <div class="mb-3 text-sm text-gray-400">+ {{+ $t(+ "settings.general.workspace.ai-assistant.openai-model.description"+ )+ }}+ </div>+ <NTooltip placement="top-start" :disabled="allowEdit">+ <template #trigger>+ <NInput+ v-model:value="state.openAIModel"+ class="mb-4 w-full"+ :disabled="!allowEdit"+ />+ </template>+ <span class="text-sm text-gray-400 -translate-y-2">+ {{ $t("settings.general.workspace.only-admin-can-edit") }}+ </span>+ </NTooltip>+<div class="flex justify-end"><NButtontype="primary"@@ -124,6 +149,7 @@ import { FeatureBadge, FeatureModal } from "../FeatureGuard";interface LocalState {openAIKey: string;openAIEndpoint: string;+ openAIModel: string;showFeatureModal: boolean;}@@ -138,6 +164,7 @@ const containerRef = ref<HTMLDivElement>();const state = reactive<LocalState>({openAIKey: "",openAIEndpoint: "",+ openAIModel: "",showFeatureModal: false,});@@ -147,20 +174,25 @@ const openAIKeySetting = settingV1Store.getSettingByName(const openAIEndpointSetting = settingV1Store.getSettingByName("bb.plugin.openai.endpoint");+const openAIModelSetting = settingV1Store.getSettingByName(+ "bb.plugin.openai.model"+);watchEffect(() => {state.openAIKey = maskKey(openAIKeySetting?.value?.stringValue);state.openAIEndpoint = openAIEndpointSetting?.value?.stringValue ?? "";+ state.openAIModel = openAIModelSetting?.value?.stringValue ?? "";});const allowSave = computed((): boolean => {const openAIKeyUpdated =state.openAIKey !== maskKey(openAIKeySetting?.value?.stringValue) ||(state.openAIKey && !state.openAIKey.includes("***"));- return (- openAIKeyUpdated ||- state.openAIEndpoint !== openAIEndpointSetting?.value?.stringValue- );+ const openAIEndpointUpdated =+ state.openAIEndpoint !== openAIEndpointSetting?.value?.stringValue;+ const openAIModelUpdated =+ state.openAIModel !== openAIModelSetting?.value?.stringValue;+ return openAIKeyUpdated || openAIEndpointUpdated || openAIModelUpdated;});function maskKey(key: string | undefined): string {@@ -194,6 +226,14 @@ const updateOpenAIKeyEndpoint = async () => {},});}+ if (state.openAIEndpoint !== openAIModelSetting?.value?.stringValue) {+ await settingV1Store.upsertSetting({+ name: "bb.plugin.openai.model",+ value: {+ stringValue: state.openAIModel,+ },+ });+ }pushNotification({module: "bytebase",style: "SUCCESS",diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex ed0b56580a..df73a846aa 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -758,6 +758,10 @@"openai-endpoint": {"self": "OpenAI API Endpoint","description": "Supply private deployment of OpenAI API Endpoint."+ },+ "openai-model": {+ "self": "OpenAI Model Name",+ "description": "Supply private deployment of OpenAI Model name."}},"announcement": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 63d7f2dd01..9d0c52ed49 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -758,6 +758,10 @@"openai-endpoint": {"self": "Punto de conexión de API de OpenAI","description": "Proporcione una implementación privada del Punto de conexión de API de OpenAI."+ },+ "openai-model": {+ "self": "Nombre del modelo de OpenAI",+ "description": "Suministro de implementación privada del nombre del modelo de OpenAI."}},"announcement": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 21af84463f..579aba7925 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -758,6 +758,10 @@"openai-endpoint": {"self": "OpenAI API エンドポイント","description": "プライベート展開用の OpenAI API エンドポイントを提供します。"+ },+ "openai-model": {+ "self": "OpenAIモデル名",+ "description": "供給プライベートデプロイメントのOpenAIモデル名。"}},"announcement": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex d9227b3c02..e7d4462de6 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -758,6 +758,10 @@"openai-endpoint": {"self": "OpenAI API Endpoint","description": "提供私有化部署的 OpenAI API Endpoint。"+ },+ "openai-model": {+ "self": "OpenAI Model Name",+ "description": "提供私有化部署的 OpenAI 模型名称。"}},"announcement": {diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vueindex 586ede2c08..b1804541da 100644--- a/frontend/src/plugins/ai/components/ChatPanel.vue+++ b/frontend/src/plugins/ai/components/ChatPanel.vue@@ -37,6 +37,7 @@ import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";import * as promptUtils from "../logic/prompt";import { useConversationStore } from "../store";import type { OpenAIMessage, OpenAIResponse } from "../types";+import { OPENAI_DEFAULT_MODEL } from "@/types";import ActionBar from "./ActionBar.vue";import ChatView from "./ChatView";import DynamicSuggestions from "./DynamicSuggestions.vue";@@ -55,7 +56,7 @@ const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());const store = useConversationStore();const context = useAIContext();-const { openAIKey, openAIEndpoint, showHistoryDialog, pendingSendChat } =+const { openAIKey, openAIEndpoint, openAIModel, showHistoryDialog, pendingSendChat } =context;const {list: conversationList,@@ -114,7 +115,10 @@ const requestAI = async (query: string) => {? "https://api.openai.com/v1/chat/completions": openAIEndpoint.value + "/v1/chat/completions";const messages: OpenAIMessage[] = [];-+ const model =+ openAIModel.value === ""+ ? OPENAI_DEFAULT_MODEL+ : openAIModel.value;conversation.messageList.forEach((message) => {const { author, prompt } = message;messages.push({@@ -123,7 +127,7 @@ const requestAI = async (query: string) => {});});const body = {- model: "gpt-3.5-turbo",+ model: model,messages,temperature: 0,stop: ["#", ";"],diff --git a/frontend/src/plugins/ai/components/ProvideAIContext.vue b/frontend/src/plugins/ai/components/ProvideAIContext.vueindex 58598c3bf4..d6ed7b2e1f 100644--- a/frontend/src/plugins/ai/components/ProvideAIContext.vue+++ b/frontend/src/plugins/ai/components/ProvideAIContext.vue@@ -34,10 +34,16 @@ const openAIKeySetting = settingV1Store.getSettingByName(const openAIEndpointSetting = settingV1Store.getSettingByName("bb.plugin.openai.endpoint");+const openAIModelSetting = settingV1Store.getSettingByName(+ "bb.plugin.openai.model"+);const openAIKey = computed(() => openAIKeySetting?.value?.stringValue ?? "");const openAIEndpoint = computed(() => openAIEndpointSetting?.value?.stringValue ?? "");+const openAIModel = computed(+ () => openAIModelSetting?.value?.stringValue ?? ""+)const { instance, database } = useConnectionOfCurrentSQLEditorTab();const databaseMetadata = useMetadata(@@ -59,6 +65,7 @@ const store = useConversationStore();const context: AIContext = {openAIKey,openAIEndpoint,+ openAIModel,engine: computed(() => instance.value.engine),databaseMetadata,schema,diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.tsindex b2c85da643..b053ada44a 100644--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts@@ -4,6 +4,7 @@ import { computed, reactive, ref } from "vue";import { hashCode } from "@/bbkit/BBUtil";import { WebStorageHelper } from "@/utils";import type { OpenAIMessage, OpenAIResponse } from "../types";+import { OPENAI_DEFAULT_MODEL } from "@/types";import { useAIContext } from "./context";import * as promptUtils from "./prompt";@@ -42,8 +43,12 @@ export const useDynamicSuggestions = () => {const requestAI = async (messages: OpenAIMessage[]) => {await new Promise((resolve) => setTimeout(resolve, 1000));+ const modelName =+ context.openAIModel.value === ""+ ? OPENAI_DEFAULT_MODEL+ : context.openAIModel.valueconst body = {- model: "gpt-3.5-turbo",+ model: modelName,messages,temperature: 0,stop: ["#", ";"],diff --git a/frontend/src/plugins/ai/types/context.ts b/frontend/src/plugins/ai/types/context.tsindex 6a73da6ebf..267bb92a52 100644--- a/frontend/src/plugins/ai/types/context.ts+++ b/frontend/src/plugins/ai/types/context.ts@@ -20,6 +20,7 @@ export type AIChatInfo = {export type AIContext = {openAIKey: Ref<string>;openAIEndpoint: Ref<string>;+ openAIModel: Ref<string>;engine: Ref<Engine | undefined>;databaseMetadata: Ref<DatabaseMetadata | undefined>;schema: Ref<string | undefined>;diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex e2b17a4576..bdd84c448d 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -14,6 +14,7 @@ export const TEXT_VALIDATION_DELAY = 1000;export const ENTERPRISE_INQUIRE_LINK ="https://www.bytebase.com/contact-us?source=console";+export const OPENAI_DEFAULT_MODEL = "gpt-3.5-turbo";// Routerexport type RouterSlug = {issueSlug?: string;diff --git a/frontend/src/types/setting.ts b/frontend/src/types/setting.tsindex 7f501506a8..9aa79d919f 100644--- a/frontend/src/types/setting.ts+++ b/frontend/src/types/setting.ts@@ -8,6 +8,7 @@ export type SettingName =| "bb.workspace.approval.external"| "bb.plugin.openai.key"| "bb.plugin.openai.endpoint"+ | "bb.plugin.openai.model"| "bb.enterprise.trial"| "bb.workspace.schema-template"| "bb.workspace.data-classification"