ai

package
v0.100.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 16, 2026 License: MIT Imports: 18 Imported by: 0

README

DivineSense AI 大脑 (ai/)

ai 包是 DivineSense 的认知核心,囊括了从基础的 LLM 集成到高级自主 Agent(智能体)的所有智能能力。

🧠 系统架构 (知识图谱)

此架构图展示了 AI 模块的“宏观架构”与数据流转。

graph TD
    User[👤 用户] <--> API[📡 API 层]
    API <--> Router[🚦 路由系统]
    
    subgraph Brain [🧠 AI 大脑]
        direction TB
        
        %% Layer 1: 决策与编排
        Router --> |意图| Agents[🦜 智能体 / 鹦鹉]
        
        subgraph Cortex [认知引擎]
            Agents --> Orchestrator[🎼 编排器]
            Agents --> Universal[🤖 通用鹦鹉]
            Agents --> Geek[👨‍💻 极客鹦鹉]
        end
        
        %% Layer 2: 技能与感知
        subgraph Skills [技能与感知]
            Universal --> Time[🕰️ 时间解析]
            Universal --> Summary[📝 摘要]
            Universal --> Tags[🏷️ 标签]
            Universal --> Format[✨ 格式化]
            Universal --> Services[🔧 业务服务]
        end
        
        %% Layer 3: 记忆与上下文
        subgraph MemoryLobe [记忆与上下文]
            Context[🥡 上下文] --> Budget[💰 预算分配]
            Context --> ShortTerm[💭 短期记忆]
            Context --> LongTerm[📚 情景/图谱]
            Review[🔁 复习] --> SM2[📉 SM-2 算法]
        end
        
        %% Layer 4: 基础设施
        subgraph Foundation [核心基建]
            LLM[🔌 core/llm]
            Embed[🔢 core/embedding]
            Rerank[📶 core/reranker]
            Cache[⚡ 缓存]
            Config[⚙️ 配置加载]
        end
        
        Agents --> Context
        Skills --> Foundation
        MemoryLobe --> Foundation
    end
    
    %% 跨依赖
    Router --> Cache
    Router --> LLM
    LongTerm --> Graph[🕸️ 知识图谱]
    
    %% 输出
    Agents --> Response[💬 响应]

📚 微观架构与算法

1. 感知与路由 (前额叶)
  • routing: 四层意图分类架构
    • 算法: L0:LRU缓存 -> L1:规则匹配 (加权关键词) -> L2:历史匹配 (向量相似度) -> L3:LLM兜底
  • duplicate: 混合相似度检测
    • 算法: 得分 = 0.5*向量相似度 + 0.3*标签重合度 + 0.2*时间衰减
  • aitime: 自然语言时间解析
    • 流程: 正则匹配 -> NLP处理 (相对时间/中文语义) -> 标准化时间。
2. Agent 智能体系统 (鹦鹉)
  • agents: 自主实体系统。
    • UniversalParrot: 配置驱动的通用 Agent (如 Memo, Schedule)。支持 Direct (直接), ReAct (推理+行动), Planning (规划), Reflexion (反思) 策略。
    • GeekParrot: 通过 Claude Code CLI 实现代码执行能力的 Agent。
    • Orchestrator: 基于 DAG 的多 Agent 协同编排,包含 Decomposer (拆解器) 和 Handoff (交接) 机制。
  • services: 业务逻辑封装 (如 schedule 的重复规则处理)。
3. 认知能力 (技能)
  • tags: 三层标签推荐系统
    • 算法: L1:统计推荐 -> L2:规则推荐 -> L3:LLM语义推荐
  • summary: 高可用摘要生成
    • 流程: 尝试 LLM -> 降级至首段提取 -> 降级至截断。
  • enrichment: 流水线处理
    • 机制: 存前 (阻塞式) + 存后 (异步并行) 增强。
4. 记忆与上下文 (海马体)
  • context: 动态 Token 管理
    • 特性: Token 预算分配 (STM/LTM/RAG 比例),增量更新 (Context Caching)。
  • graph: 个人知识图谱
    • 算法: PageRank (重要性计算), 标签传播 (社区发现)。
  • review: 间隔重复复习
    • 算法: SM-2 (SuperMemo-2) 记忆曲线算法,优化复习间隔。
  • cache: 双层缓存架构
    • 架构: L1:LRU (精确 SHA256) + L2:Semantic (向量余弦相似度)。
5. 基础设施 (脑干)
  • core: 统一的 LLM, Embedding, Reranker, Retrieval 接口。
  • observability: 全栈 logging, metrics (Prometheus), tracing (OTEL)。
  • configloader: 具备回退机制的 YAML 配置加载器。
  • timeout: 集中式系统限制,防止“认知过载”。

🔄 核心工作流

