Skip to content

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

:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797

Daniel8f3473a7f0c1
diff --git a/app/src/config/ai.ts b/app/src/config/ai.ts
index b768d84a0f..41f5f3421e 100644
--- a/app/src/config/ai.ts
+++ b/app/src/config/ai.ts
@@ -45,6 +45,32 @@ export const ai = {
<input class="b3-text-field fn__flex-center fn__block" type="number" step="1" min="1" max="64" id="apiMaxContexts" value="${window.siyuan.config.ai.openAI.apiMaxContexts}"/>
<div class="b3-label__text">${window.siyuan.languages.apiMaxContextsTip}</div>
</div>
+<div class="b3-label">
+ ${window.siyuan.languages.agentTimeout || "Agent Timeout"}
+ <div class="fn__hr"></div>
+ <div class="fn__flex">
+ <input class="b3-text-field fn__flex-1" type="number" step="1" min="0" id="agentTimeout" value="${window.siyuan.config.ai.openAI.agentTimeout || 600}"/>
+ <span class="fn__space"></span>
+ <span class="ft__on-surface fn__flex-center">s</span>
+ </div>
+ <div class="b3-label__text">${window.siyuan.languages.agentTimeoutTip || "0 = no limit"}</div>
+</div>
+<div class="b3-label">
+ ${window.siyuan.languages.agentConfirmTimeout || "Confirm Timeout"}
+ <div class="fn__hr"></div>
+ <div class="fn__flex">
+ <input class="b3-text-field fn__flex-1" type="number" step="1" min="10" max="600" id="agentConfirmTimeout" value="${window.siyuan.config.ai.openAI.agentConfirmTimeout || 120}"/>
+ <span class="fn__space"></span>
+ <span class="ft__on-surface fn__flex-center">s</span>
+ </div>
+ <div class="b3-label__text">${window.siyuan.languages.agentConfirmTimeoutTip || "Auto reject after timeout"}</div>
+</div>
+<div class="b3-label">
+ ${window.siyuan.languages.agentMaxRetries || "Max Retries"}
+ <div class="fn__hr"></div>
+ <input class="b3-text-field fn__flex-center fn__block" type="number" step="1" min="0" max="10" id="agentMaxRetries" value="${window.siyuan.config.ai.openAI.agentMaxRetries || 3}"/>
+ <div class="b3-label__text">${window.siyuan.languages.agentMaxRetriesTip || "Max API retry attempts on failure"}</div>
+</div>
<div class="b3-label">
${window.siyuan.languages.apiModel}
<div class="fn__hr"></div>
@@ -132,6 +158,38 @@ export const ai = {
<span class="fn__space"></span>
<input class="b3-text-field fn__flex-center fn__size200" type="number" step="1" min="1" max="64" id="apiMaxContexts" value="${window.siyuan.config.ai.openAI.apiMaxContexts}"/>
</div>
+<div class="fn__flex b3-label">
+ <div class="fn__flex-1">
+ ${window.siyuan.languages.agentTimeout || "Agent Timeout"}
+ <div class="b3-label__text">${window.siyuan.languages.agentTimeoutTip || "0 = no limit"}</div>
+ </div>
+ <span class="fn__space"></span>
+ <div class="fn__size200 fn__flex-center fn__flex">
+ <input class="b3-text-field fn__flex-1" type="number" step="1" min="0" id="agentTimeout" value="${window.siyuan.config.ai.openAI.agentTimeout || 600}"/>
+ <span class="fn__space"></span>
+ <span class="ft__on-surface fn__flex-center">s</span>
+ </div>
+</div>
+<div class="fn__flex b3-label">
+ <div class="fn__flex-1">
+ ${window.siyuan.languages.agentConfirmTimeout || "Confirm Timeout"}
+ <div class="b3-label__text">${window.siyuan.languages.agentConfirmTimeoutTip || "Auto reject after timeout"}</div>
+ </div>
+ <span class="fn__space"></span>
+ <div class="fn__size200 fn__flex-center fn__flex">
+ <input class="b3-text-field fn__flex-1" type="number" step="1" min="10" max="600" id="agentConfirmTimeout" value="${window.siyuan.config.ai.openAI.agentConfirmTimeout || 120}"/>
+ <span class="fn__space"></span>
+ <span class="ft__on-surface fn__flex-center">s</span>
+ </div>
+</div>
+<div class="fn__flex b3-label">
+ <div class="fn__flex-1">
+ ${window.siyuan.languages.agentMaxRetries || "Max Retries"}
+ <div class="b3-label__text">${window.siyuan.languages.agentMaxRetriesTip || "Max API retry attempts on failure"}</div>
+ </div>
+ <span class="fn__space"></span>
+ <input class="b3-text-field fn__flex-center fn__size200" type="number" step="1" min="0" max="10" id="agentMaxRetries" value="${window.siyuan.config.ai.openAI.agentMaxRetries || 3}"/>
+</div>
<div class="fn__flex b3-label">
<div class="fn__block">
${window.siyuan.languages.apiModel}
@@ -208,6 +266,9 @@ export const ai = {
apiProxy: (ai.element.querySelector("#apiProxy") as HTMLInputElement).value,
apiTimeout: parseInt((ai.element.querySelector("#apiTimeout") as HTMLInputElement).value),
apiProvider: (ai.element.querySelector("#apiProvider") as HTMLSelectElement).value,
+ agentTimeout: parseInt((ai.element.querySelector("#agentTimeout") as HTMLInputElement).value),
+ agentConfirmTimeout: parseInt((ai.element.querySelector("#agentConfirmTimeout") as HTMLInputElement).value),
+ agentMaxRetries: parseInt((ai.element.querySelector("#agentMaxRetries") as HTMLInputElement).value),
}
}, response => {
window.siyuan.config.ai = response.data;
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts
index a8c76524ed..8cae3926e5 100644
--- a/app/src/layout/dock/AgentChat.ts
+++ b/app/src/layout/dock/AgentChat.ts
@@ -8,6 +8,11 @@ import {AgentSession, SessionStore} from "./SessionStore";
interface IAgentMessage {
role: "user" | "assistant";
content: string;
+ toolCalls?: Array<{
+ name: string;
+ arguments: Record<string, unknown>;
+ result?: string;
+ }>;
}
export class AgentChat extends Model {
@@ -35,6 +40,7 @@ export class AgentChat extends Model {
private requestStartTime = 0;
private tokenDisplayEl: HTMLElement;
private defaultTitle = "";
+ private currentToolCalls: Array<{name: string; arguments: Record<string, unknown>; result?: string}> = [];
constructor(app: App, tab: Tab) {
super({app: app, id: tab.id});
@@ -114,14 +120,14 @@ export class AgentChat extends Model {
// 不支持 setSendText,直接用 sendMessage 发送
self.messages.push({role: "user", content: text});
self.appendUserMessage(text);
- self.currentAIElement = self.createAIMessagePlaceholder();
self.setStreaming(true);
var apiMessages = self.messages.map(function (m) { return {role: m.role, content: m.content}; });
self.abortController = new AbortController();
fetchAgentSSE(apiMessages, window.siyuan.config.appearance.lang, [],
function (event: ISSEResult) { self.handleSSEEvent(event); },
function (err: Error) { self.handleError(err); },
- self.abortController.signal);
+ self.abortController.signal,
+ self.sessionId);
}
};
}(examples[i] as HTMLElement));
@@ -169,7 +175,11 @@ export class AgentChat extends Model {
if (msg.role === "user") {
this.appendUserMessage(msg.content);
} else if (msg.role === "assistant") {
- this.appendPersistedAssistant(msg.content);
+ if (msg.toolCalls && msg.toolCalls.length > 0) {
+ this.appendPersistedToolCalls(msg.content, msg.toolCalls);
+ } else {
+ this.appendPersistedAssistant(msg.content);
+ }
}
}
this.scrollToBottom();
@@ -337,7 +347,11 @@ export class AgentChat extends Model {
if (msg.role === "user") {
this.appendUserMessage(msg.content);
} else if (msg.role === "assistant") {
- this.appendPersistedAssistant(msg.content);
+ if (msg.toolCalls && msg.toolCalls.length > 0) {
+ this.appendPersistedToolCalls(msg.content, msg.toolCalls);
+ } else {
+ this.appendPersistedAssistant(msg.content);
+ }
}
}
this.scrollToBottom();
@@ -350,6 +364,50 @@ export class AgentChat extends Model {
this.messagesContainer.appendChild(el);
}
+ private appendPersistedToolCalls(content: string, toolCalls: Array<{name: string; arguments: Record<string, unknown>; result?: string}>) {
+ if (content) {
+ this.appendPersistedAssistant(content);
+ }
+ var L = window.siyuan.languages;
+ for (var i = 0; i < toolCalls.length; i++) {
+ var tc = toolCalls[i];
+ var argsStr = JSON.stringify(tc.arguments, null, 2);
+ var el = document.createElement("div");
+ el.className = "agent-chat__msg agent-chat__msg--tool";
+ el.innerHTML = '<div class="agent-chat__tool-card agent-chat__tool-card--call" data-tool="' + tc.name + '">' +
+ '<div class="agent-chat__tool-header">' +
+ '<span class="agent-chat__tool-icon">&#128736;</span>' +
+ '<span class="agent-chat__tool-title">' + (L.agentToolCall || "Calling tool") + ': ' + tc.name + '</span>' +
+ '</div>' +
+ '<pre class="agent-chat__tool-body fn__none">' + this.escapeHtml(argsStr) + '</pre>' +
+'</div>';
+ var header = el.querySelector(".agent-chat__tool-header") as HTMLElement;
+ var body = el.querySelector(".agent-chat__tool-body") as HTMLElement;
+ header.addEventListener("click", function () {
+ body.classList.toggle("fn__none");
+ });
+ this.messagesContainer.appendChild(el);
+
+ if (tc.result) {
+ var rel = document.createElement("div");
+ rel.className = "agent-chat__msg agent-chat__msg--tool";
+ rel.innerHTML = '<div class="agent-chat__tool-card agent-chat__tool-card--result" data-tool="' + tc.name + '">' +
+ '<div class="agent-chat__tool-header">' +
+ '<span class="agent-chat__tool-icon">&#128196;</span>' +
+ '<span class="agent-chat__tool-title">' + (L.agentToolResult || "Tool result") + ': ' + tc.name + '</span>' +
+ '</div>' +
+ '<pre class="agent-chat__tool-body fn__none">' + this.escapeHtml(tc.result) + '</pre>' +
+'</div>';
+ var rheader = rel.querySelector(".agent-chat__tool-header") as HTMLElement;
+ var rbody = rel.querySelector(".agent-chat__tool-body") as HTMLElement;
+ rheader.addEventListener("click", function () {
+ rbody.classList.toggle("fn__none");
+ });
+ this.messagesContainer.appendChild(rel);
+ }
+ }
+ }
+
private async createSession() {
await this.saveSession();
this.sessionId = SessionStore.newSessionId();
@@ -362,6 +420,7 @@ export class AgentChat extends Model {
this.sessionPromptTokens = 0;
this.sessionCompletionTokens = 0;
this.sessionTotalDuration = 0;
+ this.currentToolCalls = [];
if (this.tokenDisplayEl) {
this.tokenDisplayEl.style.display = "none";
}
@@ -401,7 +460,6 @@ export class AgentChat extends Model {
this.appendUserMessage(text);
this.requestStartTime = Date.now();
- this.currentAIElement = this.createAIMessagePlaceholder();
var apiMessages = this.messages.map(function (m) { return {role: m.role, content: m.content}; });
var self = this;
@@ -415,6 +473,7 @@ export class AgentChat extends Model {
function (event: ISSEResult) { self.handleSSEEvent(event); },
function (err: Error) { self.handleError(err); },
this.abortController.signal,
+ this.sessionId,
);
}
@@ -427,12 +486,16 @@ export class AgentChat extends Model {
this.appendThinking(event.reasoning);
break;
case "tool_call":
+ this.currentToolCalls.push({name: event.name, arguments: event.arguments});
this.appendToolCall(event.name, event.arguments);
break;
case "confirm":
this.appendConfirm(event.name, event.arguments, event.confirmID);
break;
case "tool_result":
+ if (this.currentToolCalls.length > 0) {
+ this.currentToolCalls[this.currentToolCalls.length - 1].result = event.result;
+ }
this.appendToolResult(event.name, event.result);
break;
case "done":
@@ -445,6 +508,9 @@ export class AgentChat extends Model {
this.appendError(event.message);
this.setStreaming(false);
break;
+ case "retry":
+ this.appendRetry(event.attempt, event.maxRetries);
+ break;
}
}
@@ -473,7 +539,7 @@ export class AgentChat extends Model {
private appendToken(token: string) {
if (!this.currentAIElement) {
- return;
+ this.currentAIElement = this.createAIMessagePlaceholder();
}
var bubble = this.currentAIElement.querySelector(".agent-chat__bubble") as HTMLElement;
if (!bubble) {
@@ -607,10 +673,11 @@ export class AgentChat extends Model {
if (bubble) {
bubble.classList.remove("agent-chat__bubble--streaming");
}
- this.messages.push({role: "assistant", content: this.fullContent || " "});
+ this.messages.push({role: "assistant", content: this.fullContent || " ", toolCalls: this.currentToolCalls.length > 0 ? this.currentToolCalls.slice() : undefined});
this.currentAIElement = null;
this.currentContent = "";
this.fullContent = "";
+ this.currentToolCalls = [];
if (this.requestStartTime) {
this.sessionTotalDuration += Date.now() - this.requestStartTime;
this.requestStartTime = 0;
@@ -651,6 +718,20 @@ export class AgentChat extends Model {
this.saveSession();
}
+ private appendRetry(attempt: number, maxRetries: number) {
+ this.clearThinking();
+ var el = document.createElement("div");
+ el.className = "agent-chat__msg agent-chat__msg--thinking";
+ el.innerHTML = '<div class="agent-chat__thinking-card">' +
+ '<div class="agent-chat__thinking-header">' +
+ '<span class="agent-chat__thinking-dot"></span>' +
+ '<span class="agent-chat__thinking-text">' + this.escapeHtml("Retrying (" + attempt + "/" + maxRetries + ")...") + '</span>' +
+ '</div>' +
+'</div>';
+ this.insertBeforeAI(el);
+ this.scrollToBottom();
+ }
+
private stopGeneration() {
if (this.abortController) {
this.abortController.abort();
@@ -662,11 +743,13 @@ export class AgentChat extends Model {
bubble.classList.remove("agent-chat__bubble--streaming");
}
if (this.fullContent) {
- this.messages.push({role: "assistant", content: this.fullContent || " "});
+ this.messages.push({role: "assistant", content: this.fullContent || " ", toolCalls: this.currentToolCalls.length > 0 ? this.currentToolCalls.slice() : undefined});
}
- this.currentAIElement = null;
- this.currentContent = "";
- this.fullContent = "";
+ this.currentAIElement = null;
+ this.currentContent = "";
+ this.fullContent = "";
+ this.currentToolCalls = [];
+ this.currentToolCalls = [];
}
if (this.requestStartTime) {
this.sessionTotalDuration += Date.now() - this.requestStartTime;
diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.ts
index 48a6139e52..fe0d31b20b 100644
--- a/app/src/layout/dock/SessionStore.ts
+++ b/app/src/layout/dock/SessionStore.ts
@@ -13,7 +13,15 @@ interface SessionIndexItem {
export interface AgentSession {
id: string;
title: string;
- messages: Array<{role: string; content: string}>;
+ messages: Array<{
+ role: string;
+ content: string;
+ toolCalls?: Array<{
+ name: string;
+ arguments: Record<string, unknown>;
+ result?: string;
+ }>;
+ }>;
promptTokens?: number;
completionTokens?: number;
totalDuration?: number;
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index a544aae3bd..bb42bb2671 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -158,6 +158,18 @@ declare namespace Config {
* API request timeout (unit: seconds)
*/
apiTimeout: number;
+ /**
+ * Agent total session timeout (unit: seconds, 0 = no limit)
+ */
+ agentTimeout?: number;
+ /**
+ * Agent confirmation timeout (unit: seconds), auto-rejects on timeout
+ */
+ agentConfirmTimeout?: number;
+ /**
+ * Agent API maximum retry attempts on failure
+ */
+ agentMaxRetries?: number;
/**
* API request additional user agent field
*/
diff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.ts
index a29a2605f6..9cb4a2e3bb 100644
--- a/app/src/util/agentSSE.ts
+++ b/app/src/util/agentSSE.ts
@@ -26,6 +26,10 @@ export type ISSEResult = {
type: "usage";
promptTokens: number;
completionTokens: number;
+} | {
+ type: "retry";
+ attempt: number;
+ maxRetries: number;
};
export async function fetchAgentSSE(
@@ -35,12 +39,16 @@ export async function fetchAgentSSE(
onEvent: (event: ISSEResult) => void,
onError: (err: Error) => void,
signal?: AbortSignal,
+ sessionID?: string,
): Promise<void> {
try {
+ var body: Record<string, unknown> = {messages: messages, language: language, references: references};
+ if (sessionID) { body.sessionID = sessionID; }
+
var response = await fetch("/api/ai/agent/chat", {
method: "POST",
headers: {"Content-Type": "application/json"},
- body: JSON.stringify({messages: messages, language: language, references: references}),
+ body: JSON.stringify(body),
signal: signal,
});
@@ -134,6 +142,12 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResul
promptTokens: (data.promptTokens as number) || 0,
completionTokens: (data.completionTokens as number) || 0,
};
+ case "retry":
+ return {
+ type: "retry",
+ attempt: (data.attempt as number) || 1,
+ maxRetries: (data.maxRetries as number) || 1,
+ };
default:
return null;
}
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 82de4769d1..c37cc488b2 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -18,18 +18,44 @@ package agent
import (
"context"
+ "encoding/json"
"io"
+ "os"
+ "path/filepath"
"strings"
+ "time"
"github.com/sashabaranov/go-openai"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
-const systemPrompt = `You are a SiYuan AI assistant. You can search, read, create, and modify the user's notes.
-
-Rules:
-1. Confirm the user's intent before taking action
-2. Summarize key points instead of listing everything when there are many search results
-3. Ask for confirmation before deleting anything`
+const systemPrompt = `You are a SiYuan AI assistant. You help users manage their notes, documents, and knowledge base through the tools provided.
+
+## Domain Concepts
+- Block: the fundamental unit. Everything in SiYuan is a block with a unique ID, including documents themselves. A document block (type: NodeDocument) is the root block of a document. All content blocks (headings, paragraphs, lists, code, tables, etc.) live as children under a document block, forming a tree. Use block.get to read any block by its ID, block.get_children to browse sub-blocks, block.update to modify, block.append/insert to add content, block.delete to remove.
+- Notebook: a top-level container holding documents. Use notebook.list to see all notebooks. Specify notebook ID when creating documents.
+- hPath (human-readable path): the title-based path shown in the document tree, e.g. "/Diary/2024/June". The "path" parameter in document tools (document.create, document.move, document.list) refers to hPath, not the internal ID-based filesystem path. When a document is renamed, its hPath changes but its ID stays the same.
+
+## Tool Usage Patterns
+- Finding information: search.fulltext (keyword) → block.get (by ID) to read full content. For semantic search use search.semantic.
+- Exploring structure: document.list (see child documents under an hPath) → document.get (read document metadata and content) → block.get_children (list blocks inside a document) → block.get (read a specific block). Use breadcrumb to trace a block's location path.
+- Creating content: document.create specifies the target notebook and hPath to create a document → block.append/prepend/insert to add blocks into the document. Use dataType "markdown" for text content.
+- Modifying content: block.update with a block's ID and new markdown content.
+- Organizing: document.move (change a document's hPath), document.rename (change a document's title), block.move (reposition a block within a document).
+- Attributes/properties: use attr.get/set to read/write custom attributes on any block. Use database tools for spreadsheets/attribute views.
+
+## Response Guidelines
+- Reply in the language indicated by the user.
+- Provide context: when mentioning documents or blocks, include their titles and IDs so the user can reference them.
+- Be concise: summarize key findings rather than repeating large amounts of content.
+- Use markdown formatting for readability: bullet points, headings, code blocks for technical content.
+
+## Safety
+- Confirm before deleting documents, blocks, or data.
+- Confirm before moving or renaming important items.
+- Read operations (get, list, search, query) are always safe and do not need confirmation.
+- Do not expose or log API keys, passwords, or sensitive configuration.`
const maxToolCallRounds = 64
@@ -53,6 +79,8 @@ type AgentEvent struct {
Error string
PromptTokens int
CompletionTokens int
+ RetryAttempt int
+ RetryMax int
}
type UserMessage struct {
@@ -60,12 +88,35 @@ type UserMessage struct {
Content string `json:"content"`
}
+type AgentMessage struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+ ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`
+}
+
+type AgentToolCall struct {
+ Name string `json:"name"`
+ Arguments map[string]interface{} `json:"arguments"`
+ Result string `json:"result,omitempty"`
+}
+
type Reference struct {
ID string `json:"id"`
Title string `json:"title"`
}
-func AgentChat(ctx context.Context, client *openai.Client, model string, history []UserMessage, language string, references []Reference) <-chan AgentEvent {
+type agentCheckpoint struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Messages []AgentMessage `json:"messages"`
+ PromptTokens int `json:"promptTokens"`
+ CompletionTokens int `json:"completionTokens"`
+ TotalDuration int64 `json:"totalDuration"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
+
+func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, history []UserMessage, language string, references []Reference, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {
ch := make(chan AgentEvent, 100)
go func() {
@@ -74,6 +125,12 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, history
tools := convertMCPToolsToOpenAI()
messages := buildMessages(history, language, references)
var totalPrompt, totalCompletion int
+ startTime := time.Now().UnixMilli()
+
+ checkpointMsgs := make([]AgentMessage, 0, len(history))
+ for _, h := range history {
+ checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: h.Role, Content: h.Content})
+ }
for round := 0; round < maxToolCallRounds; round++ {
select {
@@ -98,9 +155,10 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, history
MaxCompletionTokens: 4096,
}
- stream, err := client.CreateChatCompletionStream(ctx, req)
- if err != nil {
- ch <- AgentEvent{Type: "error", Error: "API request failed: " + err.Error()}
+ stream, streamErr := createStreamWithRetry(ctx, client, req, maxRetries, ch)
+ if streamErr != nil {
+ ch <- AgentEvent{Type: "error", Error: "API request failed: " + streamErr.Error()}
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
return
}
@@ -161,7 +219,20 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, history
ToolCalls: aggregatedToolCalls,
})
+ checkpointMsg := AgentMessage{
+ Role: "assistant",
+ Content: contentBuilder.String(),
+ }
for _, tc := range aggregatedToolCalls {
+ checkpointMsg.ToolCalls = append(checkpointMsg.ToolCalls, AgentToolCall{
+ Name: tc.Function.Name,
+ Arguments: parseToolArgs(tc.Function.Arguments),
+ })
+ }
+ checkpointMsgs = append(checkpointMsgs, checkpointMsg)
+ assistantIdx := len(checkpointMsgs) - 1
+
+ for i, tc := range aggregatedToolCalls {
args := parseToolArgs(tc.Function.Arguments)
action := ""
if a, ok := args["action"]; ok {
@@ -179,21 +250,36 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, history
ch <- AgentEvent{Type: "confirm", Name: tc.Function.Name, Arguments: args, ConfirmID: confirmID}
ch2 := make(chan bool, 1)
confirmChannels[confirmID] = ch2
+ var confirmResult string
+ var approved bool
+ timedOut := false
+
select {
- case approved := <-ch2:
+ case approved = <-ch2:
delete(confirmChannels, confirmID)
- if !approved {
- ch <- AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: "User rejected this operation"}
- messages = append(messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleTool,
- Content: "User rejected this operation",
- ToolCallID: tc.ID,
- })
- continue
- }
case <-ctx.Done():
delete(confirmChannels, confirmID)
return
+ case <-time.After(confirmTimeout):
+ delete(confirmChannels, confirmID)
+ timedOut = true
+ confirmResult = "Confirmation timed out, operation skipped automatically"
+ ch <- AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: confirmResult}
+ }
+
+ if timedOut || !approved {
+ if confirmResult == "" {
+ confirmResult = "User rejected this operation"
+ ch <- AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: confirmResult}
+ }
+ messages = append(messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleTool,
+ Content: confirmResult,
+ ToolCallID: tc.ID,
+ })
+ checkpointMsgs[assistantIdx].ToolCalls[i].Result = confirmResult
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
+ continue
}
}
@@ -210,11 +296,15 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, history
Content: result,
ToolCallID: tc.ID,
})
+ checkpointMsgs[assistantIdx].ToolCalls[i].Result = result
}
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
continue
}
content := contentBuilder.String()
+ checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content})
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
if content == "" {
content = " "
}
@@ -229,6 +319,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, history
}
ch <- AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion}
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
ch <- AgentEvent{Type: "done"}
}()
@@ -355,3 +446,97 @@ func langName(lang string) string {
return "English"
}
}
+
+func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int, completionTokens int, startTime int64) {
+ if sessionID == "" {
+ return
+ }
+
+ cp := agentCheckpoint{
+ ID: sessionID,
+ Title: "AI Agent",
+ Messages: messages,
+ PromptTokens: promptTokens,
+ CompletionTokens: completionTokens,
+ TotalDuration: time.Now().UnixMilli() - startTime,
+ CreatedAt: startTime,
+ UpdatedAt: time.Now().UnixMilli(),
+ }
+
+ dir := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions")
+ _ = os.MkdirAll(dir, 0755)
+
+ path := filepath.Join(dir, sessionID+".json")
+ existing, err := os.ReadFile(path)
+ if err == nil {
+ var old agentCheckpoint
+ if json.Unmarshal(existing, &old) == nil && old.Title != "" && old.Title != "AI Agent" {
+ cp.Title = old.Title
+ }
+ if old.CreatedAt > 0 {
+ cp.CreatedAt = old.CreatedAt
+ }
+ }
+
+ data, err := json.MarshalIndent(cp, "", " ")
+ if err != nil {
+ return
+ }
+ _ = filelock.WriteFile(path, data)
+}
+
+func createStreamWithRetry(ctx context.Context, client *openai.Client, req openai.ChatCompletionRequest, maxRetries int, ch chan<- AgentEvent) (*openai.ChatCompletionStream, error) {
+ if maxRetries <= 0 {
+ maxRetries = 1
+ }
+
+ var lastErr error
+ for attempt := 0; attempt < maxRetries; attempt++ {
+ if attempt > 0 {
+ backoff := time.Duration(1<<uint(attempt-1)) * time.Second
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(backoff):
+ }
+ ch <- AgentEvent{Type: "retry", RetryAttempt: attempt + 1, RetryMax: maxRetries}
+ }
+
+ stream, err := client.CreateChatCompletionStream(ctx, req)
+ if err == nil {
+ return stream, nil
+ }
+
+ lastErr = err
+ if !isRetryableError(err) {
+ return nil, err
+ }
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ }
+ return nil, lastErr
+}
+
+func isRetryableError(err error) bool {
+ if err == nil {
+ return false
+ }
+ msg := err.Error()
+ if strings.Contains(msg, "401") || strings.Contains(msg, "Unauthorized") {
+ return false
+ }
+ if strings.Contains(msg, "402") || strings.Contains(msg, "Payment Required") {
+ return false
+ }
+ if strings.Contains(msg, "403") || strings.Contains(msg, "Forbidden") {
+ return false
+ }
+ if strings.Contains(msg, "400") || strings.Contains(msg, "Bad Request") {
+ return false
+ }
+ if strings.Contains(msg, "context canceled") || strings.Contains(msg, "context deadline exceeded") {
+ return false
+ }
+ return true
+}
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 8db794cb27..6e56bcca8d 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -31,6 +31,7 @@ import (
)
type agentChatReq struct {
+ SessionID string `json:"sessionID"`
Messages []agent.UserMessage `json:"messages"`
Language string `json:"language"`
References []agent.Reference `json:"references"`
@@ -63,6 +64,15 @@ func agentChat(c *gin.Context) {
model.Conf.AI.OpenAI.APIProvider,
)
+ confirmTimeout := time.Duration(model.Conf.AI.OpenAI.AgentConfirmTimeout) * time.Second
+ if confirmTimeout <= 0 {
+ confirmTimeout = 120 * time.Second
+ }
+ maxRetries := model.Conf.AI.OpenAI.AgentMaxRetries
+ if maxRetries <= 0 {
+ maxRetries = 3
+ }
+
var eventCh <-chan agent.AgentEvent
ctx, cancel := context.WithCancel(context.Background())
defer func() {
@@ -73,7 +83,7 @@ func agentChat(c *gin.Context) {
}()
}()
- eventCh = agent.AgentChat(ctx, client, model.Conf.AI.OpenAI.APIModel, req.Messages, req.Language, req.References)
+ eventCh = agent.AgentChat(ctx, client, model.Conf.AI.OpenAI.APIModel, req.SessionID, req.Messages, req.Language, req.References, confirmTimeout, maxRetries)
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
@@ -88,9 +98,12 @@ func agentChat(c *gin.Context) {
if timeout <= 0 {
timeout = 30
}
- totalTimeout := time.Duration(timeout) * time.Second * 10
- if totalTimeout > 300*time.Second {
- totalTimeout = 300 * time.Second
+ totalTimeout := time.Duration(model.Conf.AI.OpenAI.AgentTimeout) * time.Second
+ if totalTimeout <= 0 {
+ totalTimeout = time.Duration(timeout) * time.Second * 10
+ }
+ if totalTimeout > 3600*time.Second {
+ totalTimeout = 3600 * time.Second
}
deadline := time.After(totalTimeout)
@@ -191,6 +204,11 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {
})
case "done":
return writeSSEEvent(c, "done", map[string]interface{}{})
+ case "retry":
+ return writeSSEEvent(c, "retry", map[string]interface{}{
+ "attempt": event.RetryAttempt,
+ "maxRetries": event.RetryMax,
+ })
}
return nil
}
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index abbfd5d625..199a6e91c5 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -30,31 +30,37 @@ type AI struct {
}
type OpenAI struct {
- APIKey string `json:"apiKey"`
- APITimeout int `json:"apiTimeout"`
- APIProxy string `json:"apiProxy"`
- APIModel string `json:"apiModel"`
- APIMaxTokens int `json:"apiMaxTokens"`
- APITemperature float64 `json:"apiTemperature"`
- APIMaxContexts int `json:"apiMaxContexts"`
- APIBaseURL string `json:"apiBaseURL"`
- APIUserAgent string `json:"apiUserAgent"`
- APIProvider string `json:"apiProvider"` // OpenAI, Azure
- APIVersion string `json:"apiVersion"` // Azure API version
- EmbeddingModel string `json:"embeddingModel"`
- EmbeddingBaseURL string `json:"embeddingBaseURL"`
- EmbeddingAPIKey string `json:"embeddingAPIKey"`
+ APIKey string `json:"apiKey"`
+ APITimeout int `json:"apiTimeout"`
+ APIProxy string `json:"apiProxy"`
+ APIModel string `json:"apiModel"`
+ APIMaxTokens int `json:"apiMaxTokens"`
+ APITemperature float64 `json:"apiTemperature"`
+ APIMaxContexts int `json:"apiMaxContexts"`
+ APIBaseURL string `json:"apiBaseURL"`
+ APIUserAgent string `json:"apiUserAgent"`
+ APIProvider string `json:"apiProvider"` // OpenAI, Azure
+ APIVersion string `json:"apiVersion"` // Azure API version
+ EmbeddingModel string `json:"embeddingModel"`
+ EmbeddingBaseURL string `json:"embeddingBaseURL"`
+ EmbeddingAPIKey string `json:"embeddingAPIKey"`
+ AgentTimeout int `json:"agentTimeout"` // total session timeout, seconds, 0 = no limit
+ AgentConfirmTimeout int `json:"agentConfirmTimeout"` // confirmation timeout, seconds
+ AgentMaxRetries int `json:"agentMaxRetries"` // max API retry attempts on failure
}
func NewAI() *AI {
openAI := &OpenAI{
- APITemperature: 1.0,
- APIMaxContexts: 7,
- APITimeout: 30,
- APIModel: openai.GPT3Dot5Turbo,
- APIBaseURL: "https://api.openai.com/v1",
- APIUserAgent: util.UserAgent,
- APIProvider: "OpenAI",
+ APITemperature: 1.0,
+ APIMaxContexts: 7,
+ APITimeout: 30,
+ APIModel: openai.GPT3Dot5Turbo,
+ APIBaseURL: "https://api.openai.com/v1",
+ APIUserAgent: util.UserAgent,
+ APIProvider: "OpenAI",
+ AgentTimeout: 600,
+ AgentConfirmTimeout: 120,
+ AgentMaxRetries: 3,
}
openAI.APIKey = os.Getenv("SIYUAN_OPENAI_API_KEY")
@@ -107,5 +113,20 @@ func NewAI() *AI {
if embeddingModel := os.Getenv("SIYUAN_OPENAI_EMBEDDING_MODEL"); "" != embeddingModel {
openAI.EmbeddingModel = embeddingModel
}
+ if agentTimeout := os.Getenv("SIYUAN_OPENAI_AGENT_TIMEOUT"); "" != agentTimeout {
+ if v, err := strconv.Atoi(agentTimeout); err == nil {
+ openAI.AgentTimeout = v
+ }
+ }
+ if agentConfirmTimeout := os.Getenv("SIYUAN_OPENAI_AGENT_CONFIRM_TIMEOUT"); "" != agentConfirmTimeout {
+ if v, err := strconv.Atoi(agentConfirmTimeout); err == nil {
+ openAI.AgentConfirmTimeout = v
+ }
+ }
+ if agentMaxRetries := os.Getenv("SIYUAN_OPENAI_AGENT_MAX_RETRIES"); "" != agentMaxRetries {
+ if v, err := strconv.Atoi(agentMaxRetries); err == nil {
+ openAI.AgentMaxRetries = v
+ }
+ }
return &AI{OpenAI: openAI}
}