@hivehub/vectorizer-sdk
v3.3.0
Published
TypeScript SDK for Vectorizer - High-performance vector database. Ships the VectorizerRPC binary transport (default in v3.x) plus the legacy REST client.
Readme
Vectorizer TypeScript SDK
High-performance TypeScript SDK for Vectorizer vector database.
Package: @hivehub/vectorizer-sdk
Version: 3.2.0
v3.2 — backpressure-aware client (HTTP 429 + Retry-After)
VectorizerClient now honors server-side bulk-upsert backpressure
introduced in Vectorizer 3.2.0 (#263).
On HTTP 429 the client parses the Retry-After header (seconds form,
1 s default, 30 s cap), sleeps, and retries up to 3 times before
surfacing a typed error. Pre-3.2.0 clients bounced 429s into a
generic 5xx and lost the retry budget.
The same semantics ship in every first-party SDK (Rust, Python,
TypeScript, Go, C#). See tests/retry-after.test.ts for the
contract.
v3.1 — /insert_vectors + stable client-id upserts
insertVectors(collection, vectors, publicKey?)— bulk-insert pre-computed embeddings with caller-supplied vector ids. Skips the embedding pipeline entirely.insert/insertTexts: the requestidis now used verbatim as the storedVector.id(non-chunked) or as<id>#<chunkIndex>(chunked), so re-running the same payload upserts in place.- Chunked vectors expose a flat payload layout (
{content, file_path, chunk_index, parent_id, ...userMetadata}). Legacy nested payloads from ≤ 3.0.x stay readable during the deprecation window.
Client-id contract: non-empty, length ≤ 256, no leading/trailing
whitespace, must not contain #.
v3.0 — VectorizerRPC is the default transport
Starting with v3.0, the recommended transport is VectorizerRPC: a
binary, length-prefixed MessagePack protocol over raw TCP (port 15503
by default). It replaces JSON parsing on the hot path with a single
@msgpack/msgpack decode, removes per-request HTTP framing, and
supports multiplexed call/response on a single long-lived TCP
connection. The spec is at docs/specs/VECTORIZER_RPC.md.
The legacy REST VectorizerClient (over fetch) stays available for
browsers (which can't open raw TCP sockets), ops scripts, and
anything that already targets HTTP.
import { RpcClient } from '@hivehub/vectorizer-sdk';
const client = await RpcClient.connectUrl('vectorizer://127.0.0.1:15503');
await client.hello({ clientName: 'my-app' });
console.log(await client.listCollections());
const hits = await client.searchBasic('docs', 'vector database', 5);
for (const hit of hits) console.log(hit.id, hit.score);
client.close();Switching transports
| Goal | API |
|---|---|
| Default RPC (Node) | await RpcClient.connectUrl('vectorizer://host:15503') |
| Bare host:port (RPC) | await RpcClient.connect('host:15503') |
| Legacy REST | new VectorizerClient({ baseURL: 'http://host:15002' }) |
| Browsers | REST only — vectorizer:// URLs need raw TCP, which browsers don't expose. |
The standalone JavaScript SDK was retired in v3.0. This TypeScript package ships compiled CommonJS + ESM and is fully usable from plain JavaScript projects.
Features
- ✅ VectorizerRPC (default in v3.x): binary, low-latency, multiplexed
- ✅ Complete TypeScript Support: Full type safety and IntelliSense
- ✅ Async/Await: Modern async programming patterns
- ✅ Multiple Transport Protocols: RPC, HTTP/HTTPS, UMICP support
- ✅ HTTP Client: Native fetch-based HTTP client with robust error handling
- ✅ UMICP Protocol: High-performance protocol with compression and encryption
- ✅ Comprehensive Validation: Input validation and error handling
- ✅ 12 Custom Exceptions: Robust error management
- ✅ Logging: Configurable logging system
- ✅ Collection Management: CRUD operations for collections
- ✅ Vector Operations: Insert, search, update, delete vectors
- ✅ Semantic Search: Text and vector similarity search
- ✅ Intelligent Search: AI-powered search with query expansion, MMR diversification, and domain expansion
- ✅ Semantic Search: Advanced semantic search with reranking and similarity thresholds
- ✅ Contextual Search: Context-aware search with metadata filtering
- ✅ Multi-Collection Search: Cross-collection search with intelligent aggregation
- ✅ Hybrid Search: Combine dense and sparse vectors for improved search quality
- ✅ Discovery Operations: Collection filtering, query expansion, and intelligent discovery
- ✅ File Operations: File content retrieval, chunking, project outlines, and related files
- ✅ Graph Relationships: Automatic relationship discovery, path finding, and edge management
- ✅ Summarization: Text and context summarization with multiple methods
- ✅ Workspace Management: Multi-workspace support for project organization
- ✅ Backup & Restore: Collection backup and restore operations
- ✅ Batch Operations: Efficient bulk insert, update, delete, and search
- ✅ Qdrant Compatibility: Full Qdrant 1.14.x REST API compatibility for easy migration
- Snapshots API (create, list, delete, recover)
- Sharding API (create shard keys, distribute data)
- Cluster Management API (status, recovery, peer management, metadata)
- Query API (query, batch query, grouped queries with prefetch)
- Search Groups and Matrix API (grouped results, similarity matrices)
- Named Vectors support (partial)
- Quantization configuration (PQ and Binary)
- ✅ Embedding Generation: Text embedding support
Installation
npm install @hivehub/vectorizer-sdk
# Or specific version
npm install @hivehub/[email protected]Quick Start
import { VectorizerClient } from "@hivehub/vectorizer-sdk";
// Create client
const client = new VectorizerClient({
baseURL: "http://localhost:15002",
apiKey: "your-api-key-here",
});Package layout (per-surface clients)
VectorizerClient is a facade that mixes in nine per-surface clients —
each one is also exported standalone if you only need a slice of the
API:
src/client/
├── _base.ts BaseClient + Transport interface (shared plumbing)
├── core.ts CoreClient — health, stats, embed
├── collections.ts CollectionsClient — list / get / create / update / delete
├── vectors.ts VectorsClient — single + batch vector ops
├── search.ts SearchClient — vector / text / intelligent / hybrid
├── discovery.ts DiscoveryClient — discover / filter / score / expand
├── files.ts FilesClient — file content + uploads
├── graph.ts GraphClient — nodes / edges / paths
├── qdrant.ts QdrantClient — Qdrant 1.14 compatibility
├── admin.ts AdminClient — dashboard / workspace / backups
└── index.ts VectorizerClient facade (mixes all surfaces in)Per-surface usage when you want a smaller import:
import { SearchClient } from "@hivehub/vectorizer-sdk";
const search = new SearchClient({ baseURL: "http://localhost:15002" });
const results = await search.searchVectors("documents", { query_vector: [...], limit: 5 });The _base.Transport interface is the seam the upcoming RPC client
(phase6_sdk-typescript-rpc) plugs into — every per-surface client
calls Transport methods, never fetch directly. Browser builds keep
the REST Transport; Node / Deno / Bun builds will expose the new
RpcTransport over the canonical vectorizer://host:15503 URL scheme
as the default.
// Test / RPC-readiness regression guard:
class MockTransport implements Transport { /* ... */ }
const client = new VectorizerClient({ transport: new MockTransport() });
// Health check
const health = await client.healthCheck();
console.log("Server status:", health.status);
// Create collection
const collection = await client.createCollection({
name: "documents",
dimension: 768,
similarity_metric: "cosine",
});
// Insert vectors
const vectors = [
{
data: [0.1, 0.2, 0.3 /* ... 768 dimensions */],
metadata: { source: "document1.pdf" },
},
];
await client.insertVectors("documents", vectors);
// Search vectors
const results = await client.searchVectors("documents", {
query_vector: [0.1, 0.2, 0.3 /* ... 768 dimensions */],
limit: 5,
});
// Text search
const textResults = await client.searchText("documents", {
query: "machine learning algorithms",
limit: 5,
});
// Generate embeddings
const embedding = await client.embedText({
text: "machine learning algorithms",
});
// Hybrid search (dense + sparse vectors)
const hybridResults = await client.hybridSearch({
collection: "documents",
query: "machine learning",
query_sparse: {
indices: [0, 5, 10, 15],
values: [0.8, 0.6, 0.9, 0.7],
},
alpha: 0.7,
algorithm: "rrf",
dense_k: 20,
sparse_k: 20,
final_k: 10,
});
// Graph Operations (requires graph enabled in collection config)
// List all graph nodes
const nodes = await client.listGraphNodes("documents");
console.log(`Graph has ${nodes.count} nodes`);
// Get neighbors of a node
const neighbors = await client.getGraphNeighbors("documents", "document1");
console.log(`Node has ${neighbors.neighbors.length} neighbors`);
// Find related nodes within 2 hops
const related = await client.findRelatedNodes("documents", "document1", {
max_hops: 2,
relationship_type: "SIMILAR_TO",
});
console.log(`Found ${related.related.length} related nodes`);
// Find shortest path between two nodes
const path = await client.findGraphPath({
collection: "documents",
source: "document1",
target: "document2",
});
if (path.found) {
console.log(`Path found: ${path.path.map(n => n.id).join(" -> ")}`);
}
// Create explicit relationship
const edge = await client.createGraphEdge({
collection: "documents",
source: "document1",
target: "document2",
relationship_type: "REFERENCES",
weight: 0.9,
});
console.log(`Created edge: ${edge.edge_id}`);
// Discover SIMILAR_TO edges for entire collection
const discoveryResult = await client.discoverGraphEdges("documents", {
similarity_threshold: 0.7,
max_per_node: 10,
});
console.log(`Discovered ${discoveryResult.edges_created} edges`);
// Discover edges for a specific node
const nodeDiscovery = await client.discoverGraphEdgesForNode(
"documents",
"document1",
{
similarity_threshold: 0.7,
max_per_node: 10,
}
);
console.log(`Discovered ${nodeDiscovery.edges_created} edges for node`);
// Get discovery status
const status = await client.getGraphDiscoveryStatus("documents");
console.log(
`Discovery status: ${status.total_nodes} nodes, ` +
`${status.total_edges} edges, ` +
`${status.progress_percentage.toFixed(1)}% complete`
);
// Qdrant-compatible API usage
const qdrantCollections = await client.qdrantListCollections();
const qdrantResults = await client.qdrantSearchPoints(
"documents",
embedding.embedding,
10
);Configuration
HTTP Configuration (Default)
const client = new VectorizerClient({
baseURL: "http://localhost:15002", // API base URL
apiKey: "your-api-key", // API key for authentication
timeout: 30000, // Request timeout in ms
headers: {
// Custom headers
"User-Agent": "MyApp/1.0",
},
logger: {
// Logger configuration
level: "info", // debug, info, warn, error
enabled: true,
},
});UMICP Configuration (High Performance)
UMICP (Universal Messaging and Inter-process Communication Protocol) provides significant performance benefits:
- Automatic Compression: GZIP, DEFLATE, or LZ4 compression for large payloads
- Built-in Encryption: Optional encryption for secure communication
- Lower Latency: Optimized binary protocol with checksums
- Request Validation: Automatic request/response validation
Using Connection String
const client = new VectorizerClient({
connectionString: "umicp://localhost:15003",
apiKey: "your-api-key",
});Using Explicit Configuration
const client = new VectorizerClient({
protocol: "umicp",
apiKey: "your-api-key",
umicp: {
host: "localhost",
port: 15003,
compression: "gzip", // 'gzip', 'deflate', 'lz4', or 'none'
encryption: true, // Enable encryption
priority: "normal", // 'low', 'normal', 'high'
},
});When to Use UMICP
Use UMICP when:
- Large Payloads: Inserting or searching large batches of vectors
- High Throughput: Need maximum performance for production workloads
- Secure Communication: Require encryption without TLS overhead
- Low Latency: Need minimal protocol overhead
Use HTTP when:
- Development: Quick testing and debugging
- Firewall Restrictions: Only HTTP/HTTPS allowed
- Simple Deployments: No need for custom protocol setup
Protocol Comparison
| Feature | HTTP/HTTPS | UMICP | | ----------- | -------------------- | ---------------------------- | | Compression | Manual (gzip header) | Automatic (GZIP/DEFLATE/LZ4) | | Encryption | TLS required | Built-in optional | | Latency | Standard | Lower | | Firewall | Widely supported | May require configuration | | Debugging | Easy (browser tools) | Requires UMICP tools |
Master/Slave Configuration (Read/Write Separation)
Vectorizer supports Master-Replica replication for high availability and read scaling. The SDK provides automatic routing - writes go to master, reads are distributed across replicas.
Basic Setup
import { VectorizerClient } from "@hivehub/vectorizer-sdk";
// Configure with master and replicas - SDK handles routing automatically
const client = new VectorizerClient({
hosts: {
master: "http://master-node:15002",
replicas: ["http://replica1:15002", "http://replica2:15002"],
},
apiKey: "your-api-key",
readPreference: "replica", // "master" | "replica" | "nearest"
});
// Writes automatically go to master
await client.createCollection({
name: "documents",
dimension: 768,
similarity_metric: "cosine",
});
await client.insertTexts("documents", [
{ id: "doc1", text: "Sample document", metadata: { source: "api" } },
]);
// Reads automatically go to replicas (load balanced)
const results = await client.searchVectors("documents", {
query: "sample",
limit: 10,
});
const collections = await client.listCollections();Read Preferences
| Preference | Description | Use Case |
|------------|-------------|----------|
| "replica" | Route reads to replicas (round-robin) | Default for high read throughput |
| "master" | Route all reads to master | When you need read-your-writes consistency |
| "nearest" | Route to the node with lowest latency | Geo-distributed deployments |
Read-Your-Writes Consistency
For operations that need to immediately read what was just written:
// Option 1: Override read preference for specific operation
await client.insertTexts("docs", [newDoc]);
const result = await client.getVector("docs", newDoc.id, { readPreference: "master" });
// Option 2: Use a transaction-like pattern
const result = await client.withMaster(async (masterClient) => {
await masterClient.insertTexts("docs", [newDoc]);
return await masterClient.getVector("docs", newDoc.id);
});Automatic Operation Routing
The SDK automatically classifies operations:
| Operation Type | Routed To | Methods |
|---------------|-----------|---------|
| Writes | Always Master | insertTexts, insertVectors, updateVector, deleteVector, createCollection, deleteCollection |
| Reads | Based on readPreference | searchVectors, getVector, listCollections, intelligentSearch, semanticSearch, hybridSearch |
Standalone Mode (Single Node)
For development or single-node deployments:
// Single node - no replication
const client = new VectorizerClient({
baseURL: "http://localhost:15002",
apiKey: "your-api-key",
});API Reference
Collection Management
// List collections
const collections = await client.listCollections();
// Get collection info
const info = await client.getCollection("documents");
// Create collection
const collection = await client.createCollection({
name: "documents",
dimension: 768,
similarity_metric: "cosine",
description: "Document embeddings",
});
// Update collection
const updated = await client.updateCollection("documents", {
description: "Updated description",
});
// Delete collection
await client.deleteCollection("documents");Vector Operations
// Insert vectors
const vectors = [
{
data: [0.1, 0.2, 0.3],
metadata: { source: "doc1.pdf" },
},
];
await client.insertVectors("documents", vectors);
// Get vector
const vector = await client.getVector("documents", "vector-id");
// Update vector
const updated = await client.updateVector("documents", "vector-id", {
metadata: { updated: true },
});
// Delete vector
await client.deleteVector("documents", "vector-id");
// Delete multiple vectors — returns DeleteReport with per-id status.
const deleteReport = await client.deleteVectors("documents", [
"id1",
"id2",
"id3",
]);
console.log(`deleted=${deleteReport.deleted} failed=${deleteReport.failed}`);
// Tier demotion: move vectors between collections without re-embedding
// (issue #265). The server inserts into `dst` BEFORE deleting from
// `src`, so a mid-batch crash leaves a recoverable duplicate, never
// data loss. Per-id outcomes (`ok | missing_in_src |
// dst_insert_failed | src_delete_failed`) populate `results` without
// aborting the batch.
const moveReport = await client.moveToCollection("hot", "warm", [
"vec-1",
"vec-2",
]);
for (const row of moveReport.results) {
if (row.status !== "ok") {
console.warn("move failed", row);
}
}Control surface (3.4)
Admin / observability
const client = new VectorizerClient({ baseURL: "http://localhost:15002" });
// Server health, uptime, collection/vector counts
const stats = await client.getStats();
console.log("Total vectors:", stats.total_vectors);
const status = await client.getStatus();
console.log(`Server v${status.version}, uptime: ${status.uptime}s`);
// Recent logs
const logs = await client.getLogs({ lines: 50, level: "INFO" });
for (const entry of logs) {
console.log(`${entry.timestamp}: ${entry.message}`);
}
// Per-collection indexing progress
const progress = await client.getIndexingProgress();
for (const [collection, pct] of Object.entries(progress.progress)) {
console.log(`${collection}: ${pct.toFixed(1)}% complete`);
}
// Force flush one collection
await client.forceSaveCollection("my_docs");
// List and clean empty collections
const empty = await client.listEmptyCollections();
if (empty.length > 0) {
const report = await client.cleanupEmptyCollections();
console.log(`Cleaned up ${report.deleted} empty collections`);
}
// List workspaces
const workspaces = await client.listWorkspaces();
console.log("Workspaces:", workspaces);Auth
const client = new VectorizerClient({ baseURL: "http://localhost:15002" });
// Current user info
const user = await client.me();
console.log(`Logged in as: ${user.username} (roles: ${user.roles.join(", ")})`);
// Refresh token with extended TTL
const token = await client.refreshToken();
console.log(`Token refreshed, expires in: ${token.expires_in} seconds`);
// Validate password before creating account
const report = await client.validatePassword("MySecure123!");
console.log(`Valid: ${report.valid}, feedback: ${report.feedback.join(", ")}`);
// Create API key for programmatic access
const apiKey = await client.createApiKey({
name: "integration-key",
expires_in: 86400 * 365, // 1 year
});
console.log("API Key:", apiKey.api_key);
// List and revoke API keys
const keys = await client.listApiKeys();
for (const key of keys) {
console.log(`Key: ${key.id} (expires: ${key.expires_at})`);
}
await client.revokeApiKey(keys[0].id);
// Change password
await client.changePassword("newPassword123!");
// Logout
await client.logout();Replication
const client = new VectorizerClient({ baseURL: "http://localhost:15002" });
// Check replication role and status
const status = await client.getReplicationStatus();
console.log(`Role: ${status.role}, enabled: ${status.enabled}`);
// Get replication statistics (lag, bytes synced)
const stats = await client.getReplicationStats();
console.log(`Bytes synced: ${stats.bytes_synced}`);
// List all replicas connected to this master
const replicas = await client.listReplicas();
for (const replica of replicas) {
console.log(`Replica: ${replica.address} (lag: ${replica.lag_ms}ms)`);
}Discovery pipeline
The discovery pipeline chains six stages from broad search to final LLM-ready prompt:
const client = new VectorizerClient({ baseURL: "http://localhost:15002" });
// Stage 1: Broad discovery — multi-query search across all collections
const broad = await client.broadDiscovery({
query: "machine learning algorithms",
max_results: 20,
});
console.log(`Found ${broad.results.length} broad results`);
// Stage 2: Semantic focus — narrow search to top collection
const focused = await client.semanticFocus({
query: "neural networks",
collection: "research",
max_results: 10,
});
console.log(`Focused results: ${focused.results.length}`);
// Stage 3: Promote README — elevate high-quality chunks
const promoted = await client.promoteReadme({
results: focused.results,
readme_boost: 2.0,
});
// Stage 4: Compress evidence — distill to bullet points
const bullets = await client.compressEvidence({
chunks: promoted.results,
max_bullets: 15,
});
console.log("Evidence bullets:", bullets.bullets);
// Stage 5: Build answer plan — organize bullets into sections
const plan = await client.buildAnswerPlan({
evidence: bullets.bullets,
max_sections: 5,
});
console.log("Sections:", plan.sections);
// Stage 6: Render LLM prompt — final markdown string for LLM
const llmPrompt = await client.renderLlmPrompt({
plan,
style: "formal",
});
console.log("LLM prompt:\n", llmPrompt.markdown);Hub backups
const client = new VectorizerClient({ baseURL: "http://localhost:15002" });
const userId = "user-123";
// List user's backups
const backups = await client.listUserBackups(userId);
for (const backup of backups) {
console.log(`Backup: ${backup.id} (size: ${backup.size_bytes} bytes)`);
}
// Create a new backup
const newBackup = await client.createUserBackup({
user_id: userId,
name: "full-backup-2024-01",
description: "January full backup",
collections: undefined, // backup all
});
console.log("Created backup:", newBackup.id);
// Restore a backup
await client.restoreUserBackup({
user_id: userId,
backup_id: newBackup.id,
});
console.log("Restore started");
// Delete old backup
await client.deleteUserBackup(userId, backups[0].id);Search Operations
// Vector similarity search
const results = await client.searchVectors("documents", {
query_vector: [0.1, 0.2, 0.3],
limit: 10,
threshold: 0.8,
include_metadata: true,
});
// Text semantic search
const textResults = await client.searchText("documents", {
query: "machine learning",
limit: 10,
threshold: 0.8,
include_metadata: true,
model: "bert-base",
});Advanced Search Operations
Intelligent Search
AI-powered search with query expansion, MMR diversification, and domain expansion:
const results = await client.intelligentSearch({
query: "machine learning algorithms",
collections: ["documents", "research"],
max_results: 15,
domain_expansion: true,
technical_focus: true,
mmr_enabled: true,
mmr_lambda: 0.7,
});Semantic Search
Advanced semantic search with reranking and similarity thresholds:
const results = await client.semanticSearch({
query: "neural networks",
collection: "documents",
max_results: 10,
semantic_reranking: true,
similarity_threshold: 0.6,
});Contextual Search
Context-aware search with metadata filtering:
const results = await client.contextualSearch({
query: "API documentation",
collection: "docs",
context_filters: {
category: "backend",
language: "typescript",
},
max_results: 10,
});Multi-Collection Search
Cross-collection search with intelligent aggregation:
const results = await client.multiCollectionSearch({
query: "authentication",
collections: ["docs", "code", "tickets"],
max_total_results: 20,
max_per_collection: 5,
cross_collection_reranking: true,
});Discovery Operations
Filter Collections
Filter collections based on query relevance:
const filtered = await client.filterCollections({
query: "machine learning",
min_score: 0.5,
});Expand Queries
Expand queries with related terms:
const expanded = await client.expandQueries({
query: "neural networks",
max_expansions: 5,
});Discover
Intelligent discovery across collections:
const discovery = await client.discover({
query: "authentication methods",
max_results: 10,
});File Operations
Get File Content
Retrieve file content from collection:
const content = await client.getFileContent({
collection: "docs",
file_path: "src/client.ts",
});List Files
List all files in a collection:
const files = await client.listFilesInCollection({
collection: "docs",
});Get File Chunks
Get ordered chunks of a file:
const chunks = await client.getFileChunksOrdered({
collection: "docs",
file_path: "README.md",
chunk_size: 1000,
});Get Project Outline
Get project structure outline:
const outline = await client.getProjectOutline({
collection: "codebase",
});Get Related Files
Find files related to a specific file:
const related = await client.getRelatedFiles({
collection: "codebase",
file_path: "src/client.ts",
max_results: 5,
});Summarization Operations
Summarize Text
Summarize text using various methods:
const summary = await client.summarizeText({
text: "Long document text...",
method: "extractive", // 'extractive', 'abstractive', 'hybrid'
max_length: 200,
});Summarize Context
Summarize context with metadata:
const summary = await client.summarizeContext({
context: "Document context...",
method: "abstractive",
focus: "key_points",
});Workspace Management
Add Workspace
Add a new workspace:
await client.addWorkspace({
name: "my-project",
path: "/path/to/project",
});List Workspaces
List all workspaces:
const workspaces = await client.listWorkspaces();Remove Workspace
Remove a workspace:
await client.removeWorkspace({
name: "my-project",
});Backup Operations
Create Backup
Create a backup of collections:
const backup = await client.createBackup({
name: "backup-2024-11-24",
});List Backups
List all available backups:
const backups = await client.listBackups();Restore Backup
Restore from a backup:
await client.restoreBackup({
filename: "backup-2024-11-24.vecdb",
});Embedding Operations
// Generate embeddings
const embedding = await client.embedText({
text: "machine learning algorithms",
model: "bert-base",
parameters: {
max_length: 512,
normalize: true,
},
});Error Handling
import {
VectorizerError,
AuthenticationError,
CollectionNotFoundError,
ValidationError,
NetworkError,
ServerError,
} from "@hivehub/vectorizer-sdk";
try {
await client.createCollection({
name: "documents",
dimension: 768,
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Authentication failed:", error.message);
} else if (error instanceof ValidationError) {
console.error("Validation error:", error.message);
} else if (error instanceof NetworkError) {
console.error("Network error:", error.message);
} else {
console.error("Unknown error:", error.message);
}
}Types
// Vector types
interface Vector {
id: string;
data: number[];
metadata?: Record<string, unknown>;
}
// Collection types
interface Collection {
name: string;
dimension: number;
similarity_metric: "cosine" | "euclidean" | "dot_product";
description?: string;
created_at?: Date;
updated_at?: Date;
}
// Search result types
interface SearchResult {
id: string;
score: number;
data: number[];
metadata?: Record<string, unknown>;
}
// Client configuration
interface VectorizerClientConfig {
baseURL?: string;
wsURL?: string;
apiKey?: string;
timeout?: number;
headers?: Record<string, string>;
logger?: LoggerConfig;
}Development
# Install dependencies
npm install
# Build
npm run build
# Watch mode
npm run build:watch
# Test
npm test
# Test with coverage
npm run test:coverage
# Lint
npm run lint
# Lint and fix
npm run lint:fixLicense
MIT License - see LICENSE for details.
