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7B,wEAAwE;CACxE,wBAAwB;CACxB,6BAA6B;CAC7B,gDAAgD;CAChD,wCAAwC;CACxC,oDAAoD;CACpD,YAAY;CACZ,UAAU;CACV,QAAQ;CAER,sBAAsB;CACtB,MAAM;CAEN,oDAAoD;CACpD,oDAAoD;CACpD,oDAAoD;CACpD,+BAA+B;CAC/B,8BAA8B;CAC9B,gBAAgB;CAChB,SAAS;CACT,qCAAqC;CACrC,MAAM;CAEN,6DAA6D;CAC7D,2EAA2E;CAC3E,uCAAuC;CACvC,mCAAmC;CACnC,iBAAiB;CACjB,kBAAkB;CAClB,YAAY;CACZ,gDAAgD;CAChD,0DAA0D;CAC1D,8DAA8D;CAC9D,4DAA4D;CAC5D,YAAY;CACZ,mCAAmC;CACnC,wBAAwB;CACxB,mCAAmC;CACnC,4BAA4B;CAC5B,QAAQ;CAER,sCAAsC;CACtC,4FAA4F;CAC5F,MAAM;CAEN,QAAQ;CACR,OAAO;CACP,oHAAoH;CACpH,QAAQ;CACR,wHAAwH;CACxH,6DAA6D;CAC7D,+BAA+B;CAC/B,4BAA4B;CAC5B,wBAAwB;CACxB,yDAAyD;CACzD,UAAU;CACV,mCAAmC;CACnC,4BAA4B;CAC5B,QAAQ;CACR,iEAAiE;CACjE,2EAA2E;CAC3E,MAAM;CAEN,qFAAqF;CACrF,yEAAyE;CACzE,sGAAsG;CACtG,wBAAwB;CACxB,uDAAuD;CACvD,gCAAgC;CAChC,0DAA0D;CAC1D,UAAU;CACV,2BAA2B;CAC3B,eAAe;CACf,wDAAwD;CACxD,gCAAgC;CAChC,sDAAsD;CACtD,UAAU;CACV,uBAAuB;CACvB,QAAQ;CACR,MAAM;CACN,IAAI;;;;","sources":["src/index.ts","src/algorithm/index.ts","src/algorithm/apply.ts","src/utils/index.ts","src/constants/index.ts","src/algorithm/blueprint.ts","src/algorithm/signals.ts","src/algorithm/library.ts","src/firstbatch.ts","src/api/index.ts","src/api/firstbatch.ts","src/lossy/scalar/index.ts","src/integrations/index.ts","src/integrations/pinecone.ts","src/integrations/base.ts","src/integrations/typesense.ts","src/integrations/weaviate.ts","src/integrations/supabase.ts"],"sourcesContent":["export {Signals} from './algorithm/';\nexport {FirstBatch} from './firstbatch';\nexport {Pinecone, Weaviate} from './integrations';\nexport type {FirstBatchConfig, Signal} from './types';\n","export * from './apply';\nexport * from './blueprint';\nexport * from './signals';\nexport * from './library';\n","import {maximalMarginalRelevance, applyThreshold} from '../utils';\nimport type {BatchType, DistanceMetric, Query, QueryMetadata, QueryResult} from '../types';\n\nexport function applyAlgorithm(\n  results: QueryResult[][],\n  queries: Query[],\n  batchType: BatchType,\n  options: {\n    removeDuplicates: boolean;\n    applyThreshold: number;\n    applyMMR: boolean;\n    distanceMetric: DistanceMetric;\n    // shuffle?: boolean; // enabled by default until further changes\n  }\n): [string[], QueryMetadata[]] {\n  // TODO: can we do this in a better way?\n  if (batchType === 'personalized') {\n    batchType = 'random';\n  }\n  if (results.length !== queries.length) {\n    throw new Error('Number of results is not equal to number of queries');\n  }\n\n  // apply threshold to query results\n  // not done for random batch\n  if (batchType !== 'random' && options.applyThreshold) {\n    results = results.map(r => {\n      return applyThreshold(r, options.applyThreshold ?? 0, options.distanceMetric);\n    });\n  }\n\n  // apply maximal marginal relevance\n  // not done for biased batch\n  if (batchType !== 'biased' && options.applyMMR) {\n    results = results.map((r, i) =>\n      // TODO: move 0.5 to constants\n      maximalMarginalRelevance(queries[i].embedding, r, 0.5, queries[i].top_k_mmr)\n    );\n  }\n\n  // filter duplicates\n  if (options.removeDuplicates && results.length !== 0) {\n    // FIXME: refactor / analyze this, could be wrong\n    const ids = results.flat().map(r => r.id);\n    const uniqueIds = new Set<string>(ids).keys();\n    const idx: number[] = [];\n    for (const uniqueId of uniqueIds) {\n      idx.push(ids.indexOf(uniqueId));\n    }\n\n    results.forEach(result => {\n      result = idx.map(i => result[i]);\n    });\n  }\n\n  // sort w.r.t scores\n  results.forEach(result => {\n    result.sort((a, b) => (a.score && b.score ? b.score - a.score : 1));\n  });\n\n  // get ids and metadata from each result, topK many\n  let ids: string[] = [];\n  let metadatas: QueryMetadata[] = [];\n  results.forEach((result, i) => {\n    const k = queries[i].top_k;\n\n    // FIXME: why do we have `undefined` here sometimes? we shouldnt have\n    // to do this filtering everytime\n    ids = ids.concat(\n      result\n        .slice(0, k)\n        .map(r => r.id)\n        .filter(r => r !== undefined)\n    );\n    metadatas = metadatas.concat(\n      result\n        .slice(0, k)\n        .map(r => r.metadata)\n        .filter(r => r !== undefined)\n    );\n  });\n\n  // NOTE: this used to be optional, but we now have it on by default\n  // shuffled indices via Schwartzian transform; works better for smaller arrays than Fisher-Yates\n  const idx = Array.from({length: ids.length}, (_, i) => ({i, sort: Math.random()}))\n    .sort((a, b) => a.sort - b.sort)\n    .map(({i}) => i);\n\n  ids = ids.map((_, i, self) => self[idx[i]]);\n  metadatas = metadatas.map((_, i, self) => self[idx[i]]);\n\n  return [ids, metadatas];\n}\n","import type {QueryResult, Query, Vector, DistanceMetric} from '../types';\nimport {divide, index, matrix, mean, Matrix, multiply, norm, range} from 'mathjs';\nimport constants from '../constants';\n\nfunction getRow(matrix: Matrix, ind: number): Matrix {\n  return matrix.subset(index(ind, range(0, matrix.size()[1])));\n}\n\nfunction argsort(mat: Matrix): number[] {\n  const array2D: number[][] = matrix(mat).toArray() as number[][];\n  const indices: number[] = array2D.map((_, index) => index);\n  indices.sort((a, b) => array2D[a][0] - array2D[b][0]);\n\n  return indices;\n}\n\n/** Generate a random vector with the specified dimension.  */\nexport function generateVector(dim: number): number[] {\n  const vec = new Array(dim).fill(0).map(() => Math.random());\n  const norm = Math.sqrt(vec.reduce((sum, val) => sum + val * val, 0));\n  return vec.map(val => val / (norm + Number.EPSILON));\n}\n\n/** Generate an array of random vectors with the specified dimension and count. */\nexport function generateVectors(dim: number, numVectors: number): Vector[] {\n  return Array.from({length: numVectors}, () => generateVector(dim));\n}\n\nexport function generateQuery(dim: number, topK: number, includeValues: boolean): Query {\n  return {\n    embedding: generateVector(dim),\n    top_k: topK,\n    top_k_mmr: Math.floor(topK / constants.MMR_TOPK_FACTOR),\n    include_values: includeValues,\n    filter: {},\n    include_metadata: true,\n  };\n}\n\n// TODO: instead of random_batch_request with defaults, have the defaults apply here?\nexport function generateBatch(numVecs: number, dim: number, topK: number, includeValues: boolean): Query[] {\n  return Array.from({length: numVecs}, () => generateQuery(dim, topK, includeValues));\n}\n\n// Adjust weights to meet batch size requirements.\nexport function adjustWeights(weights: number[], batchSize: number, confidenceInterval: number): number[] {\n  const minWeight = Math.min(...weights);\n  if (minWeight < 1) {\n    const diff = 1 - minWeight;\n    weights = weights.map(w => w + diff);\n  }\n\n  const sum = weights.reduce((sum, w) => sum + w, 0);\n  if (!(batchSize - confidenceInterval <= sum && sum <= batchSize + confidenceInterval)) {\n    const scaleFactor = batchSize / sum;\n    weights = weights.map(w => Math.ceil(w * scaleFactor));\n  }\n\n  return weights;\n}\n\nexport function applyThreshold(\n  queries: QueryResult[],\n  threshold: number,\n  distanceMetric: DistanceMetric\n): QueryResult[] {\n  console.log(queries.map(({id, score}) => ({id, score})));\n  const avg = mean(matrix(queries.map(q => q.score))) as number;\n  if (distanceMetric !== 'euclidean_dist') {\n    // this is a similarity metric, threshold should be lower than the score\n    // i.e. we keep the scores higher than the threshold\n    threshold = Math.min(threshold, avg);\n    return queries.filter(q => q.score! >= threshold);\n  } else {\n    // this is a distance metric, threshold should be higher than the score\n    // i.e. we keep the scores lower than the threshold\n    threshold = Math.max(threshold, avg);\n    return queries.filter(q => q.score! <= threshold);\n  }\n}\n\n// Perform maximal marginal relevance ranking.\nexport function maximalMarginalRelevance(\n  queryEmbedding: Vector,\n  queryResults: QueryResult[],\n  lambdaMult: number = 0.5,\n  k: number = 4\n): QueryResult[] {\n  // TODO: should we check for `scores` before doing this? kind of like:\n  // if (this.scores?.length === 0) return new Matrix();\n  const embeddings: Matrix = matrix(queryResults.map(q => q.vector));\n  const query: Matrix = matrix(queryEmbedding);\n\n  if (Math.min(k, embeddings.size()[0]) <= 0) {\n    // return the input itself\n    return queryResults;\n  }\n\n  const queryMatrix = matrix(query);\n  const embeddingsNorm = norm(embeddings, 'fro');\n  const queryNorm = norm(queryMatrix, 'fro');\n  const a = multiply(embeddings, queryMatrix);\n  const b = multiply(embeddingsNorm, queryNorm);\n\n  const dists = divide(a, b) as Matrix;\n  const minVal: number[] = argsort(dists);\n\n  const indices: number[] = [minVal[0]];\n  let selected = getRow(embeddings, minVal[0]).toArray() as number[][];\n  while (indices.length < Math.min(k, embeddings.size()[0])) {\n    let bestScore = -Infinity;\n    let idxToAdd = -1;\n    const similarityToSelected = cosineSimilarityMatrix(embeddings.toArray() as number[][], selected);\n\n    for (let i = 0; i < dists.size()[0]; i++) {\n      if (indices.includes(i)) {\n        continue;\n      }\n      const queryScore = dists.get([i]);\n      const redundantScore = Math.max(...similarityToSelected[i]);\n      const equationScore = lambdaMult * queryScore - (1 - lambdaMult) * redundantScore;\n\n      if (equationScore > bestScore) {\n        bestScore = equationScore;\n        idxToAdd = i;\n      }\n    }\n    indices.push(idxToAdd);\n    selected = selected.concat(getRow(embeddings, idxToAdd).toArray() as number[]);\n  }\n\n  return indices.map(i => queryResults[i]);\n}\n\nfunction dotProduct(a: number[], b: number[]): number {\n  return a.reduce((sum, val, index) => sum + val * b[index], 0);\n}\n\nfunction magnitude(vector: number[]): number {\n  return Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));\n}\n\nfunction cosineSimilarityMatrix(A: number[][], B: number[][]): number[][] {\n  if (A[0].length !== B[0].length) {\n    throw new Error('Matrices must have the same number of columns');\n  }\n\n  const similarities: number[][] = [];\n  for (let i = 0; i < A.length; i++) {\n    const rowSimilarities: number[] = [];\n    for (let j = 0; j < B.length; j++) {\n      const dot = dotProduct(A[i], B[j]);\n      const magA = magnitude(A[i]);\n      const magB = magnitude(B[j]);\n      rowSimilarities.push(dot / (magA * magB));\n    }\n    similarities.push(rowSimilarities);\n  }\n  return similarities;\n}\n","import type {DistanceMetric, VertexParameters} from '../types';\nimport type library from '../algorithm/library';\n\nexport default {\n  /** Default values. */\n  DEFAULTS: {\n    QUANTIZER_TRAIN_SIZE: 100,\n    QUANTIZER_TYPE: 'scalar' satisfies 'scalar' | 'product',\n    QUANTIZER_TOPK: 5,\n    EMBEDDING_LAST_N: 50,\n    EMBEDDING_SIZE: 1536,\n    DISTANCE_METRIC: 'cosine_sim' satisfies DistanceMetric,\n    CONFIDENCE_INTERVAL_RATIO: 0.15,\n    HISTORY_FIELD: 'id',\n    BATCH_SIZE: 10,\n    KEY: 'text',\n    ENABLE_HISTORY: false,\n    VERBOSE: false,\n    PARAMS: {\n      mu: 0,\n      alpha: 0,\n      r: 0,\n      last_n: 0,\n      n_topics: 0,\n      remove_duplicates: true,\n      apply_threshold: 0,\n      apply_mmr: false,\n    } satisfies VertexParameters,\n  },\n  /** Factor applied to TOPK when MMR is to be applied. */\n  MMR_TOPK_FACTOR: 2,\n  MIN_TOPK: 5,\n  /** Preset algorithm names. */\n  PRESET_ALGORITHMS: {\n    UNIQUE_JOURNEYS: 'Unique_Journeys'.toUpperCase(),\n    CONTENT_CURATION: 'User_Centric_Promoted_Content_Curations'.toUpperCase(),\n    AI_AGENTS: 'User_Intent_AI_Agents'.toUpperCase(),\n    RECOMMENDATIONS: 'Individually_Crafted_Recommendations'.toUpperCase(),\n    NAVIGATION: 'Navigable_UX'.toUpperCase(),\n  } satisfies Record<keyof typeof library, string>,\n} as const;\n","import type {DFA, Edge, Vertex, Signal} from '../types';\nimport {Signals} from './signals';\nimport constants from '../constants';\n\nexport class Blueprint {\n  vertices: Vertex[] = [];\n  edges: Edge[] = [];\n  map: Record<string, Vertex> = {};\n\n  constructor(dfa: DFA) {\n    // extends Signals\n    // FIXME: doing this overwrites the weights if they are different!\n    if (dfa.signals) {\n      dfa.signals.forEach(signal => {\n        Signals[signal.label] = signal;\n      });\n    }\n\n    // add vertices (nodes)\n    dfa.nodes.forEach(node => {\n      this.addVertex({\n        name: node.name,\n        batchType: node.batch_type,\n        params: {\n          ...constants.DEFAULTS.PARAMS,\n          ...node.params,\n        },\n      });\n    });\n\n    // add edges\n    dfa.edges.forEach(edge => {\n      if (!(edge.edge_type in Signals)) {\n        throw `No signal found for: ${edge.edge_type} of edge ${edge.name}.`;\n      }\n      if (!(edge.start in this.map)) {\n        throw `Start vertex '${edge.start}' of edge ${edge.name} does not exist.`;\n      }\n      if (!(edge.end in this.map)) {\n        throw `End vertex '${edge.end}' of edge ${edge.name} does not exist.`;\n      }\n\n      this.addEdge({\n        name: edge.name,\n        signal: Signals[edge.edge_type],\n        start: this.map[edge.start],\n        end: this.map[edge.end],\n      });\n    });\n\n    // validate connections\n    this.vertices.forEach(node => {\n      // get edges that have this node as the starting node\n      const edges = this.edges.filter(e => e.start.name === node.name);\n\n      // find edges that are not BATCH actions\n      const nonBatchEdges = edges.filter(e => e.signal.label !== 'BATCH');\n\n      // check if edges that have this node as its start vertex contain 'batch' action\n      if (nonBatchEdges.length === edges.length) {\n        throw new Error(`Node '${node.name}' is missing a 'BATCH' signal.`);\n      }\n\n      // within all action types of these edges, we must either have all signals; or some amount of signals along with the DEFAULT signal\n      const signals = nonBatchEdges.map(e => e.signal);\n      if (!signals.some(s => s.label === 'DEFAULT') && signals.length !== Object.keys(Signals).length) {\n        throw new Error(`Node '${node.name}' does not have all signals covered, or is missing the DEFAULT signal.`);\n      }\n    });\n  }\n\n  addVertex(vertex: Vertex) {\n    // no duplicate vertices with the same name allowed\n    if (vertex.name in this.map) {\n      throw new Error(`Vertex '${vertex.name}' already exists`);\n    }\n\n    this.vertices.push(vertex);\n    this.map[vertex.name] = vertex;\n  }\n\n  addEdge(edge: Edge) {\n    // no duplicate edge names allowed\n    if (this.edges.some(e => e.name === edge.name)) {\n      throw new Error(`Edge '${edge.name}' already exists`);\n    }\n\n    // check if vertices exist\n    // we expect them to exist because vertices are added before edges in `parseDFA`\n    if (!(edge.start.name in this.map)) {\n      throw new Error('Could not find the start vertex named: ' + edge.start.name);\n    }\n    if (!(edge.end.name in this.map)) {\n      throw new Error('Could not find the end vertex named: ' + edge.end.name);\n    }\n\n    this.edges.push(edge);\n  }\n\n  /**\n   *\n   * @param state name of the current state (vertex)\n   * @param signal signal to be applied\n   * @returns the source and destination vertices\n   */\n  step(state: string, signal: Signal): {source: Vertex; destination: Vertex} {\n    // find the vertex with this state\n    let source: Vertex;\n    if (!(state in this.map)) {\n      if (state === '0') {\n        // FIXME: edge case until API is fixed\n        // API will request the state 0 referring to the first state.\n        // is this due to \"initial state\" maybe?\n        source = this.vertices[0];\n      } else {\n        throw new Error('No vertex found for ' + state);\n      }\n    } else {\n      source = this.map[state];\n    }\n\n    // find an edge from that vertex with the given action, or a DEFAULT edge\n    const edge =\n      this.edges.find(e => e.start.name === source.name && e.signal.label === signal.label) ||\n      this.edges.find(e => e.signal.label === Signals.DEFAULT.label);\n\n    if (!edge) {\n      // this should never happen if DFA parser works correctly\n      throw new Error('Expected to find an edge.');\n    }\n\n    return {source, destination: edge.end};\n  }\n}\n","import type {Signal} from '../types';\n\nconst presetSignals = {\n  DEFAULT: {label: 'DEFAULT', weight: 1},\n  BATCH: {label: 'BATCH', weight: 0},\n  ADD_TO_CART: {label: 'ADD_TO_CART', weight: 16},\n  ITEM_VIEW: {label: 'ITEM_VIEW', weight: 10},\n  APPLY: {label: 'APPLY', weight: 18},\n  PURCHASE: {label: 'PURCHASE', weight: 20},\n  HIGHLIGHT: {label: 'HIGHLIGHT', weight: 8},\n  GLANCE_VIEW: {label: 'GLANCE_VIEW', weight: 14},\n  CAMPAIGN_CLICK: {label: 'CAMPAIGN_CLICK', weight: 6},\n  CATEGORY_VISIT: {label: 'CATEGORY_VISIT', weight: 10},\n  SHARE: {label: 'SHARE', weight: 10},\n  MERCHANT_VIEW: {label: 'MERCHANT_VIEW', weight: 10},\n  REIMBURSED: {label: 'REIMBURSED', weight: 20},\n  APPROVED: {label: 'APPROVED', weight: 18},\n  REJECTED: {label: 'REJECTED', weight: 18},\n  SHARE_ARTICLE: {label: 'SHARE_ARTICLE', weight: 10},\n  COMMENT: {label: 'COMMENT', weight: 12},\n  PERSPECTIVES_SWITCH: {label: 'PERSPECTIVES_SWITCH', weight: 8},\n  REPOST: {label: 'REPOST', weight: 20},\n  SUBSCRIBE: {label: 'SUBSCRIBE', weight: 18},\n  SHARE_PROFILE: {label: 'SHARE_PROFILE', weight: 10},\n  PAID_SUBSCRIBE: {label: 'PAID_SUBSCRIBE', weight: 20},\n  SAVE: {label: 'SAVE', weight: 8},\n  FOLLOW_TOPIC: {label: 'FOLLOW_TOPIC', weight: 10},\n  WATCH: {label: 'WATCH', weight: 20},\n  CLICK_LINK: {label: 'CLICK_LINK', weight: 6},\n  RECOMMEND: {label: 'RECOMMEND', weight: 12},\n  FOLLOW: {label: 'FOLLOW', weight: 10},\n  VISIT_PROFILE: {label: 'VISIT_PROFILE', weight: 12},\n  AUTO_PLAY: {label: 'AUTO_PLAY', weight: 4},\n  SAVE_ARTICLE: {label: 'SAVE_ARTICLE', weight: 8},\n  REPLAY: {label: 'REPLAY', weight: 20},\n  READ: {label: 'READ', weight: 14},\n  LIKE: {label: 'LIKE', weight: 8},\n  CLICK_EMAIL_LINK: {label: 'CLICK_EMAIL_LINK', weight: 6},\n  ADD_TO_LIST: {label: 'ADD_TO_LIST', weight: 12},\n  FOLLOW_AUTHOR: {label: 'FOLLOW_AUTHOR', weight: 10},\n  SEARCH: {label: 'SEARCH', weight: 15},\n  CLICK_AD: {label: 'CLICK_AD', weight: 6},\n} as const;\n\n/** Preset set of signals, you can use these or add your own signals to this object. */\nexport const Signals: Readonly<{[signal in keyof typeof presetSignals]: Signal}> & {[signal: string]: Signal} =\n  presetSignals as Record<keyof typeof presetSignals, Signal>;\n","import type {DFA} from '../types';\n\n// prettier-ignore\nconst Navigable_UX: DFA = {\n  nodes: [\n    {name: 'Exploration', batch_type: 'random',       params: {last_n: 8}},\n    {name: 'Browsing',    batch_type: 'sampled',      params: {n_topics: 12, last_n: 8}},\n    {name: 'Discovery',   batch_type: 'personalized', params: {r: 0.2, mu: 0.50, alpha: 0.7, apply_threshold: 0.3, apply_mmr: true}},\n    {name: 'Dedicated',   batch_type: 'personalized', params: {r: 0.1, mu: 0.20, alpha: 0.4, apply_threshold: 0.5, apply_mmr: true, last_n: 5}},\n    {name: 'Focus',       batch_type: 'personalized', params: {r: 0.1, mu: 0.05, alpha: 0.1, apply_threshold: 0.6, apply_mmr: false, last_n: 4}},\n    {name: 'Hyper_Focus', batch_type: 'personalized', params: {r: 0.0, mu: 0.00, alpha: 0.0, apply_threshold: 0.7, apply_mmr: false, last_n: 2}},\n  ],\n  edges: [\n    {name: 'edge1',   edge_type: 'DEFAULT', start: 'Exploration', end: 'Hyper_Focus'},\n    {name: 'edge2',   edge_type: 'DEFAULT', start: 'Browsing',    end: 'Hyper_Focus'},\n    {name: 'edge3',   edge_type: 'DEFAULT', start: 'Discovery',   end: 'Hyper_Focus'},\n    {name: 'edge4',   edge_type: 'DEFAULT', start: 'Dedicated',   end: 'Hyper_Focus'},\n    {name: 'edge5',   edge_type: 'DEFAULT', start: 'Focus',       end: 'Hyper_Focus'},\n    {name: 'edge6',   edge_type: 'DEFAULT', start: 'Hyper_Focus', end: 'Hyper_Focus'},\n    {name: 'edge7',   edge_type: 'BATCH',   start: 'Exploration', end: 'Browsing'},\n    {name: 'edge8',   edge_type: 'BATCH',   start: 'Browsing',    end: 'Browsing'},\n    {name: 'edge9',   edge_type: 'BATCH',   start: 'Discovery',   end: 'Discovery'},\n    {name: 'edge10',  edge_type: 'BATCH',   start: 'Dedicated',   end: 'Discovery'},\n    {name: 'edge11',  edge_type: 'BATCH',   start: 'Focus',       end: 'Dedicated'},\n    {name: 'edge12',  edge_type: 'BATCH',   start: 'Hyper_Focus', end: 'Focus'},\n  ],\n};\n\n// prettier-ignore\nconst Individually_Crafted_Recommendations: DFA = {\n  nodes: [\n    {name: 'Recommendation',  batch_type: 'personalized', params: {r: 0, mu: 0.00, alpha: 0.0, apply_threshold: 0.7, apply_mmr: false, last_n: 1}},\n    {name: 'Expansion',       batch_type: 'personalized', params: {r: 0, mu: 0.05, alpha: 0.4, apply_threshold: 0.7, apply_mmr: true, last_n: 2}},\n    {name: 'Discovery',       batch_type: 'personalized', params: {r: 0, mu: 0.10, alpha: 1.0, apply_threshold: 0.6, apply_mmr: true, last_n: 4}},\n  ],\n  edges: [\n    {name: 'edge1', edge_type: 'DEFAULT', start: 'Discovery',       end: 'Recommendation'},\n    {name: 'edge2', edge_type: 'DEFAULT', start: 'Expansion',       end: 'Recommendation'},\n    {name: 'edge3', edge_type: 'DEFAULT', start: 'Recommendation',  end: 'Recommendation'},\n    {name: 'edge4', edge_type: 'BATCH',   start: 'Recommendation',  end: 'Expansion'},\n    {name: 'edge5', edge_type: 'BATCH',   start: 'Expansion',       end: 'Discovery'},\n    {name: 'edge6', edge_type: 'BATCH',   start: 'Discovery',       end: 'Discovery'},\n  ],\n};\n\n// prettier-ignore\nconst Unique_Journeys: DFA = {\n  nodes: [\n    {name: 'Welcome',     batch_type: 'biased',       params: {r: 0.2, mu: 0.20, alpha: 0.4, apply_threshold: 0.7, apply_mmr: false, last_n: 5}},\n    {name: 'Exploration', batch_type: 'personalized', params: {r: 0.3, mu: 0.60, alpha: 0.7, apply_threshold: 0.3, apply_mmr: true, last_n: 8}},\n    {name: 'Discovery',   batch_type: 'personalized', params: {r: 0.2, mu: 0.40, alpha: 0.5, apply_threshold: 0.3, apply_mmr: true, last_n: 6}},\n    {name: 'Dedicated',   batch_type: 'personalized', params: {r: 0.1, mu: 0.20, alpha: 0.4, apply_threshold: 0.5, apply_mmr: true, last_n: 5}},\n    {name: 'Focus',       batch_type: 'personalized', params: {r: 0.1, mu: 0.05, alpha: 0.1, apply_threshold: 0.6, apply_mmr: false, last_n: 4}},\n    {name: 'Hyper_Focus', batch_type: 'personalized', params: {r: 0.0, mu: 0.00, alpha: 0.0, apply_threshold: 0.7, apply_mmr: false, last_n: 2}},\n  ],\n  edges: [\n    {name: 'edge1',  edge_type: 'DEFAULT', start: 'Welcome',      end: 'Hyper_Focus'},\n    {name: 'edge2',  edge_type: 'DEFAULT', start: 'Exploration',  end: 'Hyper_Focus'},\n    {name: 'edge3',  edge_type: 'DEFAULT', start: 'Discovery',    end: 'Hyper_Focus'},\n    {name: 'edge4',  edge_type: 'DEFAULT', start: 'Dedicated',    end: 'Hyper_Focus'},\n    {name: 'edge5',  edge_type: 'DEFAULT', start: 'Focus',        end: 'Hyper_Focus'},\n    {name: 'edge6',  edge_type: 'DEFAULT', start: 'Hyper_Focus',  end: 'Hyper_Focus'},\n    {name: 'edge7',  edge_type: 'BATCH',   start: 'Welcome',      end: 'Exploration'},\n    {name: 'edge8',  edge_type: 'BATCH',   start: 'Exploration',  end: 'Welcome'},\n    {name: 'edge9',  edge_type: 'BATCH',   start: 'Discovery',    end: 'Exploration'},\n    {name: 'edge10', edge_type: 'BATCH',   start: 'Dedicated',    end: 'Discovery'},\n    {name: 'edge11', edge_type: 'BATCH',   start: 'Focus',        end: 'Dedicated'},\n    {name: 'edge12', edge_type: 'BATCH',   start: 'Hyper_Focus',  end: 'Focus'},\n  ],\n};\n\n// prettier-ignore\nconst User_Centric_Promoted_Content_Curations: DFA = {\n  nodes: [\n    {name: 'Exploration', batch_type: 'sampled',      params: {n_topics: 8, last_n: 3}},\n    {name: 'Curated',     batch_type: 'personalized', params: {r: 0, mu: 0.1, alpha: 0.3, apply_threshold: 0.6, apply_mmr: false, last_n: 1}},\n  ],\n  edges: [\n    {name: 'edge1', edge_type: 'DEFAULT', start: 'Exploration', end: 'Curated'},\n    {name: 'edge2', edge_type: 'DEFAULT', start: 'Curated',     end: 'Curated'},\n    {name: 'edge3', edge_type: 'BATCH',   start: 'Exploration', end: 'Exploration'},\n    {name: 'edge4', edge_type: 'BATCH',   start: 'Curated',     end: 'Curated'},\n  ],\n};\n\n// prettier-ignore\nconst User_Intent_AI_Agents: DFA = {\n  nodes: [\n    {name: 'Welcome',     batch_type: 'biased',       params: {r: 0, mu: 0.1, alpha: 0.4, apply_threshold: 0.8, apply_mmr: false, last_n: 12}},\n    {name: 'Expansion',   batch_type: 'personalized', params: {r: 0, mu: 0.2, alpha: 0.6, apply_threshold: 0.6, apply_mmr: true, last_n: 12}},\n    {name: 'Exploration', batch_type: 'personalized', params: {r: 0, mu: 0.5, alpha: 0.6, apply_threshold: 0.5, apply_mmr: true, last_n: 12}},\n    {name: 'Focus',       batch_type: 'personalized', params: {r: 0, mu: 0.0, alpha: 0.0, apply_threshold: 0.8, apply_mmr: false, last_n: 6}},\n  ],\n  edges: [\n    {name: 'edge1', edge_type: 'DEFAULT', start: 'Welcome',     end: 'Hyper_Focus'},\n    {name: 'edge2', edge_type: 'DEFAULT', start: 'Expansion',   end: 'Hyper_Focus'},\n    {name: 'edge3', edge_type: 'DEFAULT', start: 'Exploration', end: 'Hyper_Focus'},\n    {name: 'edge4', edge_type: 'DEFAULT', start: 'Focus',       end: 'Hyper_Focus'},\n    {name: 'edge1', edge_type: 'BATCH',   start: 'Welcome',     end: 'Welcome'},\n    {name: 'edge2', edge_type: 'BATCH',   start: 'Expansion',   end: 'Exploration'},\n    {name: 'edge3', edge_type: 'BATCH',   start: 'Exploration', end: 'Exploration'},\n    {name: 'edge4', edge_type: 'BATCH',   start: 'Focus',       end: 'Expansion'},\n  ],\n};\n\nexport default {\n  /** ### Unique Journeys\n   *\n   * Enable users to access the right content from the very beginning by\n   * tailoring their experience based on their starting point.\n   *\n   * #### Target\n   *\n   * Shape user journey from the very beginning. Might be best for traffic source or seasonal campaigns based welcoming, and recurring visitor experiences.\n   *\n   * #### Description\n   *\n   * Providing focused content starting from first load by utilizing user embeddings from previous sessions or adding seasonal effect to the experience.\n   *\n   * For example adding summer collection as bias during summer. Then letting navigate themselves just as we do in the Navigable_UX algorithm.\n   *\n   * Potential KPIs:\n   * - Up-Any engagement metric\n   * - Time spent before first interaction\n   * - Conversion rate of recurring visitors\n   * - Time spent on application or Bounce rate\n   */\n  UNIQUE_JOURNEYS: Unique_Journeys,\n\n  /** ### Not User Targeting but User-Centric Promoted Content Curations\n   *\n   * Shift away from conventional targeting techniques and embrace a user-centric approach to deliver promoted\n   * items or ads in a captivating format.\n   *\n   * This approach allows users to actively influence the curation of promoted content,\n   * ensuring it aligns seamlessly with their preferences and resulting in a highly interactive and enjoyable experience.\n   *\n   * #### Target\n   *\n   * Not force your users to see irrelevant promoted content but provide an engaging campaign discovery.\n   *\n   * People ignore ads because targeting only pollutes feeds. Therefore the aim is improveing campaign\n   * CTR by providing true content for right users at the right time.\n   *\n   * #### Description\n   *\n   * Promoting contents in hyper-personalized manner by keeping curation focused after first interaction to forever.\n   *\n   * Potential KPIs:\n   * - CTR\n   */\n  CONTENT_CURATION: User_Centric_Promoted_Content_Curations,\n\n  /** ### User-Intent AI Agents\n   *\n   * Empower your AI agents with real-time insights into user intentions, derived from their interactions.\n   *\n   * This infusion of user intent brings intimacy to AI-driven experiences,\n   * making users feel more connected and understood.\n   *\n   * #### Target\n   *\n   * Serving personal AI assistance that reflects user interactions that are not restricted with prompts.\n   *\n   * #### Description\n   *\n   * Not giving space for false navigation and keeping the AI agent as much as closer to user intentions.\n   *\n   * Because people are being demotivated by hallucinated conversations with AI too fast.\n   *\n   * Potential KPIs:\n   * - Time spent with AI agents\n   * - Chat Rating\n   * - Conversion rate through AI agents\n   */\n  AI_AGENTS: User_Intent_AI_Agents,\n\n  /** ### Individually Crafted Recommendations\n   *\n   * Offer users not only similar but also adjacent items in a personalized manner.\n   *\n   * This approach allows users to discover new and relevant content on their own terms,\n   * enhancing their exploration and satisfaction.\n   *\n   * #### Target\n   *\n   * Increase up-sell and help you to improve average order value.\n   *\n   * #### Description\n   *\n   * Making highly focused recommendations after first interaction.\n   *\n   * But enable users to explore more items from a wider perspective to keep users within\n   * recommendations space until they find something to add their cart.\n   *\n   * Potential KPIs:\n   * - Up-sell and cross-sell metrics\n   * - Average Order Value\n   * - Number of items per order\n   */\n  RECOMMENDATIONS: Individually_Crafted_Recommendations,\n\n  /** ### Navigable UX\n   *\n   * Transform your user experience into a navigable journey by leveraging user interactions.\n   * Every user action contributes to shaping their unique experience.\n   *\n   * #### Target\n   *\n   * Anonymous sessions to navigable experiences\n   *\n   * #### Description\n   *\n   * Trying to serve various content until receiving first signal from users.\n   *\n   * Then crafting the experience sharply regarding signals. Gradually providing more space for exploration if user\n   * keeps loosing interest in current topics.\n   *\n   * Potential KPIs:\n   * - Any engagement metric\n   * - Time spent on application or Bounce rate\n   * - Conversion rate of anonymous sessions\n   */\n  NAVIGATION: Navigable_UX,\n} as const;\n","import log from 'loglevel';\nimport {applyAlgorithm} from './algorithm/apply';\nimport {Blueprint} from './algorithm/blueprint';\nimport {FirstBatchAPI} from './api';\nimport constants from './constants';\nimport {ScalarQuantizer} from './lossy/scalar';\nimport {VectorStore} from './integrations/base';\nimport {generateBatch, adjustWeights} from './utils';\nimport type {WeightedVectors, Signal, QueryMetadata, FirstBatchConfig, Query, AlgorithmType} from './types';\nimport {Signals} from './algorithm/signals';\nimport library from './algorithm/library';\n\nexport class FirstBatch extends FirstBatchAPI {\n  readonly batchSize: number;\n  readonly quantizerTrainSize: number;\n  readonly quantizerType: 'scalar' | 'product';\n  readonly enableHistory: boolean;\n  readonly verbose: boolean;\n\n  private readonly store: Record<string, VectorStore> = {};\n  logger: log.Logger = log.getLogger('FirstBatchLogger');\n\n  constructor(apiKey: string, config?: FirstBatchConfig) {\n    super(apiKey);\n\n    this.batchSize = config?.batchSize ?? constants.DEFAULTS.BATCH_SIZE;\n    this.enableHistory = config?.enableHistory ?? constants.DEFAULTS.ENABLE_HISTORY;\n    this.verbose = config?.verbose ?? constants.DEFAULTS.VERBOSE;\n\n    this.logger.setLevel(this.verbose ? 'INFO' : 'WARN');\n\n    this.quantizerTrainSize = config?.quantizerTrainSize ?? constants.DEFAULTS.QUANTIZER_TRAIN_SIZE;\n    this.quantizerType = config?.quantizerType ?? constants.DEFAULTS.QUANTIZER_TYPE;\n    if (this.quantizerType === 'product') {\n      this.logger.warn(\"Product quantization not yet supported, defaulting to 'scalar'\");\n      this.quantizerType = 'scalar';\n    }\n  }\n\n  static async new(apiKey: string, config?: FirstBatchConfig): Promise<FirstBatch> {\n    const personalized = new FirstBatch(apiKey, config);\n    await personalized.init();\n    personalized.logger.info('Using: ' + personalized.url);\n    return personalized;\n  }\n\n  /** Add a vector store to the container.\n   *\n   * If this vector store has not beed registered to the API before,\n   * it will be \"sketched\" with respect to the `quantizerType`, which may take some time.\n   *\n   * @param vdbid vectorDB ID of your choice\n   * @param vectorStore a `VectorStore` instance\n   */\n  async addVectorStore(name: string, vectorStore: VectorStore) {\n    const exists = await this.vdbExists(name);\n    if (!exists) {\n      this.logger.info(`Vector store \"${name}\" not found, sketching a new one.`);\n\n      if (this.quantizerType === 'scalar') {\n        this.logger.info('Initializing with scalar quantizer, this might take some time...');\n\n        const quantizer = new ScalarQuantizer(256);\n        const batchSize = Math.min(Math.floor(this.quantizerTrainSize / constants.DEFAULTS.QUANTIZER_TOPK), 500);\n        const vectors = await vectorStore\n          .multiSearch(generateBatch(batchSize, vectorStore.embeddingSize, constants.DEFAULTS.QUANTIZER_TOPK, true))\n          .then(results => results.flatMap(result => result.map(r => r.vector)));\n\n        quantizer.train(vectors);\n\n        await this.initVectordbScalar(\n          name,\n          vectors.map(v => quantizer.compress(v).vector),\n          quantizer.quantiles\n        );\n      } else if (this.quantizerType === 'product') {\n        throw new Error('Product quantization is not supported yet');\n      } else {\n        this.quantizerType satisfies never;\n        throw new Error('Invalid quantizer type: ' + this.quantizerType);\n      }\n    }\n\n    // add to local storage\n    this.store[name] = vectorStore;\n  }\n\n  /**\n   * Fetches the user embeddings for a specific session.\n   *\n   * @param session session object\n   * @returns vectors and weights\n   */\n  async userEmbeddings(sessionId: string) {\n    return super.getUserEmbeddings(sessionId);\n  }\n\n  /**\n   * Creates a new session with the provided parameters & vector database ID.\n   * This method returns the sessionID; however, you can provide the sessionID with this method to create a persistent session.\n   *\n   * @param algorithm algorithm label\n   * @param vdbid vectorDB id\n   * @param options optional `sessionId` or `customId`\n   * - if `sessionId` is given, a persistent-session will be created and this same id will be returned\n   * - `customId` is only expected when `algorithm = 'CUSTOM'`\n   * @returns session object\n   */\n  async session(\n    algorithm: keyof typeof constants.PRESET_ALGORITHMS | 'SIMPLE' | 'CUSTOM',\n    vdbid: string,\n    options?: {sessionId?: string; customId?: string}\n  ) {\n    // if algorithm label is non-standard, the label is factory and factoryId is the algorithm name\n    const label = ['SIMPLE', 'CUSTOM'].includes(algorithm) ? algorithm : 'FACTORY';\n\n    const sessionResponse = await this.createSession(label, vdbid, {\n      sessionId: options?.sessionId,\n      customId: label == 'CUSTOM' ? options?.customId : undefined,\n      factoryId: label == 'FACTORY' ? algorithm : undefined,\n    });\n\n    // TODO: we had the following statement here originally:\n    // `isPersistent: options?.sessionId !== undefined`\n    // this is added to session object, but is not used.\n    // if the time comes, keep this in mind.\n\n    return sessionResponse.data;\n  }\n\n  /**\n   * Add a signal to current session.\n   *\n   * @param session session object\n   * @param signal a {@link Signal}\n   * @param contentId id of a returned item from batch\n   * @returns `true` is signal was added succesfully\n   */\n  async addSignal(sessionId: string, signal: Signal, contentId: string) {\n    const sessionResponse = await this.getSession(sessionId);\n    const vectorStore = this.store[sessionResponse.vdbid];\n    if (vectorStore === undefined) {\n      throw new Error('Vector Store is undefined, have you called `addVectorStore` function?');\n    }\n\n    const fetchResult = await vectorStore.fetch(contentId);\n\n    const blueprint = await this.getBlueprint(sessionResponse.algorithm);\n    const {source, destination} = blueprint.step(sessionResponse.state, signal);\n    const signalResponse = await this.signal(sessionId, fetchResult.vector, destination.name, signal);\n    if (signalResponse.success && this.enableHistory) {\n      await this.addHistory(sessionId, [contentId]);\n    }\n\n    return {\n      source,\n      destination,\n      success: signalResponse.success,\n    };\n  }\n\n  /**\n   * Get a new batch.\n   *\n   * @param session session object\n   * @param options optional batch size, and bias parameters (vectors and weights)\n   * @returns ids and metadata\n   */\n  async batch(\n    sessionId: string,\n    options?: {\n      batchSize?: number;\n      bias?: WeightedVectors;\n    }\n    // FIXME: return [string, QueryMetadata][]\n  ): Promise<[string[], QueryMetadata[]]> {\n    const response = await this.getSession(sessionId);\n    const vectorStore = this.store[response.vdbid];\n    if (vectorStore === undefined) {\n      throw new Error('Vector Store is undefined, you should add it.'); // FIXME: better msg\n    }\n\n    const batchSize = options?.batchSize ?? this.batchSize;\n    const historyIds = this.enableHistory ? await this.getHistory(sessionId) : [];\n    const blueprint = await this.getBlueprint(response.algorithm);\n\n    const {source, destination} = blueprint.step(response.state, Signals.BATCH);\n    const {params, batchType} = source;\n    const algorithmOptions = {\n      applyMMR: params.apply_mmr,\n      applyThreshold: params.apply_threshold,\n      removeDuplicates: params.remove_duplicates,\n      distanceMetric: vectorStore.distanceMetric,\n    };\n\n    switch (response.algorithm.type) {\n      case 'CUSTOM':\n        this.logger.info(\n          `Session | CUSTOM | ${response.algorithm.customId} | ${batchType} batch of ${batchSize} vectors`\n        );\n        break;\n      case 'FACTORY':\n        this.logger.info(\n          `Session | FACTORY | ${response.algorithm.factoryId} | ${batchType} batch of ${batchSize} vectors`\n        );\n        break;\n      case 'SIMPLE':\n        this.logger.info(`Session | SIMPLE | ${batchType} batch of ${batchSize} vectors`);\n        break;\n    }\n\n    let queries: Query[];\n    if (batchType === 'random') {\n      queries = generateBatch(\n        batchSize,\n        vectorStore.embeddingSize,\n        constants.MIN_TOPK * constants.MMR_TOPK_FACTOR,\n        params.apply_mmr || params.apply_threshold !== 0\n      );\n    } else if (batchType === 'biased' || batchType === 'personalized') {\n      // check if bias exists\n      if (batchType === 'biased' && options?.bias === undefined) {\n        throw new Error('Bias vectors and weights must be provided for biased batch');\n      }\n\n      if (!response.has_embeddings && batchType === 'personalized') {\n        // act like random batch\n        this.logger.warn('No embeddings found for personalized batch, switching to random batch.');\n        queries = generateBatch(\n          batchSize,\n          vectorStore.embeddingSize,\n          constants.MIN_TOPK * constants.MMR_TOPK_FACTOR,\n          true\n        );\n      } else {\n        // act like biased batch\n        const biasOptions = {params, bias: options?.bias};\n        const batchResponse = await this.biasedBatch(sessionId, response.vdbid, destination.name, biasOptions);\n        queries = this.queryWrapper(response.vdbid, batchSize, batchResponse, historyIds, algorithmOptions);\n      }\n    } else if (batchType === 'sampled') {\n      const batchResponse = await this.sampledBatch(sessionId, response.vdbid, destination.name, params.n_topics);\n      queries = this.queryWrapper(response.vdbid, batchSize, batchResponse, historyIds, algorithmOptions);\n    } else {\n      batchType satisfies never;\n      throw new Error('Invalid batch type: ' + batchType);\n    }\n\n    await this.updateState(sessionId, destination.name, batchType);\n    const searchResults = await vectorStore.multiSearch(queries);\n\n    let [ids, metadatas] = applyAlgorithm(searchResults, queries, batchType, algorithmOptions);\n\n    // take only `batchSize` many results\n    ids = ids.slice(0, batchSize);\n    metadatas = metadatas.slice(0, batchSize);\n\n    if (this.enableHistory) {\n      await this.addHistory(sessionId, ids);\n    }\n\n    return [ids, metadatas];\n  }\n\n  private queryWrapper(\n    vdbid: string,\n    batchSize: number,\n    response: WeightedVectors,\n    history: string[],\n    options?: {\n      applyMMR?: boolean;\n      applyThreshold?: number;\n      filter?: Record<string, string>;\n    }\n  ): Query[] {\n    const applyMMR = options?.applyMMR ?? false;\n    const includeValues = applyMMR || options?.applyThreshold !== undefined;\n\n    const topKs = adjustWeights(\n      response.weights,\n      batchSize,\n      Math.max(batchSize * constants.DEFAULTS.CONFIDENCE_INTERVAL_RATIO, 1)\n    )\n      // ensure that topK is at least some value, otherwise too small values cause problems\n      .map(k => Math.max(k, constants.MIN_TOPK))\n      // if applyMMR, increase k for better results\n      .map(k => (applyMMR ? k * constants.MMR_TOPK_FACTOR : k));\n\n    const hasHistory = this.enableHistory && history.length !== 0;\n    const metadataFilter = hasHistory ? this.store[vdbid].historyFilter(history, options?.filter) : {}; // FIXME: default, but can it be undefined?\n\n    return response.vectors.map((vector, i): Query => {\n      const topK = Math.max(topKs[i], constants.MIN_TOPK);\n\n      return {\n        embedding: vector,\n        top_k: applyMMR ? topK * constants.MMR_TOPK_FACTOR : topK,\n        top_k_mmr: applyMMR ? topK : Math.floor(topK / constants.MMR_TOPK_FACTOR),\n        include_metadata: true,\n        include_values: includeValues,\n        filter: metadataFilter,\n      };\n    });\n  }\n\n  private async getBlueprint(algorithm: AlgorithmType): Promise<Blueprint> {\n    switch (algorithm.type) {\n      case 'SIMPLE': {\n        return new Blueprint(library.CONTENT_CURATION);\n      }\n      case 'CUSTOM': {\n        const blueprint = await this.getCustomBlueprint(algorithm.customId);\n        return new Blueprint(blueprint);\n      }\n      case 'FACTORY': {\n        const blueprint = library[algorithm.factoryId as keyof typeof library];\n        if (!blueprint) {\n          throw new Error('Could not find a DFA with label: ' + algorithm.factoryId);\n        }\n        return new Blueprint(blueprint);\n      }\n    }\n  }\n}\n","export * from './firstbatch';\n","import axios, {AxiosInstance} from 'axios';\nimport {createHash} from 'crypto';\nimport constants from '../constants';\nimport type {Vertex, WeightedVectors, DFA, Signal, AlgorithmType} from '../types';\n\n/** Endpoint to get region w.r.t user's API key. */\nconst REGION_URL = 'https://idp.firstbatch.xyz/v1/teams/team/get-team-information';\n\n/** HollowDB regions, the field names are important. */\nconst REGIONS = {\n  'us-east-1': 'https://aws-us-east-1.hollowdb.xyz/',\n  'us-west-1': 'https://aws-us-west-1.hollowdb.xyz/',\n  'eu-central-1': 'https://aws-eu-central-1.hollowdb.xyz/',\n  'ap-southeast-1': 'https://aws-ap-southeast-1.hollowdb.xyz/',\n} as const;\n\nexport class FirstBatchAPI {\n  /** API key of this client. */\n  private apiKey: string = '';\n  /** Prepared Axios instance with base URL and headers set, see {@link init}. */\n  private axios: AxiosInstance = axios.create();\n  /** TeamID of this client. */\n  teamId: string = '';\n  /** Backend URL with respect to the region of the API key. */\n  url: string = '';\n  /** Region for this client. */\n  region: string = '';\n\n  /** Acts as a constructor. */\n  protected constructor(apiKey: string) {\n    this.apiKey = apiKey;\n  }\n\n  /** POST request wrapper. The actual response is wrapped within `data` field of the Axios response.\n   *\n   * @template T type of the returned JSON data\n   * @template I type of the input data field values\n   */\n  private async post<T, I = unknown>(url: string, data: Record<string, I>) {\n    const axiosResponse = await this.axios.post<{\n      success: boolean;\n      code: number;\n      message?: string | undefined;\n      data: T;\n    }>(url, data);\n\n    if (axiosResponse.status != 200) {\n      throw new Error(`FirstBatch API failed with ${axiosResponse.statusText} (${axiosResponse.status}) at ${url}`);\n    }\n\n    return axiosResponse.data;\n  }\n\n  /** Initializes vectorDB, returns error message as a response if there was one. */\n  protected async initVectordbScalar(vdbid: string, quantizedVectors: number[][], quantiles: number[]) {\n    return await this.post<string>('embeddings/init_vdb', {\n      key: createHash('md5').update(this.apiKey).digest('hex'),\n      vdbid: vdbid,\n      mode: 'scalar',\n      region: this.region,\n      quantized_vecs: quantizedVectors,\n      quantiles: quantiles,\n    });\n  }\n\n  /** Initializes vectorDB, returns error message as a response if there was one. */\n  protected async initVectordbProduct(\n    vdbid: string,\n    quantizedVectors: number[][],\n    quantizedVectorResiduals: number[][],\n    codebook: number[][],\n    codebookResidual: number[][],\n    M: number,\n    Ks: number,\n    Ds: number\n  ) {\n    return await this.post<string>('embeddings/init_vdb', {\n      key: createHash('md5').update(this.apiKey).digest('hex'),\n      vdbid: vdbid,\n      mode: 'product',\n      region: this.region,\n      quantized_vecs: quantizedVectors,\n      quantized_residuals: quantizedVectorResiduals,\n      codebook: codebook,\n      codebook_residual: codebookResidual,\n      M: M,\n      Ks: Ks,\n      Ds: Ds,\n    });\n  }\n\n  /** Updates history, returns error message as a response if there was one. */\n  protected async addHistory(sessionId: string, ids: string[]) {\n    return await this.post<string>('embeddings/update_history', {id: sessionId, ids});\n  }\n\n  protected async createSession(\n    algorithm: string,\n    vdbid: string,\n    options?: {\n      customId?: string;\n      factoryId?: string;\n      sessionId?: string;\n      hasEmbeddings?: string;\n    }\n  ) {\n    const sessionId = options?.sessionId ? this.teamId + '-' + options.sessionId : undefined;\n    return await this.post<string>('embeddings/create_session', {\n      vdbid,\n      algorithm,\n      id: sessionId,\n      custom_id: options?.customId,\n      factory_id: options?.factoryId,\n      has_embeddings: options?.hasEmbeddings ?? false,\n    });\n  }\n\n  /** Updates state, returns error message as a response if there was one. */\n  protected async updateState(sessionId: string, state: string, batchType: Vertex['batchType']) {\n    return await this.post<string>('embeddings/update_state', {\n      id: sessionId,\n      state: state,\n      batch_type: batchType.toUpperCase(), // NOTE: api expects uppercased values for this field\n    });\n  }\n\n  /** Adds a signal, returns error message as a response if there was one. */\n  protected async signal(sessionId: string, vector: number[], stateName: string, signal: Signal) {\n    return this.post<string>('embeddings/signal', {\n      id: sessionId,\n      state: stateName,\n      signal: signal.weight,\n      signal_label: signal.label,\n      vector: vector,\n    });\n  }\n\n  protected async biasedBatch(\n    sessionId: string,\n    vdbid: string,\n    state: string,\n    options?: {\n      bias?: WeightedVectors;\n      params?: Vertex['params'];\n    }\n  ) {\n    const response = await this.post<WeightedVectors>('embeddings/biased_batch', {\n      id: sessionId,\n      vdbid: vdbid,\n      state: state,\n      params: options?.params,\n      bias_vectors: options?.bias?.vectors,\n      bias_weights: options?.bias?.weights,\n    });\n    return response.data;\n  }\n\n  protected async sampledBatch(\n    sessionId: string,\n    vdbid: string,\n    state: string,\n    nTopics: number,\n    params?: Record<string, number>\n  ) {\n    const response = await this.post<WeightedVectors>('embeddings/sampled_batch', {\n      id: sessionId,\n      n: nTopics,\n      vdbid: vdbid,\n      state: state,\n      params: params,\n    });\n    return response.data;\n  }\n\n  protected async getSession(sessionId: string) {\n    const response = await this.post<{\n      state: string;\n      algorithm: 'SIMPLE' | 'CUSTOM' | 'FACTORY';\n      vdbid: string;\n      has_embeddings: boolean;\n      factory_id?: string;\n      custom_id?: string;\n    }>('embeddings/get_session', {id: sessionId});\n\n    const data = response.data;\n\n    let algorithm: AlgorithmType = {\n      type: 'SIMPLE',\n    };\n\n    if (data.algorithm === 'FACTORY') {\n      if (data.factory_id === undefined) {\n        throw new Error('Did not get factory_id from API for a FACTORY algorithm.');\n      }\n\n      algorithm = {\n        type: 'FACTORY',\n        factoryId: data.factory_id,\n      };\n    }\n\n    if (data.algorithm === 'CUSTOM') {\n      if (data.custom_id === undefined) {\n        throw new Error('Did not get custom_id from API for a CUSTOM algorithm.');\n      }\n      algorithm = {\n        type: 'CUSTOM',\n        customId: data.custom_id,\n      };\n    }\n\n    return {\n      ...data,\n      algorithm,\n    };\n  }\n\n  protected async getHistory(sessionId: string) {\n    const response = await this.post<{ids: string[]}>('embeddings/get_history', {id: sessionId});\n    return response.data.ids;\n  }\n\n  protected async getUserEmbeddings(sessionId: string, lastN?: number) {\n    const response = await this.post<WeightedVectors>('embeddings/get_embeddings', {\n      id: sessionId,\n      last_n: lastN ?? constants.DEFAULTS.EMBEDDING_LAST_N,\n    });\n    return response.data;\n  }\n\n  protected async vdbExists(vdbid: string) {\n    const response = await this.post<boolean>('embeddings/vdb_exists', {vdbid});\n    return response.data;\n  }\n\n  /**\n   * Retrieve the blueprint of some custom id.\n   *\n   * @param customId algorithm id\n   * @returns a DFA (TODO: is this a string & object or always an object?)\n   */\n  protected async getCustomBlueprint(customId: string) {\n    const response = await this.post<DFA>('embeddings/get_blueprint', {id: customId});\n    // FIXME: do we ever receive a string here?\n    return response.data;\n  }\n\n  /** Initialize the client.\n   *\n   * Retrieves the region for the set API key, and creates an Axios instance for the client. */\n  protected async init() {\n    const headers = {\n      'x-api-key': this.apiKey,\n      'Content-Type': 'application/json',\n    };\n\n    // first, get the region & team data\n    const axiosResponse = await axios.get<{\n      success: boolean;\n      code: number;\n      message?: string | undefined;\n      data: {\n        teamID: string;\n        region: keyof typeof REGIONS;\n      };\n    }>(REGION_URL, {\n      headers,\n      validateStatus: status => {\n        if (status != 200) {\n          throw new Error(`Region request failed with ${status} at ${REGION_URL}`);\n        }\n        return true;\n      },\n    });\n\n    const {teamID, region} = axiosResponse.data.data; // notice the 2 data's\n    this.teamId = teamID;\n    this.region = region;\n    const regionBaseURL = REGIONS[region];\n    if (!regionBaseURL) {\n      throw new Error('No such region: ' + region);\n    }\n\n    // then, set up the axios client with the region base URL\n    this.url = regionBaseURL;\n    this.axios = axios.create({\n      baseURL: this.url,\n      headers: headers,\n      // override Axios internal handler so that we can handle ourselves\n      validateStatus: () => true,\n    });\n\n    // useful for debugging\n    if (process.env.VERBOSE_TEST) {\n      this.axios.interceptors.request.use(request => {\n        console.log(`REQ ${request.baseURL! + request.url}`);\n        return request;\n      });\n      this.axios.interceptors.response.use(response => {\n        console.log(`RES ${response.statusText} (${response.status})`);\n        console.log(response.data);\n        return response;\n      });\n    }\n  }\n}\n","import type {Quantizer, CompressedVector, Vector} from '../../types';\nimport {TDigest} from 'tdigest';\n\nexport class ScalarQuantizer implements Quantizer {\n  private quantizer: TDigest;\n  private levels: number;\n  quantiles: number[] = [];\n\n  constructor(levels: number = 256) {\n    this.quantizer = new TDigest(false);\n    this.levels = levels;\n    this.quantiles = [];\n  }\n\n  train(data: Vector[]): void {\n    // concat all vectors within the data\n    const scalars = data.reduce((acc, cur) => acc.concat(cur));\n\n    for (const scalar of scalars) {\n      this.quantizer.push(scalar);\n    }\n    this.quantiles = Array.from({length: this.levels}, (_, i) => this.quantizer.percentile(i / this.levels));\n  }\n\n  findIndex(scalar: number): number {\n    for (let i = 0; i < this.quantiles.length; i++) {\n      if (scalar < this.quantiles[i]) {\n        return i;\n      }\n    }\n    return this.levels - 1;\n  }\n\n  private dequantize(qv: number[]): number[] {\n    return qv.map(val => this.quantiles[val]);\n  }\n\n  private quantize(v: number[]): number[] {\n    return v.map(val => this.quantizeScalar(val));\n  }\n\n  private quantizeScalar(scalar: number): number {\n    return this.findIndex(scalar);\n  }\n\n  compress(data: Vector): CompressedVector {\n    const quantizedData: number[] = this.quantize(data);\n    return {\n      vector: quantizedData,\n      // id: data.id,\n    };\n  }\n\n  decompress(data: CompressedVector): Vector {\n    return this.dequantize(data.vector);\n  }\n}\n","export * from './pinecone';\nexport * from './typesense';\nexport * from './weaviate';\nexport * from './supabase';\nexport * from './base';\n","import type {Index, QueryResponse} from '@pinecone-database/pinecone';\nimport type {Query, DistanceMetric, MetadataFilter, QueryResult} from '../types';\nimport {VectorStore} from './base';\n\nexport class Pinecone extends VectorStore {\n  index: Index;\n\n  /**\n   * @param index a Pinecone index\n   * @param namespace (optional) namespace\n   * @param distanceMetric (optional) distance metric, defaults to cosine similarity\n   */\n  constructor(\n    index: Index,\n    kwargs?: {\n      historyField?: string;\n      embeddingSize?: number;\n      distanceMetric?: DistanceMetric;\n    }\n  ) {\n    super({\n      embeddingSize: kwargs?.embeddingSize,\n      distanceMetric: kwargs?.distanceMetric,\n      historyField: kwargs?.historyField,\n    });\n    this.index = index;\n  }\n\n  async search(query: Query): Promise<QueryResult[]> {\n    const result: QueryResponse = await this.index.query({\n      vector: query.embedding,\n      topK: query.top_k,\n      filter: query.filter,\n      includeMetadata: query.include_metadata,\n      includeValues: query.include_values,\n    });\n    if (result.matches === undefined) {\n      throw Error('No valid match for query');\n    }\n\n    return result.matches.map(r => ({\n      id: r.id,\n      metadata: r.metadata,\n      score: r.score ?? 0.0,\n      vector: r.values,\n    }));\n  }\n\n  async fetch(id: string) {\n    const result = await this.index.fetch([id]);\n    if (result.records && id in result.records) {\n      const {values, metadata} = result.records[id];\n      return {vector: values, metadata: metadata ?? {}, id};\n    }\n\n    throw new Error('Could not find a result.');\n  }\n\n  historyFilter(ids: string[], prevFilter?: object): MetadataFilter {\n    const filter = {\n      [this.historyField]: {$nin: ids},\n    };\n\n    if (prevFilter) {\n      const merged: Record<string, any> = {...prevFilter};\n\n      if (merged[this.historyField]) {\n        merged[this.historyField].$nin = Array.from(\n          new Set([...(merged[this.historyField].$nin || []), ...filter[this.historyField].$nin])\n        );\n      } else {\n        merged[this.historyField] = filter[this.historyField];\n      }\n\n      for (const [key, value] of Object.entries(filter)) {\n        if (key !== this.historyField && !(key in merged)) {\n          merged[key] = value;\n        }\n      }\n\n      return merged;\n    } else {\n      return filter;\n    }\n  }\n}\n","import constants from '../constants';\nimport type {MetadataFilter, Query, DistanceMetric, FetchResult, QueryResult} from '../types';\n\n/** Base vector store implementation.\n *\n * Every integration must extend & implement this abstract class.\n */\nexport abstract class VectorStore {\n  public embeddingSize: number;\n  public distanceMetric: DistanceMetric;\n  protected readonly historyField: string;\n\n  constructor(options?: {embeddingSize?: number; distanceMetric?: DistanceMetric; historyField?: string}) {\n    this.embeddingSize = options?.embeddingSize ?? constants.DEFAULTS.EMBEDDING_SIZE;\n    this.distanceMetric = options?.distanceMetric ?? constants.DEFAULTS.DISTANCE_METRIC;\n    this.historyField = options?.historyField ?? constants.DEFAULTS.HISTORY_FIELD;\n  }\n\n  async multiSearch(queries: Query[]): Promise<QueryResult[][]> {\n    return await Promise.all(queries.map(q => this.search(q)));\n  }\n\n  async multiFetch(ids: string[]): Promise<FetchResult[]> {\n    return await Promise.all(ids.map(id => this.fetch(id)));\n  }\n\n  public abstract search(query: Query): Promise<QueryResult[]>;\n  public abstract fetch(id: string): Promise<FetchResult>;\n  public abstract historyFilter(ids: string[], prevFilter?: object): MetadataFilter;\n}\n","// import type {Query, MetadataFilter, QueryMetadata, DistanceMetric, Vector, FetchResult} from '../types';\n// import {QueryResult} from '../query';\n// import constants from '../constants';\n// import {Client as TypesenseClient} from 'typesense';\n// import Collection from 'typesense/lib/Typesense/Collection';\n// import {MultiSearchRequestWithPresetSchema} from 'typesense/lib/Typesense/MultiSearch';\n// import {VectorStore} from './base';\n\n// export class Typesense extends VectorStore {\n//   private client: TypesenseClient;\n//   private collectionName: string;\n//   private collection: Collection; // FIXME: this is not used\n//   private metadataKey: string; // FIXME: this is not used\n\n//   constructor(\n//     client: TypesenseClient,\n//     kwargs?: {\n//       collectionName?: string;\n//       historyField?: string;\n//       embeddingSize?: number;\n//       distanceMetric?: DistanceMetric;\n//     }\n//   ) {\n//     super({\n//       embeddingSize: kwargs?.embeddingSize,\n//       distanceMetric: kwargs?.distanceMetric,\n//       historyField: kwargs?.historyField || '_id',\n//     });\n//     this.client = client;\n//     this.collectionName = kwargs?.collectionName || 'my_collection';\n//     this.collection = client.collections(this.collectionName);\n//     this.metadataKey = 'metadata';\n//   }\n\n//   async search(query: Query): Promise<QueryResult[]> {\n//     let queryObj;\n//     if (query.filter) {\n//       queryObj = {\n//         q: '*',\n//         vector_query: 'vec:({query.embedding.vector}, k:{query.top_k})',\n//         collection: this.collectionName,\n//       };\n//     } else {\n//       queryObj = {\n//         q: '*',\n//         vector_query: 'vec:({query.embedding.vector}, k:{query.top_k})',\n//         collection: this.collectionName,\n//         filter_by: query.filter,\n//       };\n//     }\n//     const res = await this.client.multiSearch.perform({searches: [queryObj as MultiSearchRequestWithPresetSchema]}, {});\n\n//     const ids: string[] = [];\n//     const scores: number[] = [];\n//     const vectors: Vector[] = [];\n//     const metadatas: QueryMetadata[] = [];\n//     const metadataObject: Record<string, any> = {};\n\n//     const q = new QueryResult_({vectors, metadatas, scores, ids});\n//     const hits = res.results[0]['hits'] as any[];\n//     for (let i = 0; i < hits.length; i++) {\n//       const document = res.results[0]['hits'][i];\n//       for (const [k, v] of Object.entries(document)) {\n//         if (k !== 'vec') {\n//           metadataObject[k] = v;\n//         }\n//       }\n//       const vecObj: number[] = document['vec'];\n//       q.metadatas.push(metadataObject);\n//       q.vectors.push({vector: vecObj, dim: vecObj.length, id: document['id']} as Vector);\n//       q.scores.push(document['vector_distance']);\n//       q.ids.push(document['id']);\n//     }\n//     return q;\n//   }\n\n//   async fetch(id: string): Promise<FetchResult> {\n//     const res = await this.client\n//       .collections<{\n//         vec: Vector;\n//         metadata: QueryMetadata;\n//         id: string;\n//       }>(this.collectionName)\n//       .documents(id)\n//       .retrieve();\n//     return {vector: res.vec, metadata: res.metadata, id: res.id};\n//   }\n\n//   historyFilter(ids: string[], prevFilter?: {[key: string]: any} | string): MetadataFilter {\n//     if (this.historyField !== '_id') {\n//       throw new Error(\"TypeSense doesn't allow filtering on id field. Try duplicating id in another field like _id.\");\n//     }\n\n//     let filter = `${this.historyField}:!=[${ids.join(',')}]`;\n\n//     if (prevFilter !== undefined && typeof prevFilter === 'string') {\n//       filter += ` && ${prevFilter}`;\n//     }\n\n//     // FIXME: implement this later\n//     return {};\n//   }\n// }\n","import type {WeaviateClient} from 'weaviate-ts-client';\nimport type {RecordMetadata} from '@pinecone-database/pinecone';\nimport type {Query, MetadataFilter, DistanceMetric, FetchResult, QueryResult} from '../types';\nimport {VectorStore} from './base';\n\nexport class Weaviate extends VectorStore {\n  private client: WeaviateClient;\n  private readonly className: string;\n  private readonly outputFields: string[] = [];\n\n  /** A wrapper for the Weaviate client.\n   * @param client a Weaviate client\n   * @param className (optional) className name\n   * @param outputFields (optional) an array of field names for outputs\n   * @param historyField (optional) the name of the `id` field for history filtering\n   * @param distanceMetric (optional) optional distance metric, defaults to cosine similarity\n   */\n  constructor(\n    client: WeaviateClient,\n    kwargs?: {\n      className?: string;\n      outputFields?: string[];\n      embeddingSize?: number;\n      historyField?: string;\n      distanceMetric?: DistanceMetric;\n    }\n  ) {\n    super({\n      embeddingSize: kwargs?.embeddingSize,\n      distanceMetric: kwargs?.distanceMetric,\n      historyField: kwargs?.historyField,\n    });\n    this.client = client;\n    this.className = kwargs?.className ?? 'my_collection';\n    this.outputFields = kwargs?.outputFields ?? ['text'];\n  }\n\n  async search(query: Query, options?: {additional?: string}): Promise<QueryResult[]> {\n    let queryObject = this.client.graphql.get();\n    queryObject.withClassName(this.className);\n    queryObject.withFields(this.outputFields?.join(' ') as string);\n\n    // FIXME: metadata causes issues when these fields are undefined, check later\n    if (typeof query.filter === 'object' && query.filter['operands'] && query.filter['operator']) {\n      queryObject = queryObject.withWhere({\n        operands: query.filter['operands'],\n        operator: query.filter['operator'],\n      });\n    }\n\n    if (options?.additional) {\n      queryObject = queryObject.withFields(`_additional { ${options.additional} }`);\n    }\n\n    if (query.include_values) {\n      queryObject = queryObject.withFields('_additional { vector } _additional { id } _additional { distance }');\n    } else {\n      queryObject = queryObject.withFields('_additional { id } _additional { distance }');\n    }\n\n    const result = await queryObject.withNearVector({vector: query.embedding}).withLimit(query.top_k).do();\n    const data = result.data['Get'][this.className.charAt(0).toUpperCase() + this.className.slice(1)];\n\n    return data.map((res: any) => ({\n      id: res['_additional'].id,\n      metadata: Object.fromEntries(this.outputFields.map(k => [k, res[k]])),\n      scores: res['_additional'].distance, // FIXME: is this correct? high score = high distance seems fishy\n      vector: res['_additional'].vector,\n    }));\n  }\n\n  async fetch(id: string): Promise<FetchResult> {\n    const result = await this.client.data.getterById().withClassName(this.className).withVector().withId(id).do();\n    const vector = result.vector as number[];\n    const metadata = {id, data: result.properties as RecordMetadata};\n    return {vector, metadata, id};\n  }\n\n  historyFilter(\n    ids: string[],\n    prevFilter?: {\n      operands: any[];\n      operator: string;\n    }\n  ): MetadataFilter {\n    const filter = prevFilter || {\n      operator: 'And',\n      operands: [],\n    };\n\n    for (const id of ids) {\n      const f = {\n        path: [this.historyField],\n        operator: 'NotEqual',\n        valueText: id,\n      };\n      filter.operands.push(f);\n    }\n\n    return filter;\n  }\n}\n","// import type {SupabaseClient} from '@supabase/supabase-js';\n// import type {PostgrestFilterBuilder} from '@supabase/postgrest-js';\n// import type {MetadataFilter, QueryMetadata, DistanceMetric, FetchResult, Vector, Query} from '../types';\n// import {QueryResult} from '../query';\n// import {VectorStore} from './base';\n\n// // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\n// export type SupabaseMetadata = Record<string, any>;\n// // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\n// export type SupabaseFilter = PostgrestFilterBuilder<any, any, any>;\n// export type SupabaseFilterRPCCall = (rpcCall: SupabaseFilter) => SupabaseFilter;\n\n// // compatible with Python FirstBatch SDK\n// export type SupabaseRecord = [string, number[], SupabaseMetadata];\n\n// /** Interface for the response returned when searching embeddings. */\n// interface SearchEmbeddingsResponse {\n//   id: number;\n//   content: string;\n//   metadata: object;\n//   embedding: number[];\n//   similarity: number;\n// }\n\n// // based on https://supabase.com/docs/guides/ai/vector-columns?database-method=sql\n// export class Supabase extends VectorStore {\n//   private client: SupabaseClient;\n//   private collectionName: string;\n//   private queryName: string;\n\n//   constructor(\n//     client: SupabaseClient,\n//     kwargs?: {\n//       collectionName?: string;\n//       queryName?: string;\n//       embeddingSize?: number;\n//       historyField?: string;\n//       distanceMetric?: DistanceMetric;\n//     }\n//   ) {\n//     super({\n//       embeddingSize: kwargs?.embeddingSize,\n//       distanceMetric: kwargs?.distanceMetric,\n//       historyField: kwargs?.historyField,\n//     });\n//     this.client = client;\n//     this.collectionName = kwargs?.collectionName || 'documents';\n//     this.queryName = kwargs?.queryName || 'match_documents';\n//   }\n\n//   async search(query: Query): Promise<QueryResult[]> {\n//     const ids: string[] = [];\n//     const scores: number[] = [];\n//     const vectors: Vector[] = [];\n//     const metadata: QueryMetadata[] = [];\n\n//     if (query.include_values) {\n//       const result = await this.queryWrapper(query.embedding.vector, query.top_k, query.filter as SupabaseFilter);\n\n//       const idsScore: Record<string, number[]> = Object.fromEntries(result.map(r => [r[0], r[1]]));\n//       const fetches = await this.fetchWrapper(Object.keys(idsScore));\n//       for (const f of fetches) {\n//         ids.push(f[0]);\n//         // FIXME: bad type\n//         // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n//         // @ts-ignore\n//         scores.push(idsScore[f[0]]);\n//         if (query.include_metadata) {\n//           vectors.push({vector: f[1], id: f[0]});\n//           metadata.push(f[2]);\n//         }\n//       }\n//     } else {\n//       const results = await this.queryWrapper(query.embedding.vector, query.top_k, query.filter);\n//       for (const r of results) {\n//         ids.push(r[0]);\n//         // FIXME: bad type\n//         // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n//         // @ts-ignore\n//         scores.push(r[0]);\n//         vectors.push({vector: [], id: r[0]});\n//         if (query.include_metadata) {\n//           vectors.push({vector: r[1], id: r[0]});\n//         }\n//       }\n//     }\n\n//     // TODO: return\n//   }\n\n//   async fetch(id: string): Promise<FetchResult> {\n//     const result = await this.fetchWrapper([id]);\n//     const metadata: QueryMetadata = result[0][2];\n//     const vector: Vector = {\n//       vector: result[0][1],\n//       id: id,\n//     };\n//     return {vector, metadata, id};\n//   }\n\n//   /** Simple SELECT query to vectors with matching ids. */\n//   private async fetchWrapper(ids: string[]): Promise<SupabaseRecord[]> {\n//     const result = await this.client\n//       .from(this.collectionName)\n//       .select<\n//         string,\n//         {\n//           id: SearchEmbeddingsResponse['id'];\n//           content: SearchEmbeddingsResponse['content'];\n//           embedding: SearchEmbeddingsResponse['embedding'];\n//           metadata: SearchEmbeddingsResponse['metadata'];\n//         }\n//       >('id,embedding,metadata')\n//       .in('id', ids);\n//     if (result.status !== 200) {\n//       throw result.error;\n//     }\n\n//     const data = result.data || [];\n//     return data.map(d => [d.id.toString(), d.embedding, d.metadata as SupabaseMetadata]);\n//   }\n\n//   /**\n//    *\n//    * Reference: https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/vectorstores/supabase.ts#L148\n//    */\n//   private async queryWrapper(data: number[], limit: number, filter: Record<string, any>): Promise<SupabaseRecord[]> {\n//     const result = await this.client.rpc(this.queryName, {\n//       query_embedding: data,\n//       match_count: limit,\n//       filter: filter,\n//       // TODO: add `include` args here within the rpc?\n//     });\n//     if (result.status !== 200) {\n//       throw result.error;\n//     }\n//     const results = result.data as SearchEmbeddingsResponse[];\n//     return results.map(r => [r.id.toString(), r.embedding, r.metadata]);\n//   }\n\n//   historyFilter(ids: string[], prevFilter?: Record<string, any>): MetadataFilter {\n//     // TODO: is there a better query option instead of `and`ing `ne`s?\n//     // TODO: these two branches are the same, just assign exisrting filter at first if there is one\n//     if (prevFilter) {\n//       prevFilter['$and'] = prevFilter['$and'] || [];\n//       for (const id in ids) {\n//         prevFilter['$and'].push({id_field: {$ne: id}});\n//       }\n//       return prevFilter;\n//     } else {\n//       const filter: Record<string, any> = {$and: []};\n//       for (const id in ids) {\n//         filter['$and'].push({id_field: {$ne: id}});\n//       }\n//       return filter;\n//     }\n//   }\n// }\n"],"names":[],"version":3,"file":"index.mjs.map","sourceRoot":"../"}