mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* fix(langfuse): upload base64 media and export its reference from the langfuse callback
The v2 SDK replaced base64 payloads in a trace's input, output and metadata with
Langfuse media references and uploaded the bytes before ingestion. The v4 export
channel sends spans through litellm's own exporter, which had no such step, so
images reached Langfuse inline and multiplied the stored trace size on servers
that do not extract them.
The export channel now replaces data URIs and the Anthropic and Vertex typed
blocks with the same references and uploads the bytes through the Langfuse media
REST API on one background thread per channel.
* fix(langfuse): bound queued media by bytes and stop trusting the storage response
Media the uploader has no room for now stays inline in the span, the cap counts
decoded bytes, and a failed upload makes flush report failure. The storage PUT
no longer follows redirects and Langfuse is told the storage status without the
storage response body. A data URI followed by text is left as it is, trace level
media is registered without an observation, and queued uploads get five seconds
to finish at shutdown.
* fix(langfuse): validate upload URLs for request-supplied hosts and queue an attribute's media as a whole
A Langfuse host that comes with a key's or team's credentials now has the upload
URLs it returns checked with validate_url, so it cannot point the upload at an
internal address. A host the operator configured keeps naming its own storage.
The media of one attribute is queued all together or not at all, so an attribute
that stays inline no longer leaves part of its media uploading.
* fix(langfuse): keep media inline while Langfuse cannot store it
A Langfuse with no media route or bucket, or one whose upload URL is refused, answers the same
way for every payload. After the first such answer the uploader turns media away, so the exporter
keeps it inline, and one upload per pause checks whether Langfuse takes media again.
* fix(langfuse): re-send a media registration that does not reach Langfuse
The span export keeps trying through a short Langfuse outage, so a trace could arrive with a
reference whose single registration attempt had failed. Registration now waits out the same delays.
* fix(langfuse): replace base64 media in model parameters
A call rejected before the provider, such as an unknown model or a failed key check, is logged
with its request body as the model parameters, which left the image inline in those traces.
* Revert "fix(langfuse): replace base64 media in model parameters"
This reverts commit 3a4894c78e.
* fix(langfuse): leave the media storage response body unread
Only the status of the storage PUT is used, and an upload URL can answer with a body of any size.
* fix(langfuse): always export the media reference, as the Langfuse SDK does
Drops the pause that kept media inline after the media API failed. A self-hosted Langfuse needs a media bucket, as its docs state.
* fix(langfuse): read the HTTP client from the handler on every media upload
litellm closes a pooled client once its cache entry expires (one hour plus
the close grace) and the handler opens another. The uploader held the first
client, so later uploads raised 'client has been closed' and traces kept a
reference with no file. The span exporter already reads handler.client per
request.
* perf(langfuse): skip the media parse for values that only mention base64
extract_media parsed and walked any value that held the text base64 or
mime_type. It now parses only a value that holds a base64 data URI, or a
content type key next to a data key, which every payload it replaces has.
* test(langfuse): check media-free values by their output only
* fix(langfuse): stop validating the media upload URL for key and team hosts
The Langfuse host on a key or team is not validated by default, so checking only the
upload URL it returns added no protection. The check resolved DNS on the proxy and
refused storage that is private or reachable only through an egress proxy, which left
the trace with a media reference and no file.
* fix(langfuse): restart the media upload thread in a forked child
A fork copies the upload queue but none of the parent's threads, so a child forked after
the first logged call wrote media references that nothing uploaded. The child now gets
its own queue and thread, and the parent keeps uploading what it had queued.
* fix(langfuse): upload Gemini inline_data parts as media
The Langfuse SDK replaces Gemini inline_data and inlineData parts with a media reference. The callback now does the same, so a Gemini-native request with an image no longer stores its base64 inline.
* fix(langfuse): size the media upload queue from an env setting and stop keeping media inline when it is full
LANGFUSE_MEDIA_QUEUE_MAX_BYTES sets how many decoded bytes wait for upload per
export channel, 100 MB when unset. Media that does not fit is no longer kept
inline in the span: the span carries the reference, the upload is skipped with
a warning and counted as failed, as the Langfuse SDK does when its queue is
full.
* fix(langfuse): give a forked child its own failure lock
A lock a parent thread held at the fork stays locked in the child. The queue
test now holds the first upload until the second has been turned away.
154 lines
5.5 KiB
Python
154 lines
5.5 KiB
Python
import os
|
|
import re
|
|
from collections.abc import Iterator
|
|
from typing import Final
|
|
|
|
# Define the base directory for the litellm repository and documentation path
|
|
repo_base = "./litellm" # Change this to your actual path
|
|
|
|
_GETENV_ARGS = r"""\(\s*['"]([^'"]+)['"]\s*(?:,\s*[^)]*)?\)"""
|
|
_GET_SECRET_ARGS = r"""\(\s*['"]([^'"]+)['"]\s*(?:,\s*[^)]*|,\s*default_value=[^)]*)?\)"""
|
|
|
|
ENV_KEY_PATTERNS: tuple[re.Pattern[str], ...] = (
|
|
re.compile(r"os\.getenv" + _GETENV_ARGS),
|
|
re.compile(r"(?<![\w.])(?:litellm\.(?:utils\.)?)?get_secret(?:_str|_bool)?" + _GET_SECRET_ARGS),
|
|
)
|
|
|
|
DOCS_BASE = "./docs/my-website/docs"
|
|
REFERENCE_TABLE_PATH = f"{DOCS_BASE}/proxy/config_settings.md"
|
|
DOCS_SUFFIXES = (".md", ".mdx")
|
|
DOCUMENTED_KEY_PATTERN = re.compile(r"\b[A-Z][A-Z0-9_]*\b")
|
|
|
|
# Terminal/environment detection variables that should not be documented
|
|
# These are internal variables used for terminal detection, not user-configurable settings
|
|
# Guard-only env vars: read solely to raise on invalid values; the only valid
|
|
# value is the default, so there is nothing meaningful to document.
|
|
EXCLUDED_GUARD_ONLY_VARS = {
|
|
"MAVVRIK_FOCUS_FREQUENCY",
|
|
}
|
|
|
|
# Temporary/internal rollout flags are intentionally not added to the public
|
|
# environment settings docs until the feature is ready for broad use.
|
|
EXCLUDED_ROLLOUT_FLAGS = {
|
|
"LITELLM_USE_RUST_OCR",
|
|
"LITELLM_RUST",
|
|
"LITELLM_BUILTIN_PASS_THROUGH_ROUTES_FIRST",
|
|
}
|
|
|
|
# Internal infrastructure tuning parameters for streaming/queue management
|
|
# These are advanced settings with sensible defaults that most users should not modify
|
|
EXCLUDED_INTERNAL_TUNING_VARS = {
|
|
"ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS",
|
|
"ANTHROPIC_MESSAGES_DETACHED_STREAM_DRAIN_TIMEOUT_SECONDS",
|
|
"ANTHROPIC_MESSAGES_STREAM_CLIENT_STALL_TIMEOUT_SECONDS",
|
|
"ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE",
|
|
"RESPONSES_API_DISCONNECT_DRAIN_TIMEOUT_SECONDS",
|
|
"DEFAULT_S3_MAX_ADAPTIVE_CONCURRENCY",
|
|
"LANGFUSE_MEDIA_QUEUE_MAX_BYTES",
|
|
}
|
|
|
|
EXCLUDED_TERMINAL_VARS = {
|
|
"TERM",
|
|
"TERM_PROGRAM",
|
|
"TERM_PROGRAM_VERSION",
|
|
"TERM_SESSION_ID",
|
|
"VTE_VERSION",
|
|
"KITTY_WINDOW_ID",
|
|
"KONSOLE_VERSION",
|
|
"ITERM_PROFILE",
|
|
"ITERM_PROFILE_NAME",
|
|
"ITERM_SESSION_ID",
|
|
"WEZTERM_VERSION",
|
|
"WT_SESSION",
|
|
"GNOME_TERMINAL_SCREEN",
|
|
"ALACRITTY_SOCKET",
|
|
}
|
|
|
|
EXCLUDED_KEYS = frozenset(
|
|
EXCLUDED_TERMINAL_VARS | EXCLUDED_GUARD_ONLY_VARS | EXCLUDED_ROLLOUT_FLAGS | EXCLUDED_INTERNAL_TUNING_VARS
|
|
)
|
|
|
|
# Directories to skip (dependencies, venvs, caches) - only scan litellm source
|
|
SKIP_DIRS = {
|
|
".venv",
|
|
"venv",
|
|
"__pycache__",
|
|
".git",
|
|
"node_modules",
|
|
"site-packages",
|
|
".eggs",
|
|
"dist",
|
|
"build",
|
|
}
|
|
|
|
NON_SDK_SOURCE_DIRS: Final = frozenset(
|
|
{"cli", "deploy", "enterprise", "packaging", "proxy-extras", "runtime", "rust", "scripts", "ui", "vscode-extension"}
|
|
)
|
|
|
|
|
|
def extract_env_keys(source: str) -> frozenset[str]:
|
|
"""Return every documentable env var name read by the given Python source."""
|
|
return frozenset(
|
|
match for pattern in ENV_KEY_PATTERNS for match in pattern.findall(source) if match not in EXCLUDED_KEYS
|
|
)
|
|
|
|
|
|
def collect_env_keys(base_dir: str) -> frozenset[str]:
|
|
"""Return every documentable env var name read anywhere under ``base_dir``."""
|
|
return frozenset(
|
|
key
|
|
for file_path in _files_with_suffix(base_dir, (".py",), NON_SDK_SOURCE_DIRS)
|
|
for key in extract_env_keys(_read_text(file_path))
|
|
)
|
|
|
|
|
|
def _files_with_suffix(
|
|
base_dir: str, suffixes: tuple[str, ...], skip_root_dirs: frozenset[str] = frozenset()
|
|
) -> Iterator[str]:
|
|
for root, dirs, files in os.walk(base_dir):
|
|
# Skip dependency/venv directories - prevents picking up env vars from installed packages
|
|
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and (root != base_dir or d not in skip_root_dirs)]
|
|
yield from (os.path.join(root, name) for name in files if name.endswith(suffixes))
|
|
|
|
|
|
def _read_text(file_path: str) -> str:
|
|
with open(file_path, "r", encoding="utf-8") as f:
|
|
return f.read()
|
|
|
|
|
|
def extract_documented_keys(docs_content: str) -> frozenset[str]:
|
|
"""Return every env-var-shaped name mentioned anywhere in a documentation page."""
|
|
return frozenset(DOCUMENTED_KEY_PATTERN.findall(docs_content))
|
|
|
|
|
|
def collect_documented_keys(docs_dir: str) -> frozenset[str]:
|
|
"""Return every env-var-shaped name mentioned on any page under ``docs_dir``."""
|
|
return frozenset(
|
|
key
|
|
for file_path in _files_with_suffix(docs_dir, DOCS_SUFFIXES)
|
|
for key in extract_documented_keys(_read_text(file_path))
|
|
)
|
|
|
|
|
|
def undocumented_env_keys(base_dir: str, docs_dir: str) -> frozenset[str]:
|
|
"""Return the env vars read under ``base_dir`` that no page under ``docs_dir`` mentions."""
|
|
return collect_env_keys(base_dir) - collect_documented_keys(docs_dir)
|
|
|
|
|
|
def main() -> None:
|
|
if not os.path.isdir(DOCS_BASE):
|
|
raise Exception(f"No documentation found at {DOCS_BASE}; check out BerriAI/litellm-docs into docs/my-website")
|
|
|
|
undocumented_keys = undocumented_env_keys(repo_base, DOCS_BASE)
|
|
if undocumented_keys:
|
|
raise Exception(
|
|
f"Environment variables read under {repo_base} but mentioned nowhere in the docs: "
|
|
f"{sorted(undocumented_keys)}"
|
|
f"\nDocument each one, either on the relevant provider page or as a row in the "
|
|
f"'environment variables - Reference' table in {REFERENCE_TABLE_PATH}"
|
|
)
|
|
print(f"Every environment variable read under {repo_base} is documented")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|