后端:
1. LLM 客户端从 newAgent/llm 提升为 infra/llm 基础设施层
- 删除 backend/newAgent/llm/(ark.go / ark_adapter.go / client.go / json.go)
- 等价迁移至 backend/infra/llm/,所有 newAgent node 与 service 统一改引用 infrallm
- 消除 newAgent 对模型客户端的私有依赖,为 memory / websearch 等多模块复用铺路
2. RAG 基础设施完成可运行态接入(factory / runtime / observer / service 四层成型)
- 新建 backend/infra/rag/factory.go / runtime.go / observe.go / observer.go /
service.go:工厂创建、运行时生命周期、轻量观测接口、检索服务门面
- 更新 infra/rag/config/config.go:补齐 Milvus / Embed / Reranker 全部配置项与默认值
- 更新 infra/rag/embed/eino_embedder.go:增强 Eino embedding 适配,支持 BaseURL / APIKey 环境变量 / 超时 /
维度等参数
- 更新 infra/rag/store/milvus_store.go:完整实现 Milvus 向量存储(建集合 / 建 Index / Upsert / Search /
Delete),支持 COSINE / L2 / IP 度量
- 更新 infra/rag/core/pipeline.go:适配 Runtime 接口,Pipeline 由 factory 注入而非手动拼装
- 更新 infra/rag/corpus/memory_corpus.go / vector_store.go:对接 Memory 模块数据源与 Store 接口扩展
3. Memory 模块从 Day1 骨架升级为 Day2 完整可运行态
- 新建 memory/module.go:统一门面 Module,对外封装 EnqueueExtract / ReadService / ManageService / WithTx /
StartWorker,启动层只依赖这一个入口
- 新建 memory/orchestrator/llm_write_orchestrator.go:LLM 驱动的记忆抽取编排器,替代原 mock 抽取
- 新建 memory/service/read_service.go:按用户开关过滤 + 轻量重排 + 访问时间刷新的读取链路
- 新建 memory/service/manage_service.go:记忆管理面能力(列出 / 软删除 / 开关读写),删除同步写审计日志
- 新建 memory/service/common.go:服务层公共工具
- 新建 memory/worker/loop.go:后台轮询循环 RunPollingLoop,定时抢占 pending 任务并推进
- 新建 memory/utils/audit.go / settings.go:审计日志构造、用户设置过滤等纯函数
- 更新 memory/model/item.go / job.go / settings.go / config.go / status.go:补齐 DTO 字段与状态常量
- 更新 memory/repo/item_repo.go / job_repo.go / audit_repo.go / settings_repo.go:补齐 CRUD 与查询能力
- 更新 memory/worker/runner.go:Runner 对接 Module 与 LLM 抽取器,任务状态机完整化
- 更新 memory/README.md:同步模块现状说明
4. newAgent 接入 Memory 读取注入与工具注册依赖预埋
- 新建 service/agentsvc/agent_memory.go:定义 MemoryReader 接口 + injectMemoryContext,在 graph
执行前统一补充记忆上下文
- 更新 service/agentsvc/agent.go:新增 memoryReader 字段与 SetMemoryReader 方法
- 更新 service/agentsvc/agent_newagent.go:调用 injectMemoryContext 注入 pinned block,检索失败仅降级不阻断主链路
- 更新 newAgent/tools/registry.go:新增 DefaultRegistryDeps(含 RAGRuntime),工具注册表支持依赖注入
5. 启动流程与事件处理器接线更新
- 更新 cmd/start.go:初始化 RAG Runtime → Memory Module → 注册事件处理器 → 启动 Worker 后台轮询
- 更新 service/events/memory_extract_requested.go:改用 memory.Module.WithTx(tx) 统一门面,事件处理器不再直接依赖
repo/service 内部包
6. 缓存插件与配置同步
- 更新 middleware/cache_deleter.go:静默忽略 MemoryJob / MemoryItem / MemoryAuditLog / MemoryUserSetting
等新模型,避免日志刷屏;清理冗余注释
- 更新 config.example.yaml:补齐 rag / memory / websearch 配置段及默认值
- 更新 go.mod / go.sum:新增 eino-ext/openai / json-patch / go-openai 依赖
前端:无 仓库:无
199 lines
6.1 KiB
Go
199 lines
6.1 KiB
Go
package events
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
kafkabus "github.com/LoveLosita/smartflow/backend/infra/kafka"
|
|
outboxinfra "github.com/LoveLosita/smartflow/backend/infra/outbox"
|
|
"github.com/LoveLosita/smartflow/backend/memory"
|
|
memorymodel "github.com/LoveLosita/smartflow/backend/memory/model"
|
|
"github.com/LoveLosita/smartflow/backend/model"
|
|
"github.com/spf13/viper"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
// EventTypeMemoryExtractRequested 是“记忆抽取请求”事件类型。
|
|
EventTypeMemoryExtractRequested = "memory.extract.requested"
|
|
maxMemorySourceTextLength = 1500
|
|
)
|
|
|
|
// RegisterMemoryExtractRequestedHandler 注册“记忆抽取请求”消费者。
|
|
//
|
|
// 职责边界:
|
|
// 1. 只负责把事件转为 memory_jobs 任务;
|
|
// 2. 不在消费回调里执行 LLM 重计算;
|
|
// 3. 通过 memory.Module.WithTx(tx) 复用同一套接入门面,保证事务边界仍由 outbox 掌控。
|
|
func RegisterMemoryExtractRequestedHandler(
|
|
bus *outboxinfra.EventBus,
|
|
outboxRepo *outboxinfra.Repository,
|
|
memoryModule *memory.Module,
|
|
) error {
|
|
if bus == nil {
|
|
return errors.New("event bus is nil")
|
|
}
|
|
if outboxRepo == nil {
|
|
return errors.New("outbox repository is nil")
|
|
}
|
|
if memoryModule == nil {
|
|
return errors.New("memory module is nil")
|
|
}
|
|
|
|
handler := func(ctx context.Context, envelope kafkabus.Envelope) error {
|
|
var payload model.MemoryExtractRequestedPayload
|
|
if unmarshalErr := json.Unmarshal(envelope.Payload, &payload); unmarshalErr != nil {
|
|
_ = outboxRepo.MarkDead(ctx, envelope.OutboxID, "解析记忆抽取载荷失败: "+unmarshalErr.Error())
|
|
return nil
|
|
}
|
|
|
|
if validateErr := validateMemoryExtractPayload(payload); validateErr != nil {
|
|
_ = outboxRepo.MarkDead(ctx, envelope.OutboxID, "记忆抽取载荷非法: "+validateErr.Error())
|
|
return nil
|
|
}
|
|
|
|
return outboxRepo.ConsumeAndMarkConsumed(ctx, envelope.OutboxID, func(tx *gorm.DB) error {
|
|
jobPayload := memorymodel.ExtractJobPayload{
|
|
UserID: payload.UserID,
|
|
ConversationID: strings.TrimSpace(payload.ConversationID),
|
|
AssistantID: strings.TrimSpace(payload.AssistantID),
|
|
RunID: strings.TrimSpace(payload.RunID),
|
|
SourceMessageID: payload.SourceMessageID,
|
|
SourceRole: strings.TrimSpace(payload.SourceRole),
|
|
SourceText: strings.TrimSpace(payload.SourceText),
|
|
OccurredAt: payload.OccurredAt,
|
|
TraceID: strings.TrimSpace(payload.TraceID),
|
|
IdempotencyKey: strings.TrimSpace(payload.IdempotencyKey),
|
|
}
|
|
return memoryModule.WithTx(tx).EnqueueExtract(ctx, jobPayload, envelope.EventID)
|
|
})
|
|
}
|
|
|
|
return bus.RegisterEventHandler(EventTypeMemoryExtractRequested, handler)
|
|
}
|
|
|
|
// EnqueueMemoryExtractRequestedInTx 在事务内写入 memory.extract.requested outbox 消息。
|
|
//
|
|
// 设计目的:
|
|
// 1. 让“聊天消息已落库”和“记忆抽取事件已入队”同事务提交;
|
|
// 2. 任意一步失败都整体回滚,避免出现链路断点。
|
|
func EnqueueMemoryExtractRequestedInTx(
|
|
ctx context.Context,
|
|
outboxRepo *outboxinfra.Repository,
|
|
kafkaCfg kafkabus.Config,
|
|
chatPayload model.ChatHistoryPersistPayload,
|
|
) error {
|
|
if !isMemoryWriteEnabled() {
|
|
return nil
|
|
}
|
|
if outboxRepo == nil {
|
|
return errors.New("outbox repository is nil")
|
|
}
|
|
|
|
memoryPayload, shouldEnqueue := buildMemoryExtractPayloadFromChat(chatPayload)
|
|
if !shouldEnqueue {
|
|
return nil
|
|
}
|
|
|
|
payloadJSON, err := json.Marshal(memoryPayload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
outboxPayload := outboxinfra.OutboxEventPayload{
|
|
EventType: EventTypeMemoryExtractRequested,
|
|
EventVersion: outboxinfra.DefaultEventVersion,
|
|
AggregateID: strings.TrimSpace(chatPayload.ConversationID),
|
|
Payload: payloadJSON,
|
|
}
|
|
|
|
_, err = outboxRepo.CreateMessage(
|
|
ctx,
|
|
EventTypeMemoryExtractRequested,
|
|
kafkaCfg.Topic,
|
|
strings.TrimSpace(chatPayload.ConversationID),
|
|
outboxPayload,
|
|
kafkaCfg.MaxRetry,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func buildMemoryExtractPayloadFromChat(chatPayload model.ChatHistoryPersistPayload) (model.MemoryExtractRequestedPayload, bool) {
|
|
role := strings.ToLower(strings.TrimSpace(chatPayload.Role))
|
|
if role != "user" {
|
|
return model.MemoryExtractRequestedPayload{}, false
|
|
}
|
|
|
|
sourceText := strings.TrimSpace(chatPayload.Message)
|
|
if sourceText == "" {
|
|
return model.MemoryExtractRequestedPayload{}, false
|
|
}
|
|
|
|
truncatedSourceText := truncateByRune(sourceText, maxMemorySourceTextLength)
|
|
now := time.Now()
|
|
return model.MemoryExtractRequestedPayload{
|
|
UserID: chatPayload.UserID,
|
|
ConversationID: strings.TrimSpace(chatPayload.ConversationID),
|
|
// Day1 先保留 assistant_id/run_id 空值,后续从主链路上下文补齐。
|
|
AssistantID: "",
|
|
RunID: "",
|
|
SourceMessageID: 0,
|
|
SourceRole: role,
|
|
SourceText: truncatedSourceText,
|
|
OccurredAt: now,
|
|
TraceID: "",
|
|
IdempotencyKey: buildMemoryExtractIdempotencyKey(chatPayload.UserID, chatPayload.ConversationID, truncatedSourceText),
|
|
}, true
|
|
}
|
|
|
|
func validateMemoryExtractPayload(payload model.MemoryExtractRequestedPayload) error {
|
|
if payload.UserID <= 0 {
|
|
return errors.New("user_id is invalid")
|
|
}
|
|
if strings.TrimSpace(payload.ConversationID) == "" {
|
|
return errors.New("conversation_id is empty")
|
|
}
|
|
if strings.TrimSpace(payload.SourceRole) == "" {
|
|
return errors.New("source_role is empty")
|
|
}
|
|
if strings.TrimSpace(payload.SourceText) == "" {
|
|
return errors.New("source_text is empty")
|
|
}
|
|
if strings.TrimSpace(payload.IdempotencyKey) == "" {
|
|
return errors.New("idempotency_key is empty")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func buildMemoryExtractIdempotencyKey(userID int, conversationID, sourceText string) string {
|
|
raw := fmt.Sprintf("%d|%s|%s", userID, strings.TrimSpace(conversationID), strings.TrimSpace(sourceText))
|
|
sum := sha256.Sum256([]byte(raw))
|
|
return "memory_extract_" + strconv.Itoa(userID) + "_" + hex.EncodeToString(sum[:8])
|
|
}
|
|
|
|
func truncateByRune(raw string, max int) string {
|
|
if max <= 0 {
|
|
return ""
|
|
}
|
|
|
|
runes := []rune(raw)
|
|
if len(runes) <= max {
|
|
return raw
|
|
}
|
|
return string(runes[:max])
|
|
}
|
|
|
|
func isMemoryWriteEnabled() bool {
|
|
if !viper.IsSet("memory.enabled") {
|
|
return true
|
|
}
|
|
return viper.GetBool("memory.enabled")
|
|
}
|