-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[ENH] Add nomic embedding function #4911
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
Merged
+159
−0
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
129 changes: 129 additions & 0 deletions
129
chromadb/utils/embedding_functions/nomic_embedding_function.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| from chromadb.api.types import ( | ||
| Embeddings, | ||
| Documents, | ||
| EmbeddingFunction, | ||
| Space, | ||
| ) | ||
| from chromadb.utils.embedding_functions.schemas import validate_config_schema | ||
| from typing import List, Dict, Any, TypedDict, Optional | ||
| import os | ||
| import numpy as np | ||
|
|
||
|
|
||
| class NomicQueryConfig(TypedDict): | ||
| task_type: str | ||
|
|
||
|
|
||
| class NomicEmbeddingFunction(EmbeddingFunction[Documents]): | ||
| """ | ||
| This class is used to get embeddings for a list of texts using the Nomic API. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: str, | ||
| task_type: str, | ||
| query_config: Optional[NomicQueryConfig], | ||
| api_key_env_var: str = "NOMIC_API_KEY", | ||
| ): | ||
| """ | ||
| Initialize the NomicEmbeddingFunction. | ||
|
|
||
| Args: | ||
| model (str): The name of the model to use for text embeddings. | ||
| task_type (str): The type of task to embed with. See reference https://docs.nomic.ai/platform/embeddings-and-retrieval/text-embedding#embedding-task-types | ||
| query_config (Optional[NomicQueryConfig]): The configuration for setting task type for queries | ||
| api_key_env_var (str): The environment variable name for the Nomic API key. Defaults to "NOMIC_API_KEY". | ||
|
|
||
| Supported task types: search_document, search_query, classification, clustering | ||
| """ | ||
| try: | ||
| from nomic import embed | ||
| except ImportError: | ||
| raise ValueError( | ||
| "The nomic python package is not installed. Please install it with `pip install nomic`" | ||
| ) | ||
|
|
||
| self.model = model | ||
| self.task_type = task_type | ||
| self.api_key_env_var = api_key_env_var | ||
| self.api_key = os.getenv(api_key_env_var) | ||
| self.query_config = query_config | ||
| if not self.api_key: | ||
| raise ValueError(f"The {api_key_env_var} environment variable is not set.") | ||
| self.embed = embed | ||
|
|
||
| def __call__(self, input: Documents) -> Embeddings: | ||
| if not all(isinstance(item, str) for item in input): | ||
| raise ValueError("Nomic only supports text documents, not images") | ||
| output = self.embed.text( | ||
| model=self.model, | ||
| texts=input, | ||
| task_type=self.task_type, | ||
| ) | ||
| return [np.array(data.embedding) for data in output.data] | ||
|
|
||
| def embed_query(self, input: Documents) -> Embeddings: | ||
| if not all(isinstance(item, str) for item in input): | ||
| raise ValueError("Nomic only supports text queries, not images") | ||
|
|
||
| task_type = ( | ||
| self.query_config.get("task_type") if self.query_config else self.task_type | ||
| ) | ||
| output = self.embed.text( | ||
| model=self.model, | ||
| texts=input, | ||
| task_type=task_type, | ||
| ) | ||
| return [np.array(data.embedding) for data in output.data] | ||
|
|
||
| @staticmethod | ||
| def name() -> str: | ||
| return "nomic" | ||
|
|
||
| def default_space(self) -> Space: | ||
| return "cosine" | ||
|
|
||
| def supported_spaces(self) -> List[Space]: | ||
| return ["cosine", "l2", "ip"] | ||
|
|
||
| @staticmethod | ||
| def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": | ||
| model = config.get("model") | ||
| api_key_env_var = config.get("api_key_env_var") | ||
| task_type = config.get("task_type") | ||
| query_config = config.get("query_config") | ||
| if model is None or api_key_env_var is None or task_type is None: | ||
| assert False, "This code should not be reached" # this is for type checking | ||
| return NomicEmbeddingFunction( | ||
| model=model, | ||
| api_key_env_var=api_key_env_var, | ||
| task_type=task_type, | ||
| query_config=query_config, | ||
| ) | ||
|
|
||
| def get_config(self) -> Dict[str, Any]: | ||
| return { | ||
| "model": self.model, | ||
| "api_key_env_var": self.api_key_env_var, | ||
| "task_type": self.task_type, | ||
| "query_config": self.query_config, | ||
| } | ||
|
|
||
| def validate_config_update( | ||
| self, old_config: Dict[str, Any], new_config: Dict[str, Any] | ||
| ) -> None: | ||
| if "model" in new_config: | ||
| raise ValueError( | ||
| "The model cannot be changed after the embedding function has been initialized." | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def validate_config(config: Dict[str, Any]) -> None: | ||
| """ | ||
| Validate the configuration using the JSON schema. | ||
|
|
||
| Args: | ||
| config: Configuration to validate | ||
| """ | ||
| validate_config_schema(config, "nomic") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| { | ||
|
Collaborator
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. Can we validate that we are using these in schema? |
||
| "$schema": "http://json-schema.org/draft-07/schema#", | ||
| "title": "Nomic Embedding Function Schema", | ||
| "description": "Schema for the Nomic embedding function configuration", | ||
| "version": "1.0.0", | ||
| "type": "object", | ||
| "properties": { | ||
| "model": { | ||
| "type": "string", | ||
| "description": "Parameter model for the Nomic embedding function" | ||
| }, | ||
| "api_key_env_var": { | ||
| "type": "string", | ||
| "description": "Parameter api_key_env_var for the Nomic embedding function" | ||
| }, | ||
| "task_type": { | ||
| "type": "string", | ||
| "description": "Parameter task_type for the Nomic embedding function" | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.