1use serde::{Deserialize, Serialize};
2
3pub type VectorId = String;
5
6pub type NamespaceId = String;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Vector {
12 pub id: VectorId,
13 pub values: Vec<f32>,
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub metadata: Option<serde_json::Value>,
16 #[serde(skip_serializing_if = "Option::is_none")]
18 pub ttl_seconds: Option<u64>,
19 #[serde(skip_serializing_if = "Option::is_none")]
21 pub expires_at: Option<u64>,
22}
23
24impl Vector {
25 pub fn is_expired(&self) -> bool {
27 if let Some(expires_at) = self.expires_at {
28 let now = std::time::SystemTime::now()
29 .duration_since(std::time::UNIX_EPOCH)
30 .unwrap_or_default()
31 .as_secs();
32 now >= expires_at
33 } else {
34 false
35 }
36 }
37
38 #[inline]
41 pub fn is_expired_at(&self, now_secs: u64) -> bool {
42 self.expires_at.is_some_and(|exp| now_secs >= exp)
43 }
44
45 pub fn apply_ttl(&mut self) {
47 if let Some(ttl) = self.ttl_seconds {
48 let now = std::time::SystemTime::now()
49 .duration_since(std::time::UNIX_EPOCH)
50 .unwrap_or_default()
51 .as_secs();
52 self.expires_at = Some(now + ttl);
53 }
54 }
55
56 pub fn remaining_ttl(&self) -> Option<u64> {
58 self.expires_at.and_then(|expires_at| {
59 let now = std::time::SystemTime::now()
60 .duration_since(std::time::UNIX_EPOCH)
61 .unwrap_or_default()
62 .as_secs();
63 if now < expires_at {
64 Some(expires_at - now)
65 } else {
66 None
67 }
68 })
69 }
70}
71
72#[derive(Debug, Deserialize)]
74pub struct UpsertRequest {
75 pub vectors: Vec<Vector>,
76}
77
78#[derive(Debug, Serialize, Deserialize)]
80pub struct UpsertResponse {
81 pub upserted_count: usize,
82}
83
84#[derive(Debug, Deserialize)]
87pub struct ColumnUpsertRequest {
88 pub ids: Vec<VectorId>,
90 pub vectors: Vec<Vec<f32>>,
92 #[serde(default)]
95 pub attributes: std::collections::HashMap<String, Vec<serde_json::Value>>,
96 #[serde(default)]
98 pub ttl_seconds: Option<u64>,
99 #[serde(default)]
101 pub dimension: Option<usize>,
102}
103
104impl ColumnUpsertRequest {
105 pub fn to_vectors(&self) -> Result<Vec<Vector>, String> {
107 let count = self.ids.len();
108
109 if self.vectors.len() != count {
111 return Err(format!(
112 "vectors array length ({}) doesn't match ids array length ({})",
113 self.vectors.len(),
114 count
115 ));
116 }
117
118 for (attr_name, attr_values) in &self.attributes {
119 if attr_values.len() != count {
120 return Err(format!(
121 "attribute '{}' array length ({}) doesn't match ids array length ({})",
122 attr_name,
123 attr_values.len(),
124 count
125 ));
126 }
127 }
128
129 let expected_dim = if let Some(dim) = self.dimension {
132 Some(dim)
133 } else {
134 self.vectors.first().map(|v| v.len())
135 };
136
137 if let Some(expected) = expected_dim {
138 for (i, vec) in self.vectors.iter().enumerate() {
139 if vec.len() != expected {
140 return Err(format!(
141 "vectors[{}] has dimension {} but expected {}",
142 i,
143 vec.len(),
144 expected
145 ));
146 }
147 }
148 }
149
150 let mut vectors = Vec::with_capacity(count);
152 for i in 0..count {
153 let metadata = if self.attributes.is_empty() {
155 None
156 } else {
157 let mut meta = serde_json::Map::new();
158 for (attr_name, attr_values) in &self.attributes {
159 let value = &attr_values[i];
160 if !value.is_null() {
161 meta.insert(attr_name.clone(), value.clone());
162 }
163 }
164 if meta.is_empty() {
165 None
166 } else {
167 Some(serde_json::Value::Object(meta))
168 }
169 };
170
171 let mut vector = Vector {
172 id: self.ids[i].clone(),
173 values: self.vectors[i].clone(),
174 metadata,
175 ttl_seconds: self.ttl_seconds,
176 expires_at: None,
177 };
178 vector.apply_ttl();
179 vectors.push(vector);
180 }
181
182 Ok(vectors)
183 }
184}
185
186#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
188#[serde(rename_all = "snake_case")]
189pub enum DistanceMetric {
190 #[default]
191 Cosine,
192 Euclidean,
193 DotProduct,
194}
195
196#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
203#[serde(rename_all = "snake_case")]
204pub enum ReadConsistency {
205 Strong,
207 #[default]
209 Eventual,
210 #[serde(rename = "bounded_staleness")]
212 BoundedStaleness,
213}
214
215#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
217pub struct StalenessConfig {
218 #[serde(default = "default_max_staleness_ms")]
220 pub max_staleness_ms: u64,
221}
222
223fn default_max_staleness_ms() -> u64 {
224 5000 }
226
227#[derive(Debug, Deserialize)]
229pub struct QueryRequest {
230 pub vector: Vec<f32>,
231 #[serde(default = "default_top_k")]
232 pub top_k: usize,
233 #[serde(default)]
234 pub distance_metric: DistanceMetric,
235 #[serde(default = "default_true")]
236 pub include_metadata: bool,
237 #[serde(default)]
238 pub include_vectors: bool,
239 #[serde(default)]
241 pub filter: Option<FilterExpression>,
242 #[serde(default)]
244 pub cursor: Option<String>,
245 #[serde(default)]
248 pub consistency: ReadConsistency,
249 #[serde(default)]
251 pub staleness_config: Option<StalenessConfig>,
252}
253
254fn default_top_k() -> usize {
255 10
256}
257
258fn default_true() -> bool {
259 true
260}
261
262#[derive(Debug, Serialize, Deserialize)]
264pub struct SearchResult {
265 pub id: VectorId,
266 pub score: f32,
267 #[serde(skip_serializing_if = "Option::is_none")]
268 pub metadata: Option<serde_json::Value>,
269 #[serde(skip_serializing_if = "Option::is_none")]
270 pub vector: Option<Vec<f32>>,
271}
272
273#[derive(Debug, Serialize, Deserialize)]
275pub struct QueryResponse {
276 pub results: Vec<SearchResult>,
277 #[serde(skip_serializing_if = "Option::is_none")]
279 pub next_cursor: Option<String>,
280 #[serde(skip_serializing_if = "Option::is_none")]
282 pub has_more: Option<bool>,
283 #[serde(default)]
285 pub search_time_ms: u64,
286}
287
288#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct PaginationCursor {
295 pub last_score: f32,
297 pub last_id: String,
299}
300
301impl PaginationCursor {
302 pub fn new(last_score: f32, last_id: String) -> Self {
304 Self {
305 last_score,
306 last_id,
307 }
308 }
309
310 pub fn encode(&self) -> String {
312 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
313 let json = serde_json::to_string(self).unwrap_or_default();
314 URL_SAFE_NO_PAD.encode(json.as_bytes())
315 }
316
317 pub fn decode(cursor: &str) -> Option<Self> {
319 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
320 let bytes = URL_SAFE_NO_PAD.decode(cursor).ok()?;
321 let json = String::from_utf8(bytes).ok()?;
322 serde_json::from_str(&json).ok()
323 }
324}
325
326#[derive(Debug, Deserialize)]
328pub struct DeleteRequest {
329 pub ids: Vec<VectorId>,
330}
331
332#[derive(Debug, Serialize)]
334pub struct DeleteResponse {
335 pub deleted_count: usize,
336}
337
338#[derive(Debug, Clone, Deserialize)]
344pub struct BatchQueryItem {
345 #[serde(default)]
347 pub id: Option<String>,
348 pub vector: Vec<f32>,
350 #[serde(default = "default_batch_top_k")]
352 pub top_k: u32,
353 #[serde(default)]
355 pub filter: Option<FilterExpression>,
356 #[serde(default)]
358 pub include_metadata: bool,
359 #[serde(default)]
361 pub consistency: ReadConsistency,
362 #[serde(default)]
364 pub staleness_config: Option<StalenessConfig>,
365}
366
367fn default_batch_top_k() -> u32 {
368 10
369}
370
371#[derive(Debug, Deserialize)]
373pub struct BatchQueryRequest {
374 pub queries: Vec<BatchQueryItem>,
376}
377
378#[derive(Debug, Serialize)]
380pub struct BatchQueryResult {
381 #[serde(skip_serializing_if = "Option::is_none")]
383 pub id: Option<String>,
384 pub results: Vec<SearchResult>,
386 pub latency_ms: f64,
388 #[serde(skip_serializing_if = "Option::is_none")]
390 pub error: Option<String>,
391}
392
393#[derive(Debug, Serialize)]
395pub struct BatchQueryResponse {
396 pub results: Vec<BatchQueryResult>,
398 pub total_latency_ms: f64,
400 pub query_count: usize,
402}
403
404#[derive(Debug, Deserialize)]
410pub struct MultiVectorSearchRequest {
411 pub positive_vectors: Vec<Vec<f32>>,
413 #[serde(default)]
415 pub positive_weights: Option<Vec<f32>>,
416 #[serde(default)]
418 pub negative_vectors: Option<Vec<Vec<f32>>>,
419 #[serde(default)]
421 pub negative_weights: Option<Vec<f32>>,
422 #[serde(default = "default_top_k")]
424 pub top_k: usize,
425 #[serde(default)]
427 pub distance_metric: DistanceMetric,
428 #[serde(default)]
430 pub score_threshold: Option<f32>,
431 #[serde(default)]
433 pub enable_mmr: bool,
434 #[serde(default = "default_mmr_lambda")]
436 pub mmr_lambda: f32,
437 #[serde(default = "default_true")]
439 pub include_metadata: bool,
440 #[serde(default)]
442 pub include_vectors: bool,
443 #[serde(default)]
445 pub filter: Option<FilterExpression>,
446 #[serde(default)]
448 pub consistency: ReadConsistency,
449 #[serde(default)]
451 pub staleness_config: Option<StalenessConfig>,
452}
453
454fn default_mmr_lambda() -> f32 {
455 0.5
456}
457
458#[derive(Debug, Serialize, Deserialize)]
460pub struct MultiVectorSearchResult {
461 pub id: VectorId,
462 pub score: f32,
464 #[serde(skip_serializing_if = "Option::is_none")]
466 pub mmr_score: Option<f32>,
467 #[serde(skip_serializing_if = "Option::is_none")]
469 pub original_rank: Option<usize>,
470 #[serde(skip_serializing_if = "Option::is_none")]
471 pub metadata: Option<serde_json::Value>,
472 #[serde(skip_serializing_if = "Option::is_none")]
473 pub vector: Option<Vec<f32>>,
474}
475
476#[derive(Debug, Serialize, Deserialize)]
478pub struct MultiVectorSearchResponse {
479 pub results: Vec<MultiVectorSearchResult>,
480 #[serde(skip_serializing_if = "Option::is_none")]
482 pub computed_query_vector: Option<Vec<f32>>,
483}
484
485#[derive(Debug, Serialize, Deserialize)]
491pub struct IndexDocumentRequest {
492 pub id: String,
493 pub text: String,
494 #[serde(skip_serializing_if = "Option::is_none")]
495 pub metadata: Option<serde_json::Value>,
496}
497
498#[derive(Debug, Deserialize)]
500pub struct IndexDocumentsRequest {
501 pub documents: Vec<IndexDocumentRequest>,
502}
503
504#[derive(Debug, Serialize, Deserialize)]
506pub struct IndexDocumentsResponse {
507 pub indexed_count: usize,
508}
509
510#[derive(Debug, Deserialize)]
512pub struct FullTextSearchRequest {
513 pub query: String,
514 #[serde(default = "default_top_k")]
515 pub top_k: usize,
516 #[serde(default)]
518 pub filter: Option<FilterExpression>,
519}
520
521#[derive(Debug, Serialize, Deserialize)]
523pub struct FullTextSearchResult {
524 pub id: String,
525 pub score: f32,
526 #[serde(skip_serializing_if = "Option::is_none")]
527 pub metadata: Option<serde_json::Value>,
528}
529
530#[derive(Debug, Serialize, Deserialize)]
532pub struct FullTextSearchResponse {
533 pub results: Vec<FullTextSearchResult>,
534 #[serde(default)]
536 pub search_time_ms: u64,
537}
538
539#[derive(Debug, Deserialize)]
541pub struct DeleteDocumentsRequest {
542 pub ids: Vec<String>,
543}
544
545#[derive(Debug, Serialize)]
547pub struct DeleteDocumentsResponse {
548 pub deleted_count: usize,
549}
550
551#[derive(Debug, Serialize)]
553pub struct FullTextIndexStats {
554 pub document_count: u32,
555 pub unique_terms: usize,
556 pub avg_doc_length: f32,
557}
558
559#[derive(Debug, Deserialize)]
565pub struct HybridSearchRequest {
566 #[serde(default)]
569 pub vector: Option<Vec<f32>>,
570 pub text: String,
572 #[serde(default = "default_top_k")]
574 pub top_k: usize,
575 #[serde(default = "default_vector_weight")]
578 pub vector_weight: f32,
579 #[serde(default)]
581 pub distance_metric: DistanceMetric,
582 #[serde(default = "default_true")]
584 pub include_metadata: bool,
585 #[serde(default)]
587 pub include_vectors: bool,
588 #[serde(default)]
590 pub filter: Option<FilterExpression>,
591}
592
593fn default_vector_weight() -> f32 {
594 0.5 }
596
597#[derive(Debug, Serialize, Deserialize)]
599pub struct HybridSearchResult {
600 pub id: String,
601 pub score: f32,
603 pub vector_score: f32,
605 pub text_score: f32,
607 #[serde(skip_serializing_if = "Option::is_none")]
608 pub metadata: Option<serde_json::Value>,
609 #[serde(skip_serializing_if = "Option::is_none")]
610 pub vector: Option<Vec<f32>>,
611}
612
613#[derive(Debug, Serialize, Deserialize)]
615pub struct HybridSearchResponse {
616 pub results: Vec<HybridSearchResult>,
617 #[serde(default)]
619 pub search_time_ms: u64,
620}
621
622#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
628#[serde(untagged)]
629pub enum FilterValue {
630 String(String),
631 Number(f64),
632 Integer(i64),
633 Boolean(bool),
634 StringArray(Vec<String>),
635 NumberArray(Vec<f64>),
636}
637
638impl FilterValue {
639 pub fn as_f64(&self) -> Option<f64> {
641 match self {
642 FilterValue::Number(n) => Some(*n),
643 FilterValue::Integer(i) => Some(*i as f64),
644 _ => None,
645 }
646 }
647
648 pub fn as_str(&self) -> Option<&str> {
650 match self {
651 FilterValue::String(s) => Some(s.as_str()),
652 _ => None,
653 }
654 }
655
656 pub fn as_bool(&self) -> Option<bool> {
658 match self {
659 FilterValue::Boolean(b) => Some(*b),
660 _ => None,
661 }
662 }
663}
664
665#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
667#[serde(rename_all = "snake_case")]
668pub enum FilterCondition {
669 #[serde(rename = "$eq")]
671 Eq(FilterValue),
672 #[serde(rename = "$ne")]
674 Ne(FilterValue),
675 #[serde(rename = "$gt")]
677 Gt(FilterValue),
678 #[serde(rename = "$gte")]
680 Gte(FilterValue),
681 #[serde(rename = "$lt")]
683 Lt(FilterValue),
684 #[serde(rename = "$lte")]
686 Lte(FilterValue),
687 #[serde(rename = "$in")]
689 In(Vec<FilterValue>),
690 #[serde(rename = "$nin")]
692 NotIn(Vec<FilterValue>),
693 #[serde(rename = "$exists")]
695 Exists(bool),
696 #[serde(rename = "$contains")]
701 Contains(String),
702 #[serde(rename = "$icontains")]
704 IContains(String),
705 #[serde(rename = "$startsWith")]
707 StartsWith(String),
708 #[serde(rename = "$endsWith")]
710 EndsWith(String),
711 #[serde(rename = "$glob")]
713 Glob(String),
714 #[serde(rename = "$regex")]
716 Regex(String),
717}
718
719#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
721#[serde(untagged)]
722pub enum FilterExpression {
723 And {
725 #[serde(rename = "$and")]
726 conditions: Vec<FilterExpression>,
727 },
728 Or {
730 #[serde(rename = "$or")]
731 conditions: Vec<FilterExpression>,
732 },
733 Field {
735 #[serde(flatten)]
736 field: std::collections::HashMap<String, FilterCondition>,
737 },
738}
739
740#[derive(Debug, Clone, Serialize, Deserialize, Default)]
746pub struct QuotaConfig {
747 #[serde(skip_serializing_if = "Option::is_none")]
749 pub max_vectors: Option<u64>,
750 #[serde(skip_serializing_if = "Option::is_none")]
752 pub max_storage_bytes: Option<u64>,
753 #[serde(skip_serializing_if = "Option::is_none")]
755 pub max_dimensions: Option<usize>,
756 #[serde(skip_serializing_if = "Option::is_none")]
758 pub max_metadata_bytes: Option<usize>,
759 #[serde(default)]
761 pub enforcement: QuotaEnforcement,
762}
763
764#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
766#[serde(rename_all = "snake_case")]
767pub enum QuotaEnforcement {
768 None,
770 Soft,
772 #[default]
774 Hard,
775}
776
777#[derive(Debug, Clone, Serialize, Deserialize, Default)]
779pub struct QuotaUsage {
780 pub vector_count: u64,
782 pub storage_bytes: u64,
784 pub avg_dimensions: Option<usize>,
786 pub avg_metadata_bytes: Option<usize>,
788 pub last_updated: u64,
790}
791
792impl QuotaUsage {
793 pub fn new(vector_count: u64, storage_bytes: u64) -> Self {
795 let now = std::time::SystemTime::now()
796 .duration_since(std::time::UNIX_EPOCH)
797 .unwrap_or_default()
798 .as_secs();
799 Self {
800 vector_count,
801 storage_bytes,
802 avg_dimensions: None,
803 avg_metadata_bytes: None,
804 last_updated: now,
805 }
806 }
807
808 pub fn touch(&mut self) {
810 self.last_updated = std::time::SystemTime::now()
811 .duration_since(std::time::UNIX_EPOCH)
812 .unwrap_or_default()
813 .as_secs();
814 }
815}
816
817#[derive(Debug, Clone, Serialize, Deserialize)]
819pub struct QuotaStatus {
820 pub namespace: String,
822 pub config: QuotaConfig,
824 pub usage: QuotaUsage,
826 #[serde(skip_serializing_if = "Option::is_none")]
828 pub vector_usage_percent: Option<f32>,
829 #[serde(skip_serializing_if = "Option::is_none")]
831 pub storage_usage_percent: Option<f32>,
832 pub is_exceeded: bool,
834 #[serde(skip_serializing_if = "Vec::is_empty")]
836 pub exceeded_quotas: Vec<String>,
837}
838
839impl QuotaStatus {
840 pub fn new(namespace: String, config: QuotaConfig, usage: QuotaUsage) -> Self {
842 let vector_usage_percent = config
843 .max_vectors
844 .map(|max| (usage.vector_count as f32 / max as f32) * 100.0);
845
846 let storage_usage_percent = config
847 .max_storage_bytes
848 .map(|max| (usage.storage_bytes as f32 / max as f32) * 100.0);
849
850 let mut exceeded_quotas = Vec::new();
851
852 if let Some(max) = config.max_vectors {
853 if usage.vector_count > max {
854 exceeded_quotas.push("max_vectors".to_string());
855 }
856 }
857
858 if let Some(max) = config.max_storage_bytes {
859 if usage.storage_bytes > max {
860 exceeded_quotas.push("max_storage_bytes".to_string());
861 }
862 }
863
864 let is_exceeded = !exceeded_quotas.is_empty();
865
866 Self {
867 namespace,
868 config,
869 usage,
870 vector_usage_percent,
871 storage_usage_percent,
872 is_exceeded,
873 exceeded_quotas,
874 }
875 }
876}
877
878#[derive(Debug, Deserialize)]
880pub struct SetQuotaRequest {
881 pub config: QuotaConfig,
883}
884
885#[derive(Debug, Serialize)]
887pub struct SetQuotaResponse {
888 pub success: bool,
890 pub namespace: String,
892 pub config: QuotaConfig,
894 pub message: String,
896}
897
898#[derive(Debug, Clone, Serialize)]
900pub struct QuotaCheckResult {
901 pub allowed: bool,
903 #[serde(skip_serializing_if = "Option::is_none")]
905 pub reason: Option<String>,
906 pub usage: QuotaUsage,
908 #[serde(skip_serializing_if = "Option::is_none")]
910 pub exceeded_quota: Option<String>,
911}
912
913#[derive(Debug, Serialize)]
915pub struct QuotaListResponse {
916 pub quotas: Vec<QuotaStatus>,
918 pub total: u64,
920 #[serde(skip_serializing_if = "Option::is_none")]
922 pub default_config: Option<QuotaConfig>,
923}
924
925#[derive(Debug, Serialize)]
927pub struct DefaultQuotaResponse {
928 pub config: Option<QuotaConfig>,
930}
931
932#[derive(Debug, Deserialize)]
934pub struct SetDefaultQuotaRequest {
935 pub config: Option<QuotaConfig>,
937}
938
939#[derive(Debug, Deserialize)]
941pub struct QuotaCheckRequest {
942 pub vector_ids: Vec<String>,
944 #[serde(default)]
946 pub dimensions: Option<usize>,
947 #[serde(default)]
949 pub metadata_bytes: Option<usize>,
950}
951
952#[derive(Debug, Deserialize)]
958pub struct ExportRequest {
959 #[serde(default = "default_export_top_k")]
961 pub top_k: usize,
962 #[serde(skip_serializing_if = "Option::is_none")]
964 pub cursor: Option<String>,
965 #[serde(default = "default_true")]
967 pub include_vectors: bool,
968 #[serde(default = "default_true")]
970 pub include_metadata: bool,
971}
972
973fn default_export_top_k() -> usize {
974 1000
975}
976
977impl Default for ExportRequest {
978 fn default() -> Self {
979 Self {
980 top_k: 1000,
981 cursor: None,
982 include_vectors: true,
983 include_metadata: true,
984 }
985 }
986}
987
988#[derive(Debug, Clone, Serialize, Deserialize)]
990pub struct ExportedVector {
991 pub id: String,
993 #[serde(skip_serializing_if = "Option::is_none")]
995 pub values: Option<Vec<f32>>,
996 #[serde(skip_serializing_if = "Option::is_none")]
998 pub metadata: Option<serde_json::Value>,
999 #[serde(skip_serializing_if = "Option::is_none")]
1001 pub ttl_seconds: Option<u64>,
1002}
1003
1004impl From<&Vector> for ExportedVector {
1005 fn from(v: &Vector) -> Self {
1006 Self {
1007 id: v.id.clone(),
1008 values: Some(v.values.clone()),
1009 metadata: v.metadata.clone(),
1010 ttl_seconds: v.ttl_seconds,
1011 }
1012 }
1013}
1014
1015#[derive(Debug, Serialize)]
1017pub struct ExportResponse {
1018 pub vectors: Vec<ExportedVector>,
1020 #[serde(skip_serializing_if = "Option::is_none")]
1022 pub next_cursor: Option<String>,
1023 pub total_count: usize,
1025 pub returned_count: usize,
1027}
1028
1029#[derive(Debug, Clone, Serialize, Deserialize)]
1036#[serde(untagged)]
1037pub enum RankBy {
1038 VectorSearch {
1041 field: String,
1042 method: VectorSearchMethod,
1043 query_vector: Vec<f32>,
1044 },
1045 FullTextSearch {
1047 field: String,
1048 method: String, query: String,
1050 },
1051 AttributeOrder {
1053 field: String,
1054 direction: SortDirection,
1055 },
1056 Sum(Vec<RankBy>),
1058 Max(Vec<RankBy>),
1060 Product { weight: f32, ranking: Box<RankBy> },
1062}
1063
1064#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1066pub enum VectorSearchMethod {
1067 #[default]
1069 ANN,
1070 #[serde(rename = "kNN")]
1072 KNN,
1073}
1074
1075#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1077#[serde(rename_all = "lowercase")]
1078#[derive(Default)]
1079pub enum SortDirection {
1080 Asc,
1081 #[default]
1082 Desc,
1083}
1084
1085#[derive(Debug, Deserialize)]
1087pub struct UnifiedQueryRequest {
1088 pub rank_by: RankByInput,
1090 #[serde(default = "default_top_k")]
1092 pub top_k: usize,
1093 #[serde(default)]
1095 pub filter: Option<FilterExpression>,
1096 #[serde(default = "default_true")]
1098 pub include_metadata: bool,
1099 #[serde(default)]
1101 pub include_vectors: bool,
1102 #[serde(default)]
1104 pub distance_metric: DistanceMetric,
1105}
1106
1107#[derive(Debug, Clone, Serialize, Deserialize)]
1115#[serde(from = "serde_json::Value")]
1116pub struct RankByInput(pub RankBy);
1117
1118impl From<serde_json::Value> for RankByInput {
1119 fn from(value: serde_json::Value) -> Self {
1120 RankByInput(parse_rank_by(&value).unwrap_or_else(|| {
1121 RankBy::AttributeOrder {
1123 field: "id".to_string(),
1124 direction: SortDirection::Asc,
1125 }
1126 }))
1127 }
1128}
1129
1130fn parse_rank_by(value: &serde_json::Value) -> Option<RankBy> {
1132 let arr = value.as_array()?;
1133 if arr.is_empty() {
1134 return None;
1135 }
1136
1137 let first = arr.first()?.as_str()?;
1138
1139 match first {
1140 "Sum" => {
1142 let rankings = arr.get(1)?.as_array()?;
1143 let parsed: Option<Vec<RankBy>> = rankings.iter().map(parse_rank_by).collect();
1144 Some(RankBy::Sum(parsed?))
1145 }
1146 "Max" => {
1147 let rankings = arr.get(1)?.as_array()?;
1148 let parsed: Option<Vec<RankBy>> = rankings.iter().map(parse_rank_by).collect();
1149 Some(RankBy::Max(parsed?))
1150 }
1151 "Product" => {
1152 let weight = arr.get(1)?.as_f64()? as f32;
1153 let ranking = parse_rank_by(arr.get(2)?)?;
1154 Some(RankBy::Product {
1155 weight,
1156 ranking: Box::new(ranking),
1157 })
1158 }
1159 "ANN" => {
1161 let query_vector = parse_vector_array(arr.get(1)?)?;
1162 Some(RankBy::VectorSearch {
1163 field: "vector".to_string(),
1164 method: VectorSearchMethod::ANN,
1165 query_vector,
1166 })
1167 }
1168 "kNN" => {
1169 let query_vector = parse_vector_array(arr.get(1)?)?;
1170 Some(RankBy::VectorSearch {
1171 field: "vector".to_string(),
1172 method: VectorSearchMethod::KNN,
1173 query_vector,
1174 })
1175 }
1176 field => {
1178 let second = arr.get(1)?;
1179
1180 if let Some(method_str) = second.as_str() {
1182 match method_str {
1183 "ANN" => {
1184 let query_vector = parse_vector_array(arr.get(2)?)?;
1185 Some(RankBy::VectorSearch {
1186 field: field.to_string(),
1187 method: VectorSearchMethod::ANN,
1188 query_vector,
1189 })
1190 }
1191 "kNN" => {
1192 let query_vector = parse_vector_array(arr.get(2)?)?;
1193 Some(RankBy::VectorSearch {
1194 field: field.to_string(),
1195 method: VectorSearchMethod::KNN,
1196 query_vector,
1197 })
1198 }
1199 "BM25" => {
1200 let query = arr.get(2)?.as_str()?;
1201 Some(RankBy::FullTextSearch {
1202 field: field.to_string(),
1203 method: "BM25".to_string(),
1204 query: query.to_string(),
1205 })
1206 }
1207 "asc" => Some(RankBy::AttributeOrder {
1208 field: field.to_string(),
1209 direction: SortDirection::Asc,
1210 }),
1211 "desc" => Some(RankBy::AttributeOrder {
1212 field: field.to_string(),
1213 direction: SortDirection::Desc,
1214 }),
1215 _ => None,
1216 }
1217 } else {
1218 None
1219 }
1220 }
1221 }
1222}
1223
1224fn parse_vector_array(value: &serde_json::Value) -> Option<Vec<f32>> {
1226 let arr = value.as_array()?;
1227 arr.iter().map(|v| v.as_f64().map(|n| n as f32)).collect()
1228}
1229
1230#[derive(Debug, Serialize, Deserialize)]
1232pub struct UnifiedQueryResponse {
1233 pub results: Vec<UnifiedSearchResult>,
1235 #[serde(skip_serializing_if = "Option::is_none")]
1237 pub next_cursor: Option<String>,
1238}
1239
1240#[derive(Debug, Serialize, Deserialize)]
1242pub struct UnifiedSearchResult {
1243 pub id: String,
1245 #[serde(rename = "$dist", skip_serializing_if = "Option::is_none")]
1248 pub dist: Option<f32>,
1249 #[serde(skip_serializing_if = "Option::is_none")]
1251 pub metadata: Option<serde_json::Value>,
1252 #[serde(skip_serializing_if = "Option::is_none")]
1254 pub vector: Option<Vec<f32>>,
1255}
1256
1257#[derive(Debug, Clone, Serialize, Deserialize)]
1263pub enum AggregateFunction {
1264 Count,
1266 Sum { field: String },
1268 Avg { field: String },
1270 Min { field: String },
1272 Max { field: String },
1274}
1275
1276#[derive(Debug, Clone, Serialize, Deserialize)]
1278#[serde(from = "serde_json::Value")]
1279pub struct AggregateFunctionInput(pub AggregateFunction);
1280
1281impl From<serde_json::Value> for AggregateFunctionInput {
1282 fn from(value: serde_json::Value) -> Self {
1283 parse_aggregate_function(&value)
1284 .map(AggregateFunctionInput)
1285 .unwrap_or_else(|| {
1286 AggregateFunctionInput(AggregateFunction::Count)
1288 })
1289 }
1290}
1291
1292fn parse_aggregate_function(value: &serde_json::Value) -> Option<AggregateFunction> {
1294 let arr = value.as_array()?;
1295 if arr.is_empty() {
1296 return None;
1297 }
1298
1299 let func_name = arr.first()?.as_str()?;
1300
1301 match func_name {
1302 "Count" => Some(AggregateFunction::Count),
1303 "Sum" => {
1304 let field = arr.get(1)?.as_str()?;
1305 Some(AggregateFunction::Sum {
1306 field: field.to_string(),
1307 })
1308 }
1309 "Avg" => {
1310 let field = arr.get(1)?.as_str()?;
1311 Some(AggregateFunction::Avg {
1312 field: field.to_string(),
1313 })
1314 }
1315 "Min" => {
1316 let field = arr.get(1)?.as_str()?;
1317 Some(AggregateFunction::Min {
1318 field: field.to_string(),
1319 })
1320 }
1321 "Max" => {
1322 let field = arr.get(1)?.as_str()?;
1323 Some(AggregateFunction::Max {
1324 field: field.to_string(),
1325 })
1326 }
1327 _ => None,
1328 }
1329}
1330
1331#[derive(Debug, Deserialize)]
1333pub struct AggregationRequest {
1334 pub aggregate_by: std::collections::HashMap<String, AggregateFunctionInput>,
1337 #[serde(default)]
1340 pub group_by: Vec<String>,
1341 #[serde(default)]
1343 pub filter: Option<FilterExpression>,
1344 #[serde(default = "default_agg_limit")]
1346 pub limit: usize,
1347}
1348
1349fn default_agg_limit() -> usize {
1350 100
1351}
1352
1353#[derive(Debug, Serialize, Deserialize)]
1355pub struct AggregationResponse {
1356 #[serde(skip_serializing_if = "Option::is_none")]
1358 pub aggregations: Option<std::collections::HashMap<String, serde_json::Value>>,
1359 #[serde(skip_serializing_if = "Option::is_none")]
1361 pub aggregation_groups: Option<Vec<AggregationGroup>>,
1362}
1363
1364#[derive(Debug, Serialize, Deserialize)]
1366pub struct AggregationGroup {
1367 #[serde(flatten)]
1369 pub group_key: std::collections::HashMap<String, serde_json::Value>,
1370 #[serde(flatten)]
1372 pub aggregations: std::collections::HashMap<String, serde_json::Value>,
1373}
1374
1375#[derive(Debug, Clone, Serialize, Deserialize)]
1381pub struct TextDocument {
1382 pub id: VectorId,
1384 pub text: String,
1386 #[serde(skip_serializing_if = "Option::is_none")]
1388 pub metadata: Option<serde_json::Value>,
1389 #[serde(skip_serializing_if = "Option::is_none")]
1391 pub ttl_seconds: Option<u64>,
1392}
1393
1394#[derive(Debug, Deserialize)]
1396pub struct TextUpsertRequest {
1397 pub documents: Vec<TextDocument>,
1399 #[serde(default)]
1401 pub model: Option<EmbeddingModelType>,
1402}
1403
1404#[derive(Debug, Serialize, Deserialize)]
1406pub struct TextUpsertResponse {
1407 pub upserted_count: usize,
1409 pub tokens_processed: usize,
1411 pub model: EmbeddingModelType,
1413 pub embedding_time_ms: u64,
1415}
1416
1417#[derive(Debug, Deserialize)]
1419pub struct TextQueryRequest {
1420 pub text: String,
1422 #[serde(default = "default_top_k")]
1424 pub top_k: usize,
1425 #[serde(default)]
1427 pub filter: Option<FilterExpression>,
1428 #[serde(default)]
1430 pub include_vectors: bool,
1431 #[serde(default = "default_true")]
1433 pub include_text: bool,
1434 #[serde(default)]
1436 pub model: Option<EmbeddingModelType>,
1437}
1438
1439#[derive(Debug, Serialize, Deserialize)]
1441pub struct TextQueryResponse {
1442 pub results: Vec<TextSearchResult>,
1444 pub model: EmbeddingModelType,
1446 pub embedding_time_ms: u64,
1448 pub search_time_ms: u64,
1450}
1451
1452#[derive(Debug, Serialize, Deserialize)]
1454pub struct TextSearchResult {
1455 pub id: VectorId,
1457 pub score: f32,
1459 #[serde(skip_serializing_if = "Option::is_none")]
1461 pub text: Option<String>,
1462 #[serde(skip_serializing_if = "Option::is_none")]
1464 pub metadata: Option<serde_json::Value>,
1465 #[serde(skip_serializing_if = "Option::is_none")]
1467 pub vector: Option<Vec<f32>>,
1468}
1469
1470#[derive(Debug, Deserialize)]
1472pub struct BatchTextQueryRequest {
1473 pub queries: Vec<String>,
1475 #[serde(default = "default_top_k")]
1477 pub top_k: usize,
1478 #[serde(default)]
1480 pub filter: Option<FilterExpression>,
1481 #[serde(default)]
1483 pub include_vectors: bool,
1484 #[serde(default)]
1486 pub model: Option<EmbeddingModelType>,
1487}
1488
1489#[derive(Debug, Serialize, Deserialize)]
1491pub struct BatchTextQueryResponse {
1492 pub results: Vec<Vec<TextSearchResult>>,
1494 pub model: EmbeddingModelType,
1496 pub embedding_time_ms: u64,
1498 pub search_time_ms: u64,
1500}
1501
1502#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
1510pub enum EmbeddingModelType {
1511 #[default]
1513 #[serde(rename = "minilm")]
1514 MiniLM,
1515 #[serde(rename = "bge-small")]
1517 BgeSmall,
1518 #[serde(rename = "e5-small")]
1520 E5Small,
1521}
1522
1523impl EmbeddingModelType {
1524 pub fn dimension(&self) -> usize {
1526 match self {
1527 EmbeddingModelType::MiniLM => 384,
1528 EmbeddingModelType::BgeSmall => 384,
1529 EmbeddingModelType::E5Small => 384,
1530 }
1531 }
1532}
1533
1534impl std::fmt::Display for EmbeddingModelType {
1535 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1536 match self {
1537 EmbeddingModelType::MiniLM => write!(f, "minilm"),
1538 EmbeddingModelType::BgeSmall => write!(f, "bge-small"),
1539 EmbeddingModelType::E5Small => write!(f, "e5-small"),
1540 }
1541 }
1542}
1543
1544#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1550#[serde(rename_all = "snake_case")]
1551#[derive(Default)]
1552pub enum MemoryType {
1553 #[default]
1555 Episodic,
1556 Semantic,
1558 Procedural,
1560 Working,
1562}
1563
1564impl std::fmt::Display for MemoryType {
1565 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1566 match self {
1567 MemoryType::Episodic => write!(f, "episodic"),
1568 MemoryType::Semantic => write!(f, "semantic"),
1569 MemoryType::Procedural => write!(f, "procedural"),
1570 MemoryType::Working => write!(f, "working"),
1571 }
1572 }
1573}
1574
1575#[derive(Debug, Clone, Serialize, Deserialize)]
1577pub struct Memory {
1578 pub id: String,
1579 #[serde(default)]
1580 pub memory_type: MemoryType,
1581 pub content: String,
1582 pub agent_id: String,
1583 #[serde(skip_serializing_if = "Option::is_none")]
1584 pub session_id: Option<String>,
1585 #[serde(default = "default_importance")]
1586 pub importance: f32,
1587 #[serde(default)]
1588 pub tags: Vec<String>,
1589 #[serde(skip_serializing_if = "Option::is_none")]
1590 pub metadata: Option<serde_json::Value>,
1591 pub created_at: u64,
1592 pub last_accessed_at: u64,
1593 #[serde(default)]
1594 pub access_count: u32,
1595 #[serde(skip_serializing_if = "Option::is_none")]
1596 pub ttl_seconds: Option<u64>,
1597 #[serde(skip_serializing_if = "Option::is_none")]
1598 pub expires_at: Option<u64>,
1599}
1600
1601fn default_importance() -> f32 {
1602 0.5
1603}
1604
1605impl Memory {
1606 pub fn new(id: String, content: String, agent_id: String, memory_type: MemoryType) -> Self {
1608 let now = std::time::SystemTime::now()
1609 .duration_since(std::time::UNIX_EPOCH)
1610 .unwrap_or_default()
1611 .as_secs();
1612 Self {
1613 id,
1614 memory_type,
1615 content,
1616 agent_id,
1617 session_id: None,
1618 importance: 0.5,
1619 tags: Vec::new(),
1620 metadata: None,
1621 created_at: now,
1622 last_accessed_at: now,
1623 access_count: 0,
1624 ttl_seconds: None,
1625 expires_at: None,
1626 }
1627 }
1628
1629 pub fn is_expired(&self) -> bool {
1631 if let Some(expires_at) = self.expires_at {
1632 let now = std::time::SystemTime::now()
1633 .duration_since(std::time::UNIX_EPOCH)
1634 .unwrap_or_default()
1635 .as_secs();
1636 now >= expires_at
1637 } else {
1638 false
1639 }
1640 }
1641
1642 pub fn to_vector_metadata(&self) -> serde_json::Value {
1644 let mut meta = serde_json::Map::new();
1645 meta.insert("_dakera_type".to_string(), serde_json::json!("memory"));
1646 meta.insert(
1647 "memory_type".to_string(),
1648 serde_json::json!(self.memory_type),
1649 );
1650 meta.insert("content".to_string(), serde_json::json!(self.content));
1651 meta.insert("agent_id".to_string(), serde_json::json!(self.agent_id));
1652 if let Some(ref sid) = self.session_id {
1653 meta.insert("session_id".to_string(), serde_json::json!(sid));
1654 }
1655 meta.insert("importance".to_string(), serde_json::json!(self.importance));
1656 meta.insert("tags".to_string(), serde_json::json!(self.tags));
1657 meta.insert("created_at".to_string(), serde_json::json!(self.created_at));
1658 meta.insert(
1659 "last_accessed_at".to_string(),
1660 serde_json::json!(self.last_accessed_at),
1661 );
1662 meta.insert(
1663 "access_count".to_string(),
1664 serde_json::json!(self.access_count),
1665 );
1666 if let Some(ref ttl) = self.ttl_seconds {
1667 meta.insert("ttl_seconds".to_string(), serde_json::json!(ttl));
1668 }
1669 if let Some(ref expires) = self.expires_at {
1670 meta.insert("expires_at".to_string(), serde_json::json!(expires));
1671 }
1672 if let Some(ref user_meta) = self.metadata {
1673 meta.insert("user_metadata".to_string(), user_meta.clone());
1674 }
1675 serde_json::Value::Object(meta)
1676 }
1677
1678 pub fn to_vector(&self, embedding: Vec<f32>) -> Vector {
1680 let mut v = Vector {
1681 id: self.id.clone(),
1682 values: embedding,
1683 metadata: Some(self.to_vector_metadata()),
1684 ttl_seconds: self.ttl_seconds,
1685 expires_at: self.expires_at,
1686 };
1687 v.apply_ttl();
1688 v
1689 }
1690
1691 pub fn from_vector(vector: &Vector) -> Option<Self> {
1693 let meta = vector.metadata.as_ref()?.as_object()?;
1694 let entry_type = meta.get("_dakera_type")?.as_str()?;
1695 if entry_type != "memory" {
1696 return None;
1697 }
1698
1699 Some(Memory {
1700 id: vector.id.clone(),
1701 memory_type: serde_json::from_value(meta.get("memory_type")?.clone())
1702 .unwrap_or_default(),
1703 content: meta.get("content")?.as_str()?.to_string(),
1704 agent_id: meta.get("agent_id")?.as_str()?.to_string(),
1705 session_id: meta
1706 .get("session_id")
1707 .and_then(|v| v.as_str())
1708 .map(String::from),
1709 importance: meta
1710 .get("importance")
1711 .and_then(|v| v.as_f64())
1712 .unwrap_or(0.5) as f32,
1713 tags: meta
1714 .get("tags")
1715 .and_then(|v| serde_json::from_value(v.clone()).ok())
1716 .unwrap_or_default(),
1717 metadata: meta.get("user_metadata").cloned(),
1718 created_at: meta.get("created_at").and_then(|v| v.as_u64()).unwrap_or(0),
1719 last_accessed_at: meta
1720 .get("last_accessed_at")
1721 .and_then(|v| v.as_u64())
1722 .unwrap_or(0),
1723 access_count: meta
1724 .get("access_count")
1725 .and_then(|v| v.as_u64())
1726 .unwrap_or(0) as u32,
1727 ttl_seconds: vector.ttl_seconds,
1728 expires_at: vector.expires_at,
1729 })
1730 }
1731}
1732
1733#[derive(Debug, Clone, Serialize, Deserialize)]
1735pub struct Session {
1736 pub id: String,
1737 pub agent_id: String,
1738 pub started_at: u64,
1739 #[serde(skip_serializing_if = "Option::is_none")]
1740 pub ended_at: Option<u64>,
1741 #[serde(skip_serializing_if = "Option::is_none")]
1742 pub summary: Option<String>,
1743 #[serde(skip_serializing_if = "Option::is_none")]
1744 pub metadata: Option<serde_json::Value>,
1745 #[serde(default)]
1747 pub memory_count: usize,
1748}
1749
1750impl Session {
1751 pub fn new(id: String, agent_id: String) -> Self {
1752 let now = std::time::SystemTime::now()
1753 .duration_since(std::time::UNIX_EPOCH)
1754 .unwrap_or_default()
1755 .as_secs();
1756 Self {
1757 id,
1758 agent_id,
1759 started_at: now,
1760 ended_at: None,
1761 summary: None,
1762 metadata: None,
1763 memory_count: 0,
1764 }
1765 }
1766
1767 pub fn to_vector_metadata(&self) -> serde_json::Value {
1769 let mut meta = serde_json::Map::new();
1770 meta.insert("_dakera_type".to_string(), serde_json::json!("session"));
1771 meta.insert("agent_id".to_string(), serde_json::json!(self.agent_id));
1772 meta.insert("started_at".to_string(), serde_json::json!(self.started_at));
1773 if let Some(ref ended) = self.ended_at {
1774 meta.insert("ended_at".to_string(), serde_json::json!(ended));
1775 }
1776 if let Some(ref summary) = self.summary {
1777 meta.insert("summary".to_string(), serde_json::json!(summary));
1778 }
1779 if let Some(ref user_meta) = self.metadata {
1780 meta.insert("user_metadata".to_string(), user_meta.clone());
1781 }
1782 meta.insert(
1783 "memory_count".to_string(),
1784 serde_json::json!(self.memory_count),
1785 );
1786 serde_json::Value::Object(meta)
1787 }
1788
1789 pub fn to_vector(&self, embedding: Vec<f32>) -> Vector {
1791 Vector {
1792 id: self.id.clone(),
1793 values: embedding,
1794 metadata: Some(self.to_vector_metadata()),
1795 ttl_seconds: None,
1796 expires_at: None,
1797 }
1798 }
1799
1800 pub fn from_vector(vector: &Vector) -> Option<Self> {
1802 let meta = vector.metadata.as_ref()?.as_object()?;
1803 let entry_type = meta.get("_dakera_type")?.as_str()?;
1804 if entry_type != "session" {
1805 return None;
1806 }
1807
1808 Some(Session {
1809 id: vector.id.clone(),
1810 agent_id: meta.get("agent_id")?.as_str()?.to_string(),
1811 started_at: meta.get("started_at").and_then(|v| v.as_u64()).unwrap_or(0),
1812 ended_at: meta.get("ended_at").and_then(|v| v.as_u64()),
1813 summary: meta
1814 .get("summary")
1815 .and_then(|v| v.as_str())
1816 .map(String::from),
1817 metadata: meta.get("user_metadata").cloned(),
1818 memory_count: meta
1819 .get("memory_count")
1820 .and_then(|v| v.as_u64())
1821 .unwrap_or(0) as usize,
1822 })
1823 }
1824}
1825
1826#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1828#[serde(rename_all = "snake_case")]
1829#[derive(Default)]
1830pub enum DecayStrategy {
1831 #[default]
1832 Exponential,
1833 Linear,
1834 StepFunction,
1835 PowerLaw,
1837 Logarithmic,
1839 Flat,
1841}
1842
1843#[derive(Debug, Clone, Serialize, Deserialize)]
1845pub struct DecayConfig {
1846 #[serde(default)]
1847 pub strategy: DecayStrategy,
1848 #[serde(default = "default_half_life_hours")]
1849 pub half_life_hours: f64,
1850 #[serde(default = "default_min_importance")]
1851 pub min_importance: f32,
1852}
1853
1854fn default_half_life_hours() -> f64 {
1855 168.0 }
1857
1858fn default_min_importance() -> f32 {
1859 0.01
1860}
1861
1862impl Default for DecayConfig {
1863 fn default() -> Self {
1864 Self {
1865 strategy: DecayStrategy::default(),
1866 half_life_hours: default_half_life_hours(),
1867 min_importance: default_min_importance(),
1868 }
1869 }
1870}
1871
1872#[derive(Debug, Deserialize)]
1878pub struct StoreMemoryRequest {
1879 pub content: String,
1880 pub agent_id: String,
1881 #[serde(default)]
1882 pub memory_type: MemoryType,
1883 #[serde(skip_serializing_if = "Option::is_none")]
1884 pub session_id: Option<String>,
1885 #[serde(default = "default_importance")]
1886 pub importance: f32,
1887 #[serde(default)]
1888 pub tags: Vec<String>,
1889 #[serde(skip_serializing_if = "Option::is_none")]
1890 pub metadata: Option<serde_json::Value>,
1891 #[serde(skip_serializing_if = "Option::is_none")]
1892 pub ttl_seconds: Option<u64>,
1893 #[serde(skip_serializing_if = "Option::is_none")]
1898 pub expires_at: Option<u64>,
1899 #[serde(skip_serializing_if = "Option::is_none")]
1901 pub id: Option<String>,
1902}
1903
1904#[derive(Debug, Serialize)]
1906pub struct StoreMemoryResponse {
1907 pub memory: Memory,
1908 pub embedding_time_ms: u64,
1909}
1910
1911#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1915#[serde(rename_all = "lowercase")]
1916pub enum RoutingMode {
1917 #[default]
1919 Auto,
1920 Vector,
1922 Bm25,
1924 Hybrid,
1926}
1927
1928#[derive(Debug, Deserialize)]
1930pub struct RecallRequest {
1931 pub query: String,
1932 pub agent_id: String,
1933 #[serde(default = "default_top_k")]
1934 pub top_k: usize,
1935 #[serde(default)]
1936 pub memory_type: Option<MemoryType>,
1937 #[serde(default)]
1938 pub session_id: Option<String>,
1939 #[serde(default)]
1940 pub tags: Option<Vec<String>>,
1941 #[serde(default)]
1942 pub min_importance: Option<f32>,
1943 #[serde(default = "default_true")]
1945 pub importance_weighted: bool,
1946 #[serde(default)]
1948 pub include_associated: bool,
1949 #[serde(default)]
1951 pub associated_memories_cap: Option<usize>,
1952 #[serde(default)]
1954 pub since: Option<String>,
1955 #[serde(default)]
1957 pub until: Option<String>,
1958 #[serde(default)]
1961 pub associated_memories_depth: Option<u8>,
1962 #[serde(default)]
1965 pub associated_memories_min_weight: Option<f32>,
1966 #[serde(default)]
1970 pub routing: RoutingMode,
1971}
1972
1973#[derive(Debug, Serialize, Deserialize)]
1975pub struct RecallResult {
1976 pub memory: Memory,
1977 pub score: f32,
1978 #[serde(skip_serializing_if = "Option::is_none")]
1980 pub weighted_score: Option<f32>,
1981 #[serde(skip_serializing_if = "Option::is_none")]
1983 pub smart_score: Option<f32>,
1984 #[serde(skip_serializing_if = "Option::is_none")]
1987 pub depth: Option<u8>,
1988}
1989
1990#[derive(Debug, Serialize)]
1992pub struct RecallResponse {
1993 pub memories: Vec<RecallResult>,
1994 pub query_embedding_time_ms: u64,
1995 pub search_time_ms: u64,
1996 #[serde(skip_serializing_if = "Option::is_none")]
1999 pub associated_memories: Option<Vec<RecallResult>>,
2000}
2001
2002#[derive(Debug, Deserialize)]
2004pub struct ForgetRequest {
2005 pub agent_id: String,
2006 #[serde(default)]
2007 pub memory_ids: Option<Vec<String>>,
2008 #[serde(default)]
2009 pub memory_type: Option<MemoryType>,
2010 #[serde(default)]
2011 pub session_id: Option<String>,
2012 #[serde(default)]
2013 pub tags: Option<Vec<String>>,
2014 #[serde(default)]
2016 pub below_importance: Option<f32>,
2017}
2018
2019#[derive(Debug, Serialize)]
2021pub struct ForgetResponse {
2022 pub deleted_count: usize,
2023}
2024
2025#[derive(Debug, Deserialize)]
2027pub struct UpdateMemoryRequest {
2028 #[serde(default)]
2029 pub content: Option<String>,
2030 #[serde(default)]
2031 pub importance: Option<f32>,
2032 #[serde(default)]
2033 pub tags: Option<Vec<String>>,
2034 #[serde(default)]
2035 pub metadata: Option<serde_json::Value>,
2036 #[serde(default)]
2037 pub memory_type: Option<MemoryType>,
2038}
2039
2040#[derive(Debug, Deserialize)]
2042pub struct UpdateImportanceRequest {
2043 pub memory_id: String,
2044 pub importance: f32,
2045 pub agent_id: String,
2046}
2047
2048#[derive(Debug, Deserialize)]
2050pub struct ConsolidateRequest {
2051 pub agent_id: String,
2052 #[serde(default)]
2054 pub memory_ids: Option<Vec<String>>,
2055 #[serde(default = "default_consolidation_threshold")]
2057 pub threshold: f32,
2058 #[serde(default)]
2060 pub target_type: Option<MemoryType>,
2061}
2062
2063fn default_consolidation_threshold() -> f32 {
2064 0.85
2065}
2066
2067#[derive(Debug, Serialize)]
2069pub struct ConsolidateResponse {
2070 pub consolidated_memory: Memory,
2071 pub source_memory_ids: Vec<String>,
2072 pub memories_removed: usize,
2073}
2074
2075#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2077#[serde(rename_all = "lowercase")]
2078pub enum FeedbackSignal {
2079 Upvote,
2081 Downvote,
2083 Flag,
2085 Positive,
2087 Negative,
2089}
2090
2091#[derive(Debug, Clone, Serialize, Deserialize)]
2093pub struct FeedbackHistoryEntry {
2094 pub signal: FeedbackSignal,
2095 pub timestamp: u64,
2096 pub old_importance: f32,
2097 pub new_importance: f32,
2098}
2099
2100#[derive(Debug, Deserialize)]
2102pub struct FeedbackRequest {
2103 pub agent_id: String,
2104 pub memory_id: String,
2105 pub signal: FeedbackSignal,
2106}
2107
2108#[derive(Debug, Deserialize)]
2110pub struct MemoryFeedbackRequest {
2111 pub agent_id: String,
2112 pub signal: FeedbackSignal,
2113}
2114
2115#[derive(Debug, Serialize)]
2117pub struct FeedbackResponse {
2118 pub memory_id: String,
2119 pub new_importance: f32,
2120 pub signal: FeedbackSignal,
2121}
2122
2123#[derive(Debug, Serialize)]
2125pub struct FeedbackHistoryResponse {
2126 pub memory_id: String,
2127 pub entries: Vec<FeedbackHistoryEntry>,
2128}
2129
2130#[derive(Debug, Serialize)]
2132pub struct AgentFeedbackSummary {
2133 pub agent_id: String,
2134 pub upvotes: u64,
2135 pub downvotes: u64,
2136 pub flags: u64,
2137 pub total_feedback: u64,
2138 pub health_score: f32,
2140}
2141
2142#[derive(Debug, Deserialize)]
2144pub struct MemoryImportancePatchRequest {
2145 pub agent_id: String,
2146 pub importance: f32,
2147}
2148
2149#[derive(Debug, Deserialize)]
2151pub struct FeedbackHealthQuery {
2152 pub agent_id: String,
2153}
2154
2155#[derive(Debug, Serialize)]
2157pub struct FeedbackHealthResponse {
2158 pub agent_id: String,
2159 pub health_score: f32,
2161 pub memory_count: usize,
2162 pub avg_importance: f32,
2163}
2164
2165#[derive(Debug, Deserialize)]
2167pub struct SearchMemoriesRequest {
2168 pub agent_id: String,
2169 #[serde(default)]
2170 pub query: Option<String>,
2171 #[serde(default)]
2172 pub memory_type: Option<MemoryType>,
2173 #[serde(default)]
2174 pub session_id: Option<String>,
2175 #[serde(default)]
2176 pub tags: Option<Vec<String>>,
2177 #[serde(default)]
2178 pub min_importance: Option<f32>,
2179 #[serde(default)]
2180 pub max_importance: Option<f32>,
2181 #[serde(default)]
2182 pub created_after: Option<u64>,
2183 #[serde(default)]
2184 pub created_before: Option<u64>,
2185 #[serde(default = "default_top_k")]
2186 pub top_k: usize,
2187 #[serde(default)]
2188 pub sort_by: Option<MemorySortField>,
2189 #[serde(default)]
2191 pub routing: RoutingMode,
2192}
2193
2194#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
2196#[serde(rename_all = "snake_case")]
2197pub enum MemorySortField {
2198 CreatedAt,
2199 LastAccessedAt,
2200 Importance,
2201 AccessCount,
2202}
2203
2204#[derive(Debug, Serialize)]
2206pub struct SearchMemoriesResponse {
2207 pub memories: Vec<RecallResult>,
2208 pub total_count: usize,
2209}
2210
2211#[derive(Debug, Deserialize)]
2217pub struct SessionStartRequest {
2218 pub agent_id: String,
2219 #[serde(skip_serializing_if = "Option::is_none")]
2220 pub metadata: Option<serde_json::Value>,
2221 #[serde(skip_serializing_if = "Option::is_none")]
2223 pub id: Option<String>,
2224}
2225
2226#[derive(Debug, Serialize)]
2228pub struct SessionStartResponse {
2229 pub session: Session,
2230}
2231
2232#[derive(Debug, Deserialize)]
2234pub struct SessionEndRequest {
2235 #[serde(default)]
2236 pub summary: Option<String>,
2237 #[serde(default)]
2239 pub auto_summarize: bool,
2240}
2241
2242#[derive(Debug, Serialize)]
2244pub struct SessionEndResponse {
2245 pub session: Session,
2246 pub memory_count: usize,
2247}
2248
2249#[derive(Debug, Serialize)]
2251pub struct ListSessionsResponse {
2252 pub sessions: Vec<Session>,
2253 pub total: usize,
2254}
2255
2256#[derive(Debug, Serialize)]
2258pub struct SessionMemoriesResponse {
2259 pub session: Session,
2260 pub memories: Vec<Memory>,
2261 #[serde(skip_serializing_if = "Option::is_none")]
2263 pub total: Option<usize>,
2264}
2265
2266#[derive(Debug, Serialize, Deserialize, Clone)]
2272pub struct AgentSummary {
2273 pub agent_id: String,
2274 pub memory_count: usize,
2275 pub session_count: usize,
2276 pub active_sessions: usize,
2277}
2278
2279#[derive(Debug, Serialize)]
2281pub struct AgentStats {
2282 pub agent_id: String,
2283 pub total_memories: usize,
2284 pub memories_by_type: std::collections::HashMap<String, usize>,
2285 pub total_sessions: usize,
2286 pub active_sessions: usize,
2287 pub avg_importance: f32,
2288 pub oldest_memory_at: Option<u64>,
2289 pub newest_memory_at: Option<u64>,
2290}
2291
2292#[derive(Debug, Serialize)]
2298pub struct WakeUpResponse {
2299 pub agent_id: String,
2300 pub memories: Vec<Memory>,
2302 pub total_available: usize,
2304}
2305
2306#[derive(Debug, Deserialize)]
2308pub struct KnowledgeGraphRequest {
2309 pub agent_id: String,
2310 pub memory_id: String,
2311 #[serde(default = "default_graph_depth")]
2312 pub depth: usize,
2313 #[serde(default = "default_graph_min_similarity")]
2314 pub min_similarity: f32,
2315}
2316
2317fn default_graph_depth() -> usize {
2318 2
2319}
2320
2321fn default_graph_min_similarity() -> f32 {
2322 0.7
2323}
2324
2325#[derive(Debug, Serialize)]
2327pub struct KnowledgeGraphNode {
2328 pub memory: Memory,
2329 pub similarity: f32,
2330 pub related: Vec<KnowledgeGraphEdge>,
2331}
2332
2333#[derive(Debug, Serialize)]
2335pub struct KnowledgeGraphEdge {
2336 pub memory_id: String,
2337 pub similarity: f32,
2338 pub shared_tags: Vec<String>,
2339}
2340
2341#[derive(Debug, Serialize)]
2343pub struct KnowledgeGraphResponse {
2344 pub root: KnowledgeGraphNode,
2345 pub total_nodes: usize,
2346}
2347
2348fn default_full_graph_max_nodes() -> usize {
2353 200
2354}
2355
2356fn default_full_graph_min_similarity() -> f32 {
2357 0.50
2358}
2359
2360fn default_full_graph_cluster_threshold() -> f32 {
2361 0.60
2362}
2363
2364fn default_full_graph_max_edges_per_node() -> usize {
2365 8
2366}
2367
2368#[derive(Debug, Deserialize)]
2370pub struct FullKnowledgeGraphRequest {
2371 pub agent_id: String,
2372 #[serde(default = "default_full_graph_max_nodes")]
2373 pub max_nodes: usize,
2374 #[serde(default = "default_full_graph_min_similarity")]
2375 pub min_similarity: f32,
2376 #[serde(default = "default_full_graph_cluster_threshold")]
2377 pub cluster_threshold: f32,
2378 #[serde(default = "default_full_graph_max_edges_per_node")]
2379 pub max_edges_per_node: usize,
2380}
2381
2382#[derive(Debug, Serialize)]
2384pub struct FullGraphNode {
2385 pub id: String,
2386 pub content: String,
2387 pub memory_type: String,
2388 pub importance: f32,
2389 pub tags: Vec<String>,
2390 pub created_at: Option<String>,
2391 pub cluster_id: usize,
2392 pub centrality: f32,
2393}
2394
2395#[derive(Debug, Serialize)]
2397pub struct FullGraphEdge {
2398 pub source: String,
2399 pub target: String,
2400 pub similarity: f32,
2401 pub shared_tags: Vec<String>,
2402}
2403
2404#[derive(Debug, Serialize)]
2406pub struct GraphCluster {
2407 pub id: usize,
2408 pub node_count: usize,
2409 pub top_tags: Vec<String>,
2410 pub avg_importance: f32,
2411}
2412
2413#[derive(Debug, Serialize)]
2415pub struct GraphStats {
2416 pub total_memories: usize,
2417 pub included_memories: usize,
2418 pub total_edges: usize,
2419 pub cluster_count: usize,
2420 pub density: f32,
2421 pub hub_memory_id: Option<String>,
2422}
2423
2424#[derive(Debug, Serialize)]
2426pub struct FullKnowledgeGraphResponse {
2427 pub nodes: Vec<FullGraphNode>,
2428 pub edges: Vec<FullGraphEdge>,
2429 pub clusters: Vec<GraphCluster>,
2430 pub stats: GraphStats,
2431}
2432
2433#[derive(Debug, Deserialize)]
2435pub struct SummarizeRequest {
2436 pub agent_id: String,
2437 pub memory_ids: Vec<String>,
2438 #[serde(default)]
2439 pub target_type: Option<MemoryType>,
2440}
2441
2442#[derive(Debug, Serialize)]
2444pub struct SummarizeResponse {
2445 pub summary_memory: Memory,
2446 pub source_count: usize,
2447}
2448
2449#[derive(Debug, Deserialize)]
2451pub struct DeduplicateRequest {
2452 pub agent_id: String,
2453 #[serde(default = "default_dedup_threshold")]
2454 pub threshold: f32,
2455 #[serde(default)]
2456 pub memory_type: Option<MemoryType>,
2457 #[serde(default)]
2459 pub dry_run: bool,
2460}
2461
2462fn default_dedup_threshold() -> f32 {
2463 0.92
2464}
2465
2466#[derive(Debug, Serialize)]
2468pub struct DuplicateGroup {
2469 pub canonical_id: String,
2470 pub duplicate_ids: Vec<String>,
2471 pub avg_similarity: f32,
2472}
2473
2474#[derive(Debug, Serialize)]
2476pub struct DeduplicateResponse {
2477 pub groups: Vec<DuplicateGroup>,
2478 pub duplicates_found: usize,
2479 pub duplicates_merged: usize,
2480}
2481
2482fn default_cross_agent_min_similarity() -> f32 {
2487 0.3
2488}
2489
2490fn default_cross_agent_max_nodes_per_agent() -> usize {
2491 50
2492}
2493
2494fn default_cross_agent_max_cross_edges() -> usize {
2495 200
2496}
2497
2498#[derive(Debug, Deserialize)]
2500pub struct CrossAgentNetworkRequest {
2501 #[serde(default)]
2503 pub agent_ids: Option<Vec<String>>,
2504 #[serde(default = "default_cross_agent_min_similarity")]
2506 pub min_similarity: f32,
2507 #[serde(default = "default_cross_agent_max_nodes_per_agent")]
2509 pub max_nodes_per_agent: usize,
2510 #[serde(default)]
2512 pub min_importance: f32,
2513 #[serde(default = "default_cross_agent_max_cross_edges")]
2515 pub max_cross_edges: usize,
2516}
2517
2518#[derive(Debug, Serialize)]
2520pub struct AgentNetworkInfo {
2521 pub agent_id: String,
2522 pub memory_count: usize,
2523 pub avg_importance: f32,
2524}
2525
2526#[derive(Debug, Serialize)]
2528pub struct AgentNetworkNode {
2529 pub id: String,
2530 pub agent_id: String,
2531 pub content: String,
2532 pub importance: f32,
2533 pub tags: Vec<String>,
2534 pub memory_type: String,
2535 pub created_at: u64,
2536}
2537
2538#[derive(Debug, Serialize)]
2540pub struct AgentNetworkEdge {
2541 pub source: String,
2542 pub target: String,
2543 pub source_agent: String,
2544 pub target_agent: String,
2545 pub similarity: f32,
2546}
2547
2548#[derive(Debug, Serialize)]
2550pub struct AgentNetworkStats {
2551 pub total_agents: usize,
2552 pub total_nodes: usize,
2553 pub total_cross_edges: usize,
2554 pub density: f32,
2555}
2556
2557#[derive(Debug, Serialize)]
2559pub struct CrossAgentNetworkResponse {
2560 pub node_count: usize,
2561 pub agents: Vec<AgentNetworkInfo>,
2562 pub nodes: Vec<AgentNetworkNode>,
2563 pub edges: Vec<AgentNetworkEdge>,
2564 pub stats: AgentNetworkStats,
2565}
2566
2567#[derive(Debug, Deserialize, Default)]
2575pub struct BatchMemoryFilter {
2576 #[serde(default)]
2578 pub tags: Option<Vec<String>>,
2579 #[serde(default)]
2581 pub min_importance: Option<f32>,
2582 #[serde(default)]
2584 pub max_importance: Option<f32>,
2585 #[serde(default)]
2587 pub created_after: Option<u64>,
2588 #[serde(default)]
2590 pub created_before: Option<u64>,
2591 #[serde(default)]
2593 pub memory_type: Option<MemoryType>,
2594 #[serde(default)]
2596 pub session_id: Option<String>,
2597}
2598
2599impl BatchMemoryFilter {
2600 pub fn has_any(&self) -> bool {
2602 self.tags.is_some()
2603 || self.min_importance.is_some()
2604 || self.max_importance.is_some()
2605 || self.created_after.is_some()
2606 || self.created_before.is_some()
2607 || self.memory_type.is_some()
2608 || self.session_id.is_some()
2609 }
2610
2611 pub fn matches(&self, memory: &Memory) -> bool {
2613 if let Some(ref tags) = self.tags {
2614 if !tags.is_empty() && !tags.iter().all(|t| memory.tags.contains(t)) {
2615 return false;
2616 }
2617 }
2618 if let Some(min) = self.min_importance {
2619 if memory.importance < min {
2620 return false;
2621 }
2622 }
2623 if let Some(max) = self.max_importance {
2624 if memory.importance > max {
2625 return false;
2626 }
2627 }
2628 if let Some(after) = self.created_after {
2629 if memory.created_at < after {
2630 return false;
2631 }
2632 }
2633 if let Some(before) = self.created_before {
2634 if memory.created_at > before {
2635 return false;
2636 }
2637 }
2638 if let Some(ref mt) = self.memory_type {
2639 if memory.memory_type != *mt {
2640 return false;
2641 }
2642 }
2643 if let Some(ref sid) = self.session_id {
2644 if memory.session_id.as_ref() != Some(sid) {
2645 return false;
2646 }
2647 }
2648 true
2649 }
2650}
2651
2652#[derive(Debug, Deserialize)]
2654pub struct BatchRecallRequest {
2655 pub agent_id: String,
2657 #[serde(default)]
2659 pub filter: BatchMemoryFilter,
2660 #[serde(default = "default_batch_limit")]
2662 pub limit: usize,
2663}
2664
2665fn default_batch_limit() -> usize {
2666 100
2667}
2668
2669#[derive(Debug, Serialize)]
2671pub struct BatchRecallResponse {
2672 pub memories: Vec<Memory>,
2673 pub total: usize,
2674 pub filtered: usize,
2675}
2676
2677#[derive(Debug, Deserialize)]
2679pub struct BatchForgetRequest {
2680 pub agent_id: String,
2682 pub filter: BatchMemoryFilter,
2684}
2685
2686#[derive(Debug, Serialize)]
2688pub struct BatchForgetResponse {
2689 pub deleted_count: usize,
2690}
2691
2692#[derive(Debug, Deserialize)]
2699pub struct NamespaceEntityConfigRequest {
2700 pub extract_entities: bool,
2702 #[serde(default)]
2705 pub entity_types: Vec<String>,
2706}
2707
2708#[derive(Debug, Serialize, Deserialize)]
2710pub struct NamespaceEntityConfigResponse {
2711 pub namespace: String,
2712 pub extract_entities: bool,
2713 pub entity_types: Vec<String>,
2714}
2715
2716#[derive(Debug, Deserialize)]
2719pub struct ExtractEntitiesRequest {
2720 pub content: String,
2722 #[serde(default)]
2725 pub entity_types: Vec<String>,
2726}
2727
2728#[derive(Debug, Clone, Serialize, Deserialize)]
2730pub struct EntityResult {
2731 pub entity_type: String,
2732 pub value: String,
2733 pub score: f32,
2734 pub start: usize,
2735 pub end: usize,
2736 pub tag: String,
2738}
2739
2740#[derive(Debug, Serialize)]
2742pub struct ExtractEntitiesResponse {
2743 pub entities: Vec<EntityResult>,
2744 pub count: usize,
2745}
2746
2747#[derive(Debug, Deserialize)]
2753pub struct GraphTraverseQuery {
2754 #[serde(default = "default_ce5_graph_depth")]
2756 pub depth: u32,
2757}
2758
2759fn default_ce5_graph_depth() -> u32 {
2760 3
2761}
2762
2763#[derive(Debug, Deserialize)]
2765pub struct GraphPathQuery {
2766 pub to: String,
2768}
2769
2770#[derive(Debug, Deserialize)]
2772pub struct MemoryLinkRequest {
2773 pub target_id: String,
2775 #[serde(skip_serializing_if = "Option::is_none")]
2777 pub label: Option<String>,
2778 pub agent_id: String,
2780}
2781
2782#[derive(Debug, Serialize)]
2784pub struct GraphTraverseResponse {
2785 pub root_id: String,
2786 pub depth: u32,
2787 pub node_count: usize,
2788 pub nodes: Vec<GraphNodeResponse>,
2789}
2790
2791#[derive(Debug, Serialize)]
2793pub struct GraphNodeResponse {
2794 pub memory_id: String,
2795 pub depth: u32,
2796 pub edges: Vec<GraphEdgeResponse>,
2797}
2798
2799#[derive(Debug, Serialize)]
2801pub struct GraphEdgeResponse {
2802 pub from_id: String,
2803 pub to_id: String,
2804 pub edge_type: String,
2805 pub weight: f32,
2806 pub created_at: u64,
2807}
2808
2809#[derive(Debug, Serialize)]
2811pub struct GraphPathResponse {
2812 pub from_id: String,
2813 pub to_id: String,
2814 pub path: Vec<String>,
2816 pub hop_count: usize,
2817}
2818
2819#[derive(Debug, Serialize)]
2821pub struct MemoryLinkResponse {
2822 pub from_id: String,
2823 pub to_id: String,
2824 pub edge_type: String,
2825}
2826
2827#[derive(Debug, Serialize)]
2829pub struct GraphExportResponse {
2830 pub agent_id: String,
2831 pub namespace: String,
2832 pub node_count: usize,
2833 pub edge_count: usize,
2834 pub edges: Vec<GraphEdgeResponse>,
2835}
2836
2837#[derive(Debug, Deserialize)]
2843pub struct KgQueryParams {
2844 pub agent_id: String,
2846 #[serde(default)]
2848 pub root_id: Option<String>,
2849 #[serde(default)]
2851 pub edge_type: Option<String>,
2852 #[serde(default)]
2854 pub min_weight: Option<f32>,
2855 #[serde(default = "default_kg_depth")]
2857 pub max_depth: u32,
2858 #[serde(default = "default_kg_limit")]
2860 pub limit: usize,
2861}
2862
2863fn default_kg_depth() -> u32 {
2864 3
2865}
2866
2867fn default_kg_limit() -> usize {
2868 100
2869}
2870
2871#[derive(Debug, Serialize)]
2873pub struct KgQueryResponse {
2874 pub agent_id: String,
2875 pub node_count: usize,
2876 pub edge_count: usize,
2877 pub edges: Vec<GraphEdgeResponse>,
2878}
2879
2880#[derive(Debug, Deserialize)]
2882pub struct KgPathParams {
2883 pub agent_id: String,
2885 pub from: String,
2887 pub to: String,
2889}
2890
2891#[derive(Debug, Serialize)]
2893pub struct KgPathResponse {
2894 pub agent_id: String,
2895 pub from_id: String,
2896 pub to_id: String,
2897 pub hop_count: usize,
2898 pub path: Vec<String>,
2899}
2900
2901#[derive(Debug, Deserialize)]
2903pub struct KgExportParams {
2904 pub agent_id: String,
2906 #[serde(default = "default_kg_format")]
2908 pub format: String,
2909}
2910
2911fn default_kg_format() -> String {
2912 "json".to_string()
2913}
2914
2915#[derive(Debug, Serialize)]
2917pub struct KgExportJsonResponse {
2918 pub agent_id: String,
2919 pub format: String,
2920 pub node_count: usize,
2921 pub edge_count: usize,
2922 pub edges: Vec<GraphEdgeResponse>,
2923}
2924
2925fn default_working_ttl() -> Option<u64> {
2930 Some(14_400) }
2932fn default_episodic_ttl() -> Option<u64> {
2933 Some(2_592_000) }
2935fn default_semantic_ttl() -> Option<u64> {
2936 Some(31_536_000) }
2938fn default_procedural_ttl() -> Option<u64> {
2939 Some(63_072_000) }
2941fn default_working_decay() -> DecayStrategy {
2942 DecayStrategy::Exponential
2943}
2944fn default_episodic_decay() -> DecayStrategy {
2945 DecayStrategy::PowerLaw
2946}
2947fn default_semantic_decay() -> DecayStrategy {
2948 DecayStrategy::Logarithmic
2949}
2950fn default_procedural_decay() -> DecayStrategy {
2951 DecayStrategy::Flat
2952}
2953fn default_sr_factor() -> f64 {
2954 1.0
2955}
2956fn default_sr_base_interval() -> u64 {
2957 86_400 }
2959fn default_consolidation_enabled() -> bool {
2960 false
2961}
2962fn default_policy_consolidation_threshold() -> f32 {
2963 0.92
2964}
2965fn default_consolidation_interval_hours() -> u32 {
2966 24
2967}
2968fn default_store_dedup_threshold() -> f32 {
2969 0.95
2970}
2971
2972#[derive(Debug, Clone, Serialize, Deserialize)]
2977pub struct MemoryPolicy {
2978 #[serde(
2981 default = "default_working_ttl",
2982 skip_serializing_if = "Option::is_none"
2983 )]
2984 pub working_ttl_seconds: Option<u64>,
2985 #[serde(
2987 default = "default_episodic_ttl",
2988 skip_serializing_if = "Option::is_none"
2989 )]
2990 pub episodic_ttl_seconds: Option<u64>,
2991 #[serde(
2993 default = "default_semantic_ttl",
2994 skip_serializing_if = "Option::is_none"
2995 )]
2996 pub semantic_ttl_seconds: Option<u64>,
2997 #[serde(
2999 default = "default_procedural_ttl",
3000 skip_serializing_if = "Option::is_none"
3001 )]
3002 pub procedural_ttl_seconds: Option<u64>,
3003
3004 #[serde(default = "default_working_decay")]
3007 pub working_decay: DecayStrategy,
3008 #[serde(default = "default_episodic_decay")]
3010 pub episodic_decay: DecayStrategy,
3011 #[serde(default = "default_semantic_decay")]
3013 pub semantic_decay: DecayStrategy,
3014 #[serde(default = "default_procedural_decay")]
3016 pub procedural_decay: DecayStrategy,
3017
3018 #[serde(default = "default_sr_factor")]
3023 pub spaced_repetition_factor: f64,
3024 #[serde(default = "default_sr_base_interval")]
3026 pub spaced_repetition_base_interval_seconds: u64,
3027
3028 #[serde(default = "default_consolidation_enabled")]
3031 pub consolidation_enabled: bool,
3032 #[serde(default = "default_policy_consolidation_threshold")]
3034 pub consolidation_threshold: f32,
3035 #[serde(default = "default_consolidation_interval_hours")]
3037 pub consolidation_interval_hours: u32,
3038 #[serde(default)]
3040 pub consolidated_count: u64,
3041
3042 #[serde(default)]
3046 pub rate_limit_enabled: bool,
3047 #[serde(default, skip_serializing_if = "Option::is_none")]
3050 pub rate_limit_stores_per_minute: Option<u32>,
3051 #[serde(default, skip_serializing_if = "Option::is_none")]
3054 pub rate_limit_recalls_per_minute: Option<u32>,
3055
3056 #[serde(default)]
3064 pub dedup_on_store: bool,
3065 #[serde(default = "default_store_dedup_threshold")]
3067 pub dedup_threshold: f32,
3068}
3069
3070impl Default for MemoryPolicy {
3071 fn default() -> Self {
3072 Self {
3073 working_ttl_seconds: default_working_ttl(),
3074 episodic_ttl_seconds: default_episodic_ttl(),
3075 semantic_ttl_seconds: default_semantic_ttl(),
3076 procedural_ttl_seconds: default_procedural_ttl(),
3077 working_decay: default_working_decay(),
3078 episodic_decay: default_episodic_decay(),
3079 semantic_decay: default_semantic_decay(),
3080 procedural_decay: default_procedural_decay(),
3081 spaced_repetition_factor: default_sr_factor(),
3082 spaced_repetition_base_interval_seconds: default_sr_base_interval(),
3083 consolidation_enabled: default_consolidation_enabled(),
3084 consolidation_threshold: default_policy_consolidation_threshold(),
3085 consolidation_interval_hours: default_consolidation_interval_hours(),
3086 consolidated_count: 0,
3087 rate_limit_enabled: false,
3088 rate_limit_stores_per_minute: None,
3089 rate_limit_recalls_per_minute: None,
3090 dedup_on_store: false,
3091 dedup_threshold: default_store_dedup_threshold(),
3092 }
3093 }
3094}
3095
3096impl MemoryPolicy {
3097 pub fn ttl_for_type(&self, memory_type: &MemoryType) -> Option<u64> {
3099 match memory_type {
3100 MemoryType::Working => self.working_ttl_seconds,
3101 MemoryType::Episodic => self.episodic_ttl_seconds,
3102 MemoryType::Semantic => self.semantic_ttl_seconds,
3103 MemoryType::Procedural => self.procedural_ttl_seconds,
3104 }
3105 }
3106
3107 pub fn decay_for_type(&self, memory_type: &MemoryType) -> DecayStrategy {
3109 match memory_type {
3110 MemoryType::Working => self.working_decay,
3111 MemoryType::Episodic => self.episodic_decay,
3112 MemoryType::Semantic => self.semantic_decay,
3113 MemoryType::Procedural => self.procedural_decay,
3114 }
3115 }
3116
3117 pub fn spaced_repetition_extension(&self, access_count: u32) -> u64 {
3121 if self.spaced_repetition_factor <= 0.0 {
3122 return 0;
3123 }
3124 let ext = access_count as f64
3125 * self.spaced_repetition_factor
3126 * self.spaced_repetition_base_interval_seconds as f64;
3127 ext.round() as u64
3128 }
3129}