Skip to content

Commit ed935d4

Browse files
committed
Add LiteLLM AI gateway provider for LLM and embeddings
Signed-off-by: RheagalFire <arishalam121@gmail.com>
1 parent 90147de commit ed935d4

8 files changed

Lines changed: 1280 additions & 2 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ anthropic = ["anthropic>=0.49.0,<0.50.0"]
5252
bedrock = ["boto3>=1.35.0,<2.0.0"]
5353
ollama = ["ollama>=0.4.4,<0.5.0"]
5454
openai = ["openai>=1.51.1,<2.0.0"]
55+
litellm = ["litellm>=1.80.0,<1.87.0"]
5556
mistralai = ["mistralai>=1.0.3,<2.0.0"]
5657
qdrant = ["qdrant-client>=1.11.3,<2.0.0"]
5758
kg_creation_tools = ["neo4j-viz>=0.4.2,<0.5.0"]

src/neo4j_graphrag/embeddings/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from .bedrock import BedrockEmbeddings
1717
from .cohere import CohereEmbeddings
1818
from .google_genai import GeminiEmbedder
19+
from .litellm import LiteLLMEmbeddings
1920
from .mistral import MistralAIEmbeddings
2021
from .ollama import OllamaEmbeddings
2122
from .openai import AzureOpenAIEmbeddings, OpenAIEmbeddings
@@ -33,4 +34,5 @@
3334
"MistralAIEmbeddings",
3435
"CohereEmbeddings",
3536
"GeminiEmbedder",
37+
"LiteLLMEmbeddings",
3638
]
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
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

src/neo4j_graphrag/llm/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from .bedrock_llm import BedrockLLM
2121
from .cohere_llm import CohereLLM
2222
from .google_genai_llm import GeminiLLM
23+
from .litellm_llm import LiteLLMChat
2324
from .mistralai_llm import MistralAILLM
2425
from .ollama_llm import OllamaLLM
2526
from .openai_llm import AzureOpenAILLM, OpenAILLM
@@ -31,6 +32,7 @@
3132
"BedrockLLM",
3233
"CohereLLM",
3334
"GeminiLLM",
35+
"LiteLLMChat",
3436
"LLMResponse",
3537
"LLMUsage",
3638
"LLMBase",

0 commit comments

Comments
 (0)