Generate a dense embedding vector for the input text. Results are cached (LRU, up to 256 entries) so repeated strings do not trigger extra HTTP requests. Args: input (TEXT): Input text string to embed. Must be non-empty after stripping whitespac
(self, input: TEXT)
| 107 | |
| 108 | @lru_cache(maxsize=256) |
| 109 | def embed(self, input: TEXT) -> DenseVectorType: |
| 110 | """Generate a dense embedding vector for the input text. |
| 111 | |
| 112 | Results are cached (LRU, up to 256 entries) so repeated strings |
| 113 | do not trigger extra HTTP requests. |
| 114 | |
| 115 | Args: |
| 116 | input (TEXT): Input text string to embed. Must be non-empty |
| 117 | after stripping whitespace. |
| 118 | |
| 119 | Returns: |
| 120 | DenseVectorType: A list of floats representing the embedding. |
| 121 | |
| 122 | Raises: |
| 123 | TypeError: If *input* is not a string. |
| 124 | ValueError: If *input* is empty/whitespace-only or the server |
| 125 | returns an unexpected response format. |
| 126 | RuntimeError: If the HTTP request fails. |
| 127 | """ |
| 128 | if not isinstance(input, TEXT): |
| 129 | raise TypeError(f"Expected 'input' to be str, got {type(input).__name__}") |
| 130 | |
| 131 | input = input.strip() |
| 132 | if not input: |
| 133 | raise ValueError("Input text cannot be empty or whitespace only") |
| 134 | |
| 135 | url = self._base_url + self.ENDPOINT |
| 136 | payload = json.dumps({"model": self._model, "input": input}).encode() |
| 137 | |
| 138 | headers: dict[str, str] = {"Content-Type": "application/json"} |
| 139 | if self._api_key: |
| 140 | headers["Authorization"] = f"Bearer {self._api_key}" |
| 141 | |
| 142 | req = urllib.request.Request(url, data=payload, headers=headers, method="POST") |
| 143 | try: |
| 144 | with urllib.request.urlopen(req, timeout=self._timeout) as resp: |
| 145 | body = json.loads(resp.read()) |
| 146 | except urllib.error.HTTPError as exc: |
| 147 | raise RuntimeError( |
| 148 | f"Embedding server returned HTTP {exc.code}: {exc.read().decode()}" |
| 149 | ) from exc |
| 150 | except OSError as exc: |
| 151 | raise RuntimeError( |
| 152 | f"Could not reach embedding server at {url}: {exc}" |
| 153 | ) from exc |
| 154 | |
| 155 | try: |
| 156 | vector: list[float] = body["data"][0]["embedding"] |
| 157 | except (KeyError, IndexError) as exc: |
| 158 | raise ValueError( |
| 159 | f"Unexpected response format from embedding server: {body}" |
| 160 | ) from exc |
| 161 | |
| 162 | return vector |