cognitor 0.1.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/LICENSE.md ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2026 Riccardo Lucato
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # cognitor-typescript
2
+
3
+ TypeScript SDK for [Cognitor](https://github.com/tanaos/cognitor).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install cognitor
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```ts
14
+ import { Cognitor } from "cognitor";
15
+
16
+ const client = new Cognitor("http://localhost:7530", {
17
+ apiKey: "your-api-key",
18
+ });
19
+
20
+ console.log(await client.ping());
21
+ console.log(await client.healthReady()); // "ready" or "loading"
22
+
23
+ client.close();
24
+ ```
25
+
26
+ The `apiKey` parameter is optional, omit it if your [cognitor instance](https://github.com/tanaos/cognitor) does not require authentication.
27
+
28
+ ## Usage
29
+
30
+ ### Collections
31
+
32
+ ```ts
33
+ // Create a collection (server-side embedding)
34
+ const collection = await client.createCollection("my-collection", {
35
+ embModel: "text-embedding-3-small",
36
+ });
37
+
38
+ // Create a collection with a fixed vector dimension (client-side embedding)
39
+ const collectionWithDim = await client.createCollection("my-collection-2", {
40
+ dim: 1536,
41
+ });
42
+
43
+ // List all collections
44
+ const collections = await client.listCollections();
45
+
46
+ // Get a single collection
47
+ const oneCollection = await client.getCollection("my-collection");
48
+
49
+ // Delete a collection
50
+ await client.deleteCollection("my-collection");
51
+ ```
52
+
53
+ ### Documents
54
+
55
+ ```ts
56
+ // Add documents (texts are embedded server-side when embModel is set)
57
+ const ids = await client.addDocuments(
58
+ "my-collection",
59
+ ["Hello world", "Cognitor is a vector store"],
60
+ [{ source: "docs" }, { source: "docs" }],
61
+ );
62
+
63
+ // Add documents with explicit vectors (client-side embedding)
64
+ const idsWithVectors = await client.addDocuments(
65
+ "my-collection",
66
+ ["Hello world"],
67
+ [{ source: "docs" }],
68
+ { vectors: [[0.1, 0.2]] },
69
+ );
70
+
71
+ // Add a large number of documents in batches
72
+ const bulkIds = await client.bulkAddDocuments(
73
+ "my-collection",
74
+ ["doc 1", "doc 2"],
75
+ [{ source: "docs" }, { source: "docs" }],
76
+ { batchSize: 512 },
77
+ );
78
+
79
+ // List documents (paginated)
80
+ const page = await client.listDocuments("my-collection", { offset: 0, limit: 50 });
81
+ console.log(page.total, page.documents);
82
+
83
+ // Get a single document
84
+ const doc = await client.getDocument("my-collection", ids[0]);
85
+
86
+ // Update document metadata
87
+ const updated = await client.updateDocumentMetadata("my-collection", ids[0], {
88
+ source: "updated",
89
+ });
90
+
91
+ // Delete a document
92
+ await client.deleteDocument("my-collection", ids[0]);
93
+ ```
94
+
95
+ ### Search
96
+
97
+ ```ts
98
+ // Search by text (requires server-side embedding model)
99
+ const byText = await client.search("my-collection", {
100
+ queryText: "Hello",
101
+ topK: 10,
102
+ });
103
+
104
+ // Search by vector
105
+ const byVector = await client.search("my-collection", {
106
+ queryVector: [0.1, 0.2],
107
+ topK: 10,
108
+ });
109
+
110
+ // Filter results by metadata
111
+ const filtered = await client.search("my-collection", {
112
+ queryText: "Hello",
113
+ filters: { source: "docs" },
114
+ });
115
+
116
+ // Include vectors in results
117
+ const withVectors = await client.search("my-collection", {
118
+ queryText: "Hello",
119
+ includeVectors: true,
120
+ });
121
+
122
+ for (const hit of withVectors.results) {
123
+ console.log(`score=${hit.score.toFixed(4)} text=${JSON.stringify(hit.text)}`);
124
+ }
125
+ ```
126
+
127
+ ### Admin
128
+
129
+ ```ts
130
+ // Compact a collection (removes deleted vectors)
131
+ const result = await client.compact("my-collection");
132
+ console.log(result.deletedCount, "vectors removed");
133
+ ```
134
+
135
+ ### Health
136
+
137
+ ```ts
138
+ // Readiness probe status
139
+ const status = await client.healthReady();
140
+ if (status === "ready") {
141
+ console.log("Server is ready");
142
+ } else {
143
+ console.log("Server is still loading models");
144
+ }
145
+ ```
146
+
147
+ ### Authentication helpers
148
+
149
+ ```ts
150
+ // Register a user and obtain an API key
151
+ const apiKey = await client.register("username", "password");
152
+
153
+ // Login and obtain an API key
154
+ const newApiKey = await client.login("username", "password");
155
+ ```
@@ -0,0 +1,58 @@
1
+ import { Collection, CompactionResult, Document, ListDocumentsResult, Metadata, SearchResponse, Vector } from "./models.js";
2
+ interface CognitorOptions {
3
+ apiKey?: string;
4
+ timeout?: number;
5
+ fetchImpl?: typeof fetch;
6
+ }
7
+ type HealthReadyStatus = "ready" | "loading";
8
+ export declare class Cognitor {
9
+ private readonly baseUrl;
10
+ private readonly headers;
11
+ private readonly timeoutMs;
12
+ private readonly fetchFn;
13
+ constructor(baseUrl: string, options?: CognitorOptions);
14
+ close(): void;
15
+ ping(): Promise<string>;
16
+ healthReady(): Promise<HealthReadyStatus>;
17
+ listCollections(): Promise<Collection[]>;
18
+ getCollection(name: string): Promise<Collection>;
19
+ createCollection(name: string, options?: {
20
+ dim?: number;
21
+ embModel?: string;
22
+ }): Promise<Collection>;
23
+ deleteCollection(name: string): Promise<void>;
24
+ addDocuments(collection: string, texts: string[], metadatas: Metadata[], options?: {
25
+ vectors?: Vector[];
26
+ }): Promise<string[]>;
27
+ bulkAddDocuments(collection: string, texts: string[], metadatas: Metadata[], options?: {
28
+ vectors?: Vector[];
29
+ batchSize?: number;
30
+ }): Promise<string[]>;
31
+ listDocuments(collection: string, options?: {
32
+ offset?: number;
33
+ limit?: number;
34
+ }): Promise<ListDocumentsResult>;
35
+ getDocument(collection: string, docId: string): Promise<Document>;
36
+ deleteDocument(collection: string, docId: string): Promise<void>;
37
+ updateDocumentMetadata(collection: string, docId: string, metadata: Metadata): Promise<Document>;
38
+ search(collection: string, options?: {
39
+ queryText?: string;
40
+ queryVector?: Vector;
41
+ topK?: number;
42
+ filters?: Metadata;
43
+ includeVectors?: boolean;
44
+ performExtractiveQA?: boolean;
45
+ performReranking?: boolean;
46
+ }): Promise<SearchResponse>;
47
+ compact(collection: string): Promise<CompactionResult>;
48
+ register(username: string, password: string): Promise<string>;
49
+ login(username: string, password: string): Promise<string>;
50
+ private mapCollection;
51
+ private mapCompactionResult;
52
+ private mapSearchResult;
53
+ private request;
54
+ private requestRaw;
55
+ private makeHeaders;
56
+ private raiseForStatus;
57
+ }
58
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,278 @@
1
+ import { AuthenticationError, CognitorError, ConflictError, NotFoundError, ServerError, ValidationError, } from "./exceptions.js";
2
+ export class Cognitor {
3
+ baseUrl;
4
+ headers;
5
+ timeoutMs;
6
+ fetchFn;
7
+ constructor(baseUrl, options = {}) {
8
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
9
+ this.headers = new Headers();
10
+ if (options.apiKey) {
11
+ this.headers.set("Authorization", `Bearer ${options.apiKey}`);
12
+ }
13
+ this.timeoutMs = (options.timeout ?? 30) * 1000;
14
+ this.fetchFn = (options.fetchImpl ?? fetch).bind(globalThis);
15
+ }
16
+ close() {
17
+ // Kept for parity with the Python SDK. No explicit teardown is required for fetch.
18
+ }
19
+ // ------------------------------------------------------------------
20
+ // Base
21
+ // ------------------------------------------------------------------
22
+ async ping() {
23
+ const response = await this.request("/");
24
+ return (await response.json());
25
+ }
26
+ async healthReady() {
27
+ const response = await this.requestRaw("/health/ready", { method: "GET" });
28
+ if (response.status === 200) {
29
+ return "ready";
30
+ }
31
+ if (response.status === 503) {
32
+ return "loading";
33
+ }
34
+ await this.raiseForStatus(response);
35
+ return "loading";
36
+ }
37
+ // ------------------------------------------------------------------
38
+ // Collections
39
+ // ------------------------------------------------------------------
40
+ async listCollections() {
41
+ const response = await this.request("/collections");
42
+ const body = (await response.json());
43
+ return body.collections.map((collection) => this.mapCollection(collection));
44
+ }
45
+ async getCollection(name) {
46
+ const response = await this.request(`/collections/${encodeURIComponent(name)}`);
47
+ return this.mapCollection((await response.json()));
48
+ }
49
+ async createCollection(name, options = {}) {
50
+ const body = { name };
51
+ if (options.dim !== undefined) {
52
+ body.dim = options.dim;
53
+ }
54
+ if (options.embModel !== undefined) {
55
+ body.emb_model = options.embModel;
56
+ }
57
+ const response = await this.request("/collections", {
58
+ method: "POST",
59
+ body: JSON.stringify(body),
60
+ });
61
+ return this.mapCollection((await response.json()));
62
+ }
63
+ async deleteCollection(name) {
64
+ await this.request(`/collections/${encodeURIComponent(name)}`, { method: "DELETE" });
65
+ }
66
+ // ------------------------------------------------------------------
67
+ // Documents
68
+ // ------------------------------------------------------------------
69
+ async addDocuments(collection, texts, metadatas, options = {}) {
70
+ const body = {
71
+ texts,
72
+ metadatas,
73
+ };
74
+ if (options.vectors !== undefined) {
75
+ body.vectors = options.vectors;
76
+ }
77
+ const response = await this.request(`/collections/${encodeURIComponent(collection)}/documents`, {
78
+ method: "POST",
79
+ body: JSON.stringify(body),
80
+ });
81
+ const data = (await response.json());
82
+ return data.ids;
83
+ }
84
+ async bulkAddDocuments(collection, texts, metadatas, options = {}) {
85
+ const body = {
86
+ texts,
87
+ metadatas,
88
+ };
89
+ if (options.vectors !== undefined) {
90
+ body.vectors = options.vectors;
91
+ }
92
+ const batchSize = options.batchSize ?? 512;
93
+ const query = new URLSearchParams({ batch_size: String(batchSize) }).toString();
94
+ const response = await this.request(`/collections/${encodeURIComponent(collection)}/documents/bulk?${query}`, {
95
+ method: "POST",
96
+ body: JSON.stringify(body),
97
+ });
98
+ const data = (await response.json());
99
+ return data.ids;
100
+ }
101
+ async listDocuments(collection, options = {}) {
102
+ const offset = options.offset ?? 0;
103
+ const limit = options.limit ?? 50;
104
+ const query = new URLSearchParams({
105
+ offset: String(offset),
106
+ limit: String(limit),
107
+ }).toString();
108
+ const response = await this.request(`/collections/${encodeURIComponent(collection)}/documents?${query}`);
109
+ return (await response.json());
110
+ }
111
+ async getDocument(collection, docId) {
112
+ const response = await this.request(`/collections/${encodeURIComponent(collection)}/documents/${encodeURIComponent(docId)}`);
113
+ return (await response.json());
114
+ }
115
+ async deleteDocument(collection, docId) {
116
+ await this.request(`/collections/${encodeURIComponent(collection)}/documents/${encodeURIComponent(docId)}`, { method: "DELETE" });
117
+ }
118
+ async updateDocumentMetadata(collection, docId, metadata) {
119
+ const response = await this.request(`/collections/${encodeURIComponent(collection)}/documents/${encodeURIComponent(docId)}/metadata`, {
120
+ method: "PATCH",
121
+ body: JSON.stringify({ metadata }),
122
+ });
123
+ return (await response.json());
124
+ }
125
+ // ------------------------------------------------------------------
126
+ // Search
127
+ // ------------------------------------------------------------------
128
+ async search(collection, options = {}) {
129
+ const body = {
130
+ top_k: options.topK ?? 5,
131
+ include_vectors: options.includeVectors ?? false,
132
+ perform_extractive_qa: options.performExtractiveQA ?? true,
133
+ perform_reranking: options.performReranking ?? true,
134
+ };
135
+ if (options.queryText !== undefined) {
136
+ body.query_text = options.queryText;
137
+ }
138
+ if (options.queryVector !== undefined) {
139
+ body.query_vector = options.queryVector;
140
+ }
141
+ if (options.filters !== undefined) {
142
+ body.filters = options.filters;
143
+ }
144
+ const response = await this.request(`/collections/${encodeURIComponent(collection)}/search`, {
145
+ method: "POST",
146
+ body: JSON.stringify(body),
147
+ });
148
+ const data = (await response.json());
149
+ return {
150
+ total: data.total,
151
+ results: data.results.map((result) => this.mapSearchResult(result)),
152
+ };
153
+ }
154
+ // ------------------------------------------------------------------
155
+ // Admin
156
+ // ------------------------------------------------------------------
157
+ async compact(collection) {
158
+ const response = await this.request(`/admin/collections/${encodeURIComponent(collection)}/compact`, { method: "POST" });
159
+ return this.mapCompactionResult((await response.json()));
160
+ }
161
+ // ------------------------------------------------------------------
162
+ // Base
163
+ // ------------------------------------------------------------------
164
+ async register(username, password) {
165
+ const response = await this.request("/auth/register", {
166
+ method: "POST",
167
+ body: JSON.stringify({ username, password }),
168
+ });
169
+ const data = (await response.json());
170
+ return data.api_key;
171
+ }
172
+ async login(username, password) {
173
+ const response = await this.request("/auth/login", {
174
+ method: "POST",
175
+ body: JSON.stringify({ username, password }),
176
+ });
177
+ const data = (await response.json());
178
+ return data.api_key;
179
+ }
180
+ // ------------------------------------------------------------------
181
+ // Helpers
182
+ // ------------------------------------------------------------------
183
+ mapCollection(collection) {
184
+ return {
185
+ name: collection.name,
186
+ dim: collection.dim,
187
+ docCount: collection.doc_count,
188
+ embModel: collection.emb_model,
189
+ };
190
+ }
191
+ mapCompactionResult(result) {
192
+ return {
193
+ collectionName: result.collection_name,
194
+ vectorsBefore: result.vectors_before,
195
+ liveCount: result.live_count,
196
+ deletedCount: result.deleted_count,
197
+ };
198
+ }
199
+ mapSearchResult(result) {
200
+ return {
201
+ id: result.id,
202
+ score: result.score,
203
+ text: result.text,
204
+ metadata: result.metadata,
205
+ vector: result.vector,
206
+ answer: result.answer,
207
+ };
208
+ }
209
+ async request(path, init = {}) {
210
+ const response = await this.requestRaw(path, init);
211
+ await this.raiseForStatus(response);
212
+ return response;
213
+ }
214
+ async requestRaw(path, init) {
215
+ const controller = new AbortController();
216
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
217
+ try {
218
+ return await this.fetchFn(`${this.baseUrl}${path}`, {
219
+ ...init,
220
+ headers: this.makeHeaders(init.headers),
221
+ signal: controller.signal,
222
+ });
223
+ }
224
+ catch (error) {
225
+ if (error instanceof Error && error.name === "AbortError") {
226
+ throw new CognitorError(`Request timed out after ${this.timeoutMs}ms`);
227
+ }
228
+ throw error;
229
+ }
230
+ finally {
231
+ clearTimeout(timeout);
232
+ }
233
+ }
234
+ makeHeaders(requestHeaders) {
235
+ const headers = new Headers(this.headers);
236
+ if (requestHeaders) {
237
+ const incoming = new Headers(requestHeaders);
238
+ incoming.forEach((value, key) => headers.set(key, value));
239
+ }
240
+ if (!headers.has("Content-Type")) {
241
+ headers.set("Content-Type", "application/json");
242
+ }
243
+ return headers;
244
+ }
245
+ async raiseForStatus(response) {
246
+ if (response.ok) {
247
+ return;
248
+ }
249
+ let message = "";
250
+ try {
251
+ const json = (await response.clone().json());
252
+ message = typeof json.message === "string" ? json.message : "";
253
+ }
254
+ catch {
255
+ // Ignore JSON parsing errors and fall back to text.
256
+ }
257
+ if (!message) {
258
+ message = await response.text();
259
+ }
260
+ const code = response.status;
261
+ if (code === 401) {
262
+ throw new AuthenticationError(message, code);
263
+ }
264
+ if (code === 404) {
265
+ throw new NotFoundError(message, code);
266
+ }
267
+ if (code === 409) {
268
+ throw new ConflictError(message, code);
269
+ }
270
+ if (code === 400 || code === 422) {
271
+ throw new ValidationError(message, code);
272
+ }
273
+ if (code >= 500) {
274
+ throw new ServerError(message, code);
275
+ }
276
+ throw new CognitorError(message, code);
277
+ }
278
+ }
@@ -0,0 +1,19 @@
1
+ export declare class CognitorError extends Error {
2
+ readonly statusCode?: number;
3
+ constructor(message: string, statusCode?: number);
4
+ }
5
+ export declare class AuthenticationError extends CognitorError {
6
+ constructor(message: string, statusCode?: number);
7
+ }
8
+ export declare class NotFoundError extends CognitorError {
9
+ constructor(message: string, statusCode?: number);
10
+ }
11
+ export declare class ConflictError extends CognitorError {
12
+ constructor(message: string, statusCode?: number);
13
+ }
14
+ export declare class ValidationError extends CognitorError {
15
+ constructor(message: string, statusCode?: number);
16
+ }
17
+ export declare class ServerError extends CognitorError {
18
+ constructor(message: string, statusCode?: number);
19
+ }
@@ -0,0 +1,38 @@
1
+ export class CognitorError extends Error {
2
+ statusCode;
3
+ constructor(message, statusCode) {
4
+ super(message);
5
+ this.name = "CognitorError";
6
+ this.statusCode = statusCode;
7
+ }
8
+ }
9
+ export class AuthenticationError extends CognitorError {
10
+ constructor(message, statusCode) {
11
+ super(message, statusCode);
12
+ this.name = "AuthenticationError";
13
+ }
14
+ }
15
+ export class NotFoundError extends CognitorError {
16
+ constructor(message, statusCode) {
17
+ super(message, statusCode);
18
+ this.name = "NotFoundError";
19
+ }
20
+ }
21
+ export class ConflictError extends CognitorError {
22
+ constructor(message, statusCode) {
23
+ super(message, statusCode);
24
+ this.name = "ConflictError";
25
+ }
26
+ }
27
+ export class ValidationError extends CognitorError {
28
+ constructor(message, statusCode) {
29
+ super(message, statusCode);
30
+ this.name = "ValidationError";
31
+ }
32
+ }
33
+ export class ServerError extends CognitorError {
34
+ constructor(message, statusCode) {
35
+ super(message, statusCode);
36
+ this.name = "ServerError";
37
+ }
38
+ }
@@ -0,0 +1,3 @@
1
+ export { Cognitor } from "./client.js";
2
+ export { AuthenticationError, CognitorError, ConflictError, NotFoundError, ServerError, ValidationError, } from "./exceptions.js";
3
+ export type { AnswerPassage, Collection, CompactionResult, Document, ListDocumentsResult, Metadata, SearchResponse, SearchResult, Vector, } from "./models.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { Cognitor } from "./client.js";
2
+ export { AuthenticationError, CognitorError, ConflictError, NotFoundError, ServerError, ValidationError, } from "./exceptions.js";
@@ -0,0 +1,43 @@
1
+ export type Vector = number[];
2
+ export type Metadata = Record<string, unknown>;
3
+ export interface Collection {
4
+ name: string;
5
+ dim: number;
6
+ docCount: number;
7
+ embModel?: string;
8
+ }
9
+ export interface Document {
10
+ id: string;
11
+ vector: Vector;
12
+ text: string;
13
+ metadata: Metadata;
14
+ }
15
+ export interface ListDocumentsResult {
16
+ documents: Document[];
17
+ total: number;
18
+ offset: number;
19
+ limit: number;
20
+ }
21
+ export interface AnswerPassage {
22
+ passage: string;
23
+ start: number;
24
+ end: number;
25
+ }
26
+ export interface SearchResult {
27
+ id: string;
28
+ score: number;
29
+ text: string;
30
+ metadata: Metadata;
31
+ vector?: Vector;
32
+ answer?: AnswerPassage;
33
+ }
34
+ export interface SearchResponse {
35
+ results: SearchResult[];
36
+ total: number;
37
+ }
38
+ export interface CompactionResult {
39
+ collectionName: string;
40
+ vectorsBefore: number;
41
+ liveCount: number;
42
+ deletedCount: number;
43
+ }
package/dist/models.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "cognitor",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for the Cognitor search platform API.",
5
+ "license": "SEE LICENSE IN LICENSE.md",
6
+ "author": "Riccardo Lucato <riccardo@tanaos.com>",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/tanaos/cognitor-typescript.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/tanaos/cognitor-typescript/issues"
28
+ },
29
+ "homepage": "https://github.com/tanaos/cognitor-typescript#readme",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.json",
35
+ "clean": "rm -rf dist",
36
+ "prepublishOnly": "npm run clean && npm run build"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.8.3"
40
+ }
41
+ }