Skip to main content

ai00_mem/
core.rs

1//! 核心数据结构和类型定义
2//!
3//! 本模块包含AI00-Mem记忆系统的所有核心数据结构,包括记忆、连接、查询等类型。
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::HashMap;
9use uuid::Uuid;
10
11// 重新导出memory模块中的类型
12pub use crate::memory::{RetrievalExplanation, RetrievalResult};
13
14/// 记忆ID类型
15pub type MemoryId = String;
16
17/// 连接ID类型
18pub type ConnectionId = String;
19
20
21
22/// 会话ID类型
23pub type SessionId = String;
24
25/// 记忆类型枚举
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
27pub enum MemoryType {
28    Knowledge,    // 知识型记忆:事实、概念、技能
29    Event,        // 事件型记忆:具体发生的事情
30    Task,         // 任务型记忆:待办事项、计划
31    Conversation, // 对话型记忆:聊天记录、交互
32    Reflection,   // 反思型记忆:总结、思考
33    Goal,         // 目标型记忆:长期目标、愿望
34    Habit,        // 习惯型记忆:行为模式、偏好
35    Emotion,      // 情感型记忆:情绪状态、感受
36}
37
38/// 用户状态枚举
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40pub enum UserState {
41    /// 活跃状态
42    Active,
43    /// 学习状态
44    Learning,
45    /// 空闲状态
46    Idle,
47    /// 忙碌状态
48    Busy,
49}
50
51/// 情感状态枚举
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
53pub enum EmotionalState {
54    /// 中性
55    Neutral,
56    /// 好奇
57    Curious,
58    /// 兴奋
59    Excited,
60    /// 感兴趣
61    Interested,
62    /// 困惑
63    Confused,
64    /// 满意
65    Satisfied,
66}
67
68/// 注意力水平枚举
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
70pub enum AttentionLevel {
71    /// 低
72    Low,
73    /// 中等
74    Medium,
75    /// 高
76    High,
77}
78
79/// 记忆结构定义
80///
81/// 表示系统中的一个记忆单元,包含内容、嵌入向量、属性、连接和元数据。
82#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
83pub struct Memory {
84    /// 唯一标识符
85    pub id: MemoryId,
86    /// 记忆内容
87    pub content: String,
88    /// 记忆类型
89    pub memory_type: MemoryType,
90    /// 语义嵌入向量
91    pub embedding: Vec<f32>,
92    /// 记忆属性
93    pub attributes: MemoryAttributes,
94    /// 记忆连接
95    pub connections: MemoryConnections,
96    /// 元数据
97    pub metadata: MemoryMetadata,
98}
99
100/// 记忆属性
101///
102/// 包含记忆的各种属性信息,如关键词、标签、重要性等。
103#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
104pub struct MemoryAttributes {
105    /// 关键词列表
106    pub keywords: Vec<String>,
107    /// 标签列表
108    pub tags: Vec<String>,
109    /// 上下文描述
110    pub context: String,
111    /// 重要性评分 (0.0 - 1.0)
112    pub importance: f32,
113    /// 情感标记
114    pub emotion: Option<String>,
115    /// 来源信息
116    pub source: Option<String>,
117    /// 置信度 (0.0 - 1.0)
118    pub confidence: f32,
119    /// 语言标识
120    pub language: Option<String>,
121    /// 自定义属性
122    pub custom_attributes: HashMap<String, Value>,
123}
124
125/// 记忆连接
126///
127/// 定义记忆之间的各种连接关系。
128#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
129pub struct MemoryConnections {
130    /// 语义相关的记忆ID列表
131    pub semantic_links: Vec<MemoryId>,
132    /// 时间相关的记忆ID列表
133    pub temporal_links: Vec<MemoryId>,
134    /// 因果相关的记忆ID列表
135    pub causal_links: Vec<MemoryId>,
136    /// 主题相关的记忆ID列表
137    pub thematic_links: Vec<MemoryId>,
138    /// 自定义连接类型
139    pub custom_links: HashMap<String, Vec<MemoryId>>,
140}
141
142/// 记忆元数据
143///
144/// 包含记忆的时间戳、访问统计等元信息。
145#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
146pub struct MemoryMetadata {
147    /// 创建时间
148    pub created_at: DateTime<Utc>,
149    /// 最后更新时间
150    pub updated_at: DateTime<Utc>,
151    /// 访问次数
152    pub access_count: u64,
153    /// 最后访问时间
154    pub last_accessed: DateTime<Utc>,
155    /// 版本号
156    pub version: u32,
157    /// 是否已删除
158    pub is_deleted: bool,
159    /// 删除时间
160    pub deleted_at: Option<DateTime<Utc>>,
161    /// 自定义元数据
162    pub custom_metadata: HashMap<String, Value>,
163}
164
165/// 上下文结构
166///
167/// 表示当前的对话或操作上下文。
168#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
169pub struct Context {
170    /// 会话ID
171    pub session_id: Option<SessionId>,
172    /// 当前主题
173    pub current_topic: Option<String>,
174    /// 最近的记忆ID列表
175    pub recent_memories: Vec<MemoryId>,
176    /// 用户偏好设置
177    pub user_preferences: HashMap<String, Value>,
178    /// 环境信息
179    pub environment: HashMap<String, Value>,
180    /// 时间窗口
181    pub time_window: Option<(DateTime<Utc>, DateTime<Utc>)>,
182    /// 优先级
183    pub priority: Priority,
184}
185
186/// 优先级枚举
187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
188pub enum Priority {
189    Low,
190    Normal,
191    High,
192    Critical,
193}
194
195/// 查询结构
196///
197/// 定义记忆检索查询的参数。
198#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
199pub struct Query {
200    /// 查询文本
201    pub text: String,
202    /// 查询类型
203    pub query_type: QueryType,
204    /// 查询过滤器
205    pub filters: QueryFilters,
206    /// 结果数量限制
207    pub limit: Option<usize>,
208    /// 偏移量
209    pub offset: Option<usize>,
210    /// 排序方式
211    pub sort_by: Option<SortBy>,
212    /// 查询权重
213    pub weights: QueryWeights,
214}
215
216/// 查询类型枚举
217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
218pub enum QueryType {
219    /// 语义检索
220    Semantic,
221    /// 时间检索
222    Temporal,
223    /// 因果检索
224    Causal,
225    /// 主题检索
226    Thematic,
227    /// 混合检索
228    Mixed,
229    /// 图遍历检索
230    GraphTraversal,
231    /// 个性化PageRank检索
232    PersonalizedPageRank,
233}
234
235/// 查询过滤器
236///
237/// 定义查询的各种过滤条件。
238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
239pub struct QueryFilters {
240    /// 标签过滤
241    pub tags: Option<Vec<String>>,
242    /// 时间范围过滤
243    pub time_range: Option<(DateTime<Utc>, DateTime<Utc>)>,
244    /// 重要性阈值
245    pub importance_threshold: Option<f32>,
246    /// 来源过滤
247    pub source_filter: Option<String>,
248    /// 语言过滤
249    pub language_filter: Option<String>,
250    /// 情感过滤
251    pub emotion_filter: Option<String>,
252    /// 置信度阈值
253    pub confidence_threshold: Option<f32>,
254    /// 自定义过滤器
255    pub custom_filters: HashMap<String, Value>,
256}
257
258/// 排序方式
259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
260pub enum SortBy {
261    /// 按相关性排序
262    Relevance,
263    /// 按时间排序
264    Time,
265    /// 按重要性排序
266    Importance,
267    /// 按访问频率排序
268    AccessCount,
269    /// 按置信度排序
270    Confidence,
271    /// 自定义排序
272    Custom(String),
273}
274
275/// 查询权重
276///
277/// 定义不同检索维度的权重。
278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
279pub struct QueryWeights {
280    /// 语义权重
281    pub semantic_weight: f32,
282    /// 时间权重
283    pub temporal_weight: f32,
284    /// 重要性权重
285    pub importance_weight: f32,
286    /// 频率权重
287    pub frequency_weight: f32,
288    /// 个性化权重
289    pub personalization_weight: f32,
290}
291
292/// 连接结构
293///
294/// 表示两个记忆之间的连接关系。
295#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
296pub struct Connection {
297    /// 连接ID
298    pub id: ConnectionId,
299    /// 源记忆ID
300    pub from_memory: MemoryId,
301    /// 目标记忆ID
302    pub to_memory: MemoryId,
303    /// 连接类型
304    pub connection_type: ConnectionType,
305    /// 连接强度 (0.0 - 1.0)
306    pub strength: f32,
307    /// 创建时间
308    pub created_at: DateTime<Utc>,
309    /// 最后更新时间
310    pub updated_at: DateTime<Utc>,
311    /// 连接属性
312    pub properties: HashMap<String, Value>,
313    /// 是否双向连接
314    pub bidirectional: bool,
315}
316
317/// 连接类型枚举
318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
319pub enum ConnectionType {
320    /// 语义连接
321    Semantic,
322    /// 时间连接
323    Temporal,
324    /// 因果连接
325    Causal,
326    /// 主题连接
327    Thematic,
328    /// 层次连接
329    Hierarchical,
330    /// 引用连接
331    Reference,
332    /// 自定义连接
333    Custom(String),
334}
335
336/// 演化触发器
337///
338/// 定义触发记忆演化的各种事件。
339#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
340pub enum EvolutionTrigger {
341    /// 新记忆添加
342    NewMemoryAdded(MemoryId),
343    /// 访问模式变化
344    AccessPatternChanged(MemoryId),
345    /// 时间衰减
346    TimeDecay,
347    /// 用户反馈
348    UserFeedback(MemoryId, f32),
349    /// 连接强度变化
350    ConnectionStrengthChanged(ConnectionId),
351    /// 批量更新
352    BatchUpdate(Vec<MemoryId>),
353    /// 系统维护
354    SystemMaintenance,
355}
356
357/// 更新操作
358///
359/// 定义对记忆的各种更新操作。
360#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
361pub struct Update {
362    /// 更新ID
363    pub id: String,
364    /// 目标记忆ID
365    pub memory_id: MemoryId,
366    /// 更新类型
367    pub update_type: UpdateType,
368    /// 时间戳
369    pub timestamp: DateTime<Utc>,
370    /// 更新原因
371    pub reason: Option<String>,
372    /// 更新者信息
373    pub updater_info: Option<String>,
374}
375
376/// 更新类型枚举
377#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
378pub enum UpdateType {
379    /// 重要性调整
380    ImportanceAdjustment(f32),
381    /// 连接添加
382    ConnectionAdded(Connection),
383    /// 连接移除
384    ConnectionRemoved(ConnectionId),
385    /// 属性更新
386    AttributeUpdate(String, Value),
387    /// 内容更新
388    ContentUpdate(String),
389    /// 标签更新
390    TagUpdate(Vec<String>),
391    /// 元数据更新
392    MetadataUpdate(HashMap<String, Value>),
393}
394
395/// 交互记录
396///
397/// 记录用户与系统的交互信息。
398#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
399pub struct Interaction {
400    /// 交互ID
401    pub id: String,
402    /// 用户ID
403    pub user_id: String,
404    /// 会话ID
405    pub session_id: Option<SessionId>,
406    /// 查询内容
407    pub query: String,
408    /// 检索到的记忆ID列表
409    pub retrieved_memories: Vec<MemoryId>,
410    /// 用户反馈评分
411    pub user_feedback: Option<f32>,
412    /// 交互类型
413    pub interaction_type: InteractionType,
414    /// 时间戳
415    pub timestamp: DateTime<Utc>,
416    /// 响应时间(毫秒)
417    pub response_time_ms: Option<u64>,
418    /// 额外信息
419    pub additional_info: HashMap<String, Value>,
420}
421
422/// 交互类型枚举
423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
424pub enum InteractionType {
425    /// 查询
426    Query,
427    /// 创建记忆
428    CreateMemory,
429    /// 更新记忆
430    UpdateMemory,
431    /// 删除记忆
432    DeleteMemory,
433    /// 反馈
434    Feedback,
435    /// 浏览
436    Browse,
437}
438
439/// 统计信息
440///
441/// 系统运行统计数据。
442#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
443pub struct Statistics {
444    /// 总记忆数量
445    pub total_memories: u64,
446    /// 总连接数量
447    pub total_connections: u64,
448    /// 平均重要性
449    pub average_importance: f32,
450    /// 最近访问的记忆数量
451    pub recently_accessed_count: u64,
452    /// 系统启动时间
453    pub system_start_time: DateTime<Utc>,
454    /// 最后更新时间
455    pub last_update_time: DateTime<Utc>,
456    /// 用户统计
457    pub user_stats: HashMap<String, UserStatistics>,
458    /// 性能指标
459    pub performance_metrics: PerformanceMetrics,
460}
461
462/// 用户统计信息
463#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
464pub struct UserStatistics {
465    /// 用户ID
466    pub user_id: String,
467    /// 记忆数量
468    pub memory_count: u64,
469    /// 查询次数
470    pub query_count: u64,
471    /// 平均反馈评分
472    pub average_feedback: f32,
473    /// 最后活跃时间
474    pub last_active: DateTime<Utc>,
475    /// 偏好标签
476    pub preferred_tags: Vec<String>,
477}
478
479/// 性能指标
480#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
481pub struct PerformanceMetrics {
482    /// 平均查询时间(毫秒)
483    pub average_query_time_ms: f64,
484    /// 平均创建时间(毫秒)
485    pub average_creation_time_ms: f64,
486    /// 缓存命中率
487    pub cache_hit_rate: f32,
488    /// 内存使用量(字节)
489    pub memory_usage_bytes: u64,
490    /// 磁盘使用量(字节)
491    pub disk_usage_bytes: u64,
492    /// 每秒查询数
493    pub queries_per_second: f64,
494}
495
496// 默认实现
497impl Default for MemoryAttributes {
498    fn default() -> Self {
499        Self {
500            keywords: Vec::new(),
501            tags: Vec::new(),
502            context: String::new(),
503            importance: 0.5,
504            emotion: None,
505            source: None,
506            confidence: 1.0,
507            language: None,
508            custom_attributes: HashMap::new(),
509        }
510    }
511}
512
513impl Default for Context {
514    fn default() -> Self {
515        Self {
516            session_id: None,
517            current_topic: None,
518            recent_memories: Vec::new(),
519            user_preferences: HashMap::new(),
520            environment: HashMap::new(),
521            time_window: None,
522            priority: Priority::Normal,
523        }
524    }
525}
526
527impl Default for QueryWeights {
528    fn default() -> Self {
529        Self {
530            semantic_weight: 0.4,
531            temporal_weight: 0.2,
532            importance_weight: 0.2,
533            frequency_weight: 0.1,
534            personalization_weight: 0.1,
535        }
536    }
537}
538
539impl Default for Priority {
540    fn default() -> Self {
541        Self::Normal
542    }
543}
544
545// 辅助函数
546impl Default for MemoryMetadata {
547    fn default() -> Self {
548        let now = Utc::now();
549        Self {
550            created_at: now,
551            updated_at: now,
552            access_count: 0,
553            last_accessed: now,
554            version: 1,
555            is_deleted: false,
556            deleted_at: None,
557            custom_metadata: HashMap::new(),
558        }
559    }
560}
561
562impl Default for Memory {
563    fn default() -> Self {
564        let _now = Utc::now();
565        Self {
566            id: Uuid::new_v4().to_string(),
567            content: String::new(),
568            memory_type: MemoryType::Knowledge,
569            embedding: Vec::new(),
570            attributes: MemoryAttributes::default(),
571            connections: MemoryConnections::default(),
572            metadata: MemoryMetadata::default(),
573        }
574    }
575}
576
577impl Memory {
578    /// 创建新的记忆
579    pub fn new(
580        content: String,
581        memory_type: MemoryType,
582        embedding: Vec<f32>,
583        attributes: MemoryAttributes,
584    ) -> Self {
585        let now = Utc::now();
586        Self {
587            id: Uuid::new_v4().to_string(),
588            content,
589            memory_type,
590            embedding,
591            attributes,
592            connections: MemoryConnections::default(),
593            metadata: MemoryMetadata {
594                created_at: now,
595                updated_at: now,
596                access_count: 0,
597                last_accessed: now,
598                version: 1,
599                is_deleted: false,
600                deleted_at: None,
601                custom_metadata: HashMap::new(),
602            },
603        }
604    }
605
606    /// 更新访问信息
607    pub fn update_access(&mut self) {
608        self.metadata.access_count += 1;
609        self.metadata.last_accessed = Utc::now();
610    }
611
612    /// 检查是否匹配过滤器
613    pub fn matches_filters(&self, filters: &QueryFilters) -> bool {
614        // 标签过滤
615        if let Some(required_tags) = &filters.tags {
616            if !required_tags
617                .iter()
618                .any(|tag| self.attributes.tags.contains(tag))
619            {
620                return false;
621            }
622        }
623
624        // 时间范围过滤
625        if let Some((start, end)) = filters.time_range {
626            if self.metadata.created_at < start || self.metadata.created_at > end {
627                return false;
628            }
629        }
630
631        // 重要性阈值过滤
632        if let Some(threshold) = filters.importance_threshold {
633            if self.attributes.importance < threshold {
634                return false;
635            }
636        }
637
638        // 置信度阈值过滤
639        if let Some(threshold) = filters.confidence_threshold {
640            if self.attributes.confidence < threshold {
641                return false;
642            }
643        }
644
645        // 来源过滤
646        if let Some(source) = &filters.source_filter {
647            if self.attributes.source.as_ref() != Some(source) {
648                return false;
649            }
650        }
651
652        // 语言过滤
653        if let Some(language) = &filters.language_filter {
654            if self.attributes.language.as_ref() != Some(language) {
655                return false;
656            }
657        }
658
659        // 情感过滤
660        if let Some(emotion) = &filters.emotion_filter {
661            if self.attributes.emotion.as_ref() != Some(emotion) {
662                return false;
663            }
664        }
665
666        true
667    }
668}
669
670impl Connection {
671    /// 创建新的连接
672    pub fn new(
673        from_memory: MemoryId,
674        to_memory: MemoryId,
675        connection_type: ConnectionType,
676        strength: f32,
677    ) -> Self {
678        let now = Utc::now();
679        Self {
680            id: Uuid::new_v4().to_string(),
681            from_memory,
682            to_memory,
683            connection_type,
684            strength: strength.clamp(0.0, 1.0),
685            created_at: now,
686            updated_at: now,
687            properties: HashMap::new(),
688            bidirectional: false,
689        }
690    }
691
692    /// 更新连接强度
693    pub fn update_strength(&mut self, new_strength: f32) {
694        self.strength = new_strength.clamp(0.0, 1.0);
695        self.updated_at = Utc::now();
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    #[test]
704    fn test_memory_creation() {
705        let memory = Memory::new(
706            "Test content".to_string(),
707            MemoryType::Knowledge,
708            vec![0.1, 0.2, 0.3],
709            MemoryAttributes::default(),
710        );
711
712        assert_eq!(memory.content, "Test content");
713        assert_eq!(memory.embedding, vec![0.1, 0.2, 0.3]);
714        assert_eq!(memory.metadata.access_count, 0);
715        assert_eq!(memory.metadata.version, 1);
716    }
717
718    #[test]
719    fn test_connection_creation() {
720        let connection = Connection::new(
721            "mem1".to_string(),
722            "mem2".to_string(),
723            ConnectionType::Semantic,
724            0.8,
725        );
726
727        assert_eq!(connection.from_memory, "mem1");
728        assert_eq!(connection.to_memory, "mem2");
729        assert_eq!(connection.strength, 0.8);
730        assert!(!connection.bidirectional);
731    }
732
733    #[test]
734    fn test_memory_filters() {
735        let memory = Memory::new(
736            "Test content".to_string(),
737            MemoryType::Knowledge,
738            vec![0.1, 0.2, 0.3],
739            MemoryAttributes {
740                tags: vec!["test".to_string(), "example".to_string()],
741                importance: 0.7,
742                confidence: 0.9,
743                ..Default::default()
744            },
745        );
746
747        let filters = QueryFilters {
748            tags: Some(vec!["test".to_string()]),
749            importance_threshold: Some(0.5),
750            confidence_threshold: Some(0.8),
751            ..Default::default()
752        };
753
754        assert!(memory.matches_filters(&filters));
755
756        let strict_filters = QueryFilters {
757            importance_threshold: Some(0.9),
758            ..Default::default()
759        };
760
761        assert!(!memory.matches_filters(&strict_filters));
762    }
763
764    #[test]
765    fn test_connection_strength_clamping() {
766        let mut connection = Connection::new(
767            "mem1".to_string(),
768            "mem2".to_string(),
769            ConnectionType::Semantic,
770            1.5, // 超出范围
771        );
772
773        assert_eq!(connection.strength, 1.0); // 应该被限制在1.0
774
775        connection.update_strength(-0.5); // 负值
776        assert_eq!(connection.strength, 0.0); // 应该被限制在0.0
777    }
778}