mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* refactor(typing): narrow Any sources across providers, proxy and guardrails (wave 1) * refactor(typing): narrow Any sources across hubs, providers and proxy (wave 2) * refactor(typing): validate RunwayML task JSON and let dotprompt loaders accept exported prompts * fix: restore pass-through behavior on paths the typing pass tightened MCP client IP extraction trusts X-Forwarded-For only when use_x_forwarded_for is True, dotprompt skips a malformed JSON prompt entry instead of raising, RunwayML task payloads pass through unvalidated, and a malformed provider body raises the same AttributeError as before at the CompactifAI, Gemini, and mock transport parse sites * fix(runwayml): keep a malformed 2xx task body on the 500 path * fix(edenai,cli): keep a non-object body in the error and fail on a malformed migration report EdenAI's embedding and image generation parse dropped a non-object body from the error they raised, so the message no longer named what the provider sent. A helper now raises with the body in the message, and both paths have a regression test. `lite encryption migrate` exited 0 with no message when the proxy's report was not an object or its residual_legacy was not a number, where base crashed. It now fails with a message naming the value. The CompactifAI and Gemini image-edit non-object body tests accept TypeError or AttributeError, which both base and this branch raise, so they guard against a ValidationError instead of pinning one class. RunwayML's async parse gets the same non-object body test as the sync one. * fix: keep base's error classes, duck-typed checks and fail-closed guardrails the typing pass changed * test: annotate the new regression tests' locals with Final * test: annotate the remaining new test locals with Final
163 lines
5.9 KiB
Python
163 lines
5.9 KiB
Python
#### What this does ####
|
|
# On success + failure, log events to Logfire
|
|
|
|
import os
|
|
import traceback
|
|
from collections.abc import Mapping
|
|
from enum import Enum
|
|
from typing import Final, NamedTuple
|
|
|
|
from typing_extensions import LiteralString
|
|
|
|
from litellm._logging import print_verbose, verbose_logger
|
|
from litellm._uuid import uuid
|
|
from litellm.litellm_core_utils.redact_messages import redact_user_api_key_info
|
|
|
|
|
|
class SpanConfig(NamedTuple):
|
|
message_template: LiteralString
|
|
span_data: Mapping[str, object]
|
|
|
|
|
|
class LogfireLevel(str, Enum):
|
|
INFO = "info"
|
|
ERROR = "error"
|
|
|
|
|
|
class LogfireLogger:
|
|
# Class variables or attributes
|
|
def __init__(self):
|
|
try:
|
|
verbose_logger.debug("in init logfire logger")
|
|
import logfire
|
|
|
|
# only setting up logfire if we are sending to logfire
|
|
# in testing, we don't want to send to logfire
|
|
if logfire.DEFAULT_LOGFIRE_INSTANCE.config.send_to_logfire:
|
|
logfire.configure(token=os.getenv("LOGFIRE_TOKEN"))
|
|
except Exception as e:
|
|
print_verbose(f"Got exception on init logfire client {e}")
|
|
raise e
|
|
|
|
def _get_span_config(self, payload) -> SpanConfig:
|
|
if payload["call_type"] == "completion" or payload["call_type"] == "acompletion":
|
|
return SpanConfig(
|
|
message_template="Chat Completion with {request_data[model]!r}",
|
|
span_data={"request_data": payload},
|
|
)
|
|
elif payload["call_type"] == "embedding" or payload["call_type"] == "aembedding":
|
|
return SpanConfig(
|
|
message_template="Embedding Creation with {request_data[model]!r}",
|
|
span_data={"request_data": payload},
|
|
)
|
|
elif payload["call_type"] == "image_generation" or payload["call_type"] == "aimage_generation":
|
|
return SpanConfig(
|
|
message_template="Image Generation with {request_data[model]!r}",
|
|
span_data={"request_data": payload},
|
|
)
|
|
else:
|
|
return SpanConfig(
|
|
message_template="Litellm Call with {request_data[model]!r}",
|
|
span_data={"request_data": payload},
|
|
)
|
|
|
|
async def _async_log_event(
|
|
self,
|
|
kwargs,
|
|
response_obj,
|
|
start_time,
|
|
end_time,
|
|
print_verbose,
|
|
level: LogfireLevel,
|
|
):
|
|
self.log_event(
|
|
kwargs=kwargs,
|
|
response_obj=response_obj,
|
|
start_time=start_time,
|
|
end_time=end_time,
|
|
print_verbose=print_verbose,
|
|
level=level,
|
|
)
|
|
|
|
def log_event(
|
|
self,
|
|
kwargs,
|
|
start_time,
|
|
end_time,
|
|
print_verbose,
|
|
level: LogfireLevel,
|
|
response_obj,
|
|
):
|
|
try:
|
|
import logfire
|
|
|
|
verbose_logger.debug("logfire Logging - Enters logging function for model %s", kwargs)
|
|
|
|
if not response_obj:
|
|
response_obj = {}
|
|
litellm_params: Final = kwargs.get("litellm_params", {})
|
|
metadata: Final = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None
|
|
messages: Final = kwargs.get("messages")
|
|
optional_params: Final = kwargs.get("optional_params", {})
|
|
call_type: Final = kwargs.get("call_type", "completion")
|
|
cache_hit: Final = kwargs.get("cache_hit", False)
|
|
usage: Final = response_obj.get("usage", {})
|
|
id: Final = response_obj.get("id", str(uuid.uuid4()))
|
|
try:
|
|
response_time = (end_time - start_time).total_seconds()
|
|
except Exception:
|
|
response_time = None
|
|
|
|
# Clean Metadata before logging - never log raw metadata
|
|
# the raw metadata can contain circular references which leads to infinite recursion
|
|
# we clean out all extra litellm metadata params before logging
|
|
clean_metadata = {}
|
|
if isinstance(metadata, dict):
|
|
for key, value in metadata.items():
|
|
# clean litellm metadata before logging
|
|
if key in [
|
|
"endpoint",
|
|
"caching_groups",
|
|
"previous_models",
|
|
]:
|
|
continue
|
|
else:
|
|
clean_metadata[key] = value
|
|
|
|
clean_metadata = redact_user_api_key_info(metadata=clean_metadata)
|
|
|
|
# Build the initial payload
|
|
payload: Final = {
|
|
"id": id,
|
|
"call_type": call_type,
|
|
"cache_hit": cache_hit,
|
|
"startTime": start_time,
|
|
"endTime": end_time,
|
|
"responseTime (seconds)": response_time,
|
|
"model": kwargs.get("model", ""),
|
|
"user": kwargs.get("user", ""),
|
|
"modelParameters": optional_params,
|
|
"spend": kwargs.get("response_cost", 0),
|
|
"messages": messages,
|
|
"response": response_obj,
|
|
"usage": usage,
|
|
"metadata": clean_metadata,
|
|
}
|
|
logfire_openai: Final = logfire.with_settings(custom_scope_suffix="openai")
|
|
message_template, span_data = self._get_span_config(payload)
|
|
if level == LogfireLevel.INFO:
|
|
logfire_openai.info(
|
|
message_template,
|
|
**span_data,
|
|
)
|
|
elif level == LogfireLevel.ERROR:
|
|
logfire_openai.error(
|
|
message_template,
|
|
**span_data,
|
|
_exc_info=True,
|
|
)
|
|
print_verbose(f"\ndd Logger - Logging payload = {payload}")
|
|
|
|
print_verbose(f"Logfire Layer Logging - final response object: {response_obj}")
|
|
except Exception as e:
|
|
verbose_logger.debug("Logfire Layer Error - %s\n%s", e, traceback.format_exc())
|