W1: 用户查询处理
sequenceDiagram
    User->>Router: "查找关于 AI 的笔记"
    Router->>Router: 分类 -> 意图: MEMO_QUERY
    Router->>Agents: 路由(MEMO_QUERY) -> MemoParrot
    
    Agents->>Context: 构建上下文(历史 + RAG)
    Context-->>Agents: 返回 Prompt
    
    Agents->>LLM: 对话补全 (Chat Completion)
    LLM-->>Agents: 工具调用 (memo_search)
    
    Agents->>Tools: 执行 memo_search
    Tools-->>Agents: 返回结果
    
    Agents->>LLM: 生成回答
    Agents-->>User: 最终响应
W2: Memo 知识摄入
flowchart LR
    Input[原始 Memo] --> Enrich[✨ 增强流水线]
    
    subgraph Parallel Processing
        Enrich --> Tags[🏷️ 标签生成]
        Enrich --> Title[📑 标题生成]
        Enrich --> Summary[📝 摘要生成]
    end
    
    Tags & Title & Summary --> Save[💾 数据库保存]
    
    Save --> Embed[🔢 向量化 Embedding]
    Save --> Graph[🕸️ 更新图谱]
    Save --> Review[📅 安排复习]

📂 目录结构映射

ai/
├── core/               # Layer 0: 基础能力 (LLM, Embed, Rerank)
├── internal/           # Layer 0: 内部工具 (strutil)
├── observability/      # Layer 0: 监控 (Logs, Metrics, Traces)
├── configloader/       # Layer 0: 配置加载
├── timeout/            # Layer 0: 系统限制
├── cache/              # Layer 1: 语义缓存
├── context/            # Layer 1: 上下文窗口管理
├── services/           # Layer 2: 业务逻辑 (Schedule, Session)
├── agents/             # Layer 3: 自主智能体 (Parrots)
├── routing/            # Layer 3: 意图分类与路由
├── aitime/             # Skill: 时间解析
├── tags/               # Skill: 标签推荐
├── summary/            # Skill: 摘要生成
├── format/             # Skill: 格式化
├── enrichment/         # Skill: 处理流水线
├── duplicate/          # Skill: 去重与查重
├── review/             # Skill: 间隔复习
└── graph/              # Skill: 知识图谱

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetTitleConfigDir added in v0.100.0

func SetTitleConfigDir(dir string)

SetTitleConfigDir overrides the default config directory.

Types

type BlockContent added in v0.94.0

type BlockContent struct {
	UserInput        string
	AssistantContent string
}

BlockContent represents a simplified block for title generation.

type ChatResponse deprecated

type ChatResponse = llm.ChatResponse

ChatResponse represents the LLM response including potential tool calls.

Deprecated: Use llm.ChatResponse directly.

type Config

type Config struct {
	Embedding        EmbeddingConfig
	Reranker         RerankerConfig
	IntentClassifier IntentClassifierConfig
	LLM              LLMConfig
	UniversalParrot  UniversalParrotConfig // Phase 2: Configuration-driven parrots
	Enabled          bool
}

Config represents AI configuration.

func NewConfigFromProfile

func NewConfigFromProfile(p *profile.Profile) *Config

NewConfigFromProfile creates AI config from profile.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type ConversationPromptData added in v0.100.0

type ConversationPromptData struct {
	UserMessage string
	AIResponse  string
}

ConversationPromptData holds data for conversation title template.

type EmbeddingConfig

type EmbeddingConfig struct {
	Provider   string
	Model      string
	APIKey     string
	BaseURL    string
	Dimensions int
}

EmbeddingConfig represents vector embedding configuration.

type EmbeddingService

type EmbeddingService interface {
	// Embed generates vector for a single text.
	Embed(ctx context.Context, text string) ([]float32, error)

	// EmbedBatch generates vectors for multiple texts.
	EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

	// Dimensions returns the vector dimension.
	Dimensions() int
}

EmbeddingService is the vector embedding service interface.

func NewEmbeddingService

func NewEmbeddingService(cfg *EmbeddingConfig) (EmbeddingService, error)

NewEmbeddingService creates a new EmbeddingService.

Phase 1 Note: This is a bridge compatibility layer that maintains the original API. The actual embedding functionality has been moved to ai/core/embedding/provider.go. Future refactoring will deprecate this file in favor of the core package.

type FunctionCall deprecated

type FunctionCall = llm.FunctionCall

FunctionCall represents the function details.

Deprecated: Use llm.FunctionCall directly.

type IntentClassifierConfig

type IntentClassifierConfig struct {
	Model   string
	APIKey  string
	BaseURL string
	Enabled bool
}

IntentClassifierConfig represents intent classification LLM configuration. Uses a lightweight model for fast, cost-effective classification.

type LLMCallStats deprecated added in v0.94.0

type LLMCallStats = llm.LLMCallStats

LLMCallStats represents statistics for a single LLM call.

