Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Adjust the AI configuration structure (#17858)

Jeffrey Chenca0ce7ff2dd4
diff --git a/app/src/config/ai.ts b/app/src/config/ai.ts
index e6288ddf0b..c68e7f2354 100644
--- a/app/src/config/ai.ts
+++ b/app/src/config/ai.ts
@@ -1,11 +1,11 @@
import {fetchPost} from "../util/fetch";
function getDefaultModel() {
- const p = window.siyuan.config.ai.providers?.[0];
+ const p = window.siyuan.config.ai.providers[0];
if (!p) {
return {name: ""};
}
- const m = p.models?.[0];
+ const m = p.models[0];
if (!m) {
return {name: ""};
}
@@ -13,9 +13,9 @@ function getDefaultModel() {
}
function getDefaultProvider() {
- const p = window.siyuan.config.ai.providers?.[0];
+ const p = window.siyuan.config.ai.providers[0];
if (!p) {
- return {apiKey: "", baseURL: "", requestTimeout: 30};
+ return {apiKey: "", baseURL: "https://api.openai.com/v1", requestTimeout: 30};
}
return p;
}
@@ -40,7 +40,7 @@ export const ai = {
responsiveHTML = `<div class="b3-label">
${window.siyuan.languages.apiBaseURL}
<div class="fn__hr"></div>
- <input class="b3-text-field fn__block" id="apiBaseURL" value="${prov.baseURL || ""}"/>
+ <input class="b3-text-field fn__block" id="apiBaseURL" value="${prov.baseURL || "https://api.openai.com/v1"}"/>
<div class="b3-label__text">${window.siyuan.languages.apiBaseURLTip}</div>
</div>
<div class="b3-label">
@@ -222,16 +222,27 @@ export const ai = {
}
ai.element.querySelectorAll("input, select").forEach((item) => {
item.addEventListener("change", () => {
- const providers = window.siyuan.config.ai.providers || [];
- const firstProvider = providers[0] || {apiKey: "", baseURL: "", requestTimeout: 30, models: []};
- const firstModel = firstProvider.models?.[0] || {name: ""};
- const chat = window.siyuan.config.ai.chat || {maxHistoryMessages: 7, temperature: 1.0, maxCompletionTokens: 0};
+ const providers = window.siyuan.config.ai.providers;
+ const firstProvider: Config.IProvider = providers[0] ?? {
+ id: "",
+ apiKey: "",
+ baseURL: "",
+ requestTimeout: 30,
+ enabled: true,
+ models: [] as Config.IModel[],
+ };
+ const firstModel = firstProvider.models[0] ?? {id: "", name: "", enabled: true};
+ const chat = window.siyuan.config.ai.chat;
fetchPost("/api/setting/setAI", {
providers: [{
+ id: firstProvider.id,
+ enabled: firstProvider.enabled,
apiKey: (ai.element.querySelector("#apiKey") as HTMLInputElement)?.value || firstProvider.apiKey || "",
baseURL: (ai.element.querySelector("#apiBaseURL") as HTMLInputElement)?.value || firstProvider.baseURL || "",
requestTimeout: parseInt((ai.element.querySelector("#apiTimeout") as HTMLInputElement)?.value) || firstProvider.requestTimeout || 30,
models: [{
+ id: firstModel.id,
+ enabled: firstModel.enabled,
name: (ai.element.querySelector("#apiModel") as HTMLInputElement)?.value || firstModel.name || "",
}]
}],
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts
index ab2c985912..c6d3de3752 100644
--- a/app/src/layout/dock/AgentChat.ts
+++ b/app/src/layout/dock/AgentChat.ts
@@ -232,7 +232,7 @@ export class AgentChat extends Model {
const aiConfig = window.siyuan.config.ai;
this.modelOptions = [];
for (const prov of aiConfig.providers || []) {
- for (const m of prov.models || []) {
+ for (const m of prov.models) {
const displayName = m.displayName || m.name;
if (!displayName) {
continue;
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index 33f4a30463..f05079c7ea 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -705,7 +705,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConfig) => {
const config: Config.IUILayoutTabSearchConfig = JSON.parse(JSON.stringify(window.siyuan.storage[Constants.LOCAL_SEARCHDATA]));
- if (config.method === 4 && !window.siyuan.config.ai.embedding?.apiKey) {
+ if (config.method === 4 && !window.siyuan.config.ai.embedding.enabled) {
config.method = 0;
}
const rangeText = (getCurrentEditor()?.protyle.toolbar.range || (getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : document.createRange())).toString();
diff --git a/app/src/search/menu.ts b/app/src/search/menu.ts
index 41d3bd01e7..eb6a90df0a 100644
--- a/app/src/search/menu.ts
+++ b/app/src/search/menu.ts
@@ -375,7 +375,7 @@ export const queryMenu = (config: Config.IUILayoutTabSearchConfig, cb: () => voi
cb();
}
}).element);
- if (window.siyuan.config.ai.embedding?.apiKey) {
+ if (window.siyuan.config.ai.embedding.enabled) {
window.siyuan.menus.menu.append(new MenuItem({
icon: "iconSparkles",
label: window.siyuan.languages.semanticSearch,
@@ -589,7 +589,7 @@ export const moreMenu = async (config: Config.IUILayoutTabSearchConfig,
updateSearchResult(config, element, true);
}
}];
- if (window.siyuan.config.ai.embedding?.apiKey) {
+ if (window.siyuan.config.ai.embedding.enabled) {
searchMethodSubmenu.push({
icon: "iconSparkles",
label: window.siyuan.languages.semanticSearch,
diff --git a/app/src/search/spread.ts b/app/src/search/spread.ts
index c02018540d..b2aa5db014 100644
--- a/app/src/search/spread.ts
+++ b/app/src/search/spread.ts
@@ -41,7 +41,7 @@ export const openSearch = async (options: {
k: options.key || localData.k,
r: localData.r,
hasReplace: options.hotkey === Constants.DIALOG_REPLACE,
- method: localData.method === 4 && !window.siyuan.config.ai.embedding?.apiKey ? 0 : localData.method,
+ method: localData.method === 4 && !window.siyuan.config.ai.embedding.enabled ? 0 : localData.method,
hPath,
idPath,
group: localData.group,
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index d297e30815..003e34afa8 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -66,7 +66,7 @@ export const openGlobalSearch = (app: App, text: string, replace: boolean, searc
k: text,
r: "",
hasReplace: false,
- method: searchData ? searchData.method : (localData.method === 4 && !window.siyuan.config.ai.embedding?.apiKey ? 0 : localData.method),
+ method: searchData ? searchData.method : (localData.method === 4 && !window.siyuan.config.ai.embedding.enabled ? 0 : localData.method),
hPath: "",
idPath: [],
group: localData.group,
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 017da54019..33f98c180c 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -114,23 +114,18 @@ declare namespace Config {
* Artificial Intelligence (AI) related configuration
*/
export interface IAI {
- mcp?: IMCP;
- embedding?: IEmbedding;
- agent?: IAgent;
- chat?: IChat;
- providers?: IProvider[];
- scenarios?: IScenario[];
- }
-
- export interface IScenario {
- name: string;
- model?: string;
+ providers: IProvider[];
+ chat: IChat;
+ agent: IAgent;
+ mcp: IMCP;
+ embedding: IEmbedding;
}
/**
* AI agent global settings
*/
export interface IAgent {
+ modelId: string;
sessionTimeout: number;
confirmTimeout: number;
maxRetries: number;
@@ -143,6 +138,7 @@ declare namespace Config {
* AI chat scenario behavior settings (mirrors IAgent)
*/
export interface IChat {
+ modelId: string;
maxHistoryMessages: number;
temperature: number;
maxCompletionTokens: number;
@@ -152,10 +148,10 @@ declare namespace Config {
* Embedding model configuration
*/
export interface IEmbedding {
- id?: string;
- enabled?: boolean;
- apiKey: string;
+ id: string;
+ enabled: boolean;
baseURL: string;
+ apiKey: string;
name: string;
timeout: number;
}
@@ -164,13 +160,13 @@ declare namespace Config {
* AI provider configuration
*/
export interface IProvider {
- id?: string;
+ id: string;
+ enabled: boolean;
displayName?: string;
- enabled?: boolean;
- apiKey: string;
baseURL: string;
+ apiKey: string;
requestTimeout: number;
- models?: IModel[];
+ models: IModel[];
}
/**
@@ -178,26 +174,26 @@ declare namespace Config {
* live on IChat; Model holds only identity fields.
*/
export interface IModel {
- id?: string;
- displayName?: string;
- enabled?: boolean;
+ id: string;
+ enabled: boolean;
name: string;
+ displayName?: string;
}
/**
* MCP (Model Context Protocol) configuration
*/
export interface IMCP {
- servers?: IMCPServer[];
+ servers: IMCPServer[];
}
export interface IMCPServer {
- name: string;
enabled: boolean;
+ name: string;
+ url: string;
type: string;
command: string;
args?: string[];
- url: string;
headers?: Record<string, string>;
timeout: number;
}
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 14850a7dc1..37dc163b5d 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -34,14 +34,14 @@ import (
)
type agentChatReq struct {
- SessionID string `json:"sessionID"`
- Message string `json:"message"`
- Language string `json:"language"`
- References []agent.Reference `json:"references"`
- EditorContext agent.EditorContext `json:"editorContext"`
- PluginActions []agent.PluginAction `json:"pluginActions"`
- Model string `json:"model,omitempty"`
- Regenerate bool `json:"regenerate"`
+ SessionID string `json:"sessionID"`
+ Message string `json:"message"`
+ Language string `json:"language"`
+ References []agent.Reference `json:"references"`
+ EditorContext agent.EditorContext `json:"editorContext"`
+ PluginActions []agent.PluginAction `json:"pluginActions"`
+ Model string `json:"model,omitempty"`
+ Regenerate bool `json:"regenerate"`
}
type runningSession struct {
@@ -75,7 +75,7 @@ func agentChat(c *gin.Context) {
if modelID != "" {
selectedProvider, selectedModel = model.Conf.AI.GetModel(modelID)
} else {
- selectedProvider, selectedModel = model.Conf.AI.GetScenarioModel(conf.ScenarioAgent)
+ selectedProvider, selectedModel = model.Conf.AI.GetAgentModel()
}
if nil == selectedProvider || nil == selectedModel {
ret := gulu.Ret.NewResult()
@@ -233,7 +233,7 @@ func agentChatTitle(c *gin.Context) {
if modelID != "" {
selectedProvider, selectedModel = model.Conf.AI.GetModel(modelID)
} else {
- selectedProvider, selectedModel = model.Conf.AI.GetScenarioModel(conf.ScenarioAgent)
+ selectedProvider, selectedModel = model.Conf.AI.GetAgentModel()
}
if nil == selectedProvider || nil == selectedModel {
ret := gulu.Ret.NewResult()
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index dbc7b796ee..315cffa7fe 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -234,9 +234,6 @@ func setAI(c *gin.Context) {
if nil == ai.Chat {
ai.Chat = model.Conf.AI.Chat
}
- if len(ai.Scenarios) == 0 {
- ai.Scenarios = model.Conf.AI.Scenarios
- }
for i, p := range ai.Providers {
if nil == p {
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index e94ca095ad..f3c03deabc 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -32,10 +32,10 @@ type AI struct {
Agent *Agent `json:"agent"`
Chat *Chat `json:"chat"`
Providers []*Provider `json:"providers"`
- Scenarios []*Scenario `json:"scenarios"`
}
type Agent struct {
+ ModelID string `json:"modelId"`
SessionTimeout int `json:"sessionTimeout"`
ConfirmTimeout int `json:"confirmTimeout"`
MaxRetries int `json:"maxRetries"`
@@ -48,6 +48,7 @@ type Agent struct {
// here (instead of on Model) to mirror Agent and to decouple scenario behavior
// from the model registry. See https://github.com/siyuan-note/siyuan/issues/17797
type Chat struct {
+ ModelID string `json:"modelId"`
MaxHistoryMessages int `json:"maxHistoryMessages"` // Max number of prior turns kept as context
Temperature float64 `json:"temperature"` // Alignment with Agent.Temperature
MaxCompletionTokens int `json:"maxCompletionTokens"` // Alignment with Agent.MaxCompletionTokens
@@ -76,20 +77,10 @@ type Provider struct {
// MaxContexts remain the persisted UI-facing config (the settings page still
// reads/writes them). Chat holds the runtime view derived from them.
type Model struct {
- ID string `json:"id"`
- DisplayName string `json:"displayName,omitempty"`
- Enabled bool `json:"enabled"`
- Name string `json:"name"`
-}
-
-const (
- ScenarioChat = "chat"
- ScenarioAgent = "agent"
-)
-
-type Scenario struct {
- Name string `json:"name"`
- Model string `json:"model"`
+ ID string `json:"id"`
+ DisplayName string `json:"displayName,omitempty"`
+ Enabled bool `json:"enabled"`
+ Name string `json:"name"`
}
type MCP struct {
@@ -107,8 +98,15 @@ type MCPServer struct {
Timeout int `json:"timeout"`
}
+func defaultEmbedding() *Embedding {
+ return &Embedding{Timeout: 30}
+}
+
func NewAI() *AI {
ai := &AI{
+ Providers: []*Provider{},
+ MCP: &MCP{Servers: []MCPServer{}},
+ Embedding: defaultEmbedding(),
Agent: &Agent{
SessionTimeout: 600,
ConfirmTimeout: 120,
@@ -265,23 +263,36 @@ func (ai *AI) GetModel(id string) (*Provider, *Model) {
return nil, nil
}
-func (ai *AI) GetScenarioModel(name string) (*Provider, *Model) {
- if ai.Scenarios == nil {
+func (ai *AI) GetChatModel() (*Provider, *Model) {
+ if ai.Chat == nil || ai.Chat.ModelID == "" {
return nil, nil
}
- for _, s := range ai.Scenarios {
- if s != nil && s.Name == name && s.Model != "" {
- return ai.GetModel(s.Model)
- }
+ return ai.GetModel(ai.Chat.ModelID)
+}
+
+func (ai *AI) GetAgentModel() (*Provider, *Model) {
+ if ai.Agent == nil || ai.Agent.ModelID == "" {
+ return nil, nil
}
- return nil, nil
+ return ai.GetModel(ai.Agent.ModelID)
}
func (ai *AI) Normalize() {
+ if ai.Providers == nil {
+ ai.Providers = []*Provider{}
+ }
+ if ai.MCP == nil {
+ ai.MCP = &MCP{Servers: []MCPServer{}}
+ } else if ai.MCP.Servers == nil {
+ ai.MCP.Servers = []MCPServer{}
+ }
for _, p := range ai.Providers {
if p == nil {
continue
}
+ if p.Models == nil {
+ p.Models = []*Model{}
+ }
if !ast.IsNodeIDPattern(p.ID) {
p.ID = ast.NewNodeID()
}
@@ -294,10 +305,14 @@ func (ai *AI) Normalize() {
}
}
}
- if ai.Embedding != nil {
- if !ast.IsNodeIDPattern(ai.Embedding.ID) {
- ai.Embedding.ID = ast.NewNodeID()
- }
+ if ai.Embedding == nil {
+ ai.Embedding = defaultEmbedding()
+ }
+ if ai.Embedding.Timeout < 1 {
+ ai.Embedding.Timeout = 30
+ }
+ if !ast.IsNodeIDPattern(ai.Embedding.ID) {
+ ai.Embedding.ID = ast.NewNodeID()
}
}
@@ -418,34 +433,48 @@ func MigrateAI(data []byte) *AI {
}
ai.Normalize()
+ assignDefaultModelIDs(ai)
- if len(ai.Scenarios) == 0 {
- var m *Model
- for _, p := range ai.Providers {
- if p == nil || len(p.APIKey) == 0 || !p.Enabled {
- continue
- }
- for _, model := range p.Models {
- if model != nil && model.Name != "" && model.Enabled {
- m = model
- break
- }
- }
- if m != nil {
+ return ai
+}
+
+func assignDefaultModelIDs(ai *AI) {
+ if (ai.Chat != nil && ai.Chat.ModelID != "") || (ai.Agent != nil && ai.Agent.ModelID != "") {
+ return
+ }
+ var m *Model
+ for _, p := range ai.Providers {
+ if p == nil || len(p.APIKey) == 0 || !p.Enabled {
+ continue
+ }
+ for _, model := range p.Models {
+ if model != nil && model.Name != "" && model.Enabled {
+ m = model
break
}
}
- if m == nil && len(ai.Providers) > 0 && ai.Providers[0] != nil && len(ai.Providers[0].Models) > 0 {
- m = ai.Providers[0].Models[0]
- }
- if m != nil && m.ID != "" {
- ai.Scenarios = []*Scenario{
- {Name: ScenarioChat, Model: m.ID},
- {Name: ScenarioAgent, Model: m.ID},
- }
+ if m != nil {
+ break
}
}
- return ai
+ if m == nil && len(ai.Providers) > 0 && ai.Providers[0] != nil && len(ai.Providers[0].Models) > 0 {
+ m = ai.Providers[0].Models[0]
+ }
+ if m == nil || m.ID == "" {
+ return
+ }
+ if ai.Chat == nil {
+ ai.Chat = &Chat{}
+ }
+ if ai.Chat.ModelID == "" {
+ ai.Chat.ModelID = m.ID
+ }
+ if ai.Agent == nil {
+ ai.Agent = &Agent{MaxToolCallRounds: 64}
+ }
+ if ai.Agent.ModelID == "" {
+ ai.Agent.ModelID = m.ID
+ }
}
func findProviderByBaseURL(providers []*Provider, baseURL string) *Provider {
diff --git a/kernel/model/ai.go b/kernel/model/ai.go
index db140e1e98..04c0d564ee 100644
--- a/kernel/model/ai.go
+++ b/kernel/model/ai.go
@@ -86,7 +86,7 @@ func chatGPTComplete(msg string, contextMsgs []string, cloud bool) (ret string,
util.PushEndlessProgress("Requesting...")
defer util.ClearPushProgress(100)
- prov, m := Conf.AI.GetScenarioModel(conf.ScenarioChat)
+ prov, m := Conf.AI.GetChatModel()
if nil == prov || nil == m {
err = errors.New("no AI provider configured")
return