Files
memoryweave/go/internal/api/routes/deep_think.go
T

229 lines
6.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — 深度推理端点(人侧数据 → 三类清单)
package routes
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/xiaoxue/memoryweave/internal/governance"
)
// DeepThinkRequest 深度推理请求
type DeepThinkRequest struct {
AgentID string `json:"agent_id"`
// namespace 为空时取人侧默认命名空间
Namespace string `json:"namespace,omitempty"`
// 最大社区数(摘要开销控制)
MaxCommunities int `json:"max_communities,omitempty"`
}
// DeepThinkResponse 三类清单
type DeepThinkResponse struct {
OK bool `json:"ok"`
AgentID string `json:"agent_id"`
Namespace string `json:"namespace"`
Profiles []DeepThinkItem `json:"profiles"` // 画像规则(待拍板)
Episodes []DeepThinkItem `json:"episodes"` // 心迹/牵挂/承诺句(已处置)
Signals []DeepThinkItem `json:"signals"` // 社区摘要(信号)
ConflictsPending int `json:"conflicts_pending"`
LastRun string `json:"last_run"`
}
// DeepThinkItem 清单条目
type DeepThinkItem struct {
ID string `json:"id"`
Category string `json:"category"`
Content string `json:"content"`
Weight string `json:"weight,omitempty"` // 社区摘要用
Source string `json:"source"` // memories | graph | community
RecallOnly bool `json:"recall_only"` // 仅 recall 时注入,不持久化
}
// HandleDeepThink POST /api/v1/deep-think
func (a *API) HandleDeepThink(w http.ResponseWriter, r *http.Request) {
var req DeepThinkRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "decode request: "+err.Error())
return
}
if req.AgentID == "" {
respondError(w, 400, "agent_id required")
return
}
ns := req.Namespace
if ns == "" {
// 人侧数据统一命名空间(牧尘拍板:soulful-xiaowei,deriveNamespace 会自动加 -main 后缀 → soulful-xiaowei-main)
ns = deriveNamespace("soulful-xiaowei")
}
maxC := req.MaxCommunities
if maxC == 0 {
maxC = 10
}
now := time.Now().UTC()
resp := DeepThinkResponse{
OK: true,
AgentID: req.AgentID,
Namespace: ns,
LastRun: now.Format(time.RFC3339),
}
// 1. 画像 → category=profiles
resp.Profiles = a.fetchCategory(ns, "profiles", 20, false)
// 2. 心迹/牵挂/承诺句 → category=episodes
episodes := a.fetchCategory(ns, "episodes", 30, false)
episodes = append(episodes, a.fetchCategory(ns, "cares", 15, false)...)
resp.Episodes = episodes
// 3. 冲突(待裁决)→ 待拍板
resp.ConflictsPending = 0
if a.ConflictDetector != nil {
for _, c := range a.ConflictDetector.ListActive() {
if c.Status == "pending" {
resp.ConflictsPending++
resp.Profiles = append(resp.Profiles, DeepThinkItem{
ID: c.ID, Category: "conflict", Content: c.Description,
Source: "conflict_detector", RecallOnly: false,
})
}
}
}
// 4. 图谱社区 → 信号
cds := governance.NewCommunityDiscovery(a.GraphStore)
communities, err := cds.Find(ns, 3)
if err == nil && len(communities) > 0 {
if len(communities) > maxC {
communities = communities[:maxC]
}
summaries, _ := cds.Summarize(communities, ns, 5)
for _, c := range summaries {
resp.Signals = append(resp.Signals, DeepThinkItem{
ID: c.ID,
Category: "community",
Content: c.Summary,
Weight: strconv.FormatFloat(c.Weight, 'f', 2, 64),
Source: "community_discovery",
RecallOnly: false,
})
}
}
// 5. 图谱扩展(画像/牵挂/心迹 的邻接)
resp.Signals = append(resp.Signals, a.graphSignals(ns, resp.Profiles, resp.Episodes)...)
// 6. 写回 category=signals(异步持久化)
go a.persistSignals(resp)
respond(w, 200, map[string]interface{}{
"ok": true, "agent_id": req.AgentID, "namespace": ns,
"profiles": len(resp.Profiles),
"episodes": len(resp.Episodes),
"signals": len(resp.Signals),
"last_run": resp.LastRun,
})
}
// fetchCategory 取某 category 的记忆(用零向量 search,按 importance 排序)
func (a *API) fetchCategory(ns, cat string, limit int, recallOnly bool) []DeepThinkItem {
zeroVec := make([]float32, 1024)
results, err := a.LanceDB.Search("memories", zeroVec, limit, ns)
if err != nil {
return nil
}
var out []DeepThinkItem
for _, m := range results {
if cat != "" && m.Category != cat {
continue
}
out = append(out, DeepThinkItem{
ID: m.ID, Category: m.Category, Content: truncate(m.Content, 200),
Source: "memories", RecallOnly: recallOnly,
})
}
return out
}
// graphSignals 从图谱取画像/牵挂/心迹的邻接关系
func (a *API) graphSignals(ns string, profiles, episodes []DeepThinkItem) []DeepThinkItem {
var out []DeepThinkItem
seen := make(map[string]bool)
for _, item := range append(profiles, episodes...) {
if item.ID == "" {
continue
}
paths, err := a.GraphStore.Navigate(item.ID, 2, ns, nil)
if err != nil {
continue
}
for _, p := range paths {
to, _ := p["to"].(string)
rel, _ := p["relation"].(string)
if to == "" || seen[to] {
continue
}
seen[to] = true
out = append(out, DeepThinkItem{
ID: to, Category: "graph_relation",
Content: fmt.Sprintf("%s → %s: %s", item.ID, to, rel),
Source: "graph", RecallOnly: false,
})
}
}
return out
}
// persistSignals 把信号写回 memories(category=signals)
// 异步:不把延迟暴露给调用方
func (a *API) persistSignals(resp DeepThinkResponse) {
if len(resp.Signals) == 0 {
return
}
for _, s := range resp.Signals {
_, _ = a.LanceDB.InsertEpisode(resp.AgentID, resp.Namespace,
fmt.Sprintf("[信号] %s | 来源:%s", s.Content, s.Source), "signals")
}
}
// HandleCommunitySummarize POST /api/v1/community/summarize
// 运行 Louvain 社区发现 + 摘要(纯 Go,不调 LLM)
func (a *API) HandleCommunitySummarize(w http.ResponseWriter, r *http.Request) {
var req struct {
AgentID string `json:"agent_id"`
Namespace string `json:"namespace,omitempty"`
MaxCommunities int `json:"max_communities,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "decode request: "+err.Error())
return
}
ns := req.Namespace
if ns == "" {
ns = deriveNamespace("soulful-xiaowei")
}
maxC := req.MaxCommunities
if maxC == 0 {
maxC = 10
}
cds := governance.NewCommunityDiscovery(a.GraphStore)
communities, err := cds.Find(ns, 3)
if err != nil {
respondError(w, 500, "find communities: "+err.Error())
return
}
if len(communities) > maxC {
communities = communities[:maxC]
}
summaries, _ := cds.Summarize(communities, ns, 5)
respond(w, 200, map[string]interface{}{
"ok": true, "namespace": ns,
"communities": len(communities),
"summaries": summaries,
})
}