daimon 0.17.0

A Rust-native AI agent framework
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
# RAG (Retrieval-Augmented Generation)

Daimon provides a complete RAG pipeline for embedding-backed document retrieval. This guide covers the three-layer architecture, embedding models, vector store implementations, and how to build end-to-end RAG pipelines with agent integration.

---

## RAG Architecture in Daimon

The RAG stack is organized in three layers:

| Layer | Trait / Type | Responsibility |
|-------|--------------|-----------------|
| **VectorStore** (low-level) | `VectorStore` | Pre-computed embeddings only. Upsert, query, delete, count. No embedding logic. |
| **KnowledgeBase** (mid-level) | `KnowledgeBase` | Embedding model + vector store. Auto-embeds on ingest and search. |
| **Retriever** (high-level) | `Retriever` | Unified `retrieve(query, top_k)` interface. Query-agnostic. |

`SimpleKnowledgeBase` implements both `KnowledgeBase` and `Retriever`, bridging all three layers. You can use it as a drop-in retriever or as a full knowledge base with ingest and search.

```
┌─────────────────────────────────────────────────────────────────┐
│ Application Layer (Agent, RetrieverTool)                         │
├─────────────────────────────────────────────────────────────────┤
│ Retriever Layer — retrieve(query, top_k) → Vec<Document>        │
│   SimpleKnowledgeBase, QdrantRetriever, custom impls            │
├─────────────────────────────────────────────────────────────────┤
│ KnowledgeBase Layer — ingest + search + remove + count           │
│   SimpleKnowledgeBase (embedding + embedding on query)          │
├─────────────────────────────────────────────────────────────────┤
│ VectorStore Layer — upsert, query, delete, count (embeddings)   │
│   InMemoryVectorStoreBackend, PgVectorStore, OpenSearchVectorStore│
└─────────────────────────────────────────────────────────────────┘
```

---

## Embedding Models

The `EmbeddingModel` trait defines the embedding interface:

```rust
pub trait EmbeddingModel: Send + Sync {
    fn embed(&self, texts: &[&str]) -> impl Future<Output = Result<Vec<Vec<f32>>>> + Send;
    fn dimensions(&self) -> usize;
}
```

Implementations are available from various providers. Use `Arc<dyn ErasedEmbeddingModel>` when composing with `SimpleKnowledgeBase` or `QdrantRetriever`.

### OpenAI Embeddings

```rust
use daimon::model::openai_embed::OpenAiEmbedding;
use std::sync::Arc;

// text-embedding-3-small (1536 dims) or text-embedding-3-large (3072 dims)
let embed = Arc::new(OpenAiEmbedding::new("text-embedding-3-small"));

// Optional: override API key, base URL, or dimensions
let embed = Arc::new(
    OpenAiEmbedding::new("text-embedding-3-small")
        .with_api_key("sk-...")
        .with_base_url("https://api.openai.com/v1")
        .with_dimensions(1536)
);
```

Requires `OPENAI_API_KEY` in the environment unless set via `with_api_key`. Feature: `openai`.

### Ollama Embeddings

```rust
use daimon::model::ollama_embed::OllamaEmbedding;
use std::sync::Arc;

// nomic-embed-text, mxbai-embed-large, etc.
let embed = Arc::new(OllamaEmbedding::new("nomic-embed-text"));

// Optional: override host or dimensions
let embed = Arc::new(
    OllamaEmbedding::new("nomic-embed-text")
        .with_base_url("http://localhost:11434")
        .with_dimensions(768)
);
```

Uses `OLLAMA_HOST` (default `http://localhost:11434`) if not overridden. Feature: `ollama`.

### Amazon Bedrock Embeddings

```rust
use daimon::model::bedrock::BedrockEmbedding;
use std::sync::Arc;

// Titan Embeddings (amazon.titan-embed-text-v2:0) or Cohere
let embed = Arc::new(
    BedrockEmbedding::new("amazon.titan-embed-text-v2:0")
        .with_region("us-east-1")
        .with_dimensions(1024)
        .with_normalize(true)
);
```

Uses AWS SDK default credential chain. Feature: `bedrock`.

### Google Gemini Embeddings

```rust
use daimon::model::gemini::GeminiEmbedding;
use std::sync::Arc;

let embed = Arc::new(
    GeminiEmbedding::new("text-embedding-004")
        .with_api_key("...")  // or GOOGLE_API_KEY env
        .with_dimensions(768)
);
```

Feature: `gemini`.

### Azure OpenAI Embeddings

```rust
use daimon::model::azure::AzureOpenAiEmbedding;
use std::sync::Arc;

let embed = Arc::new(
    AzureOpenAiEmbedding::new(
        "https://my-resource.openai.azure.com",
        "text-embedding-3-small"
    )
    .with_api_key("...")  // or AZURE_OPENAI_API_KEY env
    .with_api_version("2024-10-21")
    .with_dimensions(1536)
);
```

Feature: `azure`.

---

## Vector Store Implementations

### In-Memory (Built-in)

`InMemoryVectorStoreBackend` uses brute-force cosine similarity. Ideal for development and testing.

```rust
use daimon::retriever::InMemoryVectorStoreBackend;

let store = InMemoryVectorStoreBackend::new();
```

No feature flag required. Data is lost when the process exits.

### Qdrant (feature = "qdrant")

`QdrantRetriever` implements `Retriever` directly (not `VectorStore`). It embeds queries and searches a Qdrant collection. You must ingest documents into Qdrant separately (e.g. via Qdrant SDK or another pipeline).

```rust
use daimon::retriever::QdrantRetriever;
use std::sync::Arc;

let retriever = QdrantRetriever::new(
    "http://localhost:6334",
    "my_collection",
    Arc::clone(&embedding_model),
)
.await?;

// Optional: custom payload field for document content
let retriever = retriever.with_content_field("text");
```

Requires a running Qdrant instance. Feature: `qdrant`.

### pgvector (feature = "pgvector")

PostgreSQL with the `pgvector` extension. Implements `VectorStore`. Use `PgVectorStoreBuilder` to configure and build.

```rust
use daimon_plugin_pgvector::{PgVectorStoreBuilder, DistanceMetric};
// or: use daimon::prelude::*;  (includes PgVectorStoreBuilder when pgvector enabled)

let store = PgVectorStoreBuilder::new("postgresql://user:pass@localhost/db", 1536)
    .table("my_docs")
    .distance_metric(DistanceMetric::Cosine)
    .hnsw_m(16)
    .hnsw_ef_construction(64)
    .pool_size(16)
    .auto_migrate(true)
    .build()
    .await?;
```

**Builder options:**

| Method | Default | Description |
|--------|---------|-------------|
| `table(name)` | `"daimon_vectors"` | Table name |
| `distance_metric(metric)` | `Cosine` | `Cosine`, `L2`, or `InnerProduct` |
| `hnsw_m(m)` | 16 | HNSW max connections per layer |
| `hnsw_ef_construction(ef)` | 64 | HNSW build-time search width |
| `pool_size(n)` | 16 | Connection pool size |
| `auto_migrate(enabled)` | `true` | Create extension and table on first use |

Disable `auto_migrate` and use `daimon_plugin_pgvector::migrations` for manual schema setup.

### OpenSearch (feature = "opensearch")

OpenSearch k-NN plugin. Implements `VectorStore`. Use `OpenSearchVectorStoreBuilder` to configure and build.

```rust
use daimon_plugin_opensearch::{OpenSearchVectorStoreBuilder, SpaceType, Engine};
// or: use daimon::prelude::*;

let store = OpenSearchVectorStoreBuilder::new("http://localhost:9200", 1536)
    .index("my_docs")
    .space_type(SpaceType::CosineSimilarity)
    .engine(Engine::Lucene)
    .hnsw_m(16)
    .hnsw_ef_construction(256)
    .auto_create_index(true)
    .build()
    .await?;
```

**Builder options:**

| Method | Default | Description |
|--------|---------|-------------|
| `index(name)` | `"daimon_vectors"` | Index name |
| `space_type(t)` | `CosineSimilarity` | `CosineSimilarity`, `L2`, or `InnerProduct` |
| `engine(e)` | `Lucene` | `Lucene`, `Nmslib`, or `Faiss` |
| `hnsw_m(m)` | engine default | HNSW max connections per layer |
| `hnsw_ef_construction(ef)` | engine default | HNSW build-time search width |
| `auto_create_index(enabled)` | `true` | Create index on first use |

**AWS OpenSearch Service:** Use `build_with_client()` with a pre-configured OpenSearch client (e.g. with SigV4 auth):

```toml
# Cargo.toml
daimon-plugin-opensearch = { version = "0.16", features = ["aws-auth"] }
```

```rust
use opensearch::OpenSearch;
use opensearch::http::transport::Transport;

let transport = Transport::single_node("https://my-domain.us-east-1.es.amazonaws.com")
    .build()?;  // Configure AWS auth per opensearch-rs docs
let client = OpenSearch::new(transport);

let store = OpenSearchVectorStoreBuilder::new("https://my-domain.us-east-1.es.amazonaws.com", 1536)
    .index("my_docs")
    .build_with_client(client)
    .await?;
```

---

## Building a RAG Pipeline

Full example: create embedding model, vector store, compose into `SimpleKnowledgeBase`, ingest documents, and search.

```rust
use daimon::prelude::*;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    // 1. Create embedding model
    let embed = Arc::new(
        daimon::model::openai_embed::OpenAiEmbedding::new("text-embedding-3-small")
    );

    // 2. Create vector store

    // Option A: In-memory (dev/testing)
    let store = InMemoryVectorStoreBackend::new();

    // Option B: pgvector (production)
    // let store = PgVectorStoreBuilder::new("postgresql://localhost/db", 1536)
    //     .table("docs")
    //     .build()
    //     .await?;

    // 3. Compose into SimpleKnowledgeBase
    let kb = SimpleKnowledgeBase::new(embed, store);

    // 4. Ingest documents
    let docs = vec![
        Document::new("Rust is a systems programming language focused on safety and performance.")
            .with_metadata("source", json!("rust-lang.org")),
        Document::new("Daimon is a Rust-native AI agent framework.")
            .with_metadata("source", json!("github.com/Lexmata/daimon")),
        Document::new("Embeddings are dense vector representations of text.")
            .with_metadata("topic", json!("ml")),
    ];

    let ids = kb.ingest(docs).await?;
    println!("Ingested {} documents", ids.len());

    // 5. Search documents
    let results = kb.search("What is Daimon?", 3).await?;
    for (i, doc) in results.iter().enumerate() {
        println!("--- Result {} (score: {:?}) ---", i + 1, doc.score);
        println!("{}", doc.content);
    }

    // 6. Use as agent tool via RetrieverTool
    let tool = RetrieverTool::new(
        kb,
        "search_docs",
        "Search the knowledge base for relevant documents. Use when you need to look up information.",
    )
    .with_default_top_k(5);

    let agent = Agent::builder()
        .model(/* ... */)
        .tool(tool)
        .build()?;

    let response = agent.prompt("What can you tell me about Daimon?").await?;
    println!("{}", response.text());

    Ok(())
}
```

---

## RetrieverTool

`RetrieverTool` wraps any `Retriever` as a `Tool`. The agent can search the knowledge base on demand.

```rust
use daimon::retriever::RetrieverTool;

let tool = RetrieverTool::new(
    retriever,
    "search_knowledge_base",
    "Search the knowledge base for relevant information. Use when you need to look up facts.",
);

// Optional: set default top_k when the agent omits it
let tool = tool.with_default_top_k(8);
```

**Parameters (JSON Schema):**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes || The search query |
| `top_k` | integer | No | 5 (or `with_default_top_k`) | Maximum number of results |

The tool returns formatted text: each document with its score, metadata, and content.

---

## Document Type

`Document` represents a retrieved document fragment with optional metadata and relevance score.

```rust
use daimon::retriever::Document;
use serde_json::json;

// Minimal: content only
let doc = Document::new("Hello world");

// With metadata
let doc = Document::new("Rust is fast.")
    .with_metadata("source", json!("rust-lang.org"))
    .with_metadata("page", json!(42));

// With custom ID (used by SimpleKnowledgeBase.ingest if present)
let doc = Document::new("Content")
    .with_metadata("id", json!("custom-doc-id"));

// Score is set by retrieval backends (not typically set by user)
let doc = doc.with_score(0.92);
```

**Fields:**

| Field | Type | Description |
|-------|------|-------------|
| `content` | `String` | The text content |
| `metadata` | `HashMap<String, serde_json::Value>` | Arbitrary key-value metadata (source, page, etc.) |
| `score` | `Option<f64>` | Relevance score from retrieval. `None` if backend does not provide scores |

`ScoredDocument` is an internal type: `{ document: Document, score: f64 }`. Vector stores return `Vec<ScoredDocument>`; `SimpleKnowledgeBase` converts to `Document` with `with_score` applied.

---

## Choosing a Vector Store

| Use Case | Recommendation | Notes |
|----------|----------------|-------|
| **Development / testing** | `InMemoryVectorStoreBackend` | No setup, data lost on restart |
| **PostgreSQL already in stack** | pgvector | Reuse existing DB, connection pooling |
| **Search infrastructure** | OpenSearch | k-NN + full-text, good for hybrid search |
| **Dedicated vector DB** | Qdrant | High-performance, built for vectors |
| **Custom backend** | Implement `VectorStore` | See `daimon-core::VectorStore` trait |

**Implementing a custom vector store:**

```rust
use daimon_core::{Document, ScoredDocument, VectorStore};

struct MyVectorStore { /* ... */ }

impl VectorStore for MyVectorStore {
    async fn upsert(&self, id: &str, embedding: Vec<f32>, document: Document) -> Result<()> {
        // Store in your backend
        Ok(())
    }

    async fn query(&self, embedding: Vec<f32>, top_k: usize) -> Result<Vec<ScoredDocument>> {
        // Search and return scored documents
        Ok(vec![])
    }

    async fn delete(&self, id: &str) -> Result<bool> {
        Ok(true)
    }

    async fn count(&self) -> Result<usize> {
        Ok(0)
    }
}
```

Then compose with `SimpleKnowledgeBase::new(embedding_model, my_store)`.

---

## Performance Tips

### Batch ingest

`SimpleKnowledgeBase::ingest` accepts `Vec<Document>` and embeds them in a single batch. Prefer batching over multiple single-document calls:

```rust
// Good: one batch
let ids = kb.ingest(docs).await?;

// Avoid: many small batches
for doc in docs {
    kb.ingest(vec![doc]).await?;
}
```

### HNSW parameters

- **`m`** (max connections per layer): Higher = better recall, slower writes. Typical: 16–32.
- **`ef_construction`**: Build-time search width. Higher = better index quality, slower build. Typical: 64–256.

### Connection pooling

- **pgvector:** Uses `deadpool`; tune `pool_size` to match concurrency.
- **OpenSearch:** Uses `opensearch` crate's internal transport; configure via `build_with_client` if needed.

### Embedding dimensions

- Smaller dimensions (e.g. 256) = faster search, lower quality.
- Larger dimensions (e.g. 3072) = better quality, slower and more storage.
- Match model dimensions to your vector store configuration.

### Qdrant vs VectorStore + KnowledgeBase

`QdrantRetriever` implements `Retriever` only. You must populate the Qdrant collection separately (e.g. with the same embedding model). For a unified ingest pipeline, use `SimpleKnowledgeBase` with a `VectorStore` backend (pgvector, OpenSearch, or in-memory).

---

## Document Chunking and Ingestion

Daimon does not include built-in chunking. For long documents, split text into chunks before passing to `SimpleKnowledgeBase::ingest`:

```rust
fn chunk_text(text: &str, chunk_size: usize, overlap: usize) -> Vec<String> {
    let chars: Vec<char> = text.chars().collect();
    let mut chunks = Vec::new();
    let mut start = 0;

    while start < chars.len() {
        let end = (start + chunk_size).min(chars.len());
        chunks.push(chars[start..end].iter().collect());
        start = end.saturating_sub(overlap);
    }

    chunks
}

// Usage
let long_doc = "...";  // e.g. from a file or API
let chunks = chunk_text(long_doc, 512, 50);
let docs: Vec<Document> = chunks
    .into_iter()
    .enumerate()
    .map(|(i, content)| {
        Document::new(content)
            .with_metadata("source", json!("manual.pdf"))
            .with_metadata("chunk", json!(i))
    })
    .collect();

let ids = kb.ingest(docs).await?;
```

**Chunking tips:**

- **Chunk size:** 256–1024 tokens (or ~100–400 words) is typical. Match to your embedding model's context window.
- **Overlap:** 10–20% overlap reduces boundary effects and improves context continuity.
- **Metadata:** Store `source`, `page`, `chunk` index so the agent can cite sources.

---

## Feature Flags

| Feature | Enables |
|---------|---------|
| `openai` | `OpenAiEmbedding` |
| `ollama` | `OllamaEmbedding` |
| `bedrock` | `BedrockEmbedding` |
| `gemini` | `GeminiEmbedding` |
| `azure` | `AzureOpenAiEmbedding` |
| `qdrant` | `QdrantRetriever` |
| `pgvector` | `PgVectorStore`, `PgVectorStoreBuilder` |
| `opensearch` | `OpenSearchVectorStore`, `OpenSearchVectorStoreBuilder` |

Use `full` to enable all providers and vector stores.