mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-21 09:28:14 +00:00
记忆系统在 1.1.0 支持了二进制多媒体节点,但那条链路只对**内核自己**开放: 用户在 qq 发图能落进 CAS、能被记忆引用,而插件调 Commit / DocMemory().Insert 交进来的媒体一律无处安放。原因是三层都断着,且**每一层都不报错**。 ## 一、公开 SDK:补上媒体的表达能力(全部新增,无签名变更) - `Triple` += `SentenceText`、`MediaDigests` - `Doc` += `MediaDigests`、`Attachments`;新增 `MediaAttachment` - `TextEvent` += `Attachments` - `DocMemoryAPI` += `InsertWithMedia` - `IOInjector` += `InjectInputMedia` / `InjectInputMediaSync` / `InjectInterruptMedia` - `PluginSDK` 补上一直缺失的 `SetToolBlocks` 包装(接口里有、便捷方法里没有) `MediaAttachment` 一个类型服务两个方向:给 `Data`+`MIME` 是新内容(CAS 按字节 去重),只给 `Digest` 是引用已有内容。读路径**只回元数据不回字节**——一次检索 可能命中几十份媒体,全塞回去会把跨进程消息撑爆。 媒体注入不能搭 `SetToolBlocks` 的车:那个方法只在工具处理函数内部可用,且媒体 要等下一条 tool message 才到模型手上。插件主动发起一轮带媒体的对话、以及中断 注入,需要自己的签名,且媒体在**本轮**就送到模型。 ## 二、内核桥接层:原先在静默裁字段 `internal/sdk/memory_impl.go` 此前只搬自己认识的几个字段,其余丢弃且返回 nil: - 图记忆丢 `Confidence`/`SubjectType`/`ObjectType`/`SentenceText`,又走 `Commit` 而非 `CommitWithMedia`(不回 sentenceIDs)→ 媒体绑定链 `SentenceText → sentences → sentence_id → media_refs` 一步都走不通,插件即便按格式写好标记也永远挂不上; - 知识库 `Query` 只回 ID/Title/Content,`Insert` 只写这三个;`Remove` 不解引用, 于是那些媒体永久处于「被引用」状态,GC 收不掉、磁盘只增不减 (内核的归档路径 `releaseDocMedia` 做了这一步,插件路径漏了同一步)。 规则改为:**内部结构有的字段一律透传**。标记格式处理作为包级私有辅助留在桥接 层自己手里,但必须与内核 `mediaSummaryForEvent` 字节兼容——两边要能互读对方 写下的标记。 标记插入必须在 `ds.Insert` **之前**(向量索引取 `Summary + " " + Content`, 之后补的标记检索不到),引用绑定必须在**之后**(owner_id 是 Insert 生成的 ID)。 ## 三、跨进程链路:不接线就是全体外部插件编译失败 `go test` 直接把这一层拍出来了——`procIO does not implement sdk.IOInjector`。 公开接口加方法后,生成模板不跟上,**每个外部插件都编不过**,是硬失败不是软降级。 六处接线:`protocol.go` 四个 method 常量、`capability.go` 能力归属、 `corehandler.go` 四个分派分支、`proc_core.go` 委托、`proc_main.go.tmpl` 模板侧 实现、以及三个测试替身。 ## 四、统一输入主干:把模态从「函数选择」降级为「字段」 `processTextInput` / `processMediaInput` 合并为 `processInput`。这个分叉是历史 产物而非设计:`processTextInput` 本来就处理媒体(`bindEventMedia` + `mediaSummaryForEvent`,与媒体路径尾部完全相同),`process()` 只看 `stageCtx.Extra["media_blocks"]`、根本不认识 `evt.Type`。模态是输入的**属性**, 不是输入的**种类**。 媒体路径由此获得它一直缺的六项:去重、`no_memory`、通道 `Cleaner`、中断语义、 `_consolidation_` 路由、正确的 `EventRawInput`。 最后一项是个真 bug:媒体路径发布 `"content": evt.Payload`(一个 map),而 `webui/handler.go` 断言 `.(string)` → 断言失败、`content == ""`、提前返回。 **用户发的图从来没出现在 WebUI 聊天记录里。** `media_blocks` 同时接受 `[]agentAPI.ContentBlock` 与 `[]pubsdk.ContentBlock`: 字段一致但 Go 不自动转换,只认一种的后果是另一种被静默丢弃。 ## 五、模型可调用的三个工具 `memory_commit` 的 `sentence_text` **从未暴露给模型**,而它是绑定链上的必经环节; 连同 `media_digests` 一起补进 JSON schema 与工具文档。`doc_commit` 加 `media_digests`。`doc_query` 把关联媒体单独一行附在结果末尾(正文按 2000 字截断, 标记通常就在尾部)。 标记由**内核**生成而非插件/模型拼装:要求调用方知道格式,等于让一个拼写错误 静默切断引用绑定,而全链路无人报错。 ## 六、WebUI 上传走真实媒体链路 图片/音频读回字节拼 data URL 注入 `media_blocks`(8MB 上限,超限退回按路径处理)。 此前只注入一句「文件已保存到 <路径>」,指望模型自己调 `files_read`——但那返回 文本,图片字节对模型永远不可见。附件类型识别扩展到 audio 并在缺 Content-Type 时按扩展名兜底(判错不只是卡片样式问题,图片被当普通文件就进不了视觉链路)。 ## 测试 - `internal/sdk/memory_impl_test.go`(12 例,此前该包**没有任何测试文件**) - `internal/agent/core/inputunify_test.go`(统一主干 + 双静态类型 + 三工具媒体) - `third_party/homeagent-sdk/sdk/stress_test.go`(13 例并发压测) 压测抓到两处**真**竞态(不是理论风险):`PluginSDK` 的 API 字段与 `autoRestart` 无锁,而写方(内核注入 API、插件 `SetAutoRestart`)与读方(插件后台 goroutine 注入、内核 registry 读 `AutoRestart`)天然跨 goroutine。加 `apiMu` 修掉;约定 只在持锁期间取字段值,取完即释放再调用——持锁调用会把 `InjectInputSync` 这类 阻塞到 agent 回复(可达数分钟)的方法与 `SetIOInjector` 串起来,让插件重载卡死。 测试还抓出两个自身缺陷:`bindDocMedia` 把同一份媒体数两次(`AddRef` 幂等所以表 是对的,但日志说「绑定 2 个」而实际 1 条——误导后续排查),以及用单字符实体名 时 `validEntityName` 静默跳过、`Commit` 返回 nil 却什么都没写。 存量插件不需要改一行也不需要重编:新增方法由插件调用、内核实现,不调就不受影响。 17 个 example 插件源码零改动通过类型检查。
324 lines
8.1 KiB
Go
324 lines
8.1 KiB
Go
package memory
|
||
|
||
import (
|
||
"fmt"
|
||
"log"
|
||
"strings"
|
||
"sync"
|
||
|
||
"gitcode.com/JianFeeeee/HomeAgent/internal/memory/vector"
|
||
)
|
||
|
||
type Indexer struct {
|
||
db *GraphDB
|
||
vec *vector.Store
|
||
veczer *vector.TFIDFVectorizer
|
||
mu sync.RWMutex
|
||
trained bool
|
||
recalled map[string]bool // 已通过工具调用显式召回的实体名,自动注入时跳过
|
||
}
|
||
|
||
func NewIndexer(db *GraphDB) *Indexer {
|
||
return &Indexer{
|
||
db: db,
|
||
vec: vector.NewStore(),
|
||
veczer: vector.NewTFIDFVectorizer(TokenizeWords),
|
||
recalled: make(map[string]bool),
|
||
}
|
||
}
|
||
|
||
// MarkRecalled 标记实体名已被工具调用显式召回,后续自动注入时跳过
|
||
func (idx *Indexer) MarkRecalled(names ...string) {
|
||
idx.mu.Lock()
|
||
defer idx.mu.Unlock()
|
||
for _, name := range names {
|
||
idx.recalled[name] = true
|
||
}
|
||
}
|
||
|
||
// Sync 从图数据库中同步实体名到向量索引
|
||
func (idx *Indexer) Sync() error {
|
||
idx.mu.Lock()
|
||
defer idx.mu.Unlock()
|
||
|
||
if idx.db == nil {
|
||
return nil
|
||
}
|
||
|
||
result, err := idx.db.Recall(nil, nil, 1, "")
|
||
if err != nil || result == nil {
|
||
return err
|
||
}
|
||
|
||
// 收集实体名
|
||
var names []string
|
||
for _, e := range result.Entities {
|
||
names = append(names, e.Name)
|
||
}
|
||
|
||
if len(names) == 0 {
|
||
return nil
|
||
}
|
||
|
||
// 训练向量化器
|
||
idx.veczer.Train(names)
|
||
|
||
// 重建向量索引
|
||
idx.vec = vector.NewStore()
|
||
for _, e := range result.Entities {
|
||
vec := idx.veczer.Vectorize(e.Name)
|
||
idx.vec.Insert(fmt.Sprintf("entity_%d", e.ID), e.Name, vec, map[string]string{
|
||
"type": "entity",
|
||
"name": e.Name,
|
||
})
|
||
}
|
||
|
||
idx.trained = true
|
||
log.Printf("[indexer] synced %d entities to vector index", len(names))
|
||
return nil
|
||
}
|
||
|
||
type InjectedContext struct {
|
||
Entities []Entity `json:"entities"`
|
||
Relations []Relation `json:"relations"`
|
||
Summary string `json:"summary"`
|
||
TokenEstimate int `json:"token_estimate"`
|
||
}
|
||
|
||
func (idx *Indexer) BuildContext(userInput string) *InjectedContext {
|
||
if idx.db == nil {
|
||
return &InjectedContext{Summary: ""}
|
||
}
|
||
|
||
input := CleanText(userInput)
|
||
|
||
// 1. 向量搜索:从实体名向量索引中找到相关实体
|
||
vectorEntities := idx.vectorSearchEntities(input)
|
||
|
||
// 2. 关键词搜索:已有逻辑
|
||
keywords := ExtractKeywords(input)
|
||
if len(keywords) == 0 && len(vectorEntities) == 0 {
|
||
keywords = []string{userInput}
|
||
}
|
||
|
||
// 合并关键词和向量找到的实体名
|
||
seedNames := make([]string, 0, len(vectorEntities))
|
||
for _, e := range vectorEntities {
|
||
seedNames = append(seedNames, e.Name)
|
||
}
|
||
allKeywords := append(keywords, seedNames...)
|
||
|
||
result, err := idx.db.Recall(allKeywords, nil, 2, "")
|
||
if err != nil || result == nil {
|
||
return &InjectedContext{Summary: ""}
|
||
}
|
||
|
||
// 过滤已被工具调用显式召回的实体,避免重复注入
|
||
idx.mu.RLock()
|
||
filtered := result.Entities[:0]
|
||
for _, e := range result.Entities {
|
||
if !idx.recalled[e.Name] {
|
||
filtered = append(filtered, e)
|
||
}
|
||
}
|
||
idx.mu.RUnlock()
|
||
|
||
ctx := &InjectedContext{
|
||
Entities: filtered,
|
||
Relations: nil,
|
||
}
|
||
|
||
if len(filtered) > 0 {
|
||
summary := buildIndexSummary(filtered)
|
||
ctx.Summary = summary
|
||
ctx.TokenEstimate = estimateTokens(summary) + len(filtered)*8
|
||
} else {
|
||
ctx.Summary = ""
|
||
}
|
||
|
||
return ctx
|
||
}
|
||
|
||
// vectorSearchEntities 在实体名向量索引中搜索
|
||
func (idx *Indexer) vectorSearchEntities(query string) []Entity {
|
||
idx.mu.RLock()
|
||
defer idx.mu.RUnlock()
|
||
|
||
if !idx.trained || idx.vec.Size() == 0 {
|
||
return nil
|
||
}
|
||
|
||
queryVec := idx.veczer.Vectorize(query)
|
||
results := idx.vec.Search(queryVec, 5)
|
||
|
||
var entities []Entity
|
||
for _, r := range results {
|
||
if r.Meta != nil && r.Meta["type"] == "entity" {
|
||
entities = append(entities, Entity{Name: r.Meta["name"]})
|
||
}
|
||
}
|
||
return entities
|
||
}
|
||
|
||
func (idx *Indexer) BuildToolPrompt() string {
|
||
return `## 图记忆工具
|
||
|
||
你有以下工具可以操作长期图记忆系统:
|
||
|
||
### memory_recall
|
||
检索与关键词相关的实体和关系。
|
||
参数:
|
||
- query_intent: 查询关键词,逗号分隔
|
||
- depth: 遍历深度(默认2)
|
||
|
||
### memory_commit
|
||
将三元组写入图记忆。
|
||
参数:
|
||
- triples: [{"subject": "实体名", "relation": "关系类型", "object": "目标实体",
|
||
"sentence_text": "原始句子(可选)", "media_digests": ["图片digest(可选)"]}]
|
||
填了 media_digests,日后从这条记忆就能取回当时那张图/那段音频。
|
||
|
||
### memory_introspect
|
||
查看记忆统计信息。
|
||
|
||
### memory_purge
|
||
删除或修正记忆。
|
||
参数:
|
||
- criteria: {"subject_contains": "...", "relation_type": "..."}
|
||
- mode: "soft" | "supersede"
|
||
|
||
使用方法:在推理过程中调用对应的 tool,系统会自动执行并返回结果。`
|
||
}
|
||
|
||
func (idx *Indexer) FormatContext(ctx *InjectedContext) string {
|
||
if ctx == nil || len(ctx.Entities) == 0 {
|
||
return ""
|
||
}
|
||
|
||
var b strings.Builder
|
||
b.WriteString("【记忆索引】")
|
||
|
||
if ctx.Summary != "" {
|
||
b.WriteString(" ")
|
||
b.WriteString(ctx.Summary)
|
||
}
|
||
|
||
b.WriteString(fmt.Sprintf(" 索引: "))
|
||
for i, e := range ctx.Entities {
|
||
if i >= 5 {
|
||
b.WriteString("…")
|
||
break
|
||
}
|
||
if i > 0 {
|
||
b.WriteString(", ")
|
||
}
|
||
b.WriteString(e.Name)
|
||
if e.Type != "Concept" {
|
||
b.WriteString("(" + e.Type + ")")
|
||
}
|
||
}
|
||
|
||
b.WriteString(" | 需更多细节请用 memory_recall 查询")
|
||
return b.String()
|
||
}
|
||
|
||
func (idx *Indexer) GetToolDefinitions() []map[string]interface{} {
|
||
return []map[string]interface{}{
|
||
{
|
||
"type": "function",
|
||
"function": map[string]interface{}{
|
||
"name": "memory_recall",
|
||
"description": "检索图记忆。输入查询意图关键词,返回相关实体和关系。",
|
||
"parameters": map[string]interface{}{
|
||
"type": "object",
|
||
"properties": map[string]interface{}{
|
||
"query_intent": map[string]interface{}{
|
||
"type": "string",
|
||
"description": "查询意图,支持逗号分隔多个关键词",
|
||
},
|
||
"depth": map[string]interface{}{
|
||
"type": "integer",
|
||
"description": "遍历深度,默认2",
|
||
"default": 2,
|
||
},
|
||
},
|
||
"required": []string{"query_intent"},
|
||
},
|
||
},
|
||
},
|
||
{
|
||
"type": "function",
|
||
"function": map[string]interface{}{
|
||
"name": "memory_commit",
|
||
"description": "写入图记忆。将三元组列表写入长期记忆。",
|
||
"parameters": map[string]interface{}{
|
||
"type": "object",
|
||
"properties": map[string]interface{}{
|
||
"triples": map[string]interface{}{
|
||
"type": "array",
|
||
"description": "三元组列表",
|
||
"items": map[string]interface{}{
|
||
"type": "object",
|
||
"properties": map[string]interface{}{
|
||
"subject": map[string]interface{}{"type": "string"},
|
||
"relation": map[string]interface{}{"type": "string"},
|
||
"object": map[string]interface{}{"type": "string"},
|
||
"sentence_text": map[string]interface{}{
|
||
"type": "string",
|
||
"description": "可选:这条三元组的原始句子。填了才能日后从图谱回到原文。",
|
||
},
|
||
"media_digests": map[string]interface{}{
|
||
"type": "array",
|
||
"description": "可选:这条记忆关联的媒体 digest(对话或 memory_recall 的「关联媒体」里显示的十六进制串,短的即可)。填了以后从这条记忆能取回原图/音频。",
|
||
"items": map[string]interface{}{"type": "string"},
|
||
},
|
||
},
|
||
"required": []string{"subject", "relation", "object"},
|
||
},
|
||
},
|
||
},
|
||
"required": []string{"triples"},
|
||
},
|
||
},
|
||
},
|
||
{
|
||
"type": "function",
|
||
"function": map[string]interface{}{
|
||
"name": "memory_introspect",
|
||
"description": "查看图记忆统计信息:实体数量、关系数量、热点实体。",
|
||
"parameters": map[string]interface{}{
|
||
"type": "object",
|
||
"properties": map[string]interface{}{},
|
||
},
|
||
},
|
||
},
|
||
}
|
||
}
|
||
|
||
func buildIndexSummary(entities []Entity) string {
|
||
if len(entities) == 0 {
|
||
return ""
|
||
}
|
||
|
||
var b strings.Builder
|
||
b.WriteString(fmt.Sprintf("关联 %d 个记忆实体", len(entities)))
|
||
|
||
topN := 3
|
||
if len(entities) < topN {
|
||
topN = len(entities)
|
||
}
|
||
b.WriteString(",高频:")
|
||
for i := 0; i < topN; i++ {
|
||
if i > 0 {
|
||
b.WriteString("、")
|
||
}
|
||
b.WriteString(entities[i].Name)
|
||
}
|
||
|
||
return b.String()
|
||
}
|
||
|
||
func estimateTokens(s string) int {
|
||
return len(s) / 2
|
||
}
|