461bf6fd40
CI / lint (3.11) (push) Blocked by required conditions
CI / lint (3.12) (push) Blocked by required conditions
CI / lint (3.13) (push) Blocked by required conditions
CI / shellcheck (push) Waiting to run
CI / shfmt (push) Waiting to run
CI / setup (3.11) (push) Waiting to run
CI / setup (3.12) (push) Waiting to run
CI / setup (3.13) (push) Waiting to run
CI / check-licenses (3.12) (push) Blocked by required conditions
CI / test_unit (3.11) (push) Blocked by required conditions
CI / test_unit (3.12) (push) Blocked by required conditions
CI / test_unit (3.13) (push) Blocked by required conditions
CI / test_unit_no_extras (3.11) (push) Blocked by required conditions
CI / test_unit_no_extras (3.12) (push) Blocked by required conditions
CI / test_json_to_html (3.12) (push) Blocked by required conditions
CI / test_unit_no_extras (3.13) (push) Blocked by required conditions
CI / test_unit_dependency_extras (csv, 3.11, --extra csv) (push) Blocked by required conditions
CI / test_unit_dependency_extras (csv, 3.12, --extra csv) (push) Blocked by required conditions
CI / test_unit_dependency_extras (csv, 3.13, --extra csv) (push) Blocked by required conditions
CI / test_unit_dependency_extras (docx, 3.11, --extra docx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (docx, 3.12, --extra docx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (docx, 3.13, --extra docx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (markdown, 3.11, --extra md) (push) Blocked by required conditions
CI / test_unit_dependency_extras (markdown, 3.12, --extra md) (push) Blocked by required conditions
CI / test_unit_dependency_extras (markdown, 3.13, --extra md) (push) Blocked by required conditions
CI / test_unit_dependency_extras (odt, 3.11, --extra odt) (push) Blocked by required conditions
CI / test_unit_dependency_extras (odt, 3.12, --extra odt) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pdf-image, 3.12, --extra pdf --extra image --extra paddleocr) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pdf-image, 3.13, --extra pdf --extra image --extra paddleocr) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pptx, 3.13, --extra pptx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (odt, 3.13, --extra odt) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pdf-image, 3.11, --extra pdf --extra image --extra paddleocr) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pptx, 3.11, --extra pptx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pptx, 3.12, --extra pptx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pypandoc, 3.11, --extra epub --extra org --extra rtf --extra rst) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pypandoc, 3.12, --extra epub --extra org --extra rtf --extra rst) (push) Blocked by required conditions
CI / test_unit_dependency_extras (pypandoc, 3.13, --extra epub --extra org --extra rtf --extra rst) (push) Blocked by required conditions
CI / test_unit_dependency_extras (xlsx, 3.11, --extra xlsx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (xlsx, 3.12, --extra xlsx) (push) Blocked by required conditions
CI / test_unit_dependency_extras (xlsx, 3.13, --extra xlsx) (push) Blocked by required conditions
CI / test_ingest_src (3.12) (push) Blocked by required conditions
CI / test_json_to_markdown (3.12) (push) Blocked by required conditions
CI / changelog (push) Waiting to run
CI / test_dockerfile (push) Blocked by required conditions
CodeQL / Analyze (python) (push) Waiting to run
Build And Push Docker Image / set-short-sha (push) Waiting to run
Build And Push Docker Image / build-images (linux/amd64, opensource-linux-8core) (push) Blocked by required conditions
Build And Push Docker Image / build-images (linux/arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
Build And Push Docker Image / publish-images (push) Blocked by required conditions
Partition Benchmark / setup (push) Waiting to run
Partition Benchmark / Measure and compare partition() runtime (push) Blocked by required conditions
179 lines
5.3 KiB
Python
179 lines
5.3 KiB
Python
import os
|
|
from dataclasses import dataclass, field
|
|
from typing import TYPE_CHECKING, List, Optional
|
|
|
|
import numpy as np
|
|
from pydantic import Field, SecretStr
|
|
|
|
from unstructured.documents.elements import Element
|
|
from unstructured.embed.interfaces import BaseEmbeddingEncoder, EmbeddingConfig
|
|
from unstructured.utils import requires_dependencies
|
|
|
|
USER_AGENT = "@mixedbread-ai/unstructured"
|
|
BATCH_SIZE = 128
|
|
TIMEOUT = 60
|
|
MAX_RETRIES = 3
|
|
ENCODING_FORMAT = "float"
|
|
TRUNCATION_STRATEGY = "end"
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
from mixedbread_ai.client import MixedbreadAI
|
|
from mixedbread_ai.core import RequestOptions
|
|
|
|
|
|
class MixedbreadAIEmbeddingConfig(EmbeddingConfig):
|
|
"""
|
|
Configuration class for Mixedbread AI Embedding Encoder.
|
|
|
|
Attributes:
|
|
api_key (str): API key for accessing Mixedbread AI..
|
|
model_name (str): Name of the model to use for embeddings.
|
|
"""
|
|
|
|
api_key: SecretStr = Field(
|
|
default_factory=lambda: SecretStr(os.environ.get("MXBAI_API_KEY")),
|
|
)
|
|
|
|
model_name: str = Field(
|
|
default="mixedbread-ai/mxbai-embed-large-v1",
|
|
)
|
|
|
|
@requires_dependencies(
|
|
["mixedbread_ai"],
|
|
extras="embed-mixedbreadai",
|
|
)
|
|
def get_client(self) -> "MixedbreadAI":
|
|
"""
|
|
Create the Mixedbread AI client.
|
|
|
|
Returns:
|
|
MixedbreadAI: Initialized client.
|
|
"""
|
|
from mixedbread_ai.client import MixedbreadAI
|
|
|
|
return MixedbreadAI(
|
|
api_key=self.api_key.get_secret_value(),
|
|
)
|
|
|
|
|
|
@dataclass
|
|
class MixedbreadAIEmbeddingEncoder(BaseEmbeddingEncoder):
|
|
"""
|
|
Embedding encoder for Mixedbread AI.
|
|
|
|
Attributes:
|
|
config (MixedbreadAIEmbeddingConfig): Configuration for the embedding encoder.
|
|
"""
|
|
|
|
config: MixedbreadAIEmbeddingConfig
|
|
|
|
_exemplary_embedding: Optional[List[float]] = field(init=False, default=None)
|
|
_request_options: Optional["RequestOptions"] = field(init=False, default=None)
|
|
|
|
def get_exemplary_embedding(self) -> List[float]:
|
|
"""Get an exemplary embedding to determine dimensions and unit vector status."""
|
|
return self._embed(["Q"])[0]
|
|
|
|
def initialize(self):
|
|
if self.config.api_key is None:
|
|
raise ValueError(
|
|
"The Mixedbread AI API key must be specified."
|
|
+ "You either pass it in the constructor using 'api_key'"
|
|
+ "or via the 'MXBAI_API_KEY' environment variable."
|
|
)
|
|
|
|
from mixedbread_ai.core import RequestOptions
|
|
|
|
self._request_options = RequestOptions(
|
|
max_retries=MAX_RETRIES,
|
|
timeout_in_seconds=TIMEOUT,
|
|
additional_headers={"User-Agent": USER_AGENT},
|
|
)
|
|
|
|
@property
|
|
def num_of_dimensions(self):
|
|
"""Get the number of dimensions for the embeddings."""
|
|
exemplary_embedding = self.get_exemplary_embedding()
|
|
return np.shape(exemplary_embedding)
|
|
|
|
@property
|
|
def is_unit_vector(self) -> bool:
|
|
"""Check if the embedding is a unit vector."""
|
|
exemplary_embedding = self.get_exemplary_embedding()
|
|
return np.isclose(np.linalg.norm(exemplary_embedding), 1.0)
|
|
|
|
def _embed(self, texts: List[str]) -> List[List[float]]:
|
|
"""
|
|
Embed a list of texts using the Mixedbread AI API.
|
|
|
|
Args:
|
|
texts (List[str]): List of texts to embed.
|
|
|
|
Returns:
|
|
List[List[float]]: List of embeddings.
|
|
"""
|
|
batch_size = BATCH_SIZE
|
|
batch_itr = range(0, len(texts), batch_size)
|
|
|
|
responses = []
|
|
client = self.config.get_client()
|
|
for i in batch_itr:
|
|
batch = texts[i : i + batch_size]
|
|
response = client.embeddings(
|
|
model=self.config.model_name,
|
|
normalized=True,
|
|
encoding_format=ENCODING_FORMAT,
|
|
truncation_strategy=TRUNCATION_STRATEGY,
|
|
request_options=self._request_options,
|
|
input=batch,
|
|
)
|
|
responses.append(response)
|
|
return [item.embedding for response in responses for item in response.data]
|
|
|
|
@staticmethod
|
|
def _add_embeddings_to_elements(
|
|
elements: List[Element], embeddings: List[List[float]]
|
|
) -> List[Element]:
|
|
"""
|
|
Add embeddings to elements.
|
|
|
|
Args:
|
|
elements (List[Element]): List of elements.
|
|
embeddings (List[List[float]]): List of embeddings.
|
|
|
|
Returns:
|
|
List[Element]: Elements with embeddings added.
|
|
"""
|
|
assert len(elements) == len(embeddings)
|
|
elements_w_embedding = []
|
|
for i, element in enumerate(elements):
|
|
element.embeddings = embeddings[i]
|
|
elements_w_embedding.append(element)
|
|
return elements
|
|
|
|
def embed_documents(self, elements: List[Element]) -> List[Element]:
|
|
"""
|
|
Embed a list of document elements.
|
|
|
|
Args:
|
|
elements (List[Element]): List of document elements.
|
|
|
|
Returns:
|
|
List[Element]: Elements with embeddings.
|
|
"""
|
|
embeddings = self._embed([str(e) for e in elements])
|
|
return self._add_embeddings_to_elements(elements, embeddings)
|
|
|
|
def embed_query(self, query: str) -> List[float]:
|
|
"""
|
|
Embed a query string.
|
|
|
|
Args:
|
|
query (str): Query string to embed.
|
|
|
|
Returns:
|
|
List[float]: Embedding of the query.
|
|
"""
|
|
return self._embed([query])[0]
|