-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Add Mistral AI batch processing example to MistralEmbeddingFunction #5597
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -10,13 +10,15 @@ def __init__( | |||||||||||
self, | ||||||||||||
model: str, | ||||||||||||
api_key_env_var: str = "MISTRAL_API_KEY", | ||||||||||||
max_chunk_size: int = 50 | ||||||||||||
): | ||||||||||||
""" | ||||||||||||
Initialize the MistralEmbeddingFunction. | ||||||||||||
|
||||||||||||
Args: | ||||||||||||
model (str): The name of the model to use for text embeddings. | ||||||||||||
api_key_env_var (str): The environment variable name for the Mistral API key. | ||||||||||||
max_chunk_size (int): The maximal size of chunk to embed. Default to 50. | ||||||||||||
""" | ||||||||||||
try: | ||||||||||||
from mistralai import Mistral | ||||||||||||
|
@@ -30,23 +32,29 @@ def __init__( | |||||||||||
if not self.api_key: | ||||||||||||
raise ValueError(f"The {api_key_env_var} environment variable is not set.") | ||||||||||||
self.client = Mistral(api_key=self.api_key) | ||||||||||||
self.max_chunk_size = max_chunk_size | ||||||||||||
|
||||||||||||
def __call__(self, input: Documents) -> Embeddings: | ||||||||||||
""" | ||||||||||||
Get the embeddings for a list of texts. | ||||||||||||
|
||||||||||||
Note: | ||||||||||||
Mistral AI API will provide auto-chunking in the future (https://docs.mistral.ai/capabilities/embeddings/text_embeddings/#batch-processing) | ||||||||||||
|
||||||||||||
Args: | ||||||||||||
input (Documents): A list of texts to get embeddings for. | ||||||||||||
""" | ||||||||||||
if not all(isinstance(item, str) for item in input): | ||||||||||||
raise ValueError("Mistral only supports text documents, not images") | ||||||||||||
output = self.client.embeddings.create( | ||||||||||||
model=self.model, | ||||||||||||
inputs=input, | ||||||||||||
|
||||||||||||
chunks = (input[x : x + self.max_chunk_size] for x in range(0, len(input), self.max_chunk_size)) | ||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [BestPractice] Empty input handling is missing. If
Suggested change
⚡ Committable suggestion Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Context for Agents
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I haven't added those changes since the test above should raise an error before. |
||||||||||||
embeddings_response = ( | ||||||||||||
self.client.embeddings.create(model=self.model, inputs=c) for c in chunks | ||||||||||||
Comment on lines
+51
to
+52
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [BestPractice] Missing Error Handling: API calls to Add error handling: for chunk in chunks:
try:
response = self.client.embeddings.create(model=self.model, inputs=chunk)
all_embeddings.extend([np.array(d.embedding) for d in response.data])
except Exception as e:
raise RuntimeError(f"Failed to get embeddings for chunk: {e}") from e Context for Agents
|
||||||||||||
) | ||||||||||||
|
||||||||||||
|
||||||||||||
# Extract embeddings from the response | ||||||||||||
return [np.array(data.embedding) for data in output.data] | ||||||||||||
return [np.array(d.embedding) for e in embeddings_response for d in e.data] | ||||||||||||
|
||||||||||||
@staticmethod | ||||||||||||
def name() -> str: | ||||||||||||
|
@@ -62,15 +70,17 @@ def supported_spaces(self) -> List[Space]: | |||||||||||
def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": | ||||||||||||
model = config.get("model") | ||||||||||||
api_key_env_var = config.get("api_key_env_var") | ||||||||||||
max_chunk_size = config.get("max_chunk_size") | ||||||||||||
|
||||||||||||
if model is None or api_key_env_var is None: | ||||||||||||
if model is None or api_key_env_var is None or max_chunk_size is None: | ||||||||||||
assert False, "This code should not be reached" # this is for type checking | ||||||||||||
return MistralEmbeddingFunction(model=model, api_key_env_var=api_key_env_var) | ||||||||||||
return MistralEmbeddingFunction(model=model, api_key_env_var=api_key_env_var, max_chunk_size=max_chunk_size) | ||||||||||||
|
||||||||||||
def get_config(self) -> Dict[str, Any]: | ||||||||||||
return { | ||||||||||||
"model": self.model, | ||||||||||||
"api_key_env_var": self.api_key_env_var, | ||||||||||||
"max_chunk_size": self.max_chunk_size | ||||||||||||
} | ||||||||||||
|
||||||||||||
def validate_config_update( | ||||||||||||
|
Uh oh!
There was an error while loading. Please reload this page.