An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797
Danield180f0a9cec5
diff --git a/app/src/assets/scss/business/_agentChat.scss b/app/src/assets/scss/business/_agentChat.scssindex bb2e4f35bd..276df05ac4 100644--- a/app/src/assets/scss/business/_agentChat.scss+++ b/app/src/assets/scss/business/_agentChat.scss@@ -579,7 +579,6 @@.agent-chat__buttons {display: flex;- justify-content: flex-end;gap: 8px;margin-top: 8px;}diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.tsindex ed2068e117..737d08eca5 100644--- a/app/src/layout/dock/AgentChat.ts+++ b/app/src/layout/dock/AgentChat.ts@@ -51,6 +51,7 @@ export class AgentChat extends Model {private currentThinkingText = "";private currentThinkingReasoning = "";private currentThinkingReasoningContent = "";+ private modelSelect: HTMLSelectElement;constructor(app: App, tab: Tab) {super({app: app});@@ -87,7 +88,9 @@ export class AgentChat extends Model {'<div class="agent-chat__input-area">' +'<div class="agent-chat__composer-host"></div>' +'<div class="agent-chat__buttons">' ++ '<select class="agent-chat__model b3-select"></select>' +'<span class="agent-chat__tokens fn__none"></span>' ++ '<span class="fn__flex-1"></span>' +'<button class="agent-chat__send b3-button b3-button--text">' + (L.agentSend || "Send") + "</button>" +'<button class="agent-chat__stop b3-button b3-button--cancel fn__none">' + (L.agentStop || "Stop") + "</button>" +"</div>" +@@ -102,12 +105,31 @@ export class AgentChat extends Model {this.sessionMenuBtn = panel.querySelector('.block__icon[data-type="session-menu"]') as HTMLElement;this.titleElement = panel.querySelector(".agent-chat__title") as HTMLElement;this.tokenDisplayEl = panel.querySelector(".agent-chat__tokens") as HTMLElement;+ this.modelSelect = panel.querySelector(".agent-chat__model") as HTMLSelectElement;++ this.initModelSelect();const self = this;this.composer = mountComposer(this.composerHost, function () { self.sendMessage(); });this.initSessions();}+ private initModelSelect() {+ const aiConfig = window.siyuan.config.ai;+ const mainModel = aiConfig.openAI.apiModel;+ const providers = aiConfig.providers || [];+ let html = '<option value="">' + this.escapeHtml(mainModel) + "</option>";+ for (const p of providers) {+ if (p.enabled === false) { continue; }+ html += '<option value="' + this.escapeHtml(p.apiModel) + '">' + this.escapeHtml(p.apiModel) + "</option>";+ }+ this.modelSelect.innerHTML = html;+ }++ private getSelectedModel(): string {+ return this.modelSelect.value;+ }+private showWelcome() {const L = window.siyuan.languages;const html = '<div class="agent-welcome">' +@@ -147,7 +169,8 @@ export class AgentChat extends Model {self.handleError(err);},self.abortController.signal,- self.sessionId);+ self.sessionId,+ self.getSelectedModel());}};}(examples[i] as HTMLElement));@@ -174,6 +197,7 @@ export class AgentChat extends Model {getDockByType("agentChat").toggleModel("agentChat", false, true);return;}+ if (t.closest(".agent-chat__model")) { return; }if (self.composer) { self.composer.focus(); }});}@@ -354,6 +378,7 @@ export class AgentChat extends Model {private async switchSession(id: string) {this.setStreaming(false);+ this.flushThinkingStep();await this.saveSession();const session = await SessionStore.load(id);if (!session) { return; }@@ -462,6 +487,7 @@ export class AgentChat extends Model {this.abortController = null;}this.setStreaming(false);+ this.flushThinkingStep();await this.saveSession();this.sessionId = SessionStore.newSessionId();this.sessionCreatedAt = Date.now();@@ -572,6 +598,7 @@ export class AgentChat extends Model {},this.abortController.signal,this.sessionId,+ this.getSelectedModel(),);}@@ -731,6 +758,7 @@ export class AgentChat extends Model {toolCalls: tc,reasoningContent: this.currentThinkingReasoningContent,});+ this.saveSession();}this.finishActiveThinking();this.currentThinkingText = "";@@ -802,6 +830,7 @@ export class AgentChat extends Model {}private appendReasoning(token: string) {+ this.currentThinkingReasoningContent += token;const thinking = this.messagesContainer.querySelector(".agent-chat__msg--thinking:last-child .agent-chat__thinking-body");if (!thinking) { return; }thinking.innerHTML += token;@@ -869,6 +898,13 @@ export class AgentChat extends Model {if (all[i].classList.contains("agent-chat__msg--user")) { break; }all[i].remove();}+ // Remove last group of thinking steps+ for (let i = this.thinkingSteps.length - 1; i >= 0; i--) {+ if (this.thinkingSteps[i].reasoning === "analyzing") {+ this.thinkingSteps.splice(i);+ break;+ }+ }this.currentAIElement = null;this.currentContent = "";this.fullContent = "";@@ -894,6 +930,7 @@ export class AgentChat extends Model {},this.abortController.signal,this.sessionId,+ this.getSelectedModel(),);}@@ -968,6 +1005,7 @@ export class AgentChat extends Model {reasoningContent: this.currentThinkingReasoningContent,});this.currentThinkingText = "";+ this.saveSession();}private generateTitle() {@@ -997,6 +1035,7 @@ export class AgentChat extends Model {el.innerHTML = '<div class="agent-chat__bubble agent-chat__bubble--error">' + this.escapeHtml(message) + "</div>";this.messagesContainer.appendChild(el);this.scrollToBottom();+ this.flushThinkingStep();this.saveSession();}@@ -1041,6 +1080,8 @@ export class AgentChat extends Model {}this.updateTokenDisplay();this.setStreaming(false);+ this.flushThinkingStep();+ this.saveSession();}private insertBeforeAI(el: HTMLElement) {diff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.tsindex 25e52711e2..7a0adeaa10 100644--- a/app/src/util/agentSSE.ts+++ b/app/src/util/agentSSE.ts@@ -47,10 +47,12 @@ export async function fetchAgentSSE(onError: (err: Error) => void,signal?: AbortSignal,sessionID?: string,+ model?: string,): Promise<void> {try {const body: Record<string, unknown> = {messages: messages, language: language, references: references};if (sessionID) { body.sessionID = sessionID; }+ if (model) { body.model = model; }const response = await fetch("/api/ai/agent/chat", {method: "POST",diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex da7cb92e66..050a57fae4 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -36,6 +36,7 @@ type agentChatReq struct {Messages []agent.UserMessage `json:"messages"`Language string `json:"language"`References []agent.Reference `json:"references"`+ Model string `json:"model,omitempty"`}type runningSession struct {@@ -46,7 +47,7 @@ var sessionsMu sync.Mutexvar runningSessions = map[string]*runningSession{}func agentChat(c *gin.Context) {- if "" == model.Conf.AI.OpenAI.APIKey {+ if !model.Conf.AI.HasAnyProvider() {ret := gulu.Ret.NewResult()ret.Code = -1ret.Msg = model.Conf.Language(193)@@ -63,27 +64,28 @@ func agentChat(c *gin.Context) {return}+ selectedProvider := model.Conf.AI.GetProvider(req.Model)client := util.NewOpenAIClient(- model.Conf.AI.OpenAI.APIKey,- model.Conf.AI.OpenAI.APIProxy,- model.Conf.AI.OpenAI.APIBaseURL,- model.Conf.AI.OpenAI.APIUserAgent,- model.Conf.AI.OpenAI.APIVersion,- model.Conf.AI.OpenAI.APIProvider,+ selectedProvider.APIKey,+ selectedProvider.APIProxy,+ selectedProvider.APIBaseURL,+ selectedProvider.APIUserAgent,+ selectedProvider.APIVersion,+ selectedProvider.APIProvider,)- confirmTimeout := time.Duration(model.Conf.AI.OpenAI.AgentConfirmTimeout) * time.Second+ confirmTimeout := time.Duration(selectedProvider.AgentConfirmTimeout) * time.Secondif confirmTimeout <= 0 {confirmTimeout = 120 * time.Second}- maxRetries := model.Conf.AI.OpenAI.AgentMaxRetries+ maxRetries := selectedProvider.AgentMaxRetriesif maxRetries <= 0 {maxRetries = 3}var eventCh <-chan agent.AgentEvent- eventCh = agent.AgentChat(context.Background(), client, model.Conf.AI.OpenAI.APIModel, req.SessionID, req.Messages, req.Language, req.References, confirmTimeout, maxRetries)+ eventCh = agent.AgentChat(context.Background(), client, selectedProvider.APIModel, req.SessionID, req.Messages, req.Language, req.References, confirmTimeout, maxRetries)sessionsMu.Lock()runningSessions[req.SessionID] = &runningSession{eventCh: eventCh}sessionsMu.Unlock()@@ -97,11 +99,11 @@ func agentChat(c *gin.Context) {return}- timeout := model.Conf.AI.OpenAI.APITimeout+ timeout := selectedProvider.APITimeoutif timeout <= 0 {timeout = 30}- totalTimeout := time.Duration(model.Conf.AI.OpenAI.AgentTimeout) * time.Second+ totalTimeout := time.Duration(selectedProvider.AgentTimeout) * time.Secondif totalTimeout <= 0 {totalTimeout = time.Duration(timeout) * time.Second * 10}@@ -184,16 +186,17 @@ func agentChatTitle(c *gin.Context) {return}+ selectedProvider := model.Conf.AI.GetProvider("")client := util.NewOpenAIClient(- model.Conf.AI.OpenAI.APIKey,- model.Conf.AI.OpenAI.APIProxy,- model.Conf.AI.OpenAI.APIBaseURL,- model.Conf.AI.OpenAI.APIUserAgent,- model.Conf.AI.OpenAI.APIVersion,- model.Conf.AI.OpenAI.APIProvider,+ selectedProvider.APIKey,+ selectedProvider.APIProxy,+ selectedProvider.APIBaseURL,+ selectedProvider.APIUserAgent,+ selectedProvider.APIVersion,+ selectedProvider.APIProvider,)- title := agent.GenerateTitle(client, model.Conf.AI.OpenAI.APIModel, req.Message)+ title := agent.GenerateTitle(client, selectedProvider.APIModel, req.Message)ret := gulu.Ret.NewResult()ret.Data = titlec.JSON(http.StatusOK, ret)diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 38aeeefb02..3b41a51e58 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -26,8 +26,9 @@ import ()type AI struct {- OpenAI *OpenAI `json:"openAI"`- MCP *MCPConfig `json:"mcp"`+ OpenAI *OpenAI `json:"openAI"`+ MCP *MCPConfig `json:"mcp"`+ Providers []*OpenAI `json:"providers,omitempty"`}type MCPConfig struct {@@ -63,6 +64,7 @@ type OpenAI struct {AgentTimeout int `json:"agentTimeout"` // total session timeout, seconds, 0 = no limitAgentConfirmTimeout int `json:"agentConfirmTimeout"` // confirmation timeout, secondsAgentMaxRetries int `json:"agentMaxRetries"` // max API retry attempts on failure+ Enabled *bool `json:"enabled,omitempty"`}func NewAI() *AI {@@ -146,3 +148,39 @@ func NewAI() *AI {}return &AI{OpenAI: openAI}}++func (p *OpenAI) IsEnabled() bool {+ return p.Enabled == nil || *p.Enabled+}++func (ai *AI) HasAnyProvider() bool {+ if ai.OpenAI != nil && ai.OpenAI.APIKey != "" && ai.OpenAI.IsEnabled() {+ return true+ }+ for _, p := range ai.Providers {+ if p != nil && p.APIKey != "" && p.IsEnabled() {+ return true+ }+ }+ return false+}++func (ai *AI) GetProvider(model string) *OpenAI {+ if model == "" {+ if ai.OpenAI != nil && ai.OpenAI.IsEnabled() && ai.OpenAI.APIKey != "" {+ return ai.OpenAI+ }+ for _, p := range ai.Providers {+ if p != nil && p.IsEnabled() && p.APIKey != "" {+ return p+ }+ }+ return ai.OpenAI+ }+ for _, p := range ai.Providers {+ if p != nil && p.APIModel == model && p.IsEnabled() && p.APIKey != "" {+ return p+ }+ }+ return ai.OpenAI+}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 61863cd266..7a9cb78118 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -570,6 +570,10 @@ func InitConf() {if 1 > Conf.AI.OpenAI.APIMaxContexts || 64 < Conf.AI.OpenAI.APIMaxContexts {Conf.AI.OpenAI.APIMaxContexts = 7}+ if nil == Conf.AI.OpenAI.Enabled && Conf.AI.OpenAI.APIBaseURL != "" && Conf.AI.OpenAI.APIKey != "" {+ t := true+ Conf.AI.OpenAI.Enabled = &t+ }if "" != Conf.AI.OpenAI.APIKey {logging.LogInfof("OpenAI API enabled\n"+