ruvector-data-framework 0.3.0

Core discovery framework for RuVector dataset integrations - find hidden patterns in massive datasets using vector memory, graph structures, and dynamic min-cut algorithms
Documentation
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
# AI/ML API Clients for RuVector Data Discovery Framework

This module provides comprehensive integration with AI/ML platforms for discovering models, datasets, and research papers.

## Available Clients

### 1. HuggingFaceClient

**Purpose**: Access HuggingFace model hub and inference API

**Features**:
- Search models by query and task type
- Get model details and metadata
- List and search datasets
- Run model inference
- Convert models/datasets to SemanticVectors

**API Details**:
- Base URL: `https://huggingface.co/api`
- Rate limit: 30 requests/minute (free tier)
- API key: Optional via `HUGGINGFACE_API_KEY` environment variable
- Mock fallback: Yes (when no API key provided)

**Example**:
```rust
use ruvector_data_framework::HuggingFaceClient;

let client = HuggingFaceClient::new();

// Search for BERT models
let models = client.search_models("bert", Some("fill-mask")).await?;

// Get specific model
let model = client.get_model("bert-base-uncased").await?;

// Convert to vector for discovery
if let Some(m) = model {
    let vector = client.model_to_vector(&m);
    println!("Model: {}, Embedding dim: {}", vector.id, vector.embedding.len());
}

// List datasets
let datasets = client.list_datasets(Some("nlp")).await?;

// Run inference (requires API key)
let result = client.inference(
    "bert-base-uncased",
    serde_json::json!({"inputs": "Hello [MASK]!"})
).await?;
```

### 2. OllamaClient

**Purpose**: Local LLM inference with Ollama

**Features**:
- List locally available models
- Generate text completions
- Chat with message history
- Generate embeddings
- Pull models from Ollama library
- Automatic mock fallback when Ollama not running

**API Details**:
- Base URL: `http://localhost:11434/api` (default)
- Rate limit: None (local service)
- API key: Not required
- Mock fallback: Yes (when Ollama service unavailable)

**Example**:
```rust
use ruvector_data_framework::{OllamaClient, OllamaChatMessage};

let mut client = OllamaClient::new();

// Check if Ollama is running
if client.is_available().await {
    // List available models
    let models = client.list_models().await?;

    // Generate completion
    let response = client.generate(
        "llama2",
        "Explain quantum computing in simple terms"
    ).await?;

    // Chat with message history
    let messages = vec![
        OllamaChatMessage {
            role: "user".to_string(),
            content: "What is machine learning?".to_string(),
        }
    ];
    let chat_response = client.chat("llama2", messages).await?;

    // Generate embeddings
    let embedding = client.embeddings("llama2", "sample text").await?;
    println!("Embedding dimension: {}", embedding.len());
}
```

**Setup**:
```bash
# Install Ollama
curl https://ollama.ai/install.sh | sh

# Start Ollama service
ollama serve

# Pull a model
ollama pull llama2
```

### 3. ReplicateClient

**Purpose**: Access Replicate's cloud ML model platform

**Features**:
- Get model information
- Create predictions (run models)
- Check prediction status
- List model collections
- Convert models to SemanticVectors

**API Details**:
- Base URL: `https://api.replicate.com/v1`
- Rate limit: Varies by plan
- API key: Required via `REPLICATE_API_TOKEN` environment variable
- Mock fallback: Yes (when no API token provided)

**Example**:
```rust
use ruvector_data_framework::ReplicateClient;

let client = ReplicateClient::new();

// Get model info
let model = client.get_model("stability-ai", "stable-diffusion").await?;

if let Some(m) = model {
    println!("Model: {}/{}", m.owner, m.name);

    // Convert to vector
    let vector = client.model_to_vector(&m);

    // Create a prediction
    let prediction = client.create_prediction(
        "stability-ai/stable-diffusion",
        serde_json::json!({
            "prompt": "a beautiful sunset over mountains"
        })
    ).await?;

    // Check prediction status
    let status = client.get_prediction(&prediction.id).await?;
    println!("Status: {}", status.status);
}

// List collections
let collections = client.list_collections().await?;
```

