{{ message }}
Repository navigation
Expand file tree
/
Copy pathagenticdb.rs
More file actions
1591 lines (1401 loc) · 55.1 KB
/
Copy pathagenticdb.rs
File metadata and controls
1591 lines (1401 loc) · 55.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! AgenticDB API Compatibility Layer
//!
//! # ⚠️ CRITICAL WARNING: PLACEHOLDER EMBEDDINGS
//!
//! **THIS MODULE USES HASH-BASED PLACEHOLDER EMBEDDINGS - NOT REAL SEMANTIC EMBEDDINGS**
//!
//! The `generate_text_embedding()` function creates embeddings using a simple hash function
//! that does NOT understand semantic meaning. Similarity is based on character overlap, NOT meaning.
//!
//! **For Production Use:**
//! - Integrate a real embedding model (sentence-transformers, OpenAI, Anthropic, Cohere)
//! - Use ONNX Runtime, candle, or Python bindings for inference
//! - See `/examples/onnx-embeddings` for a production-ready integration example
//!
//! **What This Means:**
//! - "dog" and "cat" will NOT be similar (different characters)
//! - "dog" and "god" WILL be similar (same characters, different order)
//! - Semantic search will not work as expected
//!
//! Provides a drop-in replacement for agenticDB with 5-table schema:
//! - vectors_table: Core embeddings + metadata
//! - reflexion_episodes: Self-critique memories
//! - skills_library: Consolidated patterns
//! - causal_edges: Cause-effect relationships with hypergraphs
//! - learning_sessions: RL training data
use crate::embeddings::{BoxedEmbeddingProvider, EmbeddingSpaceAccess, HashEmbedding};
use crate::error::{Result, RuvectorError};
use crate::types::*;
use crate::vector_db::VectorDB;
use parking_lot::RwLock;
use redb::{Database, ReadableTable, ReadableTableMetadata, TableDefinition};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
// Table definitions
const REFLEXION_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("reflexion_episodes");
const SKILLS_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("skills_library");
const CAUSAL_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("causal_edges");
const LEARNING_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("learning_sessions");
/// ADR-281 §7: the embedding-space identity the corpus was written under.
const EMBEDDING_SPACE_TABLE: TableDefinition<&str, &[u8]> =
TableDefinition::new("embedding_space_identity");
/// Key for the identity in both the sidecar table and the vector store's
/// shared config table, so it is namespaced like the other reserved keys there.
const EMBEDDING_SPACE_KEY: &str = "__ruvector_embedding_space__";
/// Reflexion episode for self-critique memory
/// Note: Serialized using JSON (not bincode) due to serde_json::Value in metadata field
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReflexionEpisode {
pub id: String,
pub task: String,
pub actions: Vec<String>,
pub observations: Vec<String>,
pub critique: String,
pub embedding: Vec<f32>,
pub timestamp: i64,
pub metadata: Option<HashMap<String, serde_json::Value>>,
}
/// Skill definition in the library
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct Skill {
pub id: String,
pub name: String,
pub description: String,
pub parameters: HashMap<String, String>,
pub examples: Vec<String>,
pub embedding: Vec<f32>,
pub usage_count: usize,
pub success_rate: f64,
pub created_at: i64,
pub updated_at: i64,
}
/// Causal edge in the hypergraph
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct CausalEdge {
pub id: String,
pub causes: Vec<String>, // Hypergraph: multiple causes
pub effects: Vec<String>, // Hypergraph: multiple effects
pub confidence: f64,
pub context: String,
pub embedding: Vec<f32>,
pub observations: usize,
pub timestamp: i64,
}
/// Learning session for RL training
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct LearningSession {
pub id: String,
pub algorithm: String, // Q-Learning, DQN, PPO, etc
pub state_dim: usize,
pub action_dim: usize,
pub experiences: Vec<Experience>,
pub model_params: Option<Vec<u8>>, // Serialized model
pub created_at: i64,
pub updated_at: i64,
}
/// Single RL experience
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct Experience {
pub state: Vec<f32>,
pub action: Vec<f32>,
pub reward: f64,
pub next_state: Vec<f32>,
pub done: bool,
pub timestamp: i64,
}
/// Prediction with confidence interval
#[derive(Debug, Clone, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct Prediction {
pub action: Vec<f32>,
pub confidence_lower: f64,
pub confidence_upper: f64,
pub mean_confidence: f64,
}
/// Query result with utility score
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UtilitySearchResult {
pub result: SearchResult,
pub utility_score: f64,
pub similarity_score: f64,
pub causal_uplift: f64,
pub latency_penalty: f64,
}
/// Main AgenticDB interface
pub struct AgenticDB {
vector_db: Arc<VectorDB>,
db: Arc<Database>,
_dimensions: usize,
embedding_provider: BoxedEmbeddingProvider,
}
impl AgenticDB {
/// Create a new AgenticDB with the given options and default hash-based embeddings
pub fn new(options: DbOptions) -> Result<Self> {
let embedding_provider = Arc::new(HashEmbedding::new(options.dimensions));
Self::with_embedding_provider(options, embedding_provider)
}
/// Create a new AgenticDB with a custom embedding provider
///
/// # Example with API embeddings
/// ```rust,no_run
/// use ruvector_core::{AgenticDB, ApiEmbedding};
/// use ruvector_core::types::DbOptions;
/// use std::sync::Arc;
///
/// let mut options = DbOptions::default();
/// options.dimensions = 1536; // OpenAI embedding dimensions
/// options.storage_path = "agenticdb.db".to_string();
///
/// # let identity = todo!("load a pinned EmbeddingSpaceIdentity");
/// let provider = Arc::new(ApiEmbedding::openai("sk-...", "text-embedding-3-small", identity)?);
/// let db = AgenticDB::with_embedding_provider(options, provider)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example with Candle (requires feature flag)
/// ```rust,no_run
/// # #[cfg(feature = "real-embeddings")]
/// # {
/// use ruvector_core::{AgenticDB, CandleEmbedding};
/// use ruvector_core::types::DbOptions;
/// use std::sync::Arc;
///
/// let mut options = DbOptions::default();
/// options.dimensions = 384; // MiniLM dimensions
/// options.storage_path = "agenticdb.db".to_string();
///
/// let provider = Arc::new(CandleEmbedding::from_pretrained(
/// "sentence-transformers/all-MiniLM-L6-v2",
/// false
/// )?);
/// let db = AgenticDB::with_embedding_provider(options, provider)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # }
/// ```
pub fn with_embedding_provider(
options: DbOptions,
embedding_provider: BoxedEmbeddingProvider,
) -> Result<Self> {
// Validate dimensions match
if options.dimensions != embedding_provider.dimensions() {
return Err(RuvectorError::InvalidDimension(format!(
"Options dimensions ({}) do not match embedding provider dimensions ({})",
options.dimensions,
embedding_provider.dimensions()
)));
}
// Create vector DB for core vector operations
let vector_db = Arc::new(VectorDB::new(options.clone())?);
// Create separate database for AgenticDB tables
let agentic_path = format!("{}.agentic", options.storage_path);
let db = Arc::new(Database::create(&agentic_path)?);
// Initialize tables
let write_txn = db.begin_write()?;
{
let reflexion = write_txn.open_table(REFLEXION_TABLE)?;
let skills = write_txn.open_table(SKILLS_TABLE)?;
let causal = write_txn.open_table(CAUSAL_TABLE)?;
let _ = write_txn.open_table(LEARNING_TABLE)?;
// ADR-281 §7: dimension equality is never proof of embedding
// compatibility, so the corpus records the identity it was written
// under and refuses a provider from a different embedding space.
//
// The identity is written to two places. The authoritative copy
// lives in the vector store's own config table — the same file as
// the vectors, so it cannot be dropped without dropping the data it
// describes. The copy in this `.agentic` sidecar is a mirror for
// tools that only open the sidecar. The primary copy wins on
// disagreement, which is what closes the "delete the sidecar to
// downgrade the check" hole: removing `{path}.agentic` now loses
// the episodes and skills, not the compatibility gate.
let mut spaces = write_txn.open_table(EMBEDDING_SPACE_TABLE)?;
let active = embedding_provider.embedding_space();
let active_id = active.embedding_space_id()?;
let stored_json = match vector_db.load_config_value(EMBEDDING_SPACE_KEY)? {
Some(primary) => Some(primary),
None => spaces
.get(EMBEDDING_SPACE_KEY)?
.map(|value| {
// Strict, not lossy: provenance bytes are never
// silently rewritten to make them parse.
String::from_utf8(value.value().to_vec())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))
})
.transpose()?,
};
match stored_json {
Some(json) => {
let stored: crate::embeddings::EmbeddingSpaceIdentity =
serde_json::from_str(&json)
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
// AgenticDB is a text-embedding, corpus-mutating handle:
// every method either embeds text or writes vectors, so
// losing those two capabilities means the handle cannot be
// opened at all. Vector-only readers (VectorDB) are
// unaffected and keep working against the same store.
let access = EmbeddingSpaceAccess::for_identities(&stored, active)?;
if !access.text_embedding || !access.corpus_mutation {
return Err(RuvectorError::EmbeddingSpaceMismatch {
stored: stored.embedding_space_id()?,
active: active_id,
});
}
// Heal a store whose primary copy predates this check, or
// whose sidecar was deleted, so the next open is gated by
// both copies again.
vector_db.save_config_value(EMBEDDING_SPACE_KEY, &json)?;
spaces.insert(EMBEDDING_SPACE_KEY, json.as_bytes())?;
}
None => {
// Pre-ADR-281 corpora carry no identity. Adopting the
// active identity keeps that data usable (the alternative
// would brick every existing store); the warning is the
// only signal available that the adoption is unverified.
//
// "Has data" must include the vectors themselves: a corpus
// whose sidecar was deleted still has every vector, and
// that is exactly the case worth shouting about.
let populated = !vector_db.is_empty()?
|| !reflexion.is_empty()?
|| !skills.is_empty()?
|| !causal.is_empty()?;
if populated {
tracing::warn!(
embedding_space_id = %active_id,
provider = %active.provider,
model_id = %active.model_id,
vectors = vector_db.len()?,
"corpus holds data but has no recorded embedding-space identity \
(pre-ADR-281 store, or its provenance was removed); adopting the \
active provider's identity WITHOUT verification — vectors already \
in this store may come from a different embedding space"
);
}
let json = serde_json::to_string(active)
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
vector_db.save_config_value(EMBEDDING_SPACE_KEY, &json)?;
spaces.insert(EMBEDDING_SPACE_KEY, json.as_bytes())?;
}
}
}
write_txn.commit()?;
Ok(Self {
vector_db,
db,
_dimensions: options.dimensions,
embedding_provider,
})
}
/// Create with default options and hash-based embeddings
pub fn with_dimensions(dimensions: usize) -> Result<Self> {
let options = DbOptions {
dimensions,
..DbOptions::default()
};
Self::new(options)
}
/// Get the embedding provider name (for debugging/logging)
pub fn embedding_provider_name(&self) -> &str {
self.embedding_provider.name()
}
// ============ Vector DB Core Methods ============
/// Insert a vector entry
pub fn insert(&self, entry: VectorEntry) -> Result<VectorId> {
self.vector_db.insert(entry)
}
/// Insert multiple vectors in a batch
pub fn insert_batch(&self, entries: Vec<VectorEntry>) -> Result<Vec<VectorId>> {
self.vector_db.insert_batch(entries)
}
/// Search for similar vectors
pub fn search(&self, query: SearchQuery) -> Result<Vec<SearchResult>> {
self.vector_db.search(query)
}
/// Delete a vector by ID
pub fn delete(&self, id: &str) -> Result<bool> {
self.vector_db.delete(id)
}
/// Get a vector by ID
pub fn get(&self, id: &str) -> Result<Option<VectorEntry>> {
self.vector_db.get(id)
}
// ============ Reflexion Memory API ============
/// Store a reflexion episode with self-critique
pub fn store_episode(
&self,
task: String,
actions: Vec<String>,
observations: Vec<String>,
critique: String,
) -> Result<String> {
let id = uuid::Uuid::new_v4().to_string();
// Generate embedding from critique for similarity search
let embedding = self.generate_passage_embedding(&critique)?;
let episode = ReflexionEpisode {
id: id.clone(),
task,
actions,
observations,
critique,
embedding: embedding.clone(),
timestamp: chrono::Utc::now().timestamp(),
metadata: None,
};
// Store in reflexion table
let write_txn = self.db.begin_write()?;
{
let mut table = write_txn.open_table(REFLEXION_TABLE)?;
// Use JSON encoding for ReflexionEpisode (contains serde_json::Value which isn't bincode-compatible)
let json = serde_json::to_vec(&episode)
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
table.insert(id.as_str(), json.as_slice())?;
}
write_txn.commit()?;
// Also index in vector DB for fast similarity search
self.vector_db.insert(VectorEntry {
id: Some(format!("reflexion_{}", id)),
vector: embedding,
metadata: Some({
let mut meta = HashMap::new();
meta.insert("type".to_string(), serde_json::json!("reflexion"));
meta.insert("episode_id".to_string(), serde_json::json!(id.clone()));
meta
}),
})?;
Ok(id)
}
/// Retrieve similar reflexion episodes
pub fn retrieve_similar_episodes(
&self,
query: &str,
k: usize,
) -> Result<Vec<ReflexionEpisode>> {
// Generate embedding for query
let query_embedding = self.generate_query_embedding(query)?;
// Search in vector DB
let results = self.vector_db.search(SearchQuery {
vector: query_embedding,
k,
filter: Some({
let mut filter = HashMap::new();
filter.insert("type".to_string(), serde_json::json!("reflexion"));
filter
}),
ef_search: None,
})?;
// Retrieve full episodes
let mut episodes = Vec::new();
let read_txn = self.db.begin_read()?;
let table = read_txn.open_table(REFLEXION_TABLE)?;
for result in results {
if let Some(metadata) = result.metadata {
if let Some(episode_id) = metadata.get("episode_id") {
let id = episode_id.as_str().unwrap();
if let Some(data) = table.get(id)? {
// Use JSON decoding for ReflexionEpisode (contains serde_json::Value which isn't bincode-compatible)
let episode: ReflexionEpisode = serde_json::from_slice(data.value())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
episodes.push(episode);
}
}
}
}
Ok(episodes)
}
// ============ Skill Library API ============
/// Create a new skill in the library
pub fn create_skill(
&self,
name: String,
description: String,
parameters: HashMap<String, String>,
examples: Vec<String>,
) -> Result<String> {
let id = uuid::Uuid::new_v4().to_string();
// Generate embedding from description
let embedding = self.generate_passage_embedding(&description)?;
let skill = Skill {
id: id.clone(),
name,
description,
parameters,
examples,
embedding: embedding.clone(),
usage_count: 0,
success_rate: 0.0,
created_at: chrono::Utc::now().timestamp(),
updated_at: chrono::Utc::now().timestamp(),
};
// Store in skills table
let write_txn = self.db.begin_write()?;
{
let mut table = write_txn.open_table(SKILLS_TABLE)?;
let data = bincode::encode_to_vec(&skill, bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
table.insert(id.as_str(), data.as_slice())?;
}
write_txn.commit()?;
// Index in vector DB
self.vector_db.insert(VectorEntry {
id: Some(format!("skill_{}", id)),
vector: embedding,
metadata: Some({
let mut meta = HashMap::new();
meta.insert("type".to_string(), serde_json::json!("skill"));
meta.insert("skill_id".to_string(), serde_json::json!(id.clone()));
meta
}),
})?;
Ok(id)
}
/// Search skills by description
pub fn search_skills(&self, query_description: &str, k: usize) -> Result<Vec<Skill>> {
let query_embedding = self.generate_query_embedding(query_description)?;
let results = self.vector_db.search(SearchQuery {
vector: query_embedding,
k,
filter: Some({
let mut filter = HashMap::new();
filter.insert("type".to_string(), serde_json::json!("skill"));
filter
}),
ef_search: None,
})?;
let mut skills = Vec::new();
let read_txn = self.db.begin_read()?;
let table = read_txn.open_table(SKILLS_TABLE)?;
for result in results {
if let Some(metadata) = result.metadata {
if let Some(skill_id) = metadata.get("skill_id") {
let id = skill_id.as_str().unwrap();
if let Some(data) = table.get(id)? {
let (skill, _): (Skill, usize) =
bincode::decode_from_slice(data.value(), bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
skills.push(skill);
}
}
}
}
Ok(skills)
}
/// Auto-consolidate action sequences into skills
pub fn auto_consolidate(
&self,
action_sequences: Vec<Vec<String>>,
success_threshold: usize,
) -> Result<Vec<String>> {
let mut skill_ids = Vec::new();
// Group similar sequences (simplified - would use clustering in production)
for sequence in action_sequences {
if sequence.len() >= success_threshold {
let description = format!("Skill: {}", sequence.join(" -> "));
let skill_id = self.create_skill(
format!("Auto-Skill-{}", uuid::Uuid::new_v4()),
description,
HashMap::new(),
sequence.clone(),
)?;
skill_ids.push(skill_id);
}
}
Ok(skill_ids)
}
// ============ Causal Memory with Hypergraphs ============
/// Add a causal edge (supporting hypergraphs with multiple causes/effects)
pub fn add_causal_edge(
&self,
causes: Vec<String>,
effects: Vec<String>,
confidence: f64,
context: String,
) -> Result<String> {
let id = uuid::Uuid::new_v4().to_string();
// Generate embedding from context
let embedding = self.generate_passage_embedding(&context)?;
let edge = CausalEdge {
id: id.clone(),
causes,
effects,
confidence,
context,
embedding: embedding.clone(),
observations: 1,
timestamp: chrono::Utc::now().timestamp(),
};
// Store in causal table
let write_txn = self.db.begin_write()?;
{
let mut table = write_txn.open_table(CAUSAL_TABLE)?;
let data = bincode::encode_to_vec(&edge, bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
table.insert(id.as_str(), data.as_slice())?;
}
write_txn.commit()?;
// Index in vector DB
self.vector_db.insert(VectorEntry {
id: Some(format!("causal_{}", id)),
vector: embedding,
metadata: Some({
let mut meta = HashMap::new();
meta.insert("type".to_string(), serde_json::json!("causal"));
meta.insert("causal_id".to_string(), serde_json::json!(id.clone()));
meta.insert("confidence".to_string(), serde_json::json!(confidence));
meta
}),
})?;
Ok(id)
}
/// Query with utility function: U = α·similarity + β·causal_uplift − γ·latency
pub fn query_with_utility(
&self,
query: &str,
k: usize,
alpha: f64,
beta: f64,
gamma: f64,
) -> Result<Vec<UtilitySearchResult>> {
let start_time = std::time::Instant::now();
let query_embedding = self.generate_query_embedding(query)?;
// Get all causal edges
let results = self.vector_db.search(SearchQuery {
vector: query_embedding,
k: k * 2, // Get more results for utility ranking
filter: Some({
let mut filter = HashMap::new();
filter.insert("type".to_string(), serde_json::json!("causal"));
filter
}),
ef_search: None,
})?;
let mut utility_results = Vec::new();
for result in results {
let similarity_score = 1.0 / (1.0 + result.score as f64); // Convert distance to similarity
// Get causal uplift from metadata
let causal_uplift = if let Some(ref metadata) = result.metadata {
metadata
.get("confidence")
.and_then(|v| v.as_f64())
.unwrap_or(0.0)
} else {
0.0
};
let latency = start_time.elapsed().as_secs_f64();
let latency_penalty = latency * gamma;
// Calculate utility: U = α·similarity + β·causal_uplift − γ·latency
let utility_score = alpha * similarity_score + beta * causal_uplift - latency_penalty;
utility_results.push(UtilitySearchResult {
result,
utility_score,
similarity_score,
causal_uplift,
latency_penalty,
});
}
// Sort by utility score (descending)
utility_results.sort_by(|a, b| b.utility_score.partial_cmp(&a.utility_score).unwrap());
utility_results.truncate(k);
Ok(utility_results)
}
// ============ Learning Sessions API ============
/// Start a new learning session
pub fn start_session(
&self,
algorithm: String,
state_dim: usize,
action_dim: usize,
) -> Result<String> {
let id = uuid::Uuid::new_v4().to_string();
let session = LearningSession {
id: id.clone(),
algorithm,
state_dim,
action_dim,
experiences: Vec::new(),
model_params: None,
created_at: chrono::Utc::now().timestamp(),
updated_at: chrono::Utc::now().timestamp(),
};
let write_txn = self.db.begin_write()?;
{
let mut table = write_txn.open_table(LEARNING_TABLE)?;
let data = bincode::encode_to_vec(&session, bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
table.insert(id.as_str(), data.as_slice())?;
}
write_txn.commit()?;
Ok(id)
}
/// Add an experience to a learning session
pub fn add_experience(
&self,
session_id: &str,
state: Vec<f32>,
action: Vec<f32>,
reward: f64,
next_state: Vec<f32>,
done: bool,
) -> Result<()> {
let read_txn = self.db.begin_read()?;
let table = read_txn.open_table(LEARNING_TABLE)?;
let data = table
.get(session_id)?
.ok_or_else(|| RuvectorError::VectorNotFound(session_id.to_string()))?;
let (mut session, _): (LearningSession, usize) =
bincode::decode_from_slice(data.value(), bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
drop(table);
drop(read_txn);
// Add experience
session.experiences.push(Experience {
state,
action,
reward,
next_state,
done,
timestamp: chrono::Utc::now().timestamp(),
});
session.updated_at = chrono::Utc::now().timestamp();
// Update session
let write_txn = self.db.begin_write()?;
{
let mut table = write_txn.open_table(LEARNING_TABLE)?;
let data = bincode::encode_to_vec(&session, bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
table.insert(session_id, data.as_slice())?;
}
write_txn.commit()?;
Ok(())
}
/// Predict action with confidence interval
pub fn predict_with_confidence(&self, session_id: &str, state: Vec<f32>) -> Result<Prediction> {
let read_txn = self.db.begin_read()?;
let table = read_txn.open_table(LEARNING_TABLE)?;
let data = table
.get(session_id)?
.ok_or_else(|| RuvectorError::VectorNotFound(session_id.to_string()))?;
let (session, _): (LearningSession, usize) =
bincode::decode_from_slice(data.value(), bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
// Simple prediction based on similar states (would use actual RL model in production)
let mut similar_actions = Vec::new();
let mut rewards = Vec::new();
for exp in &session.experiences {
let distance = euclidean_distance(&state, &exp.state);
if distance < 1.0 {
// Similarity threshold
similar_actions.push(exp.action.clone());
rewards.push(exp.reward);
}
}
if similar_actions.is_empty() {
// Return random action if no similar states
return Ok(Prediction {
action: vec![0.0; session.action_dim],
confidence_lower: 0.0,
confidence_upper: 0.0,
mean_confidence: 0.0,
});
}
// Average actions weighted by rewards
let total_reward: f64 = rewards.iter().sum();
let mut action = vec![0.0; session.action_dim];
for (act, reward) in similar_actions.iter().zip(rewards.iter()) {
let weight = reward / total_reward;
for (i, val) in act.iter().enumerate() {
action[i] += val * weight as f32;
}
}
// Calculate confidence interval (simplified)
let mean_reward = total_reward / rewards.len() as f64;
let std_dev = calculate_std_dev(&rewards, mean_reward);
Ok(Prediction {
action,
confidence_lower: mean_reward - 1.96 * std_dev,
confidence_upper: mean_reward + 1.96 * std_dev,
mean_confidence: mean_reward,
})
}
/// Get learning session by ID
pub fn get_session(&self, session_id: &str) -> Result<Option<LearningSession>> {
let read_txn = self.db.begin_read()?;
let table = read_txn.open_table(LEARNING_TABLE)?;
if let Some(data) = table.get(session_id)? {
let (session, _): (LearningSession, usize) =
bincode::decode_from_slice(data.value(), bincode::config::standard())
.map_err(|e| RuvectorError::SerializationError(e.to_string()))?;
Ok(Some(session))
} else {
Ok(None)
}
}
// ============ Helper Methods ============
/// Generate text embedding from text using the configured embedding provider.
///
/// By default, this uses hash-based embeddings (fast but not semantic).
/// Use `with_embedding_provider()` to use real embeddings.
///
/// # Example with real embeddings
/// ```rust,ignore
/// use ruvector_core::{AgenticDB, ApiEmbedding};
/// use ruvector_core::types::DbOptions;
/// use std::sync::Arc;
///
/// let mut options = DbOptions::default();
/// options.dimensions = 1536;
/// # let identity = todo!("load a pinned EmbeddingSpaceIdentity");
/// let provider = Arc::new(ApiEmbedding::openai("sk-...", "text-embedding-3-small", identity)?);
/// let db = AgenticDB::with_embedding_provider(options, provider)?;
///
/// // Now embeddings will be semantic! (internal method)
/// let embedding = db.generate_text_embedding("hello world")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
fn generate_query_embedding(&self, text: &str) -> Result<Vec<f32>> {
self.embedding_provider.embed_query(text)
}
fn generate_passage_embedding(&self, text: &str) -> Result<Vec<f32>> {
self.embedding_provider.embed_passage(text)
}
}
// Helper functions
fn euclidean_distance(a: &[f32], b: &[f32]) -> f32 {
a.iter()
.zip(b.iter())
.map(|(x, y)| (x - y).powi(2))
.sum::<f32>()
.sqrt()
}
fn calculate_std_dev(values: &[f64], mean: f64) -> f64 {
let variance = values.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / values.len() as f64;
variance.sqrt()
}
// ============ High-Level API Interfaces (ADR-001) ============
/// Policy Memory Store interface for AI agent policy memory
///
/// This interface provides Q-learning state-action lookups, contextual bandit
/// policy retrieval, and episodic memory for reasoning.
///
/// # Example
/// ```rust,ignore
/// let policy_store = db.policy_memory();
/// policy_store.store_policy("state_a", vec![0.1, 0.2], PolicyAction { action: "move_left", reward: 0.8 })?;
/// let similar = policy_store.retrieve_similar_states(¤t_state_embedding, 5)?;
/// ```
pub struct PolicyMemoryStore<'a> {
db: &'a AgenticDB,
}
/// Policy action with reward information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyAction {
/// Action taken
pub action: String,
/// Reward received
pub reward: f64,
/// Q-value estimate
pub q_value: f64,
/// State embedding
pub state_embedding: Vec<f32>,
/// Timestamp
pub timestamp: i64,
}
/// Policy entry combining state and action
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyEntry {
/// Unique identifier
pub id: String,
/// State identifier
pub state_id: String,
/// Action taken
pub action: PolicyAction,
/// Metadata
pub metadata: Option<HashMap<String, serde_json::Value>>,
}
impl<'a> PolicyMemoryStore<'a> {
/// Create a new policy memory store interface
pub fn new(db: &'a AgenticDB) -> Self {
Self { db }
}
/// Store a policy entry (state-action pair)
pub fn store_policy(
&self,
state_id: &str,
state_embedding: Vec<f32>,
action: &str,
reward: f64,
q_value: f64,
) -> Result<String> {
let id = uuid::Uuid::new_v4().to_string();
let timestamp = chrono::Utc::now().timestamp();
let _entry = PolicyEntry {
id: id.clone(),
state_id: state_id.to_string(),
action: PolicyAction {
action: action.to_string(),
reward,
q_value,
state_embedding: state_embedding.clone(),
timestamp,
},
metadata: None,
};
// Store in vector DB for similarity search
self.db.vector_db.insert(VectorEntry {
id: Some(format!("policy_{}", id)),
vector: state_embedding,
metadata: Some({
let mut meta = HashMap::new();
meta.insert("type".to_string(), serde_json::json!("policy"));
meta.insert("policy_id".to_string(), serde_json::json!(id.clone()));
meta.insert("state_id".to_string(), serde_json::json!(state_id));
meta.insert("action".to_string(), serde_json::json!(action));
meta.insert("reward".to_string(), serde_json::json!(reward));
meta.insert("q_value".to_string(), serde_json::json!(q_value));
meta
}),
})?;
Ok(id)
}
/// Retrieve similar states for policy lookup
pub fn retrieve_similar_states(
&self,
state_embedding: &[f32],
k: usize,
) -> Result<Vec<PolicyEntry>> {
let results = self.db.vector_db.search(SearchQuery {
vector: state_embedding.to_vec(),
k,
filter: Some({
let mut filter = HashMap::new();
filter.insert("type".to_string(), serde_json::json!("policy"));
filter
}),
ef_search: None,
})?;
let mut entries = Vec::new();
for result in results {
if let Some(metadata) = result.metadata {
let policy_id = metadata
.get("policy_id")
.and_then(|v| v.as_str())
.unwrap_or("");
let state_id = metadata
.get("state_id")
.and_then(|v| v.as_str())
.unwrap_or("");
let action = metadata
.get("action")
.and_then(|v| v.as_str())
.unwrap_or("");
let reward = metadata
.get("reward")
You can’t perform that action at this time.
