|
| 1 | +from pyseekdb.client.embedding_function import EmbeddingFunction, Embeddings, Documents |
| 2 | +from typing import Any, Optional |
| 3 | +import os |
| 4 | + |
| 5 | + |
| 6 | +class OpenAIBaseEmbeddingFunction(EmbeddingFunction[Documents]): |
| 7 | + """ |
| 8 | + Base embedding function for OpenAI-compatible embedding APIs. |
| 9 | +
|
| 10 | + This class provides a common implementation for embedding functions that use |
| 11 | + OpenAI-compatible APIs. It uses the `openai` package to make API calls. |
| 12 | +
|
| 13 | + Subclasses should override: |
| 14 | + - `_get_default_api_base()`: Return the default API base URL |
| 15 | + - `_get_default_api_key_env()`: Return the default API key environment variable name |
| 16 | + - `_get_model_dimensions()`: Return a dict mapping model names to their default dimensions |
| 17 | + - Optionally override `__init__` to set model-specific defaults |
| 18 | +
|
| 19 | + Example: |
| 20 | + .. code-block:: python |
| 21 | + class MyEmbeddingFunction(OpenAIBaseEmbeddingFunction): |
| 22 | + def _get_default_api_base(self): |
| 23 | + return "https://api.example.com/v1" |
| 24 | +
|
| 25 | + def _get_default_api_key_env(self): |
| 26 | + return "MY_API_KEY" |
| 27 | +
|
| 28 | + def _get_model_dimensions(self): |
| 29 | + return {"model-v1": 1536, "model-v2": 1024} |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + model_name: str, |
| 35 | + api_key_env: Optional[str] = None, |
| 36 | + api_base: Optional[str] = None, |
| 37 | + dimensions: Optional[int] = None, |
| 38 | + **kwargs: Any, |
| 39 | + ): |
| 40 | + """Initialize OpenAIBaseEmbeddingFunction. |
| 41 | +
|
| 42 | + Args: |
| 43 | + model_name (str): Name of the embedding model. |
| 44 | + api_key_env (str, optional): Name of the environment variable containing the API key. |
| 45 | + Defaults to the value returned by `_get_default_api_key_env()`. |
| 46 | + api_base (str, optional): Base URL for the API endpoint. |
| 47 | + Defaults to the value returned by `_get_default_api_base()`. |
| 48 | + dimensions (int, optional): The number of dimensions the resulting embeddings should have. |
| 49 | + Can reduce dimensions from default for models that support it. |
| 50 | + **kwargs: Additional arguments to pass to the OpenAI client. |
| 51 | + Common options include: |
| 52 | + - timeout: Request timeout in seconds |
| 53 | + - max_retries: Maximum number of retries |
| 54 | + - See https://github.com/openai/openai-python for more options |
| 55 | + """ |
| 56 | + try: |
| 57 | + from openai import OpenAI |
| 58 | + except ImportError: |
| 59 | + raise ValueError( |
| 60 | + "The openai python package is not installed. Please install it with `pip install openai`" |
| 61 | + ) |
| 62 | + |
| 63 | + # Set defaults |
| 64 | + if api_key_env is None: |
| 65 | + api_key_env = self._get_default_api_key_env() |
| 66 | + if api_base is None: |
| 67 | + api_base = self._get_default_api_base() |
| 68 | + |
| 69 | + # Validate that API key is available |
| 70 | + api_key = os.environ.get(api_key_env) |
| 71 | + if api_key is None: |
| 72 | + raise ValueError( |
| 73 | + f"API key environment variable '{api_key_env}' is not set. " |
| 74 | + f"Please set it before using {self.__class__.__name__}." |
| 75 | + ) |
| 76 | + |
| 77 | + # Store configuration |
| 78 | + self.model_name = model_name |
| 79 | + self.api_key_env = api_key_env |
| 80 | + self.api_base = api_base |
| 81 | + self._dimensions_param = dimensions |
| 82 | + self._client_kwargs = kwargs |
| 83 | + |
| 84 | + # Initialize OpenAI client |
| 85 | + self._client = OpenAI( |
| 86 | + api_key=api_key, |
| 87 | + base_url=api_base, |
| 88 | + **kwargs |
| 89 | + ) |
| 90 | + |
| 91 | + # Store original model name for dimension lookup |
| 92 | + self._model_name = model_name |
| 93 | + |
| 94 | + def _get_default_api_base(self) -> str: |
| 95 | + """Get the default API base URL for this provider. |
| 96 | +
|
| 97 | + Subclasses should override this method. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + str: Default API base URL |
| 101 | + """ |
| 102 | + raise NotImplementedError( |
| 103 | + "Subclasses must implement _get_default_api_base()" |
| 104 | + ) |
| 105 | + |
| 106 | + def _get_default_api_key_env(self) -> str: |
| 107 | + """Get the default API key environment variable name for this provider. |
| 108 | +
|
| 109 | + Subclasses should override this method. |
| 110 | +
|
| 111 | + Returns: |
| 112 | + str: Default API key environment variable name |
| 113 | + """ |
| 114 | + raise NotImplementedError( |
| 115 | + "Subclasses must implement _get_default_api_key_env()" |
| 116 | + ) |
| 117 | + |
| 118 | + def _get_model_dimensions(self) -> dict[str, int]: |
| 119 | + """Get a dictionary mapping model names to their default dimensions. |
| 120 | +
|
| 121 | + Subclasses should override this method. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + dict[str, int]: Dictionary mapping model names to dimensions |
| 125 | + """ |
| 126 | + return {} |
| 127 | + |
| 128 | + @property |
| 129 | + def dimension(self) -> int: |
| 130 | + """Get the dimension of embeddings produced by this function. |
| 131 | +
|
| 132 | + Returns the known dimension for models without making an API call. |
| 133 | + If the dimensions parameter is specified, that value is returned. |
| 134 | + Otherwise, the default dimension for the model is returned. |
| 135 | +
|
| 136 | + If the model is not in the known dimensions list, falls back to calling |
| 137 | + the parent's dimension detection (which may make an API call). |
| 138 | +
|
| 139 | + Returns: |
| 140 | + int: The dimension of embeddings for this model. |
| 141 | + """ |
| 142 | + # If dimensions parameter is explicitly set, use it |
| 143 | + if self._dimensions_param is not None: |
| 144 | + return self._dimensions_param |
| 145 | + |
| 146 | + # Check if we know the dimension for this model |
| 147 | + model_dimensions = self._get_model_dimensions() |
| 148 | + if self._model_name in model_dimensions: |
| 149 | + return model_dimensions[self._model_name] |
| 150 | + |
| 151 | + # Fallback: make an API call to get the embedding and infer the dimension |
| 152 | + # This is done by actually generating an embedding for a dummy sentence |
| 153 | + test_input = "dimension probing" |
| 154 | + try: |
| 155 | + embeddings = self([test_input]) |
| 156 | + except Exception as e: |
| 157 | + raise RuntimeError(f"Failed to determine embedding dimension via API call: {e}") |
| 158 | + if not embeddings or not isinstance(embeddings, list) or not isinstance(embeddings[0], list): |
| 159 | + raise RuntimeError("Could not get embedding dimension from API response") |
| 160 | + return len(embeddings[0]) |
| 161 | + |
| 162 | + def __call__(self, input: Documents) -> Embeddings: |
| 163 | + """Generate embeddings for the given documents. |
| 164 | +
|
| 165 | + Args: |
| 166 | + input: Documents to generate embeddings for. Can be a single string or list of strings. |
| 167 | +
|
| 168 | + Returns: |
| 169 | + Embeddings for the documents as a list of lists of floats. |
| 170 | + """ |
| 171 | + # Handle single string input |
| 172 | + if isinstance(input, str): |
| 173 | + input = [input] |
| 174 | + |
| 175 | + # Handle empty input |
| 176 | + if not input: |
| 177 | + return [] |
| 178 | + |
| 179 | + # Prepare request parameters |
| 180 | + request_params = { |
| 181 | + "model": self.model_name, |
| 182 | + "input": input, |
| 183 | + } |
| 184 | + |
| 185 | + # Add dimensions parameter if specified |
| 186 | + if self._dimensions_param is not None: |
| 187 | + request_params["dimensions"] = self._dimensions_param |
| 188 | + |
| 189 | + # Call OpenAI API |
| 190 | + response = self._client.embeddings.create(**request_params) |
| 191 | + |
| 192 | + # Extract embeddings from response |
| 193 | + embeddings = [item.embedding for item in response.data] |
| 194 | + |
| 195 | + # Validate that we got the expected number of embeddings |
| 196 | + if len(embeddings) != len(input): |
| 197 | + raise ValueError( |
| 198 | + f"Expected {len(input)} embeddings but got {len(embeddings)} from API" |
| 199 | + ) |
| 200 | + |
| 201 | + return embeddings |
0 commit comments