**Environment Setup**:
```bash
export REPLICATE_API_TOKEN="your_token_here"
```

### 4. TogetherAiClient

**Purpose**: Access Together AI's open source model hosting

**Features**:
- List available models
- Chat completions
- Generate embeddings
- Support for various open source LLMs
- Convert models to SemanticVectors

**API Details**:
- Base URL: `https://api.together.xyz/v1`
- Rate limit: Varies by plan
- API key: Required via `TOGETHER_API_KEY` environment variable
- Mock fallback: Yes (when no API key provided)

**Example**:
```rust
use ruvector_data_framework::{TogetherAiClient, TogetherMessage};

let client = TogetherAiClient::new();

// List models
let models = client.list_models().await?;

for model in models.iter().take(5) {
    println!("Model: {}", model.display_name.as_deref().unwrap_or(&model.id));
    println!("Context: {} tokens", model.context_length.unwrap_or(0));
}

// Chat completion
let messages = vec![
    TogetherMessage {
        role: "user".to_string(),
        content: "Explain neural networks".to_string(),
    }
];

let response = client.chat_completion(
    "togethercomputer/llama-2-7b",
    messages
).await?;

println!("Response: {}", response);

// Generate embeddings
let embedding = client.embeddings(
    "togethercomputer/m2-bert-80M-8k-retrieval",
    "sample text for embedding"
).await?;
```

**Environment Setup**:
```bash
export TOGETHER_API_KEY="your_key_here"
```

### 5. PapersWithCodeClient

**Purpose**: Access Papers With Code research database

**Features**:
- Search ML research papers
- Get paper details
- List datasets
- Get state-of-the-art (SOTA) benchmarks
- Search methods/techniques
- Convert papers/datasets to SemanticVectors

**API Details**:
- Base URL: `https://paperswithcode.com/api/v1`
- Rate limit: 60 requests/minute
- API key: Not required
- Mock fallback: Partial (for some endpoints)

**Example**:
```rust
use ruvector_data_framework::PapersWithCodeClient;

let client = PapersWithCodeClient::new();

// Search papers
let papers = client.search_papers("transformer").await?;

for paper in papers.iter().take(5) {
    println!("Title: {}", paper.title);
    if let Some(url) = &paper.url_abs {
        println!("URL: {}", url);
    }

    // Convert to vector
    let vector = client.paper_to_vector(paper);
    println!("Vector ID: {}", vector.id);
}

// Get specific paper
let paper = client.get_paper("attention-is-all-you-need").await?;

// List datasets
let datasets = client.list_datasets().await?;

for dataset in datasets.iter().take(5) {
    println!("Dataset: {}", dataset.name);

    // Convert to vector
    let vector = client.dataset_to_vector(dataset);
}

// Get SOTA results for a task
let sota_results = client.get_sota("image-classification").await?;

for result in sota_results {
    println!("Task: {}, Dataset: {}, Metric: {}, Value: {}",
        result.task, result.dataset, result.metric, result.value);
}
```

## Integration with RuVector Discovery

All clients provide conversion methods to transform their data into `SemanticVector` format for use with RuVector's discovery engine:

```rust
use ruvector_data_framework::{
    HuggingFaceClient, PapersWithCodeClient, Domain,
    NativeDiscoveryEngine, NativeEngineConfig
};

// Create clients
let hf_client = HuggingFaceClient::new();
let pwc_client = PapersWithCodeClient::new();

// Collect vectors from different sources
let mut vectors = Vec::new();

// Add HuggingFace models
let models = hf_client.search_models("transformer", None).await?;
for model in models {
    vectors.push(hf_client.model_to_vector(&model));
}

// Add research papers
let papers = pwc_client.search_papers("attention mechanism").await?;
for paper in papers {
    vectors.push(pwc_client.paper_to_vector(&paper));
}

// Run discovery analysis
let config = NativeEngineConfig::default();
let mut engine = NativeDiscoveryEngine::new(config);

for vector in vectors {
    engine.ingest_vector(vector)?;
}

// Detect patterns
let patterns = engine.detect_patterns()?;
println!("Found {} discovery patterns", patterns.len());
```