Deprecated: Use llm.LLMCallStats directly.

type LLMConfig

type LLMConfig struct {
	Provider    string // Provider identifier for logging/future extension: zai, deepseek, openai, ollama
	Model       string // Model name: glm-4.7, deepseek-chat, gpt-4o, etc.
	APIKey      string
	BaseURL     string
	MaxTokens   int     // default: 2048
	Temperature float32 // default: 0.7
	Timeout     int     // Request timeout in seconds (default: 120)
}

LLMConfig represents LLM configuration.

type LLMService deprecated

type LLMService = llm.Service

LLMService is the LLM service interface.

Deprecated: Use llm.Service directly.

func NewLLMService

func NewLLMService(cfg *LLMConfig) (LLMService, error)

NewLLMService creates a new LLMService.

Phase 1 Note: This is a bridge compatibility layer that maintains the original API. The actual LLM functionality has been moved to ai/core/llm/service.go.

type MemoPromptData added in v0.100.0

type MemoPromptData struct {
	Content string
	Title   string
}

MemoPromptData holds data for memo title template.

type Message deprecated

type Message = llm.Message

Message represents a chat message.

Deprecated: Use llm.Message directly.

func AssistantMessage deprecated

func AssistantMessage(content string) Message

AssistantMessage creates an assistant message.

Deprecated: Use llm.AssistantMessage directly.

func FormatMessages deprecated

func FormatMessages(systemPrompt string, userContent string, history []Message) []Message

FormatMessages formats messages for prompt templates.

Deprecated: Use llm.FormatMessages directly.

func SystemPrompt deprecated

func SystemPrompt(content string) Message

SystemPrompt creates a system message.

Deprecated: Use llm.SystemPrompt directly.

func UserMessage deprecated

func UserMessage(content string) Message

UserMessage creates a user message.

Deprecated: Use llm.UserMessage directly.

type RerankResult deprecated

type RerankResult = reranker.Result

RerankResult represents a reranking result.

Deprecated: Use reranker.Result directly.

type RerankerConfig

type RerankerConfig struct {
	Provider string
	Model    string
	APIKey   string
	BaseURL  string
	Enabled  bool
}

RerankerConfig represents reranker configuration.

type RerankerService deprecated

type RerankerService = reranker.Service

RerankerService is the reranking service interface.

Deprecated: Use reranker.Service directly.

func NewRerankerService

func NewRerankerService(cfg *RerankerConfig) RerankerService

NewRerankerService creates a new RerankerService.

Phase 1 Note: This is a bridge compatibility layer that maintains the original API. The actual reranker functionality has been moved to ai/core/reranker/service.go.

type TitleGenerator added in v0.94.0

type TitleGenerator struct {
	// contains filtered or unexported fields
}

TitleGenerator generates meaningful titles for AI conversations. Uses configuration from config/prompts/title.yaml.

func NewTitleGenerator deprecated added in v0.94.0

func NewTitleGenerator(cfg TitleGeneratorConfig) *TitleGenerator

NewTitleGenerator creates a new title generator instance.

Deprecated: Use NewTitleGeneratorWithLLM(llm LLMService) instead. This constructor is kept for backward compatibility.

func NewTitleGeneratorWithLLM added in v0.100.0

func NewTitleGeneratorWithLLM(llmService LLMService) *TitleGenerator

NewTitleGeneratorWithLLM creates a new title generator with an existing LLMService. This is the preferred constructor for dependency injection. Panics if llmService is nil.

func (*TitleGenerator) Generate added in v0.94.0

func (tg *TitleGenerator) Generate(ctx context.Context, userMessage, aiResponse string) (string, error)

Generate generates a title based on the conversation content.

func (*TitleGenerator) GenerateTitleFromBlocks added in v0.94.0

func (tg *TitleGenerator) GenerateTitleFromBlocks(ctx context.Context, blocks []BlockContent) (string, error)

GenerateTitleFromBlocks generates a title from a slice of blocks.

type TitleGeneratorConfig deprecated added in v0.94.0

type TitleGeneratorConfig struct {
	APIKey  string
	BaseURL string
	Model   string
}

TitleGeneratorConfig holds configuration for the title generator.

Deprecated: Use NewTitleGeneratorWithLLM(llm LLMService) directly. This config is kept for backward compatibility.

type TitlePromptConfig added in v0.100.0

type TitlePromptConfig struct {
	Name                 string `yaml:"name"`
	Version              string `yaml:"version"`
	SystemPrompt         string `yaml:"system_prompt"`
	ConversationTemplate string `yaml:"conversation_template"`
	MemoTemplate         string `yaml:"memo_template"`
	Params               struct {
		MaxTokens          int     `yaml:"max_tokens"`
		Temperature        float64 `yaml:"temperature"`
		TimeoutSeconds     int     `yaml:"timeout_seconds"`
		InputTruncateChars int     `yaml:"input_truncate_chars"`
		MaxRunes           int     `yaml:"max_runes"`
	} `yaml:"params"`
}

