Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'

This commit is contained in:
ruv
2026-02-28 14:39:40 -05:00
7854 changed files with 3522914 additions and 0 deletions

View File

@@ -0,0 +1,233 @@
# Cypher Query Language Reference
RuVector implements a Neo4j-compatible Cypher query language with extensions for hyperedges.
## Quick Examples
```cypher
-- Create nodes
CREATE (p:Person {name: 'Alice', age: 30})
-- Create relationships
CREATE (a:Person {name: 'Alice'})-[:KNOWS]->(b:Person {name: 'Bob'})
-- Pattern matching
MATCH (p:Person)-[:KNOWS]->(friend)
WHERE p.name = 'Alice'
RETURN friend.name
-- Hyperedges (N-ary relationships)
CREATE (a:Person)-[:ATTENDED]->(meeting:Meeting, room:Room, company:Company)
```
## Supported Clauses
### MATCH
Find patterns in the graph.
```cypher
-- Simple node
MATCH (n:Person)
RETURN n
-- With relationship
MATCH (a:Person)-[:KNOWS]->(b:Person)
RETURN a.name, b.name
-- Variable-length paths
MATCH (a)-[*1..3]->(b)
RETURN a, b
-- Optional matching
OPTIONAL MATCH (p:Person)-[:OWNS]->(c:Car)
RETURN p.name, c.model
```
### CREATE
Create new nodes and relationships.
```cypher
-- Single node
CREATE (n:Person {name: 'Alice'})
-- Multiple labels
CREATE (n:Person:Employee {name: 'Bob'})
-- With relationship
CREATE (a:Person {name: 'Alice'})-[:FRIEND]->(b:Person {name: 'Bob'})
```
### MERGE
Create if not exists, match if exists.
```cypher
MERGE (p:Person {email: 'alice@example.com'})
ON CREATE SET p.created = timestamp()
ON MATCH SET p.lastSeen = timestamp()
```
### SET
Update properties.
```cypher
MATCH (p:Person {name: 'Alice'})
SET p.age = 31, p.updated = timestamp()
```
### DELETE
Remove nodes and relationships.
```cypher
-- Delete node (must have no relationships)
MATCH (p:Person {name: 'Temp'})
DELETE p
-- Delete node and all relationships
MATCH (p:Person {name: 'Temp'})
DETACH DELETE p
```
### RETURN
Project results.
```cypher
MATCH (p:Person)
RETURN p.name AS name, p.age
ORDER BY p.age DESC
SKIP 10
LIMIT 5
```
### WITH
Intermediate projection (query chaining).
```cypher
MATCH (p:Person)
WITH p.name AS name, COUNT(*) AS count
WHERE count > 1
RETURN name, count
```
### WHERE
Filter results.
```cypher
MATCH (p:Person)
WHERE p.age > 21 AND p.city = 'NYC'
RETURN p
-- Pattern predicates
WHERE (p)-[:KNOWS]->(:Expert)
```
## Hyperedges (N-ary Relationships)
RuVector extends Cypher with hyperedge support for N-ary relationships:
```cypher
-- Create hyperedge (3+ nodes)
CREATE (author:Person)-[:WROTE]->(paper:Paper, journal:Journal, year:Year)
-- Match hyperedge
MATCH (a:Person)-[r:ATTENDED]->(meeting, room, company)
RETURN a.name, meeting.topic, room.number
```
## Expressions
### Operators
| Type | Operators |
|------|-----------|
| Arithmetic | `+`, `-`, `*`, `/`, `%`, `^` |
| Comparison | `=`, `<>`, `<`, `>`, `<=`, `>=` |
| Logical | `AND`, `OR`, `NOT`, `XOR` |
| String | `STARTS WITH`, `ENDS WITH`, `CONTAINS` |
| Null | `IS NULL`, `IS NOT NULL` |
| List | `IN`, `[]` (indexing) |
### Functions
```cypher
-- String
RETURN toUpper(name), toLower(name), trim(name), substring(name, 0, 5)
-- Numeric
RETURN abs(x), ceil(x), floor(x), round(x), sqrt(x)
-- Collections
RETURN size(list), head(list), tail(list), range(1, 10)
-- Type
RETURN type(r), labels(n), keys(n)
```
### Aggregations
```cypher
MATCH (p:Person)
RETURN
COUNT(*) AS total,
AVG(p.age) AS avgAge,
MIN(p.age) AS minAge,
MAX(p.age) AS maxAge,
SUM(p.salary) AS totalSalary,
COLLECT(p.name) AS names
```
### CASE Expressions
```cypher
MATCH (p:Person)
RETURN p.name,
CASE
WHEN p.age < 18 THEN 'minor'
WHEN p.age < 65 THEN 'adult'
ELSE 'senior'
END AS category
```
## Data Types
| Type | Example |
|------|---------|
| Integer | `42`, `-17` |
| Float | `3.14`, `-2.5e10` |
| String | `'hello'`, `"world"` |
| Boolean | `true`, `false` |
| Null | `null` |
| List | `[1, 2, 3]`, `['a', 'b']` |
| Map | `{name: 'Alice', age: 30}` |
## Path Variables
```cypher
-- Assign path to variable
MATCH p = (a:Person)-[:KNOWS*]->(b:Person)
RETURN p, length(p)
-- Path functions
RETURN nodes(p), relationships(p), length(p)
```
## Best Practices
1. **Use labels** - Always specify node labels for faster lookups
2. **Index properties** - Create indexes on frequently queried properties
3. **Limit results** - Use `LIMIT` to avoid large result sets
4. **Parameterize** - Use parameters for values to enable query caching
## See Also
- [Getting Started Guide](../guide/GETTING_STARTED.md)
- [Node.js API](./NODEJS_API.md)
- [Rust API](./RUST_API.md)
- [GNN Architecture](../gnn-layer-implementation.md)

