|
| 1 | +# Copyright (c) "Neo4j" |
| 2 | +# Neo4j Sweden AB [https://neo4j.com] |
| 3 | +# # |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# # |
| 8 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# # |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +from typing import Any, Optional |
| 19 | + |
| 20 | +from neo4j_graphrag.embeddings.base import Embedder |
| 21 | +from neo4j_graphrag.exceptions import EmbeddingsGenerationError |
| 22 | +from neo4j_graphrag.utils.rate_limit import ( |
| 23 | + RateLimitHandler, |
| 24 | + async_rate_limit_handler, |
| 25 | + rate_limit_handler, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +class LiteLLMEmbeddings(Embedder): |
| 30 | + """Embeddings via LiteLLM AI gateway. |
| 31 | +
|
| 32 | + LiteLLM provides a unified interface to 100+ embedding providers using the |
| 33 | + OpenAI embedding format. |
| 34 | +
|
| 35 | + Args: |
| 36 | + model (str): The embedding model identifier in LiteLLM format |
| 37 | + (e.g. "text-embedding-ada-002", "cohere/embed-english-v3.0"). |
| 38 | + rate_limit_handler (Optional[RateLimitHandler]): A rate limit handler |
| 39 | + to manage API rate limits. Defaults to None. |
| 40 | + **kwargs (Any): Arguments passed to ``litellm.embedding`` |
| 41 | + (e.g. ``api_key``, ``api_base``). |
| 42 | +
|
| 43 | + Raises: |
| 44 | + EmbeddingsGenerationError: If there's an error generating embeddings. |
| 45 | +
|
| 46 | + Example: |
| 47 | +
|
| 48 | + .. code-block:: python |
| 49 | +
|
| 50 | + from neo4j_graphrag.embeddings import LiteLLMEmbeddings |
| 51 | +
|
| 52 | + embedder = LiteLLMEmbeddings(model="text-embedding-ada-002", api_key="...") |
| 53 | + vector = embedder.embed_query("Some text") |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + model: str = "text-embedding-ada-002", |
| 59 | + rate_limit_handler: Optional[RateLimitHandler] = None, |
| 60 | + **kwargs: Any, |
| 61 | + ) -> None: |
| 62 | + try: |
| 63 | + import litellm |
| 64 | + except ImportError: |
| 65 | + raise ImportError( |
| 66 | + """Could not import litellm python client. |
| 67 | + Please install it with `pip install "neo4j-graphrag[litellm]"`.""" |
| 68 | + ) |
| 69 | + super().__init__(rate_limit_handler) |
| 70 | + self.litellm = litellm |
| 71 | + self.model = model |
| 72 | + self.kwargs = kwargs |
| 73 | + |
| 74 | + @rate_limit_handler |
| 75 | + def embed_query(self, text: str, **kwargs: Any) -> list[float]: |
| 76 | + """Generate embeddings for a given query using LiteLLM. |
| 77 | +
|
| 78 | + Args: |
| 79 | + text (str): The text to generate an embedding for. |
| 80 | + **kwargs (Any): Additional arguments passed to ``litellm.embedding``. |
| 81 | + """ |
| 82 | + try: |
| 83 | + response = self.litellm.embedding( |
| 84 | + model=self.model, |
| 85 | + input=[text], |
| 86 | + **self.kwargs, |
| 87 | + **kwargs, |
| 88 | + ) |
| 89 | + embedding: list[float] = response.data[0]["embedding"] |
| 90 | + return embedding |
| 91 | + except Exception as e: |
| 92 | + raise EmbeddingsGenerationError( |
| 93 | + f"Failed to generate embedding with LiteLLM: {e}" |
| 94 | + ) from e |
| 95 | + |
| 96 | + @async_rate_limit_handler |
| 97 | + async def async_embed_query(self, text: str, **kwargs: Any) -> list[float]: |
| 98 | + """Asynchronously generate embeddings for a given query using LiteLLM. |
| 99 | +
|
| 100 | + Args: |
| 101 | + text (str): The text to generate an embedding for. |
| 102 | + **kwargs (Any): Additional arguments passed to ``litellm.aembedding``. |
| 103 | + """ |
| 104 | + try: |
| 105 | + response = await self.litellm.aembedding( |
| 106 | + model=self.model, |
| 107 | + input=[text], |
| 108 | + **self.kwargs, |
| 109 | + **kwargs, |
| 110 | + ) |
| 111 | + embedding: list[float] = response.data[0]["embedding"] |
| 112 | + return embedding |
| 113 | + except Exception as e: |
| 114 | + raise EmbeddingsGenerationError( |
| 115 | + f"Failed to generate embedding with LiteLLM: {e}" |
| 116 | + ) from e |
0 commit comments