MCPcopy Create free account
hub / github.com/alibaba/zvec / embed

Method embed

python/zvec/extension/bm25_embedding_function.py:287–375  ·  view source on GitHub ↗

Generate BM25 sparse embedding for the input text. This method computes BM25 scores for the input text using DashText's SparseVectorEncoder. The encoding behavior depends on the encoding_type: - ``encoding_type="query"``: Uses ``encode_queries()`` for search queries

(self, input: TEXT)

Source from the content-addressed store, hash-verified

285
286 @lru_cache(maxsize=10)
287 def embed(self, input: TEXT) -> SparseVectorType:
288 """Generate BM25 sparse embedding for the input text.
289
290 This method computes BM25 scores for the input text using DashText's
291 SparseVectorEncoder. The encoding behavior depends on the encoding_type:
292
293 - ``encoding_type="query"``: Uses ``encode_queries()`` for search queries
294 - ``encoding_type="document"``: Uses ``encode_documents()`` for documents
295
296 The result is a sparse vector where keys are term indices in the
297 vocabulary and values are BM25 scores.
298
299 Args:
300 input (TEXT): Input text string to embed. Must be non-empty after
301 stripping whitespace.
302
303 Returns:
304 SparseVectorType: A dictionary mapping vocabulary term index to BM25 score.
305 Only non-zero scores are included. The dictionary is sorted by indices
306 (keys) in ascending order for consistent output.
307 Example: ``{1169440797: 0.29, 2045788977: 0.70, ...}``
308
309 Raises:
310 TypeError: If ``input`` is not a string.
311 ValueError: If input is empty or whitespace-only.
312 RuntimeError: If BM25 encoding fails.
313
314 Examples:
315 >>> bm25 = BM25EmbeddingFunction(language="zh", encoding_type="query")
316 >>> sparse_vec = bm25.embed("query text")
317 >>> isinstance(sparse_vec, dict)
318 True
319 >>> all(isinstance(k, int) and isinstance(v, float) for k, v in sparse_vec.items())
320 True
321
322 >>> # Verify sorted output
323 >>> keys = list(sparse_vec.keys())
324 >>> keys == sorted(keys)
325 True
326
327 >>> # Error: empty input
328 >>> bm25.embed(" ")
329 ValueError: Input text cannot be empty or whitespace only
330
331 >>> # Error: non-string input
332 >>> bm25.embed(123)
333 TypeError: Expected 'input' to be str, got int
334
335 Note:
336 - BM25 scores are relative to the vocabulary statistics
337 - Output dictionary is always sorted by indices for consistency
338 - Terms not in the vocabulary will have zero scores (not included)
339 - This method is cached (maxsize=10) for performance
340 - DashText automatically handles Chinese/English text segmentation
341 """
342 if not isinstance(input, str):
343 raise TypeError(f"Expected 'input' to be str, got {type(input).__name__}")
344

Calls

no outgoing calls