TypeScript SDK
Vectors

Vectors

The vector proxy provides semantic search and vector storage through HiveForge's managed vector database. Store documents as embeddings and search them using natural language queries, all without managing vector infrastructure or API keys.

Access the vector proxy via hiveforge.vectors.

import { HiveForgeClient } from '@producthacker/hiveforge-sdk';
 
const hiveforge = new HiveForgeClient({
  deploymentId: process.env.HIVEFORGE_DEPLOYMENT_ID!,
  deploymentSecret: process.env.HIVEFORGE_DEPLOYMENT_SECRET!,
});
await hiveforge.initialize();

Methods


upsert(options)

Insert or update vectors in the database. You can provide raw text (automatically embedded by HiveForge) or pre-computed embedding values.

// Upsert with text (auto-embedded)
const result = await hiveforge.vectors.upsert({
  vectors: [
    {
      id: 'doc-1',
      text: 'How to reset your password: Go to Settings > Security > Reset Password.',
      metadata: { category: 'auth', source: 'help-center' },
    },
    {
      id: 'doc-2',
      text: 'Updating payment methods: Navigate to Billing > Payment Methods.',
      metadata: { category: 'billing', source: 'help-center' },
    },
    {
      id: 'doc-3',
      text: 'Enabling two-factor authentication for enhanced account security.',
      metadata: { category: 'auth', source: 'help-center' },
    },
  ],
  namespace: 'help-articles',
});
 
console.log(`Upserted: ${result.upsertedCount} vectors`);
console.log(`Credits used: ${result.creditsUsed}`);
console.log(`Credits remaining: ${result.creditsRemaining}`);

With pre-computed embeddings:

// If you already have embedding values (1536 dimensions for text-embedding-3-small)
await hiveforge.vectors.upsert({
  vectors: [
    {
      id: 'vec-1',
      values: [0.0123, -0.0456, 0.0789, /* ... 1536 dimensions */],
      metadata: { source: 'custom-pipeline' },
    },
  ],
  namespace: 'custom-embeddings',
});

Parameters (VectorUpsertOptions):

ParameterTypeRequiredDescription
vectorsVectorData[]YesVectors to insert or update
namespacestringNoNamespace to upsert into (for logical separation)

VectorData type:

FieldTypeRequiredDescription
idstringYesUnique identifier for this vector
textstringNoText content (auto-embedded by HiveForge)
valuesnumber[]NoPre-computed embedding values
metadataRecord<string, unknown>NoMetadata stored alongside the vector

Provide either text or values for each vector. When text is provided, HiveForge automatically generates the embedding using text-embedding-3-small (1536 dimensions). Credits are charged per 100 vectors, rounded up.

Returns (VectorUpsertResponse):

FieldTypeDescription
successbooleanWhether the upsert succeeded
upsertedCountnumberNumber of vectors upserted
creditsUsednumberCredits consumed
creditsRemainingnumberRemaining credits
Equivalent curl request
curl -X POST https://api.hiveforge.dev/api/v1/proxy/vectors/upsert \
  -H "Content-Type: application/json" \
  -H "X-Deployment-ID: d9f2a1b4-7c3e-4f8a-b5d6-1e2f3a4b5c6d" \
  -H "X-Deployment-Secret: sk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" \
  -d '{
    "vectors": [
      {"id": "doc-1", "text": "How to reset your password", "metadata": {"category": "auth"}}
    ],
    "namespace": "help-articles"
  }'

search(options)

Search for similar vectors using a natural language query. The query is automatically embedded and compared against stored vectors.

const results = await hiveforge.vectors.search({
  query: 'How do I change my password?',
  namespace: 'help-articles',
  topK: 5,
  includeMetadata: true,
});
 
console.log(`Found ${results.matches.length} matches`);
for (const match of results.matches) {
  console.log(`  [${match.score.toFixed(3)}] ${match.id}`);
  console.log(`    Category: ${match.metadata?.category}`);
}
console.log(`Credits used: ${results.creditsUsed}`);

With metadata filtering:

const results = await hiveforge.vectors.search({
  query: 'security settings',
  namespace: 'help-articles',
  topK: 10,
  filter: {
    category: 'auth',
  },
});

Parameters (VectorSearchOptions):

ParameterTypeRequiredDefaultDescription
querystringYes--Natural language search query
namespacestringNo--Namespace to search in
topKnumberNo10Number of results (1-100)
filterRecord<string, unknown>No--Metadata filter (MongoDB-style)
includeMetadatabooleanNotrueInclude metadata in results

