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]

[Feat] v2 Custom Logger API Endpoints (#10575)

Ishaan Jaff489f1a6c2594
diff --git a/docs/my-website/docs/proxy/logging.md b/docs/my-website/docs/proxy/logging.md
index ad4cababc08..e6285ec31ee 100644
--- a/docs/my-website/docs/proxy/logging.md
+++ b/docs/my-website/docs/proxy/logging.md
@@ -11,7 +11,7 @@ Log Proxy input, output, and exceptions using:
- GCS, s3, Azure (Blob) Buckets
- Lunary
- MLflow
-- Custom Callbacks
+- Custom Callbacks - Custom code and API endpoints
- Langsmith
- DataDog
- DynamoDB
@@ -1850,103 +1850,88 @@ ModelResponse(
## Custom Callback APIs [Async]
+<Image
+ img={require('../../img/callback_api.png')}
+ style={{width: '100%', display: 'block', margin: '2rem auto'}}
+/>
+<p style={{textAlign: 'left', color: '#666'}}>
+ Send LiteLLM logs to a custom API endpoint
+</p>
+
:::info
This is an Enterprise only feature [Get Started with Enterprise here](https://github.com/BerriAI/litellm/tree/main/enterprise)
:::
+| Property | Details |
+|----------|---------|
+| Description | Log LLM Input/Output to a custom API endpoint |
+| Logged Payload | `List[StandardLoggingPayload]` LiteLLM logs a list of [`StandardLoggingPayload` objects](https://docs.litellm.ai/docs/proxy/logging_spec) to your endpoint |
+
+
+
Use this if you:
- Want to use custom callbacks written in a non Python programming language
- Want your callbacks to run on a different microservice
-#### Step 1. Create your generic logging API endpoint
+#### Usage
-Set up a generic API endpoint that can receive data in JSON format. The data will be included within a "data" field.
+1. Set `success_callback: ["generic_api"]` on litellm config.yaml
-Your server should support the following Request format:
+```yaml showLineNumbers title="litellm config.yaml"
+model_list:
+ - model_name: openai/gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: os.environ/OPENAI_API_KEY
-```shell
-curl --location https://your-domain.com/log-event \
- --request POST \
- --header "Content-Type: application/json" \
- --data '{
- "data": {
- "id": "chatcmpl-8sgE89cEQ4q9biRtxMvDfQU1O82PT",
- "call_type": "acompletion",
- "cache_hit": "None",
- "startTime": "2024-02-15 16:18:44.336280",
- "endTime": "2024-02-15 16:18:45.045539",
- "model": "gpt-3.5-turbo",
- "user": "ishaan-2",
- "modelParameters": "{'temperature': 0.7, 'max_tokens': 10, 'user': 'ishaan-2', 'extra_body': {}}",
- "messages": "[{'role': 'user', 'content': 'This is a test'}]",
- "response": "ModelResponse(id='chatcmpl-8sgE89cEQ4q9biRtxMvDfQU1O82PT', choices=[Choices(finish_reason='length', index=0, message=Message(content='Great! How can I assist you with this test', role='assistant'))], created=1708042724, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=Usage(completion_tokens=10, prompt_tokens=11, total_tokens=21))",
- "usage": "Usage(completion_tokens=10, prompt_tokens=11, total_tokens=21)",
- "metadata": "{}",
- "cost": "3.65e-05"
- }
- }'
+litellm_settings:
+ success_callback: ["generic_api"]
```
-Reference FastAPI Python Server
-
-Here's a reference FastAPI Server that is compatible with LiteLLM Proxy:
-
-```python
-# this is an example endpoint to receive data from litellm
-from fastapi import FastAPI, HTTPException, Request
-
-app = FastAPI()
+2. Set Environment Variables for the custom API endpoint
+| Environment Variable | Details | Required |
+|----------|---------|----------|
+| `GENERIC_LOGGER_ENDPOINT` | The endpoint + route we should send callback logs to | Yes |
+| `GENERIC_LOGGER_HEADERS` | Optional: Set headers to be sent to the custom API endpoint | No, this is optional |
[email protected]("/log-event")
-async def log_event(request: Request):
- try:
- print("Received /log-event request")
- # Assuming the incoming request has JSON data
- data = await request.json()
- print("Received request data:")
- print(data)
+```shell showLineNumbers title=".env"
+GENERIC_LOGGER_ENDPOINT="https://webhook-test.com/30343bc33591bc5e6dc44217ceae3e0a"
- # Your additional logic can go here
- # For now, just printing the received data
- return {"message": "Request received successfully"}
- except Exception as e:
- print(f"Error processing request: {str(e)}")
- import traceback
-
- traceback.print_exc()
- raise HTTPException(status_code=500, detail="Internal Server Error")
-
-
-if __name__ == "__main__":
- import uvicorn
- uvicorn.run(app, host="127.0.0.1", port=4000)
+# Optional: Set headers to be sent to the custom API endpoint
+GENERIC_LOGGER_HEADERS="Authorization=Bearer <your-api-key>"
+# if multiple headers, separate by commas
+GENERIC_LOGGER_HEADERS="Authorization=Bearer <your-api-key>,X-Custom-Header=custom-header-value"
```
-#### Step 2. Set your `GENERIC_LOGGER_ENDPOINT` to the endpoint + route we should send callback logs to
+3. Start the proxy
```shell
-os.environ["GENERIC_LOGGER_ENDPOINT"] = "http://localhost:4000/log-event"
+litellm --config /path/to/config.yaml
```
-#### Step 3. Create a `config.yaml` file and set `litellm_settings`: `success_callback` = ["generic"]
+4. Make a test request
-Example litellm proxy config.yaml
-
-```yaml
-model_list:
- - model_name: gpt-3.5-turbo
- litellm_params:
- model: gpt-3.5-turbo
-litellm_settings:
- success_callback: ["generic"]
+```shell
+curl -i --location 'http://0.0.0.0:4000/chat/completions' \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer sk-1234' \
+ --data '{
+ "model": "openai/gpt-4o",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ]
+}'
```
-Start the LiteLLM Proxy and make a test request to verify the logs reached your callback API
+
## Langsmith
diff --git a/docs/my-website/img/callback_api.png b/docs/my-website/img/callback_api.png
new file mode 100644
index 00000000000..b123dae2620
Binary files /dev/null and b/docs/my-website/img/callback_api.png differ
diff --git a/enterprise/enterprise_callbacks/generic_api_callback.py b/enterprise/enterprise_callbacks/generic_api_callback.py
index 2f39ce856b7..3db8f0f7cef 100644
--- a/enterprise/enterprise_callbacks/generic_api_callback.py
+++ b/enterprise/enterprise_callbacks/generic_api_callback.py
@@ -1,126 +1,264 @@
-# callback to make a request to an API endpoint
+"""
+Callback to log events to a Generic API Endpoint
-#### What this does ####
-# On success, logs events to Promptlayer
+- Creates a StandardLoggingPayload
+- Adds to batch queue
+- Flushes based on CustomBatchLogger settings
+"""
+
+import asyncio
import os
+import traceback
+import uuid
+from typing import Dict, List, Optional, Union
+import litellm
+from litellm._logging import verbose_logger
+from litellm.integrations.custom_batch_logger import CustomBatchLogger
+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+from litellm.llms.custom_httpx.http_handler import (
+ get_async_httpx_client,
+ httpxSpecialProvider,
+)
+from litellm.types.utils import StandardLoggingPayload
-from typing import Optional
-import traceback
+class GenericAPILogger(CustomBatchLogger):
+ def __init__(
+ self,
+ endpoint: Optional[str] = None,
+ headers: Optional[dict] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the GenericAPILogger
+ Args:
+ endpoint: Optional[str] = None,
+ headers: Optional[dict] = None,
+ """
+ #########################################################
+ # Init httpx client
+ #########################################################
+ self.async_httpx_client = get_async_httpx_client(
+ llm_provider=httpxSpecialProvider.LoggingCallback
+ )
+ endpoint = endpoint or os.getenv("GENERIC_LOGGER_ENDPOINT")
+ if endpoint is None:
+ raise ValueError(
+ "endpoint not set for GenericAPILogger, GENERIC_LOGGER_ENDPOINT not found in environment variables"
+ )
-#### What this does ####
-# On success + failure, log events to Supabase
+ self.headers: Dict = self._get_headers(headers)
+ self.endpoint: str = endpoint
+ verbose_logger.debug(
+ f"in init GenericAPILogger, endpoint {self.endpoint}, headers {self.headers}"
+ )
-import litellm
-import uuid
-from litellm._logging import print_verbose, verbose_logger
+ #########################################################
+ # Init variables for batch flushing logs
+ #########################################################
+ self.flush_lock = asyncio.Lock()
+ super().__init__(**kwargs, flush_lock=self.flush_lock)
+ asyncio.create_task(self.periodic_flush())
+ self.log_queue: List[Union[Dict, StandardLoggingPayload]] = []
+ def _get_headers(self, headers: Optional[dict] = None):
+ """
+ Get headers for the Generic API Logger
-class GenericAPILogger:
- # Class variables or attributes
- def __init__(self, endpoint: Optional[str] = None, headers: Optional[dict] = None):
- try:
- if endpoint is None:
- # check env for "GENERIC_LOGGER_ENDPOINT"
- if os.getenv("GENERIC_LOGGER_ENDPOINT"):
- # Do something with the endpoint
- endpoint = os.getenv("GENERIC_LOGGER_ENDPOINT")
- else:
- # Handle the case when the endpoint is not found in the environment variables
- raise ValueError(
- "endpoint not set for GenericAPILogger, GENERIC_LOGGER_ENDPOINT not found in environment variables"
- )
- headers = headers or litellm.generic_logger_headers
-
- if endpoint is None:
- raise ValueError("endpoint not set for GenericAPILogger")
- if headers is None:
- raise ValueError("headers not set for GenericAPILogger")
-
- self.endpoint = endpoint
- self.headers = headers
+ Returns:
+ Dict: Headers for the Generic API Logger
+
+ Args:
+ headers: Optional[dict] = None
+ """
+ # Process headers from different sources
+ headers_dict = {}
+
+ # 1. First check for headers from env var
+ env_headers = os.getenv("GENERIC_LOGGER_HEADERS")
+ if env_headers:
+ try:
+ # Parse headers in format "key1=value1,key2=value2" or "key1=value1"
+ header_items = env_headers.split(",")
+ for item in header_items:
+ if "=" in item:
+ key, value = item.split("=", 1)
+ headers_dict[key.strip()] = value.strip()
+ except Exception as e:
+ verbose_logger.warning(
+ f"Error parsing headers from environment variables: {str(e)}"
+ )
+ # 2. Update with litellm generic headers if available
+ if litellm.generic_logger_headers:
+ headers_dict.update(litellm.generic_logger_headers)
+
+ # 3. Override with directly provided headers if any
+ if headers:
+ headers_dict.update(headers)
+
+ return headers_dict
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ """
+ Async Log success events to Generic API Endpoint
+
+ - Creates a StandardLoggingPayload
+ - Adds to batch queue
+ - Flushes based on CustomBatchLogger settings
+
+ Raises:
+ Raises a NON Blocking verbose_logger.exception if an error occurs
+ """
+ from litellm.proxy.utils import _premium_user_check
+
+ _premium_user_check()
+
+ try:
verbose_logger.debug(
- f"in init GenericAPILogger, endpoint {self.endpoint}, headers {self.headers}"
+ "Generic API Logger - Enters logging function for model %s", kwargs
)
+ standard_logging_payload = kwargs.get("standard_logging_object", None)
- pass
+ # Backwards compatibility with old logging payload
+ if litellm.generic_api_use_v1 is True:
+ payload = self._get_v1_logging_payload(
+ kwargs=kwargs,
+ response_obj=response_obj,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ self.log_queue.append(payload)
+ else:
+ # New logging payload, StandardLoggingPayload
+ self.log_queue.append(standard_logging_payload)
+
+ if len(self.log_queue) >= self.batch_size:
+ await self.async_send_batch()
except Exception as e:
- print_verbose(f"Got exception on init GenericAPILogger client {str(e)}")
- raise e
+ verbose_logger.exception(
+ f"Generic API Logger Error - {str(e)}\n{traceback.format_exc()}"
+ )
+ pass
+
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
+ """
+ Async Log failure events to Generic API Endpoint
+
+ - Creates a StandardLoggingPayload
+ - Adds to batch queue
+ """
+ from litellm.proxy.utils import _premium_user_check
+
+ _premium_user_check()
- # This is sync, because we run this in a separate thread. Running in a sepearate thread ensures it will never block an LLM API call
- # Experience with s3, Langfuse shows that async logging events are complicated and can block LLM calls
- def log_event(
- self, kwargs, response_obj, start_time, end_time, user_id, print_verbose
- ):
try:
verbose_logger.debug(
- f"GenericAPILogger Logging - Enters logging function for model {kwargs}"
+ "Generic API Logger - Enters logging function for model %s", kwargs
)
+ standard_logging_payload = kwargs.get("standard_logging_object", None)
+
+ if litellm.generic_api_use_v1 is True:
+ payload = self._get_v1_logging_payload(
+ kwargs=kwargs,
+ response_obj=response_obj,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ self.log_queue.append(payload)
+ else:
+ self.log_queue.append(standard_logging_payload)
+
+ if len(self.log_queue) >= self.batch_size:
+ await self.async_send_batch()
- # construct payload to send custom logger
- # follows the same params as langfuse.py
- litellm_params = kwargs.get("litellm_params", {})
- metadata = (
- litellm_params.get("metadata", {}) or {}
- ) # if litellm_params['metadata'] == None
- messages = kwargs.get("messages")
- cost = kwargs.get("response_cost", 0.0)
- optional_params = kwargs.get("optional_params", {})
- call_type = kwargs.get("call_type", "litellm.completion")
- cache_hit = kwargs.get("cache_hit", False)
- usage = response_obj["usage"]
- id = response_obj.get("id", str(uuid.uuid4()))
-
- # Build the initial payload
- payload = {
- "id": id,
- "call_type": call_type,
- "cache_hit": cache_hit,
- "startTime": start_time,
- "endTime": end_time,
- "model": kwargs.get("model", ""),
- "user": kwargs.get("user", ""),
- "modelParameters": optional_params,
- "messages": messages,
- "response": response_obj,
- "usage": usage,
- "metadata": metadata,
- "cost": cost,
- }
-
- # Ensure everything in the payload is converted to str
- for key, value in payload.items():
- try:
- payload[key] = str(value)
- except Exception:
- # non blocking if it can't cast to a str
- pass
-
- import json
-
- data = {
- "data": payload,
- }
- data = json.dumps(data)
- print_verbose(f"\nGeneric Logger - Logging payload = {data}")
-
- # make request to endpoint with payload
- response = litellm.module_level_client.post(
- self.endpoint, json=data, headers=self.headers
+ except Exception as e:
+ verbose_logger.exception(
+ f"Generic API Logger Error - {str(e)}\n{traceback.format_exc()}"
)
- response_status = response.status_code
- response_text = response.text
+ async def async_send_batch(self):
+ """
+ Sends the batch of messages to Generic API Endpoint
+ """
+ try:
+ if not self.log_queue:
+ return
+
+ verbose_logger.debug(
+ f"Generic API Logger - about to flush {len(self.log_queue)} events"
+ )
- print_verbose(
- f"Generic Logger - final response status = {response_status}, response text = {response_text}"
+ # make POST request to Generic API Endpoint
+ response = await self.async_httpx_client.post(
+ url=self.endpoint,
+ headers=self.headers,
+ data=safe_dumps(self.log_queue),
)
- return response
+
+ verbose_logger.debug(
+ f"Generic API Logger - sent batch to {self.endpoint}, status code {response.status_code}"
+ )
+
except Exception as e:
- verbose_logger.error(f"Generic - {str(e)}\n{traceback.format_exc()}")
- pass
+ verbose_logger.exception(
+ f"Generic API Logger Error sending batch - {str(e)}\n{traceback.format_exc()}"
+ )
+ finally:
+ self.log_queue.clear()
+
+ def _get_v1_logging_payload(
+ self, kwargs, response_obj, start_time, end_time
+ ) -> dict:
+ """
+ Maintained for backwards compatibility with old logging payload
+
+ Returns a dict of the payload to send to the Generic API Endpoint
+ """
+ verbose_logger.debug(
+ f"GenericAPILogger Logging - Enters logging function for model {kwargs}"
+ )
+
+ # construct payload to send custom logger
+ # follows the same params as langfuse.py
+ litellm_params = kwargs.get("litellm_params", {})
+ metadata = (
+ litellm_params.get("metadata", {}) or {}
+ ) # if litellm_params['metadata'] == None
+ messages = kwargs.get("messages")
+ cost = kwargs.get("response_cost", 0.0)
+ optional_params = kwargs.get("optional_params", {})
+ call_type = kwargs.get("call_type", "litellm.completion")
+ cache_hit = kwargs.get("cache_hit", False)
+ usage = response_obj["usage"]
+ id = response_obj.get("id", str(uuid.uuid4()))
+
+ # Build the initial payload
+ payload = {
+ "id": id,
+ "call_type": call_type,
+ "cache_hit": cache_hit,
+ "startTime": start_time,
+ "endTime": end_time,
+ "model": kwargs.get("model", ""),
+ "user": kwargs.get("user", ""),
+ "modelParameters": optional_params,
+ "messages": messages,
+ "response": response_obj,
+ "usage": usage,
+ "metadata": metadata,
+ "cost": cost,
+ }
+
+ # Ensure everything in the payload is converted to str
+ for key, value in payload.items():
+ try:
+ payload[key] = str(value)
+ except Exception:
+ # non blocking if it can't cast to a str
+ pass
+
+ return payload
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 2a7894c2330..196e00f587e 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -115,6 +115,7 @@ _custom_logger_compatible_callbacks_literal = Literal[
"agentops",
"anthropic_cache_control_hook",
"bedrock_vector_store",
+ "generic_api",
]
logged_real_time_event_types: Optional[Union[List[str], Literal["*"]]] = None
_known_custom_logger_compatible_callbacks: List = list(
@@ -132,6 +133,9 @@ datadog_use_v1: Optional[bool] = False # if you want to use v1 datadog logged p
gcs_pub_sub_use_v1: Optional[bool] = (
False # if you want to use v1 gcs pubsub logged payload
)
+generic_api_use_v1: Optional[bool] = (
+ False # if you want to use v1 generic api logged payload
+)
argilla_transformation_object: Optional[Dict[str, Any]] = None
_async_input_callback: List[Union[str, Callable, CustomLogger]] = (
[]
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index c6957a4e5d6..09b9817d603 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -134,13 +134,12 @@ from .initialize_dynamic_callback_params import (
from .specialty_caches.dynamic_logging_cache import DynamicLoggingCache
try:
- from ..proxy.enterprise.enterprise_callbacks.generic_api_callback import (
- GenericAPILogger,
- )
+ from enterprise.enterprise_callbacks.generic_api_callback import GenericAPILogger
except Exception as e:
verbose_logger.debug(
f"[Non-Blocking] Unable to import GenericAPILogger - LiteLLM Enterprise Feature - {str(e)}"
)
+ GenericAPILogger = CustomLogger # type: ignore
_in_memory_loggers: List[Any] = []
@@ -165,7 +164,6 @@ dataDogLogger = None
prometheusLogger = None
dynamoLogger = None
s3Logger = None
-genericAPILogger = None
greenscaleLogger = None
lunaryLogger = None
supabaseClient = None
@@ -1564,35 +1562,6 @@ class Logging(LiteLLMLoggingBaseClass):
service_name="langfuse",
trace_id=_trace_id,
)
- if callback == "generic":
- global genericAPILogger
- verbose_logger.debug("reaches langfuse for success logging!")
- kwargs = {}
- for k, v in self.model_call_details.items():
- if (
- k != "original_response"
- ): # copy.deepcopy raises errors as this could be a coroutine
- kwargs[k] = v
- # this only logs streaming once, complete_streaming_response exists i.e when stream ends
- if self.stream:
- verbose_logger.debug(
- f"is complete_streaming_response in kwargs: {kwargs.get('complete_streaming_response', None)}"
- )
- if complete_streaming_response is None:
- continue
- else:
- print_verbose("reaches langfuse for streaming logging!")
- result = kwargs["complete_streaming_response"]
- if genericAPILogger is None:
- genericAPILogger = GenericAPILogger() # type: ignore
- genericAPILogger.log_event(
- kwargs=kwargs,
- response_obj=result,
- start_time=start_time,
- end_time=end_time,
- user_id=kwargs.get("user", None),
- print_verbose=print_verbose,
- )
if callback == "greenscale" and greenscaleLogger is not None:
kwargs = {}
for k, v in self.model_call_details.items():
@@ -3064,6 +3033,13 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_gcs_pubsub_logger = GcsPubSubLogger()
_in_memory_loggers.append(_gcs_pubsub_logger)
return _gcs_pubsub_logger # type: ignore
+ elif logging_integration == "generic_api":
+ for callback in _in_memory_loggers:
+ if isinstance(callback, GenericAPILogger):
+ return callback
+ generic_api_logger = GenericAPILogger()
+ _in_memory_loggers.append(generic_api_logger)
+ return generic_api_logger # type: ignore
elif logging_integration == "humanloop":
for callback in _in_memory_loggers:
if isinstance(callback, HumanloopLogger):
@@ -3207,8 +3183,12 @@ def get_custom_logger_compatible_class( # noqa: PLR0915
for callback in _in_memory_loggers:
if isinstance(callback, GcsPubSubLogger):
return callback
-
+ elif logging_integration == "generic_api":
+ for callback in _in_memory_loggers:
+ if isinstance(callback, GenericAPILogger):
+ return callback
return None
+
except Exception as e:
verbose_logger.exception(
f"[Non-Blocking Error] Error getting custom logger: {e}"
diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.py
index fc3a2e0650f..b6bf0a3515a 100644
--- a/litellm/proxy/health_endpoints/_health_endpoints.py
+++ b/litellm/proxy/health_endpoints/_health_endpoints.py
@@ -72,6 +72,7 @@ async def health_services_endpoint( # noqa: PLR0915
"email",
"braintrust",
"datadog",
+ "generic_api",
],
str,
] = fastapi.Query(description="Specify the service being hit."),
@@ -109,6 +110,7 @@ async def health_services_endpoint( # noqa: PLR0915
"custom_callback_api",
"langsmith",
"datadog",
+ "generic_api",
]:
raise HTTPException(
status_code=400,
@@ -120,6 +122,7 @@ async def health_services_endpoint( # noqa: PLR0915
if (
service == "openmeter"
or service == "braintrust"
+ or service == "generic_api"
or (service in litellm.success_callback and service != "langfuse")
):
_ = await litellm.acompletion(
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index 310c3cf25dc..58edfefcb62 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -4,14 +4,6 @@ model_list:
model: openai/gpt-4o
api_key: os.environ/OPENAI_API_KEY
-vector_store_registry:
- - vector_store_name: "bedrock-litellm-website-knowledgebase"
- litellm_params:
- vector_store_id: "T37J8R4WTM"
- custom_llm_provider: "bedrock"
- vector_store_description: "Bedrock vector store for the Litellm website knowledgebase"
- vector_store_metadata:
- source: "https://www.litellm.com/docs"
+litellm_settings:
+ success_callback: ["generic_api"]
-general_settings:
- store_prompts_in_spend_logs: true
\ No newline at end of file
diff --git a/litellm/utils.py b/litellm/utils.py
index 7d9da60b5de..9b8d11cfd5d 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -289,7 +289,6 @@ dataDogLogger = None
prometheusLogger = None
dynamoLogger = None
s3Logger = None
-genericAPILogger = None
greenscaleLogger = None
lunaryLogger = None
aispendLogger = None
@@ -524,9 +523,9 @@ def function_setup( # noqa: PLR0915
function_id: Optional[str] = kwargs["id"] if "id" in kwargs else None
## DYNAMIC CALLBACKS ##
- dynamic_callbacks: Optional[
- List[Union[str, Callable, CustomLogger]]
- ] = kwargs.pop("callbacks", None)
+ dynamic_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = (
+ kwargs.pop("callbacks", None)
+ )
all_callbacks = get_dynamic_callbacks(dynamic_callbacks=dynamic_callbacks)
if len(all_callbacks) > 0:
@@ -1210,9 +1209,9 @@ def client(original_function): # noqa: PLR0915
exception=e,
retry_policy=kwargs.get("retry_policy"),
)
- kwargs[
- "retry_policy"
- ] = reset_retry_policy() # prevent infinite loops
+ kwargs["retry_policy"] = (
+ reset_retry_policy()
+ ) # prevent infinite loops
litellm.num_retries = (
None # set retries to None to prevent infinite loops
)
@@ -2755,16 +2754,16 @@ def get_optional_params( # noqa: PLR0915
True # so that main.py adds the function call to the prompt
)
if "tools" in non_default_params:
- optional_params[
- "functions_unsupported_model"
- ] = non_default_params.pop("tools")
+ optional_params["functions_unsupported_model"] = (
+ non_default_params.pop("tools")
+ )
non_default_params.pop(
"tool_choice", None
) # causes ollama requests to hang
elif "functions" in non_default_params:
- optional_params[
- "functions_unsupported_model"
- ] = non_default_params.pop("functions")
+ optional_params["functions_unsupported_model"] = (
+ non_default_params.pop("functions")
+ )
elif (
litellm.add_function_to_prompt
): # if user opts to add it to prompt instead
@@ -2787,10 +2786,10 @@ def get_optional_params( # noqa: PLR0915
if "response_format" in non_default_params:
if provider_config is not None:
- non_default_params[
- "response_format"
- ] = provider_config.get_json_schema_from_pydantic_object(
- response_format=non_default_params["response_format"]
+ non_default_params["response_format"] = (
+ provider_config.get_json_schema_from_pydantic_object(
+ response_format=non_default_params["response_format"]
+ )
)
else:
non_default_params["response_format"] = type_to_response_format_param(
@@ -3806,9 +3805,9 @@ def _count_characters(text: str) -> int:
def get_response_string(response_obj: Union[ModelResponse, ModelResponseStream]) -> str:
- _choices: Union[
- List[Union[Choices, StreamingChoices]], List[StreamingChoices]
- ] = response_obj.choices
+ _choices: Union[List[Union[Choices, StreamingChoices]], List[StreamingChoices]] = (
+ response_obj.choices
+ )
response_str = ""
for choice in _choices:
diff --git a/tests/logging_callback_tests/test_generic_api_callback.py b/tests/logging_callback_tests/test_generic_api_callback.py
new file mode 100644
index 00000000000..0bdec437fe9
--- /dev/null
+++ b/tests/logging_callback_tests/test_generic_api_callback.py
@@ -0,0 +1,183 @@
+import io
+import os
+import sys
+
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+import asyncio
+import litellm
+import gzip
+import json
+import logging
+import time
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+import litellm
+from litellm import completion
+from litellm._logging import verbose_logger
+from litellm.integrations.gcs_pubsub.pub_sub import *
+from datetime import datetime, timedelta
+from litellm.types.utils import (
+ StandardLoggingPayload,
+ StandardLoggingModelInformation,
+ StandardLoggingMetadata,
+ StandardLoggingHiddenParams,
+)
+
+verbose_logger.setLevel(logging.DEBUG)
+from enterprise.enterprise_callbacks.generic_api_callback import GenericAPILogger
+
+
+
+async def test_generic_api_callback():
+ """
+ Test the GenericAPILogger callback with a standard logging payload.
+ This test mocks the HTTP client and validates that the logger properly
+ formats and sends the expected payload.
+ """
+
+ # Create a mock for the async_httpx_client's post method
+ mock_post = AsyncMock()
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.text = "OK"
+
+ # Set up an endpoint for testing
+ test_endpoint = "https://example.com/api/logs"
+ test_headers = {"Authorization": "Bearer test_token"}
+ os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint
+
+ # Initialize the GenericAPILogger and set the mock
+ generic_logger = GenericAPILogger(
+ endpoint=test_endpoint,
+ headers=test_headers,
+ flush_interval=1
+ )
+ generic_logger.async_httpx_client.post = mock_post
+ litellm.callbacks = [generic_logger]
+
+ # Make the completion call
+ response = await litellm.acompletion(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ mock_response="hi",
+ user="test_user",
+ )
+
+ # Wait for async flush
+ await asyncio.sleep(3)
+
+ # Assert httpx post was called
+ mock_post.assert_called_once()
+
+ # Get the actual request body from the mock
+ actual_url = mock_post.call_args[1]["url"]
+ print("##########\n")
+ print("logs were flushed to URL", actual_url, "with the following headers", mock_post.call_args[1]["headers"])
+ assert actual_url == test_endpoint, f"Expected URL {test_endpoint}, got {actual_url}"
+
+ # For the GenericAPILogger, it sends the payload directly as JSON in the data field
+ json_data = mock_post.call_args[1]["data"]
+ # Parse the JSON string
+
+ print("##########\n")
+ print("json_data", json_data)
+ actual_request = json.loads(json_data)
+
+ # The payload is a list of StandardLoggingPayload objects in the log queue
+ assert isinstance(actual_request, list), "Request body should be a list"
+ assert len(actual_request) > 0, "Request body list should not be empty"
+
+ # Validate the first payload item
+ payload_item: StandardLoggingPayload = StandardLoggingPayload(**actual_request[0])
+ print("##########\n")
+ print(json.dumps(payload_item, indent=4))
+ print("##########\n")
+
+
+ # Basic assertions for standard logging payload
+ assert payload_item["response_cost"] > 0, "Response cost should be greater than 0"
+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"
+ assert payload_item["model_parameters"]["user"] == "test_user", "User should be test_user"
+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"
+ assert payload_item["messages"] == [{"role": "user", "content": "Hello, world!"}], "Messages should be the same"
+ assert payload_item["response"]["choices"][0]["message"]["content"] == "hi", "Response should be hi"
+
+
+
+
+async def test_generic_api_callback_multiple_logs():
+ """
+ Test the GenericAPILogger callback with multiple chat completions
+ """
+ # Create a mock for the async_httpx_client's post method
+ mock_post = AsyncMock()
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.text = "OK"
+
+ # Set up an endpoint for testing
+ test_endpoint = "https://example.com/api/logs"
+ test_headers = {"Authorization": "Bearer test_token"}
+ os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint
+
+ # Initialize the GenericAPILogger and set the mock
+ generic_logger = GenericAPILogger(
+ endpoint=test_endpoint,
+ headers=test_headers,
+ flush_interval=5
+ )
+ generic_logger.async_httpx_client.post = mock_post
+ litellm.callbacks = [generic_logger]
+
+ # Make the completion call
+ for _ in range(10):
+ response = await litellm.acompletion(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ mock_response="hi",
+ user="test_user",
+ )
+
+ # Wait for async flush
+ await asyncio.sleep(6)
+
+ # Assert httpx post was called
+ mock_post.assert_called_once()
+
+ # Get the actual request body from the mock
+ actual_url = mock_post.call_args[1]["url"]
+ print("##########\n")
+ print("logs were flushed to URL", actual_url, "with the following headers", mock_post.call_args[1]["headers"])
+ assert actual_url == test_endpoint, f"Expected URL {test_endpoint}, got {actual_url}"
+
+ # For the GenericAPILogger, it sends the payload directly as JSON in the data field
+ json_data = mock_post.call_args[1]["data"]
+ # Parse the JSON string
+
+ print("##########\n")
+ print("json_data", json_data)
+ actual_request = json.loads(json_data)
+
+ # The payload is a list of StandardLoggingPayload objects in the log queue
+ assert isinstance(actual_request, list), "Request body should be a list"
+ assert len(actual_request) > 0, "Request body list should not be empty"
+ assert len(actual_request) == 10, "Request body list should be 10 items, since we made 10 calls"
+
+ # Validate all payload items
+ for payload_item in actual_request:
+ payload_item: StandardLoggingPayload = StandardLoggingPayload(**payload_item)
+ print("##########\n")
+ print(json.dumps(payload_item, indent=4))
+ print("##########\n")
+
+ assert payload_item["response_cost"] > 0, "Response cost should be greater than 0"
+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"
+ assert payload_item["model_parameters"]["user"] == "test_user", "User should be test_user"
+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"
+ assert payload_item["messages"] == [{"role": "user", "content": "Hello, world!"}], "Messages should be the same"
+ assert payload_item["response"]["choices"][0]["message"]["content"] == "hi", "Response should be hi"
+
diff --git a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py
index 0239ab7f51e..5aa97304cb7 100644
--- a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py
+++ b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py
@@ -42,6 +42,7 @@ from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLog
from litellm.integrations.agentops import AgentOps
from litellm.integrations.humanloop import HumanloopLogger
from litellm.proxy.hooks.dynamic_rate_limiter import _PROXY_DynamicRateLimitHandler
+from enterprise.enterprise_callbacks.generic_api_callback import GenericAPILogger
from unittest.mock import patch
# clear prometheus collectors / registry
@@ -79,6 +80,7 @@ callback_class_str_to_classType = {
"anthropic_cache_control_hook": AnthropicCacheControlHook,
"agentops": AgentOps,
"bedrock_vector_store": BedrockVectorStore,
+ "generic_api": GenericAPILogger,
}
expected_env_vars = {