700
vendor/ruvector/docs/api/NODEJS_API.md vendored Normal file
View File

@@ -0,0 +1,700 @@
# Ruvector Node.js API Reference
Complete API reference for `ruvector` npm package.
## Installation
```bash
npm install ruvector
# or
yarn add ruvector
```
## Table of Contents
1. [VectorDB](#vectordb)
2. [AgenticDB](#agenticdb)
3. [Types](#types)
4. [Advanced Features](#advanced-features)
5. [Error Handling](#error-handling)
## VectorDB
Core vector database class.
### Constructor
```typescript
new VectorDB(options: DbOptions): VectorDB
```
Create a new vector database.
**Parameters**:
```typescript
interface DbOptions {
dimensions: number;
storagePath: string;
distanceMetric?: 'euclidean' | 'cosine' | 'dotProduct' | 'manhattan';
hnsw?: HnswConfig;
quantization?: QuantizationConfig;
mmapVectors?: boolean;
}
```
**Example**:
```javascript
const { VectorDB } = require('ruvector');
const db = new VectorDB({
dimensions: 128,
storagePath: './vectors.db',
distanceMetric: 'cosine'
});
```
### insert
```typescript
async insert(entry: VectorEntry): Promise<string>
```
Insert a single vector.
**Parameters**:
```typescript
interface VectorEntry {
id?: string;
vector: Float32Array;
metadata?: Record<string, any>;
}
```
**Returns**: Promise resolving to vector ID
**Example**:
```javascript
const id = await db.insert({
vector: new Float32Array(128).fill(0.1),
metadata: { text: 'Example document' }
});
console.log('Inserted:', id);
```
### insertBatch
```typescript
async insertBatch(entries: VectorEntry[]): Promise<string[]>
```
Insert multiple vectors efficiently.
**Parameters**: Array of vector entries
**Returns**: Promise resolving to array of IDs
**Example**:
```javascript
const entries = Array.from({ length: 1000 }, (_, i) => ({
id: `vec_${i}`,
vector: new Float32Array(128).map(() => Math.random()),
metadata: { index: i }
}));
const ids = await db.insertBatch(entries);
console.log(`Inserted ${ids.length} vectors`);
```
### search
```typescript
async search(query: SearchQuery): Promise<SearchResult[]>
```
Search for similar vectors.
**Parameters**:
```typescript
interface SearchQuery {
vector: Float32Array;
k: number;
filter?: any;
includeVectors?: boolean;
includeMetadata?: boolean;
}
```
**Returns**: Promise resolving to search results
**Example**:
```javascript
const results = await db.search({
vector: new Float32Array(128).fill(0.1),
k: 10,
includeMetadata: true
});
results.forEach(result => {
console.log(`ID: ${result.id}, Distance: ${result.distance}`);
console.log(`Metadata:`, result.metadata);
});
```
### delete
```typescript
async delete(id: string): Promise<void>
```
Delete a vector by ID.
**Parameters**: Vector ID string
**Returns**: Promise resolving when complete
**Example**:
```javascript
await db.delete('vec_001');
console.log('Deleted vec_001');
```
### update
```typescript
async update(id: string, entry: VectorEntry): Promise<void>
```
Update an existing vector.
**Parameters**:
- `id`: Vector ID to update
- `entry`: New vector data
**Returns**: Promise resolving when complete
**Example**:
```javascript
await db.update('vec_001', {
vector: new Float32Array(128).fill(0.2),
metadata: { updated: true }
});
```
### count
```typescript
count(): number
```
Get total number of vectors.
**Returns**: Number of vectors
**Example**:
```javascript
const total = db.count();
console.log(`Total vectors: ${total}`);
```
## AgenticDB
Extended API for AI agents.
### Constructor
```typescript
new AgenticDB(options: DbOptions): AgenticDB
```
Create AgenticDB instance.
**Example**:
```javascript
const { AgenticDB } = require('ruvector');
const db = new AgenticDB({
dimensions: 128,
storagePath: './agenticdb.db'
});
```
### Reflexion Memory
#### storeEpisode
```typescript
async storeEpisode(
task: string,
actions: string[],
observations: string[],
critique: string
): Promise<string>
```
Store self-critique episode.
**Parameters**:
- `task`: Task description
- `actions`: Actions taken
- `observations`: Observations made
- `critique`: Self-generated critique
**Returns**: Episode ID
**Example**:
```javascript
const episodeId = await db.storeEpisode(
'Solve coding problem',
['Read problem', 'Write solution', 'Submit'],
['Tests failed', 'Edge case missed'],
'Should test edge cases before submitting'
);
```
#### retrieveEpisodes
```typescript
async retrieveEpisodes(
queryEmbedding: Float32Array,
k: number
): Promise<ReflexionEpisode[]>
```
Retrieve similar past episodes.
**Parameters**:
- `queryEmbedding`: Embedded critique or task
- `k`: Number of episodes
**Returns**: Similar episodes
**Example**:
```javascript
const episodes = await db.retrieveEpisodes(critiqueEmbedding, 5);
episodes.forEach(ep => {
console.log(`Task: ${ep.task}`);
console.log(`Critique: ${ep.critique}`);
console.log(`Actions: ${ep.actions.join(', ')}`);
});
```
### Skill Library
#### createSkill
```typescript
async createSkill(
name: string,
description: string,
parameters: Record<string, string>,
examples: string[]
): Promise<string>
```
Create a reusable skill.
**Parameters**:
- `name`: Skill name
- `description`: What the skill does
- `parameters`: Required parameters
- `examples`: Usage examples
**Returns**: Skill ID
**Example**:
```javascript
const skillId = await db.createSkill(
'authenticate_user',
'Authenticate user with JWT token',
{
token: 'string',
userId: 'string'
},
['authenticate_user(token, userId)']
);
```
#### searchSkills
```typescript
async searchSkills(
queryEmbedding: Float32Array,
k: number
): Promise<Skill[]>
```
Search for relevant skills.
**Parameters**:
- `queryEmbedding`: Embedded task description
- `k`: Number of skills
**Returns**: Relevant skills
**Example**:
```javascript
const skills = await db.searchSkills(taskEmbedding, 3);
skills.forEach(skill => {
console.log(`${skill.name}: ${skill.description}`);
console.log(`Success rate: ${(skill.successRate * 100).toFixed(1)}%`);
console.log(`Usage count: ${skill.usageCount}`);
});
```
### Causal Memory
#### addCausalEdge
```typescript
async addCausalEdge(
causes: string[],
effects: string[],
confidence: number,
context: string
): Promise<string>
```
Add cause-effect relationship.
**Parameters**:
- `causes`: Cause actions/states
- `effects`: Effect actions/states
- `confidence`: Confidence score (0-1)
- `context`: Context description
**Returns**: Edge ID
**Example**:
```javascript
const edgeId = await db.addCausalEdge(
['authenticate', 'validate_token'],
['access_granted'],
0.95,
'User authentication flow'
);
```
#### queryCausal
```typescript
async queryCausal(
queryEmbedding: Float32Array,
k: number
): Promise<CausalQueryResult[]>
```
Query causal relationships.
**Parameters**:
- `queryEmbedding`: Embedded context
- `k`: Number of results
**Returns**: Causal edges with utility scores
**Example**:
```javascript
const results = await db.queryCausal(contextEmbedding, 10);
results.forEach(result => {
console.log(`${result.edge.causes.join(', ')}${result.edge.effects.join(', ')}`);
console.log(`Confidence: ${result.edge.confidence}`);
console.log(`Utility: ${result.utilityScore.toFixed(4)}`);
});
```
### Learning Sessions
#### createLearningSession
```typescript
async createLearningSession(
algorithm: string,
stateDim: number,
actionDim: number
): Promise<string>
```
Create RL training session.
**Parameters**:
- `algorithm`: RL algorithm (Q-Learning, DQN, PPO, etc.)
- `stateDim`: State dimensionality
- `actionDim`: Action dimensionality
**Returns**: Session ID
**Example**:
```javascript
const sessionId = await db.createLearningSession('PPO', 64, 4);
```
#### addExperience
```typescript
async addExperience(
sessionId: string,
state: Float32Array,
action: Float32Array,
reward: number,
nextState: Float32Array,
done: boolean
): Promise<void>
```
Add experience to session.
**Example**:
```javascript
await db.addExperience(
sessionId,
state,
action,
1.0, // reward
nextState,
false // not done
);
```
#### predictWithConfidence
```typescript
async predictWithConfidence(
sessionId: string,
state: Float32Array
): Promise<Prediction>
```
Predict action with confidence intervals.
**Returns**:
```typescript
interface Prediction {
action: Float32Array;
confidenceLower: number;
confidenceUpper: number;
meanConfidence: number;
}
```
**Example**:
```javascript
const prediction = await db.predictWithConfidence(sessionId, state);
console.log('Action:', Array.from(prediction.action));
console.log(`Confidence: [${prediction.confidenceLower.toFixed(2)}, ${prediction.confidenceUpper.toFixed(2)}]`);
```
## Types
### VectorEntry
```typescript
interface VectorEntry {
id?: string;
vector: Float32Array;
metadata?: Record<string, any>;
}
```
### SearchQuery
```typescript
interface SearchQuery {
vector: Float32Array;
k: number;
filter?: any;
includeVectors?: boolean;
includeMetadata?: boolean;
}
```
### SearchResult
```typescript
interface SearchResult {
id: string;
distance: number;
vector?: Float32Array;
metadata?: Record<string, any>;
}
```
### ReflexionEpisode
```typescript
interface ReflexionEpisode {
id: string;
task: string;
actions: string[];
observations: string[];
critique: string;
embedding: Float32Array;
timestamp: number;
metadata?: Record<string, any>;
}
```
### Skill
```typescript
interface Skill {
id: string;
name: string;
description: string;
parameters: Record<string, string>;
examples: string[];
embedding: Float32Array;
usageCount: number;
successRate: number;
createdAt: number;
updatedAt: number;
}
```
### CausalEdge
```typescript
interface CausalEdge {
id: string;
causes: string[];
effects: string[];
confidence: number;
context: string;
embedding: Float32Array;
observations: number;
timestamp: number;
}
```
## Configuration
### DbOptions
```typescript
interface DbOptions {
dimensions: number;
storagePath: string;
distanceMetric?: 'euclidean' | 'cosine' | 'dotProduct' | 'manhattan';
hnsw?: HnswConfig;
quantization?: QuantizationConfig;
mmapVectors?: boolean;
}
```
### HnswConfig
```typescript
interface HnswConfig {
m?: number; // 16-64, default 32
efConstruction?: number; // 100-400, default 200
efSearch?: number; // 50-500, default 100
maxElements?: number; // default 10_000_000
}
```
### QuantizationConfig
```typescript
interface QuantizationConfig {
type: 'none' | 'scalar' | 'product' | 'binary';
subspaces?: number; // For product quantization
k?: number; // For product quantization
}
```
## Advanced Features
### HybridSearch
```javascript
const { HybridSearch } = require('ruvector');
const hybrid = new HybridSearch(db, {
vectorWeight: 0.7,
bm25Weight: 0.3,
k1: 1.5,
b: 0.75
});
const results = await hybrid.search(
queryVector,
['machine', 'learning'],
10
);
```
### FilteredSearch
```javascript
const { FilteredSearch } = require('ruvector');
const filtered = new FilteredSearch(db, 'preFilter');
const results = await filtered.search(queryVector, 10, {
and: [
{ field: 'category', op: 'eq', value: 'tech' },
{ field: 'score', op: 'gte', value: 0.8 }
]
});
```
### MMRSearch
```javascript
const { MMRSearch } = require('ruvector');
const mmr = new MMRSearch(db, {
lambda: 0.5,
diversityWeight: 0.3
});
const results = await mmr.search(queryVector, 20);
```
## Error Handling
All async operations throw errors on failure:
```javascript
try {
const id = await db.insert(entry);
console.log('Success:', id);
} catch (error) {
if (error.message.includes('dimension mismatch')) {
console.error('Wrong vector dimensions');
} else {
console.error('Error:', error.message);
}
}
```
## TypeScript Support
Full TypeScript type definitions included:
```typescript
import { VectorDB, VectorEntry, SearchResult } from 'ruvector';
const db = new VectorDB({
dimensions: 128,
storagePath: './vectors.db'
});
const entry: VectorEntry = {
vector: new Float32Array(128),
metadata: { text: 'Example' }
};
const id: string = await db.insert(entry);
const results: SearchResult[] = await db.search({
vector: new Float32Array(128),
k: 10
});
```
## Complete Examples
See [examples/nodejs/](../../examples/nodejs/) for complete working examples.

712
vendor/ruvector/docs/api/RUST_API.md vendored Normal file
View File

@@ -0,0 +1,712 @@
# Ruvector Rust API Reference
Complete API reference for `ruvector-core` crate.
## Table of Contents
1. [VectorDB](#vectordb)
2. [AgenticDB](#agenticdb)
3. [Types](#types)
4. [Configuration](#configuration)
5. [Advanced Features](#advanced-features)
6. [Error Handling](#error-handling)
## VectorDB
Core vector database with HNSW indexing.
### Creation
```rust
use ruvector_core::{VectorDB, DbOptions};
pub fn new(options: DbOptions) -> Result<Self>
```
Create a new vector database.
**Parameters**:
- `options`: Database configuration
**Returns**: `Result<VectorDB, RuvectorError>`
**Example**:
```rust
let mut options = DbOptions::default();
options.dimensions = 128;
options.storage_path = "./vectors.db".to_string();
let db = VectorDB::new(options)?;
```
### open
```rust
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self>
```
Open an existing database.
**Parameters**:
- `path`: Path to database directory
**Returns**: `Result<VectorDB, RuvectorError>`
**Example**:
```rust
let db = VectorDB::open("./vectors.db")?;
```
### insert
```rust
pub fn insert(&self, entry: VectorEntry) -> Result<VectorId>
```
Insert a single vector.
**Parameters**:
- `entry`: Vector entry with optional ID and metadata
**Returns**: `Result<VectorId, RuvectorError>` - ID of inserted vector
**Example**:
```rust
let entry = VectorEntry {
id: None, // Auto-generate
vector: vec![0.1; 128],
metadata: None,
};
let id = db.insert(entry)?;
```
### insert_batch
```rust
pub fn insert_batch(&self, entries: Vec<VectorEntry>) -> Result<Vec<VectorId>>
```
Insert multiple vectors efficiently.
**Parameters**:
- `entries`: Vector of entries to insert
**Returns**: `Result<Vec<VectorId>, RuvectorError>` - IDs of inserted vectors
**Time Complexity**: O(n log m) where n is batch size, m is existing vectors
**Example**:
```rust
let entries: Vec<VectorEntry> = (0..1000)
.map(|i| VectorEntry {
id: Some(format!("vec_{}", i)),
vector: vec![0.1; 128],
metadata: None,
})
.collect();
let ids = db.insert_batch(entries)?;
assert_eq!(ids.len(), 1000);
```
### search
```rust
pub fn search(&self, query: &SearchQuery) -> Result<Vec<SearchResult>>
```
Search for similar vectors.
**Parameters**:
- `query`: Search query with vector, k, filters
**Returns**: `Result<Vec<SearchResult>, RuvectorError>` - Top-k results
**Time Complexity**: O(log n) with HNSW
**Example**:
```rust
let query = SearchQuery {
vector: vec![0.1; 128],
k: 10,
filter: None,
include_vectors: false,
};
let results = db.search(&query)?;
for result in results {
println!("ID: {}, Distance: {}", result.id, result.distance);
}
```
### delete
```rust
pub fn delete(&self, id: &VectorId) -> Result<()>
```
Delete a vector by ID.
**Parameters**:
- `id`: Vector ID to delete
**Returns**: `Result<(), RuvectorError>`
**Example**:
```rust
db.delete(&"vec_001".to_string())?;
```
### update
```rust
pub fn update(&self, id: &VectorId, entry: VectorEntry) -> Result<()>
```
Update an existing vector.
**Parameters**:
- `id`: Vector ID to update
- `entry`: New vector data
**Returns**: `Result<(), RuvectorError>`
**Example**:
```rust
let new_entry = VectorEntry {
id: Some("vec_001".to_string()),
vector: vec![0.2; 128],
metadata: Some(HashMap::from([
("updated".into(), json!(true))
])),
};
db.update(&"vec_001".to_string(), new_entry)?;
```
### count
```rust
pub fn count(&self) -> usize
```
Get total number of vectors.
**Returns**: Number of vectors in database
**Example**:
```rust
let total = db.count();
println!("Total vectors: {}", total);
```
## AgenticDB
Extended API with specialized agent memory tables.
### Creation
```rust
use ruvector_core::{AgenticDB, DbOptions};
pub fn new(options: DbOptions) -> Result<Self>
```
Create AgenticDB instance.
**Example**:
```rust
let db = AgenticDB::new(DbOptions::default())?;
```
### Reflexion Memory
#### store_episode
```rust
pub fn store_episode(
&self,
task: String,
actions: Vec<String>,
observations: Vec<String>,
critique: String,
) -> Result<String>
```
Store a self-critique episode.
**Parameters**:
- `task`: Task description
- `actions`: Actions taken
- `observations`: Observations made
- `critique`: Self-generated critique
**Returns**: Episode ID
**Example**:
```rust
let id = db.store_episode(
"Solve coding problem".into(),
vec!["Read problem".into(), "Write solution".into()],
vec!["Tests failed".into()],
"Should test edge cases first".into(),
)?;
```
#### retrieve_episodes
```rust
pub fn retrieve_episodes(
&self,
query_embedding: Vec<f32>,
k: usize,
) -> Result<Vec<ReflexionEpisode>>
```
Retrieve similar past episodes.
**Parameters**:
- `query_embedding`: Embedded critique or task
- `k`: Number of episodes to retrieve
**Returns**: Similar episodes
**Example**:
```rust
let episodes = db.retrieve_episodes(critique_embedding, 5)?;
for ep in episodes {
println!("Task: {}", ep.task);
println!("Critique: {}", ep.critique);
}
```
### Skill Library
#### create_skill
```rust
pub fn create_skill(
&self,
name: String,
description: String,
parameters: HashMap<String, String>,
examples: Vec<String>,
) -> Result<String>
```
Create a reusable skill.
**Parameters**:
- `name`: Skill name
- `description`: What the skill does
- `parameters`: Required parameters
- `examples`: Usage examples
**Returns**: Skill ID
**Example**:
```rust
let id = db.create_skill(
"authenticate_user".into(),
"Authenticate user with JWT token".into(),
HashMap::from([
("token".into(), "string".into()),
("user_id".into(), "string".into()),
]),
vec!["authenticate_user(token, user_id)".into()],
)?;
```
#### search_skills
```rust
pub fn search_skills(
&self,
query_embedding: Vec<f32>,
k: usize,
) -> Result<Vec<Skill>>
```
Search for relevant skills.
**Parameters**:
- `query_embedding`: Embedded task description
- `k`: Number of skills to retrieve
**Returns**: Relevant skills
**Example**:
```rust
let skills = db.search_skills(task_embedding, 3)?;
for skill in skills {
println!("Skill: {} - {}", skill.name, skill.description);
println!("Success rate: {:.1}%", skill.success_rate * 100.0);
}
```
### Causal Memory
#### add_causal_edge
```rust
pub fn add_causal_edge(
&self,
causes: Vec<String>,
effects: Vec<String>,
confidence: f64,
context: String,
) -> Result<String>
```
Add cause-effect relationship.
**Parameters**:
- `causes`: Cause actions/states (hypergraph: multiple causes)
- `effects`: Effect actions/states (hypergraph: multiple effects)
- `confidence`: Confidence score (0-1)
- `context`: Context description
**Returns**: Edge ID
**Example**:
```rust
let id = db.add_causal_edge(
vec!["authenticate".into(), "validate_token".into()],
vec!["access_granted".into()],
0.95,
"User authentication flow".into(),
)?;
```
#### query_causal
```rust
pub fn query_causal(
&self,
query_embedding: Vec<f32>,
k: usize,
) -> Result<Vec<CausalQueryResult>>
```
Query causal relationships.
**Parameters**:
- `query_embedding`: Embedded context
- `k`: Number of results
**Returns**: Causal edges with utility scores
**Example**:
```rust
let results = db.query_causal(context_embedding, 10)?;
for result in results {
println!("Causes: {:?} → Effects: {:?}", result.edge.causes, result.edge.effects);
println!("Utility: {:.4}", result.utility_score);
}
```
### Learning Sessions
#### create_learning_session
```rust
pub fn create_learning_session(
&self,
algorithm: String,
state_dim: usize,
action_dim: usize,
) -> Result<String>
```
Create RL training session.
**Parameters**:
- `algorithm`: RL algorithm (Q-Learning, DQN, PPO, etc.)
- `state_dim`: State dimensionality
- `action_dim`: Action dimensionality
**Returns**: Session ID
**Example**:
```rust
let session_id = db.create_learning_session(
"PPO".into(),
64, // state_dim
4, // action_dim
)?;
```
#### add_experience
```rust
pub fn add_experience(
&self,
session_id: &str,
state: Vec<f32>,
action: Vec<f32>,
reward: f64,
next_state: Vec<f32>,
done: bool,
) -> Result<()>
```
Add experience to session.
**Parameters**:
- `session_id`: Session ID
- `state`: Current state
- `action`: Action taken
- `reward`: Reward received
- `next_state`: Next state
- `done`: Episode finished?
**Returns**: `Result<(), RuvectorError>`
**Example**:
```rust
db.add_experience(
&session_id,
state,
action,
1.0, // reward
next_state,
false, // not done
)?;
```
#### predict_with_confidence
```rust
pub fn predict_with_confidence(
&self,
session_id: &str,
state: Vec<f32>,
) -> Result<Prediction>
```
Predict action with confidence intervals.
**Parameters**:
- `session_id`: Session ID
- `state`: Current state
**Returns**: Prediction with confidence bounds
**Example**:
```rust
let prediction = db.predict_with_confidence(&session_id, state)?;
println!("Action: {:?}", prediction.action);
println!("Confidence: [{:.2}, {:.2}]",
prediction.confidence_lower,
prediction.confidence_upper
);
```
## Types
### VectorEntry
```rust
pub struct VectorEntry {
pub id: Option<String>,
pub vector: Vec<f32>,
pub metadata: Option<HashMap<String, serde_json::Value>>,
}
```
Entry for inserting vectors.
### SearchQuery
```rust
pub struct SearchQuery {
pub vector: Vec<f32>,
pub k: usize,
pub filter: Option<serde_json::Value>,
pub include_vectors: bool,
}
```
Query for searching vectors.
### SearchResult
```rust
pub struct SearchResult {
pub id: String,
pub distance: f32,
pub vector: Option<Vec<f32>>,
pub metadata: Option<HashMap<String, serde_json::Value>>,
}
```
Search result with ID, distance, and optional data.
### DistanceMetric
```rust
pub enum DistanceMetric {
Euclidean, // L2 distance
Cosine, // 1 - cosine_similarity
DotProduct, // -dot_product (for maximization)
Manhattan, // L1 distance
}
```
Distance metrics for similarity calculation.
## Configuration
### DbOptions
```rust
pub struct DbOptions {
pub dimensions: usize,
pub storage_path: String,
pub distance_metric: DistanceMetric,
pub hnsw: HnswConfig,
pub quantization: QuantizationConfig,
pub mmap_vectors: bool,
}
```
Database configuration options.
### HnswConfig
```rust
pub struct HnswConfig {
pub m: usize, // Connections per node (16-64)
pub ef_construction: usize, // Build quality (100-400)
pub ef_search: usize, // Search quality (50-500)
pub max_elements: usize, // Maximum vectors
}
```
HNSW index configuration.
### QuantizationConfig
```rust
pub enum QuantizationConfig {
None,
Scalar, // 4x compression
Product { subspaces: usize, k: usize }, // 8-16x compression
Binary, // 32x compression
}
```
Quantization configuration.
## Advanced Features
### HybridSearch
Combine vector similarity with keyword search.
```rust
use ruvector_core::{HybridSearch, HybridConfig};
let config = HybridConfig {
vector_weight: 0.7,
bm25_weight: 0.3,
k1: 1.5,
b: 0.75,
};
let hybrid = HybridSearch::new(&db, config)?;
let results = hybrid.search(&query_vector, &["keywords"], 10)?;
```
### FilteredSearch
Apply metadata filters.
```rust
use ruvector_core::{FilteredSearch, FilterExpression, FilterStrategy};
let filtered = FilteredSearch::new(&db, FilterStrategy::PreFilter);
let filter = FilterExpression::And(vec![
FilterExpression::Eq("category".into(), json!("tech")),
FilterExpression::Gte("score".into(), json!(0.8)),
]);
let results = filtered.search(&query, 10, Some(filter))?;
```
### MMRSearch
Maximal Marginal Relevance for diversity.
```rust
use ruvector_core::{MMRSearch, MMRConfig};
let config = MMRConfig {
lambda: 0.5, // Balance relevance vs diversity
diversity_weight: 0.3,
};
let mmr = MMRSearch::new(&db, config)?;
let results = mmr.search(&query, 20)?;
```
### ConformalPredictor
Uncertainty quantification.
```rust
use ruvector_core::{ConformalPredictor, ConformalConfig};
let mut predictor = ConformalPredictor::new(ConformalConfig {
alpha: 0.1, // 90% confidence
calibration_size: 1000,
});
predictor.calibrate(&calibration_data)?;
let prediction = predictor.predict(&query, &db)?;
```
## Error Handling
### RuvectorError
```rust
pub enum RuvectorError {
DimensionMismatch { expected: usize, got: usize },
StorageError(String),
IndexError(String),
SerializationError(String),
IoError(std::io::Error),
// ... more variants
}
```
All operations return `Result<T, RuvectorError>`.
**Example**:
```rust
match db.insert(entry) {
Ok(id) => println!("Inserted: {}", id),
Err(RuvectorError::DimensionMismatch { expected, got }) => {
eprintln!("Wrong dimensions: expected {}, got {}", expected, got);
}
Err(e) => eprintln!("Error: {}", e),
}
```
## Complete API Documentation
For complete auto-generated API docs:
```bash
cargo doc --no-deps --open
```
Or visit: [https://docs.rs/ruvector-core](https://docs.rs/ruvector-core)