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

Danielf8ec515faee8
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 80dc34f141..bd099d19ae 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -183,6 +183,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
startTime := time.Now().UnixMilli()
alwaysAllow := map[string]bool{}
var doomLoop doomLoopTracker
+ var compactCount int
checkpointMsgs := make([]AgentMessage, 0, len(history))
for _, h := range history {
@@ -214,6 +215,16 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
stream, streamErr := createStreamWithRetry(ctx, client, req, maxRetries, ch)
if streamErr != nil {
+ if compactCount < 3 && isContextOverflow(streamErr) {
+ keepTurns := 3 - compactCount
+ if keepTurns < 1 {
+ keepTurns = 1
+ }
+ messages = compactMessages(messages, keepTurns)
+ compactCount++
+ ch <- AgentEvent{Type: "thinking", Reasoning: fmt.Sprintf("context limit reached, compacting to last %d turns...", keepTurns)}
+ continue
+ }
ch <- AgentEvent{Type: "error", Error: "API request failed: " + streamErr.Error()}
saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
return
diff --git a/kernel/agent/compaction.go b/kernel/agent/compaction.go
new file mode 100644
index 0000000000..172b7ebae6
--- /dev/null
+++ b/kernel/agent/compaction.go
@@ -0,0 +1,126 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package agent
+
+import (
+ "strings"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+func isContextOverflow(err error) bool {
+ msg := err.Error()
+ return strings.Contains(msg, "context_length_exceeded") ||
+ strings.Contains(msg, "maximum context length") ||
+ strings.Contains(msg, "reduce the length") ||
+ strings.Contains(msg, "too many tokens") ||
+ strings.Contains(msg, "input is too long") ||
+ strings.Contains(msg, "exceeds the context window")
+}
+
+func compactMessages(msgs []openai.ChatCompletionMessage, keepLastUserMessages int) []openai.ChatCompletionMessage {
+ if len(msgs) <= 2 || keepLastUserMessages <= 0 {
+ return msgs
+ }
+
+ // Find cut-off point: count backwards to find the Nth user message
+ userCount := 0
+ cutIdx := 1 // default: keep only system prompt
+ for i := len(msgs) - 1; i >= 1; i-- {
+ if msgs[i].Role == openai.ChatMessageRoleUser {
+ userCount++
+ if userCount == keepLastUserMessages {
+ cutIdx = i
+ break
+ }
+ }
+ }
+
+ if cutIdx <= 1 {
+ return msgs // nothing to compact
+ }
+
+ oldMsgs := msgs[1:cutIdx]
+ summary := extractSummary(oldMsgs)
+
+ compacted := make([]openai.ChatCompletionMessage, 0, 1+1+len(msgs)-cutIdx)
+ compacted = append(compacted, msgs[0]) // system prompt
+ compacted = append(compacted, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleSystem,
+ Content: "[Earlier conversation summarized]\n" + summary + "\n\nContinue based on the summary above.",
+ })
+ compacted = append(compacted, msgs[cutIdx:]...) // recent messages
+
+ return compacted
+}
+
+func extractSummary(msgs []openai.ChatCompletionMessage) string {
+ var sb strings.Builder
+ var toolNames []string
+ var userMsgs []string
+
+ for _, m := range msgs {
+ switch m.Role {
+ case openai.ChatMessageRoleUser:
+ text := strings.TrimSpace(m.Content)
+ if text != "" {
+ if len(text) > 300 {
+ text = text[:300] + "..."
+ }
+ userMsgs = append(userMsgs, "- User: "+text)
+ }
+ case openai.ChatMessageRoleAssistant:
+ for _, tc := range m.ToolCalls {
+ toolNames = append(toolNames, tc.Function.Name)
+ }
+ }
+ }
+
+ if len(userMsgs) > 0 {
+ sb.WriteString(strings.Join(userMsgs, "\n"))
+ }
+ if len(toolNames) > 0 {
+ if sb.Len() > 0 {
+ sb.WriteString("\n")
+ }
+ seen := map[string]int{}
+ var counts []string
+ for _, name := range toolNames {
+ seen[name]++
+ }
+ for name, count := range seen {
+ if count > 1 {
+ counts = append(counts, name+" ×"+itoa(count))
+ } else {
+ counts = append(counts, name)
+ }
+ }
+ sb.WriteString("- Tools used: " + strings.Join(counts, ", "))
+ }
+
+ if sb.Len() == 0 {
+ return "(no content to summarize)"
+ }
+ return sb.String()
+}
+
+func itoa(n int) string {
+ if n < 10 {
+ return string(rune('0' + n))
+ }
+ return itoa(n/10) + string(rune('0'+n%10))
+}