Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Helicone base url support + fix for embedding cache hits on str input (#11211)

Krish Dholakiaba39f9e36035
diff --git a/docs/my-website/docs/observability/helicone_integration.md b/docs/my-website/docs/observability/helicone_integration.md
index 80935c1cc4c..9b807b8d0f6 100644
--- a/docs/my-website/docs/observability/helicone_integration.md
+++ b/docs/my-website/docs/observability/helicone_integration.md
@@ -52,6 +52,7 @@ from litellm import completion
## Set env variables
os.environ["HELICONE_API_KEY"] = "your-helicone-key"
os.environ["OPENAI_API_KEY"] = "your-openai-key"
+# os.environ["HELICONE_API_BASE"] = "" # [OPTIONAL] defaults to `https://api.helicone.ai`
# Set callbacks
litellm.success_callback = ["helicone"]
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index c3f3c3c088d..2ecc3c59dcf 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -469,6 +469,7 @@ router_settings:
| HCP_VAULT_TOKEN | Token for [Hashicorp Vault Secret Manager](../secret.md#hashicorp-vault)
| HCP_VAULT_CERT_ROLE | Role for [Hashicorp Vault Secret Manager Auth](../secret.md#hashicorp-vault)
| HELICONE_API_KEY | API key for Helicone service
+| HELICONE_API_BASE | Base URL for Helicone service, defaults to `https://api.helicone.ai`
| HOSTNAME | Hostname for the server, this will be [emitted to `datadog` logs](https://docs.litellm.ai/docs/proxy/logging#datadog)
| HOURS_IN_A_DAY | Hours in a day for calculation purposes. Default is 24
| HUGGINGFACE_API_BASE | Base URL for Hugging Face API
diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.py
index 6b41c1ff40a..8e54f698da6 100644
--- a/litellm/caching/caching_handler.py
+++ b/litellm/caching/caching_handler.py
@@ -293,6 +293,17 @@ class LLMCachingHandler:
return CachingHandlerResponse(cached_result=cached_result)
return CachingHandlerResponse(cached_result=cached_result)
+ def handle_kwargs_input_list_or_str(self, kwargs: Dict[str, Any]) -> List[str]:
+ """
+ Handles the input of kwargs['input'] being a list or a string
+ """
+ if isinstance(kwargs["input"], str):
+ return [kwargs["input"]]
+ elif isinstance(kwargs["input"], list):
+ return kwargs["input"]
+ else:
+ raise ValueError("input must be a string or a list")
+
def _process_async_embedding_cached_response(
self,
final_embedding_cached_response: Optional[EmbeddingResponse],
@@ -325,18 +336,18 @@ class LLMCachingHandler:
embedding_all_elements_cache_hit: bool = False
remaining_list = []
non_null_list = []
+ kwargs_input_as_list = self.handle_kwargs_input_list_or_str(kwargs)
for idx, cr in enumerate(cached_result):
if cr is None:
- remaining_list.append(kwargs["input"][idx])
+ remaining_list.append(kwargs_input_as_list[idx])
else:
non_null_list.append((idx, cr))
- original_kwargs_input = kwargs["input"]
kwargs["input"] = remaining_list
if len(non_null_list) > 0:
- print_verbose(f"EMBEDDING CACHE HIT! - {len(non_null_list)}")
+ verbose_logger.debug(f"EMBEDDING CACHE HIT! - {len(non_null_list)}")
final_embedding_cached_response = EmbeddingResponse(
model=kwargs.get("model"),
- data=[None] * len(original_kwargs_input),
+ data=[None] * len(kwargs_input_as_list),
)
final_embedding_cached_response._hidden_params["cache_hit"] = True
@@ -349,11 +360,11 @@ class LLMCachingHandler:
index=idx,
object="embedding",
)
- if isinstance(original_kwargs_input[idx], str):
+ if isinstance(kwargs_input_as_list[idx], str):
from litellm.utils import token_counter
prompt_tokens += token_counter(
- text=original_kwargs_input[idx], count_response_tokens=True
+ text=kwargs_input_as_list[idx], count_response_tokens=True
)
## USAGE
usage = Usage(
diff --git a/litellm/integrations/helicone.py b/litellm/integrations/helicone.py
index a526a74fbea..79585a412b3 100644
--- a/litellm/integrations/helicone.py
+++ b/litellm/integrations/helicone.py
@@ -24,6 +24,9 @@ class HeliconeLogger:
# Instance variables
self.provider_url = "https://api.openai.com/v1"
self.key = os.getenv("HELICONE_API_KEY")
+ self.api_base = os.getenv("HELICONE_API_BASE") or "https://api.hconeai.com"
+ if self.api_base.endswith("/"):
+ self.api_base = self.api_base[:-1]
def claude_mapping(self, model, messages, response_obj):
from anthropic import AI_PROMPT, HUMAN_PROMPT
@@ -139,9 +142,9 @@ class HeliconeLogger:
# Code to be executed
provider_url = self.provider_url
- url = "https://api.hconeai.com/oai/v1/log"
+ url = f"{self.api_base}/oai/v1/log"
if "claude" in model:
- url = "https://api.hconeai.com/anthropic/v1/log"
+ url = f"{self.api_base}/anthropic/v1/log"
provider_url = "https://api.anthropic.com/v1/messages"
headers = {
"Authorization": f"Bearer {self.key}",
diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml
index 6358620bf81..d6b3e450a3d 100644
--- a/litellm/proxy/_new_secret_config.yaml
+++ b/litellm/proxy/_new_secret_config.yaml
@@ -4,9 +4,10 @@ model_list:
model: openai/fake
api_key: fake-key
api_base: https://exampleopenaiendpoint-production.up.railway.app/
-
+ - model_name: "text-embedding-3-small"
+ litellm_params:
+ model: text-embedding-3-small
+ api_key: os.environ/OPENAI_API_KEY
+
litellm_settings:
cache: true
- success_callback: ["langfuse"]
- failure_callback: ["langfuse"]
- alerting: ["slack"]
diff --git a/tests/local_testing/test_caching.py b/tests/local_testing/test_caching.py
index 9de9ff31781..a1648947115 100644
--- a/tests/local_testing/test_caching.py
+++ b/tests/local_testing/test_caching.py
@@ -498,6 +498,7 @@ async def test_embedding_caching_individual_items():
)
final_prompt_tokens = embedding3.usage.prompt_tokens
assert embedding3["data"][0]["embedding"] == embedding1["data"][0]["embedding"]
+ assert len(embedding3.data) == 1
assert embedding3._hidden_params["cache_hit"] == True
assert embedding3.usage.prompt_tokens != 0
diff --git a/tests/test_litellm/caching/test_caching_handler.py b/tests/test_litellm/caching/test_caching_handler.py
new file mode 100644
index 00000000000..837ce7d405d
--- /dev/null
+++ b/tests/test_litellm/caching/test_caching_handler.py
@@ -0,0 +1,54 @@
+import asyncio
+import json
+import os
+import sys
+import time
+from unittest.mock import MagicMock, patch
+
+import httpx
+import pytest
+import respx
+from fastapi.testclient import TestClient
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+from datetime import datetime
+from unittest.mock import AsyncMock, MagicMock
+
+from litellm.caching.caching_handler import LLMCachingHandler
+
+
+async def test_process_async_embedding_cached_response():
+ llm_caching_handler = LLMCachingHandler(
+ original_function=MagicMock(),
+ request_kwargs={},
+ start_time=datetime.now(),
+ )
+
+ args = {
+ "cached_result": [
+ {
+ "embedding": [-0.025122925639152527, -0.019487135112285614],
+ "index": 0,
+ "object": "embedding",
+ }
+ ]
+ }
+
+ mock_logging_obj = MagicMock()
+ mock_logging_obj.async_success_handler = AsyncMock()
+ response, cache_hit = llm_caching_handler._process_async_embedding_cached_response(
+ final_embedding_cached_response=None,
+ cached_result=args["cached_result"],
+ kwargs={"model": "text-embedding-ada-002", "input": "test"},
+ logging_obj=mock_logging_obj,
+ start_time=datetime.now(),
+ model="text-embedding-ada-002",
+ )
+
+ assert cache_hit
+
+ print(f"response: {response}")
+ assert len(response.data) == 1