hyperspace-sdk-ts 2.2.1 → 3.0.1
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 +118 -11
- package/dist/agents.d.ts +16 -0
- package/dist/agents.js +64 -0
- package/dist/client.d.ts +17 -0
- package/dist/client.js +162 -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
|
|
@@ -39,6 +39,9 @@ async function main() {
|
|
|
39
39
|
await client.insert(1, [0.1, 0.2, 0.3], { source: "demo" }, collection);
|
|
40
40
|
await client.insert(2, [0.2, 0.1, 0.4], { source: "demo" }, collection);
|
|
41
41
|
|
|
42
|
+
// Delete vector by ID
|
|
43
|
+
await client.delete(1);
|
|
44
|
+
|
|
42
45
|
const results = await client.search([0.1, 0.2, 0.3], 5, collection);
|
|
43
46
|
console.log(results);
|
|
44
47
|
|
|
@@ -60,7 +63,7 @@ main().catch(console.error);
|
|
|
60
63
|
|
|
61
64
|
Create a new collection.
|
|
62
65
|
|
|
63
|
-
- `metric`: `"l2" | "cosine" | "poincare"`
|
|
66
|
+
- `metric`: `"l2" | "cosine" | "poincare" | "lorentz"`
|
|
64
67
|
|
|
65
68
|
### `deleteCollection(name)`
|
|
66
69
|
|
|
@@ -71,6 +74,15 @@ Delete collection and all its data.
|
|
|
71
74
|
Insert one vector. Accepts `number[]`, `Float32Array`, `Float64Array`.
|
|
72
75
|
Optional `typedMetadata` supports typed values for range/boolean filters.
|
|
73
76
|
|
|
77
|
+
### `insertText(id, text, meta?, collection?, durability?)`
|
|
78
|
+
|
|
79
|
+
Insert text to be vectorized and stored on the server side (Server-Side Embedding).
|
|
80
|
+
|
|
81
|
+
### `vectorize(text, metric?)`
|
|
82
|
+
|
|
83
|
+
Convert text to a dense vector using the server's embedding engine.
|
|
84
|
+
- `metric`: defaults to `"l2"`.
|
|
85
|
+
|
|
74
86
|
### `batchInsert(items, collection?, durability?)`
|
|
75
87
|
|
|
76
88
|
Efficient bulk insertion.
|
|
@@ -83,18 +95,17 @@ await client.batchInsert([
|
|
|
83
95
|
|
|
84
96
|
### `search(vector, topK, collection?, options?)`
|
|
85
97
|
|
|
86
|
-
Run nearest-neighbor search.
|
|
87
|
-
|
|
88
|
-
|
|
98
|
+
Run nearest-neighbor search with a raw vector.
|
|
99
|
+
|
|
100
|
+
### `searchText(text, topK, collection?, options?)`
|
|
101
|
+
|
|
102
|
+
Run nearest-neighbor search using text input. The text is vectorized on the server before searching.
|
|
89
103
|
|
|
90
104
|
```ts
|
|
91
|
-
const results = await client.
|
|
105
|
+
const results = await client.searchText("How to use HyperspaceDB?", 10, "coll", {
|
|
92
106
|
filters: [
|
|
93
|
-
{ match: { key: "category", value: "
|
|
94
|
-
|
|
95
|
-
],
|
|
96
|
-
hybridQuery: "latest smartphone",
|
|
97
|
-
hybridAlpha: 0.5
|
|
107
|
+
{ match: { key: "category", value: "docs" } }
|
|
108
|
+
]
|
|
98
109
|
});
|
|
99
110
|
```
|
|
100
111
|
|
|
@@ -102,6 +113,14 @@ const results = await client.search(vector, 10, "coll", {
|
|
|
102
113
|
|
|
103
114
|
Run multiple searches in one gRPC request to reduce RPC overhead.
|
|
104
115
|
|
|
116
|
+
### `searchWasserstein(vector, topK, collection?)`
|
|
117
|
+
|
|
118
|
+
Execute O(N) Cross-Feature Match (1D L1 CDF distance) instead of generic Poincare/L2. Ideal for comparing distributions.
|
|
119
|
+
|
|
120
|
+
### `searchMultiCollection(vector, collections, topK)`
|
|
121
|
+
|
|
122
|
+
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).
|
|
123
|
+
|
|
105
124
|
### `getDigest(collection?)`
|
|
106
125
|
|
|
107
126
|
Retrieve collection stats and logical clock.
|
|
@@ -126,6 +145,10 @@ const stream = client.subscribeToEvents(
|
|
|
126
145
|
|
|
127
146
|
Trigger index rebuild/vacuum for a collection.
|
|
128
147
|
|
|
148
|
+
### `triggerReconsolidation(collection, targetVector, learningRate)`
|
|
149
|
+
|
|
150
|
+
Trigger AI Sleep Mode natively: updates parameters using Flow Matching (Riemannian SGD) instantly via the database engine.
|
|
151
|
+
|
|
129
152
|
### `rebuildIndexWithFilter(collection, filter)`
|
|
130
153
|
|
|
131
154
|
Rebuild with metadata pruning for sleep/reconsolidation workflows.
|
|
@@ -154,10 +177,94 @@ Provided utilities:
|
|
|
154
177
|
- `parallelTransport(x, y, v, c?)`
|
|
155
178
|
- `frechetMean(points, c?, maxIter?, tol?)`
|
|
156
179
|
|
|
180
|
+
### `CognitiveMath` (Spatial AI Engine)
|
|
181
|
+
|
|
182
|
+
Provides advanced tools for Agentic AI, running entirely on the client side:
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
import { CognitiveMath } from "hyperspace-sdk-ts";
|
|
186
|
+
|
|
187
|
+
// 1. Detect Hallucinations (Entropy approaches 1.0)
|
|
188
|
+
const entropy = CognitiveMath.localEntropy(candidateThought, neighbors, 1.0);
|
|
189
|
+
|
|
190
|
+
// 2. Proof of Convergence (Negative derivative = convergence)
|
|
191
|
+
const stability = CognitiveMath.lyapunovConvergence(chainOfThought, 1.0);
|
|
192
|
+
|
|
193
|
+
// 3. Extrapolate next thought (Koopman linearization)
|
|
194
|
+
const nextThought = CognitiveMath.koopmanExtrapolate(past, current, 1.0, 1.0);
|
|
195
|
+
|
|
196
|
+
// 4. Phase-Locked Loop for topic tracking
|
|
197
|
+
const syncedThought = CognitiveMath.contextResonance(thought, globalContext, 0.5, 1.0);
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
## Embedding Pipeline (Optional)
|
|
201
|
+
|
|
202
|
+
HyperspaceDB supports **per-geometry embeddings** — each geometry (`l2`, `cosine`, `poincare`, `lorentz`) can have its own backend independently.
|
|
203
|
+
|
|
204
|
+
### Server-Side Config (`.env`)
|
|
205
|
+
|
|
206
|
+
```env
|
|
207
|
+
HYPERSPACE_EMBED=true
|
|
208
|
+
|
|
209
|
+
# Cosine via OpenAI
|
|
210
|
+
HS_EMBED_COSINE_PROVIDER=openai
|
|
211
|
+
HS_EMBED_COSINE_EMBED_MODEL=text-embedding-3-small
|
|
212
|
+
HS_EMBED_COSINE_API_KEY=sk-...
|
|
213
|
+
|
|
214
|
+
# Poincaré via HuggingFace Hub (downloads model.onnx + tokenizer.json)
|
|
215
|
+
HS_EMBED_POINCARE_PROVIDER=huggingface
|
|
216
|
+
HS_EMBED_POINCARE_HF_MODEL_ID=your-org/cde-spatial-poincare-128d
|
|
217
|
+
HS_EMBED_POINCARE_DIM=128
|
|
218
|
+
HF_TOKEN=hf_... # Optional — for gated/private models
|
|
219
|
+
|
|
220
|
+
# Lorentz via local ONNX file
|
|
221
|
+
HS_EMBED_LORENTZ_PROVIDER=local
|
|
222
|
+
HS_EMBED_LORENTZ_MODEL_PATH=./models/lorentz_128d.onnx
|
|
223
|
+
HS_EMBED_LORENTZ_TOKENIZER_PATH=./models/lorentz_128d_tokenizer.json
|
|
224
|
+
HS_EMBED_LORENTZ_DIM=129 # spatial_dim + 1 for time component
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### Client-Side Embedder
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
import { OpenAIEmbedder, HuggingFaceEmbedder, LocalOnnxEmbedder } from "hyperspace-sdk-ts";
|
|
231
|
+
|
|
232
|
+
// OpenAI API
|
|
233
|
+
const embedder = new OpenAIEmbedder({ apiKey: "sk-...", model: "text-embedding-3-small" });
|
|
234
|
+
const vector = await embedder.encode("my text");
|
|
235
|
+
|
|
236
|
+
// HuggingFace Hub — downloads model.onnx + tokenizer.json on first use
|
|
237
|
+
const embedder = new HuggingFaceEmbedder({
|
|
238
|
+
modelId: "BAAI/bge-small-en-v1.5",
|
|
239
|
+
geometry: "cosine",
|
|
240
|
+
hfToken: process.env.HF_TOKEN, // Optional
|
|
241
|
+
});
|
|
242
|
+
const vector = await embedder.encode("my text");
|
|
243
|
+
|
|
244
|
+
// Local ONNX file
|
|
245
|
+
const embedder = new LocalOnnxEmbedder({
|
|
246
|
+
modelPath: "./models/bge-small.onnx",
|
|
247
|
+
tokenizerPath: "./models/bge-small-tokenizer.json",
|
|
248
|
+
geometry: "cosine",
|
|
249
|
+
});
|
|
250
|
+
const vector = await embedder.encode("my text");
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### Supported Geometries
|
|
254
|
+
|
|
255
|
+
| Geometry | Post-Processing | Best For |
|
|
256
|
+
|---|---|---|
|
|
257
|
+
| `cosine` | Unit normalize | Semantic similarity |
|
|
258
|
+
| `l2` | Unit normalize | Euclidean distance tasks |
|
|
259
|
+
| `poincare` | Clamp to unit ball | Hierarchical data (trees, ontologies) |
|
|
260
|
+
| `lorentz` | None (model handles it) | Mixed hierarchical + semantic |
|
|
261
|
+
|
|
157
262
|
## Performance Notes
|
|
158
263
|
|
|
159
264
|
- Prefer `searchBatch` and `batchInsert` for throughput-heavy services.
|
|
160
265
|
- Reuse one client instance per process or worker.
|
|
266
|
+
- For `lorentz` geometry, dimension = spatial_dim + 1 (the time component x₀).
|
|
267
|
+
- For `huggingface` provider, models are cached locally after first download.
|
|
161
268
|
|
|
162
269
|
## Error Handling
|
|
163
270
|
|
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 {
|
|
@@ -52,6 +55,10 @@ export declare const HyperbolicMath: {
|
|
|
52
55
|
riemannianGradient(x: number[], euclideanGrad: number[], c?: number): number[];
|
|
53
56
|
parallelTransport(x: number[], y: number[], v: number[], c?: number): number[];
|
|
54
57
|
frechetMean(points: number[][], c?: number, maxIter?: number, tol?: number): number[];
|
|
58
|
+
analyzeDeltaHyperbolicity(vectors: number[][], numSamples?: number): {
|
|
59
|
+
delta: number;
|
|
60
|
+
recommendation: string;
|
|
61
|
+
};
|
|
55
62
|
};
|
|
56
63
|
export declare class HyperspaceClient {
|
|
57
64
|
private client;
|
|
@@ -62,11 +69,16 @@ export declare class HyperspaceClient {
|
|
|
62
69
|
constructor(host?: string, apiKey?: string, userId?: string);
|
|
63
70
|
createCollection(name: string, dimension: number, metric: string): Promise<boolean>;
|
|
64
71
|
deleteCollection(name: string): Promise<boolean>;
|
|
72
|
+
delete(id: number, collection?: string): Promise<boolean>;
|
|
65
73
|
insert(id: number, vector: number[] | Float32Array | Float64Array, meta?: {
|
|
66
74
|
[key: string]: string;
|
|
67
75
|
}, collection?: string, durability?: DurabilityLevel, typedMetadata?: {
|
|
68
76
|
[key: string]: TypedMetadataValue;
|
|
69
77
|
}): Promise<boolean>;
|
|
78
|
+
insertText(id: number, text: string, meta?: {
|
|
79
|
+
[key: string]: string;
|
|
80
|
+
}, collection?: string, durability?: DurabilityLevel): Promise<boolean>;
|
|
81
|
+
vectorize(text: string, metric?: string): Promise<number[]>;
|
|
70
82
|
batchInsert(items: {
|
|
71
83
|
id: number;
|
|
72
84
|
vector: number[] | Float32Array | Float64Array;
|
|
@@ -82,6 +94,9 @@ export declare class HyperspaceClient {
|
|
|
82
94
|
hybridQuery?: string;
|
|
83
95
|
hybridAlpha?: number;
|
|
84
96
|
}): Promise<SearchResult[]>;
|
|
97
|
+
searchText(text: string, topK: number, collection?: string, options?: {
|
|
98
|
+
filters?: Filter[];
|
|
99
|
+
}): Promise<SearchResult[]>;
|
|
85
100
|
searchBatch(vectors: Array<number[] | Float32Array | Float64Array>, topK: number, collection?: string): Promise<SearchResult[][]>;
|
|
86
101
|
getDigest(collection?: string): Promise<{
|
|
87
102
|
logicalClock: number;
|
|
@@ -101,5 +116,7 @@ export declare class HyperspaceClient {
|
|
|
101
116
|
}): Promise<GraphNode[]>;
|
|
102
117
|
findSemanticClusters(layer?: number, minClusterSize?: number, maxClusters?: number, maxNodes?: number, collection?: string): Promise<number[][]>;
|
|
103
118
|
subscribeToEvents(options: SubscribeOptions, onEvent: (event: EventMessage) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<EventMessage>;
|
|
119
|
+
syncHandshake(collection: string, clientBuckets: number[], clientLogicalClock?: number, clientCount?: number): Promise<hyperspace_pb.SyncHandshakeResponse.AsObject>;
|
|
120
|
+
syncPull(collection: string, bucketIndices: number[], onData: (data: hyperspace_pb.SyncVectorData.AsObject) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<hyperspace_pb.SyncVectorData>;
|
|
104
121
|
close(): void;
|
|
105
122
|
}
|
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)
|
|
@@ -149,6 +152,33 @@ exports.HyperbolicMath = {
|
|
|
149
152
|
mu = exports.HyperbolicMath.projectToBall(mu, c);
|
|
150
153
|
}
|
|
151
154
|
return mu;
|
|
155
|
+
},
|
|
156
|
+
analyzeDeltaHyperbolicity(vectors, numSamples = 1000) {
|
|
157
|
+
if (vectors.length < 4)
|
|
158
|
+
return { delta: 0, recommendation: 'euclidean' };
|
|
159
|
+
const l2Dist = (a, b) => Math.sqrt(a.reduce((s, x, i) => s + (x - b[i]) ** 2, 0));
|
|
160
|
+
let maxDelta = 0;
|
|
161
|
+
for (let s = 0; s < numSamples; s++) {
|
|
162
|
+
const indices = new Set();
|
|
163
|
+
while (indices.size < 4)
|
|
164
|
+
indices.add(Math.floor(Math.random() * vectors.length));
|
|
165
|
+
const [i, j, k, l] = Array.from(indices);
|
|
166
|
+
const d_ij = l2Dist(vectors[i], vectors[j]);
|
|
167
|
+
const d_kl = l2Dist(vectors[k], vectors[l]);
|
|
168
|
+
const d_ik = l2Dist(vectors[i], vectors[k]);
|
|
169
|
+
const d_jl = l2Dist(vectors[j], vectors[l]);
|
|
170
|
+
const d_il = l2Dist(vectors[i], vectors[l]);
|
|
171
|
+
const d_jk = l2Dist(vectors[j], vectors[k]);
|
|
172
|
+
const s1 = d_ij + d_kl;
|
|
173
|
+
const s2 = d_ik + d_jl;
|
|
174
|
+
const s3 = d_il + d_jk;
|
|
175
|
+
const sums = [s1, s2, s3].sort((a, b) => b - a);
|
|
176
|
+
const delta = (sums[0] - sums[1]) / 2.0;
|
|
177
|
+
if (delta > maxDelta)
|
|
178
|
+
maxDelta = delta;
|
|
179
|
+
}
|
|
180
|
+
const recommendation = maxDelta < 0.15 ? 'lorentz' : (maxDelta < 0.30 ? 'poincare' : 'l2');
|
|
181
|
+
return { delta: maxDelta, recommendation };
|
|
152
182
|
}
|
|
153
183
|
};
|
|
154
184
|
class HyperspaceClient {
|
|
@@ -238,6 +268,18 @@ class HyperspaceClient {
|
|
|
238
268
|
});
|
|
239
269
|
});
|
|
240
270
|
}
|
|
271
|
+
delete(id, collection = '') {
|
|
272
|
+
return new Promise((resolve, reject) => {
|
|
273
|
+
const req = new hyperspace_pb.DeleteRequest();
|
|
274
|
+
req.setCollection(collection);
|
|
275
|
+
req.setId(id);
|
|
276
|
+
this.client.delete(req, this.metadata, (err, resp) => {
|
|
277
|
+
if (err)
|
|
278
|
+
return reject(err);
|
|
279
|
+
resolve(resp.getSuccess());
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
}
|
|
241
283
|
insert(id, vector, meta, collection = '', durability = hyperspace_pb_1.DurabilityLevel.DEFAULT_LEVEL, typedMetadata) {
|
|
242
284
|
return new Promise((resolve, reject) => {
|
|
243
285
|
const req = new hyperspace_pb_1.InsertRequest();
|
|
@@ -264,6 +306,37 @@ class HyperspaceClient {
|
|
|
264
306
|
});
|
|
265
307
|
});
|
|
266
308
|
}
|
|
309
|
+
insertText(id, text, meta, collection = '', durability = hyperspace_pb_1.DurabilityLevel.DEFAULT_LEVEL) {
|
|
310
|
+
return new Promise((resolve, reject) => {
|
|
311
|
+
const req = new hyperspace_pb_1.InsertTextRequest();
|
|
312
|
+
req.setId(id);
|
|
313
|
+
req.setText(text);
|
|
314
|
+
if (meta) {
|
|
315
|
+
const map = req.getMetadataMap();
|
|
316
|
+
for (const k in meta)
|
|
317
|
+
map.set(k, meta[k]);
|
|
318
|
+
}
|
|
319
|
+
req.setCollection(collection);
|
|
320
|
+
req.setDurability(durability);
|
|
321
|
+
this.client.insertText(req, this.metadata, (err, resp) => {
|
|
322
|
+
if (err)
|
|
323
|
+
return reject(err);
|
|
324
|
+
resolve(resp.getSuccess());
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
vectorize(text, metric = 'l2') {
|
|
329
|
+
return new Promise((resolve, reject) => {
|
|
330
|
+
const req = new hyperspace_pb_1.VectorizeRequest();
|
|
331
|
+
req.setText(text);
|
|
332
|
+
req.setMetric(metric);
|
|
333
|
+
this.client.vectorize(req, this.metadata, (err, resp) => {
|
|
334
|
+
if (err)
|
|
335
|
+
return reject(err);
|
|
336
|
+
resolve(resp.getVectorList());
|
|
337
|
+
});
|
|
338
|
+
});
|
|
339
|
+
}
|
|
267
340
|
batchInsert(items, collection = '', durability = hyperspace_pb_1.DurabilityLevel.DEFAULT_LEVEL) {
|
|
268
341
|
return new Promise((resolve, reject) => {
|
|
269
342
|
const req = new hyperspace_pb_1.BatchInsertRequest();
|
|
@@ -355,6 +428,64 @@ class HyperspaceClient {
|
|
|
355
428
|
});
|
|
356
429
|
});
|
|
357
430
|
}
|
|
431
|
+
searchText(text, topK, collection = '', options) {
|
|
432
|
+
return new Promise((resolve, reject) => {
|
|
433
|
+
const req = new hyperspace_pb_1.SearchTextRequest();
|
|
434
|
+
req.setText(text);
|
|
435
|
+
req.setTopK(topK);
|
|
436
|
+
req.setCollection(collection);
|
|
437
|
+
if (options === null || options === void 0 ? void 0 : options.filters) {
|
|
438
|
+
const protoFilters = options.filters.map(f => {
|
|
439
|
+
const pf = new hyperspace_pb.Filter();
|
|
440
|
+
if (f.match) {
|
|
441
|
+
const m = new hyperspace_pb.Match();
|
|
442
|
+
m.setKey(f.match.key);
|
|
443
|
+
m.setValue(f.match.value);
|
|
444
|
+
pf.setMatch(m);
|
|
445
|
+
}
|
|
446
|
+
else if (f.range) {
|
|
447
|
+
const r = new hyperspace_pb.Range();
|
|
448
|
+
r.setKey(f.range.key);
|
|
449
|
+
if (f.range.gte !== undefined) {
|
|
450
|
+
if (Number.isInteger(f.range.gte))
|
|
451
|
+
r.setGte(f.range.gte);
|
|
452
|
+
else
|
|
453
|
+
r.setGteF64(f.range.gte);
|
|
454
|
+
}
|
|
455
|
+
if (f.range.lte !== undefined) {
|
|
456
|
+
if (Number.isInteger(f.range.lte))
|
|
457
|
+
r.setLte(f.range.lte);
|
|
458
|
+
else
|
|
459
|
+
r.setLteF64(f.range.lte);
|
|
460
|
+
}
|
|
461
|
+
pf.setRange(r);
|
|
462
|
+
}
|
|
463
|
+
return pf;
|
|
464
|
+
});
|
|
465
|
+
req.setFiltersList(protoFilters);
|
|
466
|
+
}
|
|
467
|
+
this.client.searchText(req, this.metadata, (err, resp) => {
|
|
468
|
+
if (err)
|
|
469
|
+
return reject(err);
|
|
470
|
+
const results = resp.getResultsList().map(r => {
|
|
471
|
+
const metaMap = r.getMetadataMap();
|
|
472
|
+
const meta = {};
|
|
473
|
+
if (metaMap.getLength() > 0) {
|
|
474
|
+
metaMap.forEach((entry, key) => {
|
|
475
|
+
meta[key] = entry;
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
return {
|
|
479
|
+
id: r.getId(),
|
|
480
|
+
distance: r.getDistance(),
|
|
481
|
+
metadata: meta,
|
|
482
|
+
typedMetadata: HyperspaceClient.parseTypedMetadata(r.getTypedMetadataMap())
|
|
483
|
+
};
|
|
484
|
+
});
|
|
485
|
+
resolve(results);
|
|
486
|
+
});
|
|
487
|
+
});
|
|
488
|
+
}
|
|
358
489
|
searchBatch(vectors, topK, collection = '') {
|
|
359
490
|
return new Promise((resolve, reject) => {
|
|
360
491
|
const req = new hyperspace_pb_1.BatchSearchRequest();
|
|
@@ -615,6 +746,36 @@ class HyperspaceClient {
|
|
|
615
746
|
}
|
|
616
747
|
return stream;
|
|
617
748
|
}
|
|
749
|
+
syncHandshake(collection, clientBuckets, clientLogicalClock = 0, clientCount = 0) {
|
|
750
|
+
return new Promise((resolve, reject) => {
|
|
751
|
+
if (clientBuckets.length !== 256) {
|
|
752
|
+
return reject(new Error("clientBuckets must contain exactly 256 elements"));
|
|
753
|
+
}
|
|
754
|
+
const req = new hyperspace_pb.SyncHandshakeRequest();
|
|
755
|
+
req.setCollection(collection);
|
|
756
|
+
req.setClientBucketsList(clientBuckets);
|
|
757
|
+
req.setClientLogicalClock(clientLogicalClock);
|
|
758
|
+
req.setClientCount(clientCount);
|
|
759
|
+
this.client.syncHandshake(req, this.metadata, (err, res) => {
|
|
760
|
+
if (err)
|
|
761
|
+
return reject(err);
|
|
762
|
+
resolve(res.toObject());
|
|
763
|
+
});
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
syncPull(collection, bucketIndices, onData, onError) {
|
|
767
|
+
const req = new hyperspace_pb.SyncPullRequest();
|
|
768
|
+
req.setCollection(collection);
|
|
769
|
+
req.setBucketIndicesList(bucketIndices);
|
|
770
|
+
const stream = this.client.syncPull(req, this.metadata);
|
|
771
|
+
stream.on('data', (data) => {
|
|
772
|
+
onData(data.toObject());
|
|
773
|
+
});
|
|
774
|
+
if (onError) {
|
|
775
|
+
stream.on('error', onError);
|
|
776
|
+
}
|
|
777
|
+
return stream;
|
|
778
|
+
}
|
|
618
779
|
close() {
|
|
619
780
|
this.client.close();
|
|
620
781
|
}
|
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[];
|