hyperspace-sdk-ts 2.2.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +115 -11
- package/dist/agents.d.ts +16 -0
- package/dist/agents.js +64 -0
- package/dist/client.d.ts +12 -0
- package/dist/client.js +123 -1
- package/dist/math.d.ts +44 -0
- package/dist/math.js +234 -0
- package/dist/proto/hyperspace_grpc_pb.js +403 -0
- package/dist/proto/hyperspace_pb.js +9920 -2559
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# HyperspaceDB TypeScript SDK
|
|
2
2
|
|
|
3
|
-
Official TypeScript client for HyperspaceDB gRPC API (
|
|
3
|
+
Official TypeScript client for HyperspaceDB gRPC API (v3.0.0-alpha.2).
|
|
4
4
|
|
|
5
5
|
Use this SDK for:
|
|
6
6
|
- collection lifecycle management
|
|
@@ -60,7 +60,7 @@ main().catch(console.error);
|
|
|
60
60
|
|
|
61
61
|
Create a new collection.
|
|
62
62
|
|
|
63
|
-
- `metric`: `"l2" | "cosine" | "poincare"`
|
|
63
|
+
- `metric`: `"l2" | "cosine" | "poincare" | "lorentz"`
|
|
64
64
|
|
|
65
65
|
### `deleteCollection(name)`
|
|
66
66
|
|
|
@@ -71,6 +71,15 @@ Delete collection and all its data.
|
|
|
71
71
|
Insert one vector. Accepts `number[]`, `Float32Array`, `Float64Array`.
|
|
72
72
|
Optional `typedMetadata` supports typed values for range/boolean filters.
|
|
73
73
|
|
|
74
|
+
### `insertText(id, text, meta?, collection?, durability?)`
|
|
75
|
+
|
|
76
|
+
Insert text to be vectorized and stored on the server side (Server-Side Embedding).
|
|
77
|
+
|
|
78
|
+
### `vectorize(text, metric?)`
|
|
79
|
+
|
|
80
|
+
Convert text to a dense vector using the server's embedding engine.
|
|
81
|
+
- `metric`: defaults to `"l2"`.
|
|
82
|
+
|
|
74
83
|
### `batchInsert(items, collection?, durability?)`
|
|
75
84
|
|
|
76
85
|
Efficient bulk insertion.
|
|
@@ -83,18 +92,17 @@ await client.batchInsert([
|
|
|
83
92
|
|
|
84
93
|
### `search(vector, topK, collection?, options?)`
|
|
85
94
|
|
|
86
|
-
Run nearest-neighbor search.
|
|
87
|
-
|
|
88
|
-
|
|
95
|
+
Run nearest-neighbor search with a raw vector.
|
|
96
|
+
|
|
97
|
+
### `searchText(text, topK, collection?, options?)`
|
|
98
|
+
|
|
99
|
+
Run nearest-neighbor search using text input. The text is vectorized on the server before searching.
|
|
89
100
|
|
|
90
101
|
```ts
|
|
91
|
-
const results = await client.
|
|
102
|
+
const results = await client.searchText("How to use HyperspaceDB?", 10, "coll", {
|
|
92
103
|
filters: [
|
|
93
|
-
{ match: { key: "category", value: "
|
|
94
|
-
|
|
95
|
-
],
|
|
96
|
-
hybridQuery: "latest smartphone",
|
|
97
|
-
hybridAlpha: 0.5
|
|
104
|
+
{ match: { key: "category", value: "docs" } }
|
|
105
|
+
]
|
|
98
106
|
});
|
|
99
107
|
```
|
|
100
108
|
|
|
@@ -102,6 +110,14 @@ const results = await client.search(vector, 10, "coll", {
|
|
|
102
110
|
|
|
103
111
|
Run multiple searches in one gRPC request to reduce RPC overhead.
|
|
104
112
|
|
|
113
|
+
### `searchWasserstein(vector, topK, collection?)`
|
|
114
|
+
|
|
115
|
+
Execute O(N) Cross-Feature Match (1D L1 CDF distance) instead of generic Poincare/L2. Ideal for comparing distributions.
|
|
116
|
+
|
|
117
|
+
### `searchMultiCollection(vector, collections, topK)`
|
|
118
|
+
|
|
119
|
+
Submit one vector and run parallel searches across multiple collections in one batch request (e.g. for Multi-Geometry benchmarks comparing L2, Cosine, Poincare, Lorentz).
|
|
120
|
+
|
|
105
121
|
### `getDigest(collection?)`
|
|
106
122
|
|
|
107
123
|
Retrieve collection stats and logical clock.
|
|
@@ -126,6 +142,10 @@ const stream = client.subscribeToEvents(
|
|
|
126
142
|
|
|
127
143
|
Trigger index rebuild/vacuum for a collection.
|
|
128
144
|
|
|
145
|
+
### `triggerReconsolidation(collection, targetVector, learningRate)`
|
|
146
|
+
|
|
147
|
+
Trigger AI Sleep Mode natively: updates parameters using Flow Matching (Riemannian SGD) instantly via the database engine.
|
|
148
|
+
|
|
129
149
|
### `rebuildIndexWithFilter(collection, filter)`
|
|
130
150
|
|
|
131
151
|
Rebuild with metadata pruning for sleep/reconsolidation workflows.
|
|
@@ -154,10 +174,94 @@ Provided utilities:
|
|
|
154
174
|
- `parallelTransport(x, y, v, c?)`
|
|
155
175
|
- `frechetMean(points, c?, maxIter?, tol?)`
|
|
156
176
|
|
|
177
|
+
### `CognitiveMath` (Spatial AI Engine)
|
|
178
|
+
|
|
179
|
+
Provides advanced tools for Agentic AI, running entirely on the client side:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { CognitiveMath } from "hyperspace-sdk-ts";
|
|
183
|
+
|
|
184
|
+
// 1. Detect Hallucinations (Entropy approaches 1.0)
|
|
185
|
+
const entropy = CognitiveMath.localEntropy(candidateThought, neighbors, 1.0);
|
|
186
|
+
|
|
187
|
+
// 2. Proof of Convergence (Negative derivative = convergence)
|
|
188
|
+
const stability = CognitiveMath.lyapunovConvergence(chainOfThought, 1.0);
|
|
189
|
+
|
|
190
|
+
// 3. Extrapolate next thought (Koopman linearization)
|
|
191
|
+
const nextThought = CognitiveMath.koopmanExtrapolate(past, current, 1.0, 1.0);
|
|
192
|
+
|
|
193
|
+
// 4. Phase-Locked Loop for topic tracking
|
|
194
|
+
const syncedThought = CognitiveMath.contextResonance(thought, globalContext, 0.5, 1.0);
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Embedding Pipeline (Optional)
|
|
198
|
+
|
|
199
|
+
HyperspaceDB supports **per-geometry embeddings** — each geometry (`l2`, `cosine`, `poincare`, `lorentz`) can have its own backend independently.
|
|
200
|
+
|
|
201
|
+
### Server-Side Config (`.env`)
|
|
202
|
+
|
|
203
|
+
```env
|
|
204
|
+
HYPERSPACE_EMBED=true
|
|
205
|
+
|
|
206
|
+
# Cosine via OpenAI
|
|
207
|
+
HS_EMBED_COSINE_PROVIDER=openai
|
|
208
|
+
HS_EMBED_COSINE_EMBED_MODEL=text-embedding-3-small
|
|
209
|
+
HS_EMBED_COSINE_API_KEY=sk-...
|
|
210
|
+
|
|
211
|
+
# Poincaré via HuggingFace Hub (downloads model.onnx + tokenizer.json)
|
|
212
|
+
HS_EMBED_POINCARE_PROVIDER=huggingface
|
|
213
|
+
HS_EMBED_POINCARE_HF_MODEL_ID=your-org/cde-spatial-poincare-128d
|
|
214
|
+
HS_EMBED_POINCARE_DIM=128
|
|
215
|
+
HF_TOKEN=hf_... # Optional — for gated/private models
|
|
216
|
+
|
|
217
|
+
# Lorentz via local ONNX file
|
|
218
|
+
HS_EMBED_LORENTZ_PROVIDER=local
|
|
219
|
+
HS_EMBED_LORENTZ_MODEL_PATH=./models/lorentz_128d.onnx
|
|
220
|
+
HS_EMBED_LORENTZ_TOKENIZER_PATH=./models/lorentz_128d_tokenizer.json
|
|
221
|
+
HS_EMBED_LORENTZ_DIM=129 # spatial_dim + 1 for time component
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### Client-Side Embedder
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { OpenAIEmbedder, HuggingFaceEmbedder, LocalOnnxEmbedder } from "hyperspace-sdk-ts";
|
|
228
|
+
|
|
229
|
+
// OpenAI API
|
|
230
|
+
const embedder = new OpenAIEmbedder({ apiKey: "sk-...", model: "text-embedding-3-small" });
|
|
231
|
+
const vector = await embedder.encode("my text");
|
|
232
|
+
|
|
233
|
+
// HuggingFace Hub — downloads model.onnx + tokenizer.json on first use
|
|
234
|
+
const embedder = new HuggingFaceEmbedder({
|
|
235
|
+
modelId: "BAAI/bge-small-en-v1.5",
|
|
236
|
+
geometry: "cosine",
|
|
237
|
+
hfToken: process.env.HF_TOKEN, // Optional
|
|
238
|
+
});
|
|
239
|
+
const vector = await embedder.encode("my text");
|
|
240
|
+
|
|
241
|
+
// Local ONNX file
|
|
242
|
+
const embedder = new LocalOnnxEmbedder({
|
|
243
|
+
modelPath: "./models/bge-small.onnx",
|
|
244
|
+
tokenizerPath: "./models/bge-small-tokenizer.json",
|
|
245
|
+
geometry: "cosine",
|
|
246
|
+
});
|
|
247
|
+
const vector = await embedder.encode("my text");
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### Supported Geometries
|
|
251
|
+
|
|
252
|
+
| Geometry | Post-Processing | Best For |
|
|
253
|
+
|---|---|---|
|
|
254
|
+
| `cosine` | Unit normalize | Semantic similarity |
|
|
255
|
+
| `l2` | Unit normalize | Euclidean distance tasks |
|
|
256
|
+
| `poincare` | Clamp to unit ball | Hierarchical data (trees, ontologies) |
|
|
257
|
+
| `lorentz` | None (model handles it) | Mixed hierarchical + semantic |
|
|
258
|
+
|
|
157
259
|
## Performance Notes
|
|
158
260
|
|
|
159
261
|
- Prefer `searchBatch` and `batchInsert` for throughput-heavy services.
|
|
160
262
|
- Reuse one client instance per process or worker.
|
|
263
|
+
- For `lorentz` geometry, dimension = spatial_dim + 1 (the time component x₀).
|
|
264
|
+
- For `huggingface` provider, models are cached locally after first download.
|
|
161
265
|
|
|
162
266
|
## Error Handling
|
|
163
267
|
|
package/dist/agents.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { HyperspaceClient } from './client';
|
|
2
|
+
export declare class TribunalContext {
|
|
3
|
+
private client;
|
|
4
|
+
private collectionName;
|
|
5
|
+
/**
|
|
6
|
+
* Heterogeneous Tribunal Framework (Tribunal Router).
|
|
7
|
+
* Evaluates LLM claims by verifying geometric/logical paths between concepts
|
|
8
|
+
* using the HyperspaceDB Graph Traversal API.
|
|
9
|
+
*/
|
|
10
|
+
constructor(client: HyperspaceClient, collectionName: string);
|
|
11
|
+
/**
|
|
12
|
+
* Calculates Graph-Geometric Trust Score by traversing from Concept A to Concept B.
|
|
13
|
+
* Returns a score in [0.0, 1.0]. A score of 0.0 means disconnected (Hallucination).
|
|
14
|
+
*/
|
|
15
|
+
evaluateClaim(conceptAId: number, conceptBId: number, maxDepth?: number, maxNodes?: number): Promise<number>;
|
|
16
|
+
}
|
package/dist/agents.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TribunalContext = void 0;
|
|
4
|
+
class TribunalContext {
|
|
5
|
+
/**
|
|
6
|
+
* Heterogeneous Tribunal Framework (Tribunal Router).
|
|
7
|
+
* Evaluates LLM claims by verifying geometric/logical paths between concepts
|
|
8
|
+
* using the HyperspaceDB Graph Traversal API.
|
|
9
|
+
*/
|
|
10
|
+
constructor(client, collectionName) {
|
|
11
|
+
this.client = client;
|
|
12
|
+
this.collectionName = collectionName;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Calculates Graph-Geometric Trust Score by traversing from Concept A to Concept B.
|
|
16
|
+
* Returns a score in [0.0, 1.0]. A score of 0.0 means disconnected (Hallucination).
|
|
17
|
+
*/
|
|
18
|
+
async evaluateClaim(conceptAId, conceptBId, maxDepth = 5, maxNodes = 256) {
|
|
19
|
+
if (conceptAId === conceptBId)
|
|
20
|
+
return 1.0;
|
|
21
|
+
try {
|
|
22
|
+
// Extract local geometric subgraph via the Graph Traversal API
|
|
23
|
+
const nodes = await this.client.traverse(conceptAId, 0, maxDepth, maxNodes, this.collectionName);
|
|
24
|
+
if (!nodes || nodes.length === 0)
|
|
25
|
+
return 0.0;
|
|
26
|
+
const adjList = {};
|
|
27
|
+
for (const node of nodes) {
|
|
28
|
+
adjList[node.id] = node.neighbors;
|
|
29
|
+
}
|
|
30
|
+
if (!adjList[conceptAId])
|
|
31
|
+
return 0.0;
|
|
32
|
+
// Perform BFS to find the shortest geometric path distance
|
|
33
|
+
const queue = [[conceptAId, 0]];
|
|
34
|
+
const visited = new Set([conceptAId]);
|
|
35
|
+
let pathLength = -1;
|
|
36
|
+
while (queue.length > 0) {
|
|
37
|
+
const [current, depth] = queue.shift();
|
|
38
|
+
if (current === conceptBId) {
|
|
39
|
+
pathLength = depth;
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
if (depth >= maxDepth)
|
|
43
|
+
continue;
|
|
44
|
+
const neighbors = adjList[current] || [];
|
|
45
|
+
for (const neighbor of neighbors) {
|
|
46
|
+
if (!visited.has(neighbor)) {
|
|
47
|
+
visited.add(neighbor);
|
|
48
|
+
queue.push([neighbor, depth + 1]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (pathLength === -1)
|
|
53
|
+
return 0.0; // No logical pathway
|
|
54
|
+
// Geometric Trust Score decays smoothly based on shortest path
|
|
55
|
+
const trustScore = Math.exp(-0.4 * pathLength);
|
|
56
|
+
return trustScore;
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
console.error("TribunalContext evaluateClaim Error:", e);
|
|
60
|
+
return 0.0;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
exports.TribunalContext = TribunalContext;
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import * as grpc from '@grpc/grpc-js';
|
|
2
2
|
import { DurabilityLevel, EventMessage } from './proto/hyperspace_pb';
|
|
3
|
+
import * as hyperspace_pb from './proto/hyperspace_pb';
|
|
4
|
+
export * as CognitiveMath from './math';
|
|
5
|
+
export { TribunalContext } from './agents';
|
|
3
6
|
export { DurabilityLevel };
|
|
4
7
|
export type TypedMetadataValue = string | number | boolean;
|
|
5
8
|
export interface Filter {
|
|
@@ -67,6 +70,10 @@ export declare class HyperspaceClient {
|
|
|
67
70
|
}, collection?: string, durability?: DurabilityLevel, typedMetadata?: {
|
|
68
71
|
[key: string]: TypedMetadataValue;
|
|
69
72
|
}): Promise<boolean>;
|
|
73
|
+
insertText(id: number, text: string, meta?: {
|
|
74
|
+
[key: string]: string;
|
|
75
|
+
}, collection?: string, durability?: DurabilityLevel): Promise<boolean>;
|
|
76
|
+
vectorize(text: string, metric?: string): Promise<number[]>;
|
|
70
77
|
batchInsert(items: {
|
|
71
78
|
id: number;
|
|
72
79
|
vector: number[] | Float32Array | Float64Array;
|
|
@@ -82,6 +89,9 @@ export declare class HyperspaceClient {
|
|
|
82
89
|
hybridQuery?: string;
|
|
83
90
|
hybridAlpha?: number;
|
|
84
91
|
}): Promise<SearchResult[]>;
|
|
92
|
+
searchText(text: string, topK: number, collection?: string, options?: {
|
|
93
|
+
filters?: Filter[];
|
|
94
|
+
}): Promise<SearchResult[]>;
|
|
85
95
|
searchBatch(vectors: Array<number[] | Float32Array | Float64Array>, topK: number, collection?: string): Promise<SearchResult[][]>;
|
|
86
96
|
getDigest(collection?: string): Promise<{
|
|
87
97
|
logicalClock: number;
|
|
@@ -101,5 +111,7 @@ export declare class HyperspaceClient {
|
|
|
101
111
|
}): Promise<GraphNode[]>;
|
|
102
112
|
findSemanticClusters(layer?: number, minClusterSize?: number, maxClusters?: number, maxNodes?: number, collection?: string): Promise<number[][]>;
|
|
103
113
|
subscribeToEvents(options: SubscribeOptions, onEvent: (event: EventMessage) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<EventMessage>;
|
|
114
|
+
syncHandshake(collection: string, clientBuckets: number[], clientLogicalClock?: number, clientCount?: number): Promise<hyperspace_pb.SyncHandshakeResponse.AsObject>;
|
|
115
|
+
syncPull(collection: string, bucketIndices: number[], onData: (data: hyperspace_pb.SyncVectorData.AsObject) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<hyperspace_pb.SyncVectorData>;
|
|
104
116
|
close(): void;
|
|
105
117
|
}
|
package/dist/client.js
CHANGED
|
@@ -33,12 +33,15 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.HyperspaceClient = exports.HyperbolicMath = exports.DurabilityLevel = void 0;
|
|
36
|
+
exports.HyperspaceClient = exports.HyperbolicMath = exports.DurabilityLevel = exports.TribunalContext = exports.CognitiveMath = void 0;
|
|
37
37
|
const grpc = __importStar(require("@grpc/grpc-js"));
|
|
38
38
|
const hyperspace_grpc_pb_1 = require("./proto/hyperspace_grpc_pb");
|
|
39
39
|
const hyperspace_pb_1 = require("./proto/hyperspace_pb");
|
|
40
40
|
Object.defineProperty(exports, "DurabilityLevel", { enumerable: true, get: function () { return hyperspace_pb_1.DurabilityLevel; } });
|
|
41
41
|
const hyperspace_pb = __importStar(require("./proto/hyperspace_pb")); // New, for direct access to types
|
|
42
|
+
exports.CognitiveMath = __importStar(require("./math"));
|
|
43
|
+
var agents_1 = require("./agents");
|
|
44
|
+
Object.defineProperty(exports, "TribunalContext", { enumerable: true, get: function () { return agents_1.TribunalContext; } });
|
|
42
45
|
exports.HyperbolicMath = {
|
|
43
46
|
projectToBall(x, c = 1.0) {
|
|
44
47
|
if (c <= 0)
|
|
@@ -264,6 +267,37 @@ class HyperspaceClient {
|
|
|
264
267
|
});
|
|
265
268
|
});
|
|
266
269
|
}
|
|
270
|
+
insertText(id, text, meta, collection = '', durability = hyperspace_pb_1.DurabilityLevel.DEFAULT_LEVEL) {
|
|
271
|
+
return new Promise((resolve, reject) => {
|
|
272
|
+
const req = new hyperspace_pb_1.InsertTextRequest();
|
|
273
|
+
req.setId(id);
|
|
274
|
+
req.setText(text);
|
|
275
|
+
if (meta) {
|
|
276
|
+
const map = req.getMetadataMap();
|
|
277
|
+
for (const k in meta)
|
|
278
|
+
map.set(k, meta[k]);
|
|
279
|
+
}
|
|
280
|
+
req.setCollection(collection);
|
|
281
|
+
req.setDurability(durability);
|
|
282
|
+
this.client.insertText(req, this.metadata, (err, resp) => {
|
|
283
|
+
if (err)
|
|
284
|
+
return reject(err);
|
|
285
|
+
resolve(resp.getSuccess());
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
vectorize(text, metric = 'l2') {
|
|
290
|
+
return new Promise((resolve, reject) => {
|
|
291
|
+
const req = new hyperspace_pb_1.VectorizeRequest();
|
|
292
|
+
req.setText(text);
|
|
293
|
+
req.setMetric(metric);
|
|
294
|
+
this.client.vectorize(req, this.metadata, (err, resp) => {
|
|
295
|
+
if (err)
|
|
296
|
+
return reject(err);
|
|
297
|
+
resolve(resp.getVectorList());
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
}
|
|
267
301
|
batchInsert(items, collection = '', durability = hyperspace_pb_1.DurabilityLevel.DEFAULT_LEVEL) {
|
|
268
302
|
return new Promise((resolve, reject) => {
|
|
269
303
|
const req = new hyperspace_pb_1.BatchInsertRequest();
|
|
@@ -355,6 +389,64 @@ class HyperspaceClient {
|
|
|
355
389
|
});
|
|
356
390
|
});
|
|
357
391
|
}
|
|
392
|
+
searchText(text, topK, collection = '', options) {
|
|
393
|
+
return new Promise((resolve, reject) => {
|
|
394
|
+
const req = new hyperspace_pb_1.SearchTextRequest();
|
|
395
|
+
req.setText(text);
|
|
396
|
+
req.setTopK(topK);
|
|
397
|
+
req.setCollection(collection);
|
|
398
|
+
if (options === null || options === void 0 ? void 0 : options.filters) {
|
|
399
|
+
const protoFilters = options.filters.map(f => {
|
|
400
|
+
const pf = new hyperspace_pb.Filter();
|
|
401
|
+
if (f.match) {
|
|
402
|
+
const m = new hyperspace_pb.Match();
|
|
403
|
+
m.setKey(f.match.key);
|
|
404
|
+
m.setValue(f.match.value);
|
|
405
|
+
pf.setMatch(m);
|
|
406
|
+
}
|
|
407
|
+
else if (f.range) {
|
|
408
|
+
const r = new hyperspace_pb.Range();
|
|
409
|
+
r.setKey(f.range.key);
|
|
410
|
+
if (f.range.gte !== undefined) {
|
|
411
|
+
if (Number.isInteger(f.range.gte))
|
|
412
|
+
r.setGte(f.range.gte);
|
|
413
|
+
else
|
|
414
|
+
r.setGteF64(f.range.gte);
|
|
415
|
+
}
|
|
416
|
+
if (f.range.lte !== undefined) {
|
|
417
|
+
if (Number.isInteger(f.range.lte))
|
|
418
|
+
r.setLte(f.range.lte);
|
|
419
|
+
else
|
|
420
|
+
r.setLteF64(f.range.lte);
|
|
421
|
+
}
|
|
422
|
+
pf.setRange(r);
|
|
423
|
+
}
|
|
424
|
+
return pf;
|
|
425
|
+
});
|
|
426
|
+
req.setFiltersList(protoFilters);
|
|
427
|
+
}
|
|
428
|
+
this.client.searchText(req, this.metadata, (err, resp) => {
|
|
429
|
+
if (err)
|
|
430
|
+
return reject(err);
|
|
431
|
+
const results = resp.getResultsList().map(r => {
|
|
432
|
+
const metaMap = r.getMetadataMap();
|
|
433
|
+
const meta = {};
|
|
434
|
+
if (metaMap.getLength() > 0) {
|
|
435
|
+
metaMap.forEach((entry, key) => {
|
|
436
|
+
meta[key] = entry;
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
return {
|
|
440
|
+
id: r.getId(),
|
|
441
|
+
distance: r.getDistance(),
|
|
442
|
+
metadata: meta,
|
|
443
|
+
typedMetadata: HyperspaceClient.parseTypedMetadata(r.getTypedMetadataMap())
|
|
444
|
+
};
|
|
445
|
+
});
|
|
446
|
+
resolve(results);
|
|
447
|
+
});
|
|
448
|
+
});
|
|
449
|
+
}
|
|
358
450
|
searchBatch(vectors, topK, collection = '') {
|
|
359
451
|
return new Promise((resolve, reject) => {
|
|
360
452
|
const req = new hyperspace_pb_1.BatchSearchRequest();
|
|
@@ -615,6 +707,36 @@ class HyperspaceClient {
|
|
|
615
707
|
}
|
|
616
708
|
return stream;
|
|
617
709
|
}
|
|
710
|
+
syncHandshake(collection, clientBuckets, clientLogicalClock = 0, clientCount = 0) {
|
|
711
|
+
return new Promise((resolve, reject) => {
|
|
712
|
+
if (clientBuckets.length !== 256) {
|
|
713
|
+
return reject(new Error("clientBuckets must contain exactly 256 elements"));
|
|
714
|
+
}
|
|
715
|
+
const req = new hyperspace_pb.SyncHandshakeRequest();
|
|
716
|
+
req.setCollection(collection);
|
|
717
|
+
req.setClientBucketsList(clientBuckets);
|
|
718
|
+
req.setClientLogicalClock(clientLogicalClock);
|
|
719
|
+
req.setClientCount(clientCount);
|
|
720
|
+
this.client.syncHandshake(req, this.metadata, (err, res) => {
|
|
721
|
+
if (err)
|
|
722
|
+
return reject(err);
|
|
723
|
+
resolve(res.toObject());
|
|
724
|
+
});
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
syncPull(collection, bucketIndices, onData, onError) {
|
|
728
|
+
const req = new hyperspace_pb.SyncPullRequest();
|
|
729
|
+
req.setCollection(collection);
|
|
730
|
+
req.setBucketIndicesList(bucketIndices);
|
|
731
|
+
const stream = this.client.syncPull(req, this.metadata);
|
|
732
|
+
stream.on('data', (data) => {
|
|
733
|
+
onData(data.toObject());
|
|
734
|
+
});
|
|
735
|
+
if (onError) {
|
|
736
|
+
stream.on('error', onError);
|
|
737
|
+
}
|
|
738
|
+
return stream;
|
|
739
|
+
}
|
|
618
740
|
close() {
|
|
619
741
|
this.client.close();
|
|
620
742
|
}
|
package/dist/math.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HyperspaceDB Spatial and Cognitive Math SDK
|
|
3
|
+
* Provides hyperbolic math functions and Cognitive AI metrics for solving LLM hallucinations.
|
|
4
|
+
*/
|
|
5
|
+
export declare function dot(a: number[], b: number[]): number;
|
|
6
|
+
export declare function normSq(v: number[]): number;
|
|
7
|
+
export declare function norm(v: number[]): number;
|
|
8
|
+
export declare function mobiusAdd(x: number[], y: number[], c?: number): number[];
|
|
9
|
+
export declare function expMap(x: number[], v: number[], c?: number): number[];
|
|
10
|
+
export declare function logMap(x: number[], y: number[], c?: number): number[];
|
|
11
|
+
export declare function parallelTransport(x: number[], y: number[], v: number[], c?: number): number[];
|
|
12
|
+
export declare function frechetMean(points: number[][], c?: number, maxIter?: number, tol?: number): number[];
|
|
13
|
+
/** Computes the Minkowski inner product (Lorentz product) between two vectors. */
|
|
14
|
+
export declare function lorentzProduct(u: number[], v: number[]): number;
|
|
15
|
+
/** Computes the Lorentz distance between two points on the hyperboloid. */
|
|
16
|
+
export declare function lorentzDist(u: number[], v: number[]): number;
|
|
17
|
+
/** Converts a point from the Lorentz model (Hyperboloid) to the Poincaré Ball model (129 -> 128). */
|
|
18
|
+
export declare function lorentzToPoincare(x: number[]): number[];
|
|
19
|
+
/** Converts a point from the Poincaré Ball model to the Lorentz model (128 -> 129). */
|
|
20
|
+
export declare function poincareToLorentz(p: number[]): number[];
|
|
21
|
+
/** Ensures a vector satisfies the Lorentz constraint -x0^2 + |x|^2 = -1 (stabilization). */
|
|
22
|
+
export declare function projectToHyperboloid(v: number[]): number[];
|
|
23
|
+
/**
|
|
24
|
+
* Calculates the spatial entropy (dispersion) of a `candidate` vector relative to its `neighbors`.
|
|
25
|
+
* Used to track LLM hallucinations (Task 2.3.1).
|
|
26
|
+
* Returns a value in [0, 1) where values approaching 1 imply high chaos (hallucination).
|
|
27
|
+
*/
|
|
28
|
+
export declare function localEntropy(candidate: number[], neighbors: number[][], c?: number): number;
|
|
29
|
+
/**
|
|
30
|
+
* Evaluates if a trajectory of vectors (e.g. Chain of Thought) converges to an attractor.
|
|
31
|
+
* Calculates the average energy derivative (Lyapunov function derivative).
|
|
32
|
+
* Negative values indicate convergence (stable), positive indicate divergence (chaos/hallucination).
|
|
33
|
+
*/
|
|
34
|
+
export declare function lyapunovConvergence(trajectory: number[][], c?: number): number;
|
|
35
|
+
/**
|
|
36
|
+
* Extrapolates the trajectory in linear space (Koopman linearization) by tracking the
|
|
37
|
+
* shift vector from `past` to `current` and projecting it forward.
|
|
38
|
+
*/
|
|
39
|
+
export declare function koopmanExtrapolate(past: number[], current: number[], steps: number, c?: number): number[];
|
|
40
|
+
/**
|
|
41
|
+
* Resonates a thought vector towards a global context vector (Phase-Locked Loop context synchronization).
|
|
42
|
+
* Pulls the thought towards the context along the geodesic by `resonanceFactor` [0, 1].
|
|
43
|
+
*/
|
|
44
|
+
export declare function contextResonance(thought: number[], globalContext: number[], resonanceFactor: number, c?: number): number[];
|