## Environment Variables

| Variable | Client | Required | Description |
|----------|--------|----------|-------------|
| `HUGGINGFACE_API_KEY` | HuggingFaceClient | No | Optional for public models, required for private/inference |
| `REPLICATE_API_TOKEN` | ReplicateClient | Yes* | Required for API access (*falls back to mock) |
| `TOGETHER_API_KEY` | TogetherAiClient | Yes* | Required for API access (*falls back to mock) |
| - | OllamaClient | No | Uses local Ollama service |
| - | PapersWithCodeClient | No | Public API, no key needed |

## Mock Data Fallback

All clients (except PapersWithCodeClient) provide automatic mock data when:
- API keys are not provided
- Services are unavailable
- Rate limits are exceeded (after retries)

This allows for:
- Development without API keys
- Testing without external dependencies
- Graceful degradation in production

## Rate Limiting

All clients implement automatic rate limiting:
- Configurable delays between requests
- Exponential backoff on failures
- Automatic retry logic (up to 3 retries)
- Respects API rate limits

## Error Handling

All clients use the framework's `Result<T>` type with `FrameworkError`:

```rust
use ruvector_data_framework::{HuggingFaceClient, FrameworkError};

match hf_client.search_models("bert", None).await {
    Ok(models) => {
        println!("Found {} models", models.len());
    }
    Err(FrameworkError::Network(e)) => {
        eprintln!("Network error: {}", e);
    }
    Err(e) => {
        eprintln!("Other error: {}", e);
    }
}
```

## Testing

The module includes comprehensive unit tests:

```bash
# Run all ML client tests
cargo test ml_clients

# Run specific client tests
cargo test ml_clients::tests::test_huggingface
cargo test ml_clients::tests::test_ollama
cargo test ml_clients::tests::test_replicate
cargo test ml_clients::tests::test_together
cargo test ml_clients::tests::test_paperswithcode

# Run integration tests (requires API keys)
cargo test ml_clients::tests --ignored
```

## Example Application

See `examples/ml_clients_demo.rs` for a complete demonstration:

```bash
# Run demo (uses mock data)
cargo run --example ml_clients_demo

# Run with API keys
export HUGGINGFACE_API_KEY="your_key"
export REPLICATE_API_TOKEN="your_token"
export TOGETHER_API_KEY="your_key"
cargo run --example ml_clients_demo
```

## Performance Considerations

- **HuggingFace**: 30 req/min free tier → 2 second delays
- **Ollama**: Local, minimal delays (100ms)
- **Replicate**: Pay-per-use, 1 second delays
- **Together AI**: Pay-per-use, 1 second delays
- **Papers With Code**: 60 req/min → 1 second delays

For bulk operations, use batch processing with appropriate delays.

## Architecture

All clients follow a consistent pattern:

1. **Client struct**: Holds HTTP client, embedder, base URL, credentials
2. **API response structs**: Deserialize API responses
3. **Public methods**: High-level API operations
4. **Conversion methods**: Transform to `SemanticVector`
5. **Mock methods**: Provide fallback data
6. **Retry logic**: Handle transient failures
7. **Tests**: Comprehensive unit testing

## Dependencies

- `reqwest`: HTTP client
- `tokio`: Async runtime
- `serde`: Serialization/deserialization
- `chrono`: Timestamp handling
- `urlencoding`: URL parameter encoding

## Contributing

When adding new ML API clients:

1. Follow the established pattern (see existing clients)
2. Implement rate limiting
3. Provide mock fallback data
4. Add comprehensive tests (at least 15 tests)
5. Update this documentation
6. Add example usage

## License

Same as RuVector framework license.