Returns (VectorSearchResponse):

FieldTypeDescription
successbooleanWhether the search succeeded
matchesVectorMatch[]Matching vectors sorted by similarity
creditsUsednumberCredits consumed
creditsRemainingnumberRemaining credits

VectorMatch type:

FieldTypeDescription
idstringVector ID
scorenumberSimilarity score (0-1, higher is more similar)
metadataRecord<string, unknown>Associated metadata (if includeMetadata is true)

delete(options)

Delete vectors from the database. Delete operations do not consume credits.

// Delete specific vectors
await hiveforge.vectors.delete({
  ids: ['doc-1', 'doc-2'],
  namespace: 'help-articles',
});
 
// Delete all vectors in a namespace
await hiveforge.vectors.delete({
  namespace: 'help-articles',
  deleteAll: true,
});

Parameters (VectorDeleteOptions):

ParameterTypeRequiredDescription
idsstring[]NoSpecific vector IDs to delete
namespacestringNoNamespace to delete from
deleteAllbooleanNoDelete all vectors in the namespace
⚠️

Setting deleteAll: true permanently removes all vectors in the specified namespace. This cannot be undone.

Returns (VectorDeleteResponse):

FieldTypeDescription
successbooleanWhether the delete succeeded
deletednumber | stringNumber of vectors deleted (or 'all')

getQuota()

Get vector operation quota for your deployment.

const quota = await hiveforge.vectors.getQuota();
 
console.log(`Credits available: ${quota.creditsAvailable}`);
console.log(`Credits per search: ${quota.creditsPerSearch}`);
console.log(`Credits per upsert batch: ${quota.creditsPerUpsertBatch}`);
console.log(`Searches available: ${quota.searchesAvailable}`);
console.log(`Period ends: ${quota.periodEnds}`);

Returns (VectorQuotaResponse):

FieldTypeDescription
creditsAvailablenumberTotal credits available
creditsPerSearchnumberCredit cost per search query
creditsPerUpsertBatchnumberCredit cost per 100 vectors upserted
searchesAvailablenumberNumber of searches remaining
periodEndsstringOptional ISO timestamp for period end

Error Handling

import { VectorProxyException } from '@producthacker/hiveforge-sdk';
 
try {
  await hiveforge.vectors.search({
    query: 'password reset',
    namespace: 'help-articles',
  });
} catch (error) {
  if (error instanceof VectorProxyException) {
    console.error(`Vector error [${error.code}]: ${error.message}`);
 
    if (error.creditsRequired !== undefined) {
      console.log(`Credits required: ${error.creditsRequired}`);
      console.log(`Credits available: ${error.creditsAvailable}`);
    }
  }
}

Types

import type {
  VectorData,
  VectorSearchOptions,
  VectorMatch,
  VectorSearchResponse,
  VectorUpsertOptions,
  VectorUpsertResponse,
  VectorDeleteOptions,
  VectorDeleteResponse,
  VectorQuotaResponse,
  VectorProxyError,
} from '@producthacker/hiveforge-sdk';

Full Example: RAG Knowledge Base

import { HiveForgeClient } from '@producthacker/hiveforge-sdk';
 
const hiveforge = new HiveForgeClient({
  deploymentId: process.env.HIVEFORGE_DEPLOYMENT_ID!,
  deploymentSecret: process.env.HIVEFORGE_DEPLOYMENT_SECRET!,
});
await hiveforge.initialize();
 
// Step 1: Index your documents
async function indexDocuments(docs: Array<{ id: string; content: string; title: string }>) {
  await hiveforge.vectors.upsert({
    vectors: docs.map(doc => ({
      id: doc.id,
      text: doc.content,
      metadata: { title: doc.title },
    })),
    namespace: 'knowledge-base',
  });
}
 
// Step 2: Search and generate an answer using RAG
async function answerQuestion(question: string): Promise<string> {
  // Find relevant documents
  const results = await hiveforge.vectors.search({
    query: question,
    namespace: 'knowledge-base',
    topK: 3,
  });
 
  // Build context from top matches
  const context = results.matches
    .map(m => `[${m.metadata?.title}]: ${m.id}`)
    .join('\n');
 
  // Generate answer using AI proxy with retrieved context
  const response = await hiveforge.ai.complete({
    messages: [
      {
        role: 'system',
        content: `Answer the user's question using only the following context:\n\n${context}`,
      },
      { role: 'user', content: question },
    ],
  });
 
  return response.content;
}