-
Notifications
You must be signed in to change notification settings - Fork 477
feat(examples): add custom HTTP embedding example for LM Studio / Ollama #149
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
Open
cluster2600
wants to merge
8
commits into
alibaba:main
Choose a base branch
from
cluster2600:feat/lmstudio-custom-http-embedding
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+164
−0
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ca75c18
feat(examples): add custom HTTP embedding example for LM Studio / Ollama
cluster2600 9a81b28
feat(extension): promote HTTPDenseEmbedding to first-class extension
cluster2600 e5dee48
fix(examples): resolve ruff lint errors in HTTP embedding example
cluster2600 400dacf
style: apply ruff formatter
cluster2600 eb3960e
ci: retrigger CI (flaky macOS C++ test)
cluster2600 327d718
chore: remove custom HTTP embedding example
cluster2600 697a503
Merge branch 'main' into feat/lmstudio-custom-http-embedding
cluster2600 e91e5cd
Merge branch 'main' into feat/lmstudio-custom-http-embedding
cluster2600 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| # Copyright 2025-present the zvec project | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| import urllib.request | ||
| from functools import lru_cache | ||
| from typing import Optional | ||
|
|
||
| from ..common.constants import TEXT, DenseVectorType | ||
| from .embedding_function import DenseEmbeddingFunction | ||
|
|
||
|
|
||
| class HTTPDenseEmbedding(DenseEmbeddingFunction[TEXT]): | ||
| """Dense text embedding function using any OpenAI-compatible HTTP endpoint. | ||
|
|
||
| This class calls any server that implements the ``/v1/embeddings`` API | ||
| (LM Studio, Ollama, vLLM, LocalAI, etc.) using only the Python standard | ||
| library — no extra dependencies are required. | ||
|
|
||
| The embedding dimension is detected automatically from the first server | ||
| response. | ||
|
|
||
| Args: | ||
| base_url (str, optional): Base URL of the embedding server. | ||
| Defaults to ``"http://localhost:1234"`` (LM Studio). | ||
| Common values: | ||
|
|
||
| - ``"http://localhost:1234"`` — LM Studio | ||
| - ``"http://localhost:11434"`` — Ollama | ||
| model (str, optional): Model identifier as expected by the server. | ||
| Defaults to ``"text-embedding-nomic-embed-text-v1.5@f16"``. | ||
| api_key (Optional[str], optional): Bearer token for authenticated | ||
| endpoints. Falls back to the ``OPENAI_API_KEY`` environment | ||
| variable. Leave as ``None`` for local servers that do not | ||
| require authentication. | ||
| timeout (int, optional): HTTP request timeout in seconds. | ||
| Defaults to 30. | ||
|
|
||
| Attributes: | ||
| dimension (int): Embedding vector dimensionality (auto-detected). | ||
|
|
||
| Raises: | ||
| TypeError: If ``embed()`` receives a non-string input. | ||
| ValueError: If input is empty/whitespace-only or the server returns | ||
| an unexpected response format. | ||
| RuntimeError: If the HTTP request fails or the server is unreachable. | ||
|
|
||
| Examples: | ||
| >>> from zvec.extension import HTTPDenseEmbedding | ||
| >>> | ||
| >>> # LM Studio (default) | ||
| >>> emb = HTTPDenseEmbedding() | ||
| >>> vector = emb.embed("Hello, world!") | ||
| >>> len(vector) | ||
| 768 | ||
| >>> | ||
| >>> # Ollama | ||
| >>> emb = HTTPDenseEmbedding( | ||
| ... base_url="http://localhost:11434", | ||
| ... model="nomic-embed-text", | ||
| ... ) | ||
| >>> vector = emb.embed("Semantic search with local models") | ||
|
|
||
| See Also: | ||
| - ``DenseEmbeddingFunction``: Protocol for dense embeddings. | ||
| - ``OpenAIDenseEmbedding``: Cloud embedding via the OpenAI API. | ||
| """ | ||
|
|
||
| ENDPOINT = "/v1/embeddings" | ||
|
|
||
| def __init__( | ||
| self, | ||
| base_url: str = "http://localhost:1234", | ||
| model: str = "text-embedding-nomic-embed-text-v1.5@f16", | ||
| api_key: Optional[str] = None, | ||
| timeout: int = 30, | ||
| ) -> None: | ||
| self._base_url = base_url.rstrip("/") | ||
| self._model = model | ||
| self._api_key = api_key or os.environ.get("OPENAI_API_KEY", "") | ||
| self._timeout = timeout | ||
| self._dimension: Optional[int] = None | ||
|
|
||
| @property | ||
| def dimension(self) -> int: | ||
| """int: Embedding vector dimensionality (auto-detected on first call).""" | ||
| if self._dimension is None: | ||
| self._dimension = len(self.embed("dimension probe")) | ||
| return self._dimension | ||
|
|
||
| def __call__(self, input: TEXT) -> DenseVectorType: | ||
| """Make the embedding function callable.""" | ||
| return self.embed(input) | ||
|
|
||
| @lru_cache(maxsize=256) | ||
| def embed(self, input: TEXT) -> DenseVectorType: | ||
| """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 whitespace. | ||
|
|
||
| Returns: | ||
| DenseVectorType: A list of floats representing the embedding. | ||
|
|
||
| Raises: | ||
| TypeError: If *input* is not a string. | ||
| ValueError: If *input* is empty/whitespace-only or the server | ||
| returns an unexpected response format. | ||
| RuntimeError: If the HTTP request fails. | ||
| """ | ||
| if not isinstance(input, TEXT): | ||
| raise TypeError(f"Expected 'input' to be str, got {type(input).__name__}") | ||
|
|
||
| input = input.strip() | ||
| if not input: | ||
| raise ValueError("Input text cannot be empty or whitespace only") | ||
|
|
||
| url = self._base_url + self.ENDPOINT | ||
| payload = json.dumps({"model": self._model, "input": input}).encode() | ||
|
|
||
| headers: dict[str, str] = {"Content-Type": "application/json"} | ||
| if self._api_key: | ||
| headers["Authorization"] = f"Bearer {self._api_key}" | ||
|
|
||
| req = urllib.request.Request(url, data=payload, headers=headers, method="POST") | ||
| try: | ||
| with urllib.request.urlopen(req, timeout=self._timeout) as resp: | ||
| body = json.loads(resp.read()) | ||
| except urllib.error.HTTPError as exc: | ||
| raise RuntimeError( | ||
| f"Embedding server returned HTTP {exc.code}: {exc.read().decode()}" | ||
| ) from exc | ||
| except OSError as exc: | ||
| raise RuntimeError( | ||
| f"Could not reach embedding server at {url}: {exc}" | ||
| ) from exc | ||
|
|
||
| try: | ||
| vector: list[float] = body["data"][0]["embedding"] | ||
| except (KeyError, IndexError) as exc: | ||
| raise ValueError( | ||
| f"Unexpected response format from embedding server: {body}" | ||
| ) from exc | ||
|
|
||
| return vector | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unlike
OpenAIDenseEmbedding(line 232-236), this doesn't validate that the returned vector dimension matchesself.dimension. If the server returns inconsistent dimensions across calls, this could lead to silent failures downstream.