TitlePromptConfig holds the configuration for title generation.

func GetTitlePromptConfig added in v0.100.0

func GetTitlePromptConfig() *TitlePromptConfig

GetTitlePromptConfig returns the global title prompt config, loading if necessary. Falls back to defaults if config file fails to load.

func LoadTitlePromptConfig added in v0.100.0

func LoadTitlePromptConfig() (*TitlePromptConfig, error)

LoadTitlePromptConfig loads the title prompt configuration from YAML.

func (*TitlePromptConfig) BuildConversationPrompt added in v0.100.0

func (c *TitlePromptConfig) BuildConversationPrompt(data *ConversationPromptData) (string, error)

BuildConversationPrompt builds the user prompt for conversation title generation.

func (*TitlePromptConfig) BuildMemoPrompt added in v0.100.0

func (c *TitlePromptConfig) BuildMemoPrompt(data *MemoPromptData) (string, error)

BuildMemoPrompt builds the user prompt for memo title generation.

type ToolCall deprecated

type ToolCall = llm.ToolCall

ToolCall represents a request to call a tool.

Deprecated: Use llm.ToolCall directly.

type ToolDescriptor deprecated

type ToolDescriptor = llm.ToolDescriptor

ToolDescriptor represents a function/tool available to the LLM.

Deprecated: Use llm.ToolDescriptor directly.

type UniversalParrotConfig added in v0.94.0

type UniversalParrotConfig struct {
	Enabled      bool   // Enable UniversalParrot for creating parrots from YAML configs
	ConfigDir    string // Path to parrot YAML configs (default: ./config/parrots)
	FallbackMode string // "legacy" | "error" when config load fails (default: legacy)
	BaseURL      string // Frontend base URL for generating links in prompts
}

UniversalParrotConfig represents configuration for UniversalParrot (configuration-driven parrots).

Directories

Path Synopsis
Package agent provides conversation context management for multi-turn dialogues.
Package agent provides conversation context management for multi-turn dialogues.
events
Package events provides event callback types for the agent system.
Package events provides event callback types for the agent system.
orchestrator
Package orchestrator implements the Orchestrator-Workers pattern for multi-agent coordination.
Package orchestrator implements the Orchestrator-Workers pattern for multi-agent coordination.
registry
Package registry provides metrics collection for UniversalParrot.
Package registry provides metrics collection for UniversalParrot.
tools
Package tools provides tool-level result caching for AI agents.
Package tools provides tool-level result caching for AI agents.
tools/schedule
Package schedule provides thin tool adapters for schedule operations.
Package schedule provides thin tool adapters for schedule operations.
universal
Package universal provides configuration loading for UniversalParrot.
Package universal provides configuration loading for UniversalParrot.
Package aitime provides the time parsing service interface for AI agents.
Package aitime provides the time parsing service interface for AI agents.
Package cache provides the cache service interface for AI agents.
Package cache provides the cache service interface for AI agents.
Package context provides context building for LLM prompts.
Package context provides context building for LLM prompts.
core
llm
Package duplicate provides memo duplicate detection for P2-C002.
Package duplicate provides memo duplicate detection for P2-C002.
Package format provides the formatter interface for AI text formatting.
Package format provides the formatter interface for AI text formatting.
Package graph - builder implementation for P3-C001.
Package graph - builder implementation for P3-C001.
internal
strutil
Package strutil provides string utility functions for the ai package.
Package strutil provides string utility functions for the ai package.
Package memory provides the memory extension point for AI agents.
Package memory provides the memory extension point for AI agents.
simple
Package simple provides a basic memory generator implementation.
Package simple provides a basic memory generator implementation.
observability
logging
Package logging provides structured logging utilities for AI modules.
Package logging provides structured logging utilities for AI modules.
metrics
Package metrics provides the evaluation metrics service interface for AI agents.
Package metrics provides the evaluation metrics service interface for AI agents.
tracing
Package tracing provides distributed tracing instrumentation for AI modules.
Package tracing provides distributed tracing instrumentation for AI modules.
Package review provides intelligent memo review system based on spaced repetition.
Package review provides intelligent memo review system based on spaced repetition.
Package routing provides routing result caching for performance optimization.
Package routing provides routing result caching for performance optimization.
services
session
Package session provides the session persistence service interface for AI agents.
Package session provides the session persistence service interface for AI agents.
stats
Package stats provides cost alerting for agent sessions.
Package stats provides cost alerting for agent sessions.
Package tags provides intelligent tag suggestion for memos.
Package tags provides intelligent tag suggestion for memos.
Package timeout defines centralized timeout constants for AI operations.
Package timeout defines centralized timeout constants for AI operations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL