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
//! Type definitions for the harness embeddings + retrieval module.
//!
//! These are the building blocks of retrieval-augmented context — the
//! [`EmbeddingModel`] / [`VectorStore`] / [`Retriever`] triad that lets a
//! recursive agent fetch external knowledge on demand rather than carrying it
//! all in-context.
//!
//! All public types declared here are re-exported through [`super`] so callers
//! import them from `crate::harness::embeddings` directly.
use DefaultHasher;
use ;
use ;
use async_trait;
use ;
use Value;
use crateResult;
// ── EmbeddingModel ────────────────────────────────────────────────────────────
/// Provider-neutral embedding model.
///
/// An embedding model turns text into dense [`f32`] vectors that downstream
/// vector stores and retrievers can compare with a distance metric (this module
/// uses cosine similarity). Implementations must be `Send + Sync` so they can be
/// shared across async task boundaries behind an [`Arc`].
///
/// The harness keeps embedding generation separate from the chat model
/// abstraction: chat models produce messages, embedding models produce vectors.
///
/// # Contract
/// - [`embed`](EmbeddingModel::embed) returns exactly one vector per input
/// text, in the same order as the inputs.
/// - Every returned vector has length [`dimensions`](EmbeddingModel::dimensions).
/// - Embedding the same text twice should produce the same vector for
/// deterministic implementations such as [`MockEmbeddingModel`].
// ── MockEmbeddingModel ────────────────────────────────────────────────────────
/// Deterministic, offline embedding model for tests and examples.
///
/// `MockEmbeddingModel` hashes the input text to derive a stable vector without
/// any network access. Identical text always maps to an identical vector (so
/// the cosine similarity of a text with itself is exactly `1.0`), while
/// different texts map to different vectors. This makes retrieval behaviour
/// testable offline: querying with the exact text of an indexed document ranks
/// that document first.
///
/// The vectors are **not** semantically meaningful — this model exists purely
/// for deterministic shape/retrieval tests, mirroring LangChain's
/// `DeterministicFakeEmbedding`.
///
/// # Example
/// ```
/// use tinyagents::harness::embeddings::{EmbeddingModel, MockEmbeddingModel};
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let model = MockEmbeddingModel::new(16);
/// let vectors = model.embed(&["hello".to_string()]).await.unwrap();
/// assert_eq!(vectors.len(), 1);
/// assert_eq!(vectors[0].len(), 16);
/// # });
/// ```
// ── ScoredDoc ─────────────────────────────────────────────────────────────────
/// A document returned from a vector-store or retriever query, with its
/// relevance score.
///
/// `score` is a cosine similarity in `[-1.0, 1.0]` where **higher is more
/// similar**. Results from this module's stores are returned in descending
/// score order (most similar first).
// ── VectorStore ───────────────────────────────────────────────────────────────
/// A store of dense vectors that supports nearest-neighbour search.
///
/// Implementations associate an `id` and arbitrary `metadata` with each vector,
/// and answer top-`k` similarity queries. This module's [`InMemoryVectorStore`]
/// ranks results by cosine similarity.
///
/// Implementations must be `Send + Sync` so they can be shared behind an
/// [`Arc`].
// ── InMemoryVectorStore ───────────────────────────────────────────────────────
/// A single stored vector together with its id and metadata.
pub
/// Thread-safe in-process [`VectorStore`] backed by a plain [`Vec`].
///
/// Search is a linear scan computing cosine similarity against every stored
/// vector, which is appropriate for tests, examples, and small corpora. The
/// store is cheaply clonable through the inner [`Arc`]; clones share the same
/// underlying data.
///
/// Adding a vector whose `id` already exists **replaces** the previous entry,
/// so re-indexing a document updates it in place.
///
/// # Example
/// ```
/// use tinyagents::harness::embeddings::{InMemoryVectorStore, VectorStore};
/// use serde_json::json;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let store = InMemoryVectorStore::new();
/// store.add("a".into(), vec![1.0, 0.0], json!({})).await.unwrap();
/// store.add("b".into(), vec![0.0, 1.0], json!({})).await.unwrap();
/// let hits = store.query(&[1.0, 0.0], 1).await.unwrap();
/// assert_eq!(hits[0].id, "a");
/// # });
/// ```
// ── Retriever ─────────────────────────────────────────────────────────────────
/// Query-to-document component tying an [`EmbeddingModel`] to a [`VectorStore`].
///
/// A `Retriever` embeds documents at index time and embeds queries at retrieval
/// time using the **same** embedding model, then delegates nearest-neighbour
/// search to the vector store. Both collaborators are held behind [`Arc`] so a
/// retriever is cheap to clone and share.
///
/// # Example
/// ```
/// use std::sync::Arc;
/// use tinyagents::harness::embeddings::{InMemoryVectorStore, MockEmbeddingModel, Retriever};
/// use serde_json::json;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let retriever = Retriever::new(
/// Arc::new(MockEmbeddingModel::new(32)),
/// Arc::new(InMemoryVectorStore::new()),
/// );
/// retriever
/// .index(vec![
/// ("d1".into(), "cats are great".into(), json!({})),
/// ("d2".into(), "the stock market crashed".into(), json!({})),
/// ])
/// .await
/// .unwrap();
/// let hits = retriever.retrieve("cats are great", 1).await.unwrap();
/// assert_eq!(hits[0].id, "d1");
/// # });
/// ```