Skip to content
Merged
Show file tree
Hide file tree
Changes from 110 commits
Commits
Show all changes
116 commits
Select commit Hold shift + click to select a range
b38b867
feat(batches): emit per-line JSONL batch records to callbacks
shivamrawat1 Sep 17, 2026
0ea8ce7
fix(batches): only emit line items for final batches
shivamrawat1 Sep 17, 2026
7fa8c92
chore(deps): bump soupsieve to 2.9.2 for GHSA-gjv8-xp57-g29c and GHSA…
shivamrawat1 Sep 17, 2026
c7edcce
style(batches): satisfy ruff format for line item logging
shivamrawat1 Sep 17, 2026
7f06708
chore(ui): regenerate schema.d.ts for store_batch_line_items_in_callb…
shivamrawat1 Sep 17, 2026
8908023
test(batches): cover line-item edge shapes and general settings propa…
shivamrawat1 Sep 17, 2026
8aca0c3
fix(batches): keep deployment credentials out of callback-visible params
shivamrawat1 Sep 17, 2026
ff9d30b
refactor(batches): declare credential transport attribute on Logging
shivamrawat1 Sep 17, 2026
feea6f2
chore: merge origin/main into litellm_batch_jsonl_line_item_callbacks
shivamrawat1 Sep 18, 2026
775d851
chore: merge origin/main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 23, 2026
8484b2f
test(batches): integration contract for per-line batch callback events
yucheng-berri Sep 23, 2026
b4cb884
fix(proxy): resolve store_batch_line_items_in_callbacks through the s…
yucheng-berri Sep 23, 2026
61d5ab0
test(batches): assert per-line events beside the aggregate and create…
yucheng-berri Sep 23, 2026
bc53e23
fix(proxy): drop resurrected use_legacy_interactions_schema shim from…
yucheng-berri Sep 23, 2026
4b6efef
test(batches): assert line item events carry no credentials
yucheng-berri Sep 23, 2026
ed23e2e
fix(proxy): reset batch line-item flag when the setting is absent
yucheng-berri Sep 23, 2026
096ba84
fix(batches): map anthropic batch lines through the anthropic message…
yucheng-berri Sep 23, 2026
a8fafaf
style: tag the anthropic result cast with a cast-ok reason
yucheng-berri Sep 23, 2026
c746e57
style: shorten cast-ok reason so ruff format passes
yucheng-berri Sep 23, 2026
45b7509
fix(batches): skip line-item callbacks for providers without a line r…
yucheng-berri Sep 23, 2026
bef2f04
fix(batches): reconstruct bedrock and mistral batch lines through the…
yucheng-berri Sep 23, 2026
6cbad5c
style: wrap widened provider literals so ruff format passes
yucheng-berri Sep 23, 2026
a760991
fix(batches): pair bedrock lines by recordId and type them from the r…
yucheng-berri Sep 23, 2026
271b6c6
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 23, 2026
c0b69ae
fix(batches): keep line item events out of proxy limiters and strip c…
yucheng-berri Sep 23, 2026
67d4471
fix(batches): keep cast-ok tags on the flagged cast lines for the dis…
yucheng-berri Sep 23, 2026
ee8dcfc
fix(batches): skip failed line item events in parallel request limite…
yucheng-berri Sep 23, 2026
a2fd2a8
test(batches): tolerate lifecycle spend rows when asserting no line i…
yucheng-berri Sep 23, 2026
fe11251
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 24, 2026
05d6977
fix(batches): place mutable-ok tags on the lines the discipline gate …
yucheng-berri Sep 24, 2026
f5670e0
fix(batches): skip router budget accounting for batch line item events
yucheng-berri Sep 24, 2026
0ca85b4
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 24, 2026
dd9d4fd
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 24, 2026
4c86f0b
fix(batches): keep anthropic line errors and skip native vertex batch…
yucheng-berri Sep 25, 2026
5777f7e
test(batches): restore test-quality tags on line item tests
yucheng-berri Sep 25, 2026
87d82b9
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 25, 2026
f4a6e12
Merge remote-tracking branch 'origin/main' into litellm_batch_jsonl_l…
yucheng-berri Sep 26, 2026
f3ba65d
test: move batch line-item unit test to tests/unit after merging main
yucheng-berri Sep 26, 2026
f65b5b1
fix(batches): emit batch line-item callbacks once per batch
yucheng-berri Sep 27, 2026
cffa640
fix(batches): release line-item claim when fan-out emitted nothing
yucheng-berri Sep 27, 2026
a7c9ded
fix(batches): make the line-item claim release ownership-safe
yucheng-berri Sep 29, 2026
f69d5c5
fix(batches): keep bodyless failed batch lines reaching callbacks
yucheng-berri Sep 30, 2026
5f35c25
fix(logging): seed batch line hidden params in get_hidden_params defa…
yucheng-berri Sep 30, 2026
a891065
merge: main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Sep 30, 2026
ff77170
perf(batches): reuse fetched batch result files for line-item logging
yucheng-berri Sep 30, 2026
1388dbc
fix(batches): release line-item claim when nothing was emitted
yucheng-berri Sep 30, 2026
ee21adb
Merge remote-tracking branch 'origin/main' into litellm_batch_jsonl_l…
yucheng-berri Oct 1, 2026
4d96efc
Merge remote-tracking branch 'origin/main' into litellm_batch_jsonl_l…
yucheng-berri Oct 1, 2026
64c514c
fix(batches): type batch line-item callback sites to satisfy basedpyr…
yucheng-berri Oct 1, 2026
aebde2a
style: wrap batch hidden-params cast for ruff format
yucheng-berri Oct 1, 2026
06fb342
Merge remote-tracking branch 'origin/main' into litellm_batch_jsonl_l…
yucheng-berri Oct 1, 2026
eac1ed0
fix(batches): reason suppressions for batch line-item lint deltas
yucheng-berri Oct 1, 2026
e1b9449
Merge remote-tracking branch 'origin/main' into litellm_batch_jsonl_l…
yucheng-berri Oct 1, 2026
60a47e2
chore: drop stale mutable-ok suppressions after LIT002 removal
yucheng-berri Oct 1, 2026
a7f1978
fix(batches): skip batch line-item events in ClickHouse spend sink an…
yucheng-berri Oct 4, 2026
9ca41c9
Merge origin/main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 4, 2026
9c71dae
fix(clickhouse): skip failed batch line items in the spend sink too
yucheng-berri Oct 5, 2026
8ec50a2
fix(batches): declare batch_line_items service family on claim calls
yucheng-berri Oct 5, 2026
a35d4ee
fix(integrations): keep batch line items out of the built-in metering…
yucheng-berri Oct 5, 2026
c9f67ff
style: format metering-sinks test
yucheng-berri Oct 5, 2026
1b02cb6
fix(otel): skip synthetic line-item durations in v2 metrics; isolate …
yucheng-berri Oct 5, 2026
6348a7d
Merge remote-tracking branch 'origin/main' into litellm_batch_jsonl_l…
yucheng-berri Oct 6, 2026
b139924
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 6, 2026
db33862
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 6, 2026
15fa86c
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 7, 2026
1b63787
chore: finish main merge conflict resolution for batch line items
yucheng-berri Oct 7, 2026
235019d
style: sort imports in litellm_logging after main merge
yucheng-berri Oct 7, 2026
6b8fb29
chore: merge origin/main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 7, 2026
0632fdd
Merge remote-tracking branch 'origin/main' into fix41691
yucheng-berri Oct 8, 2026
b57e4f0
test(batches): use the public hook class names main now exports
yucheng-berri Oct 8, 2026
c653e2e
fix(batches): only the batch writer can mark a callback event as a li…
yucheng-berri Oct 8, 2026
e00471b
chore(batches): keep the lint gates within main's ceilings after the …
yucheng-berri Oct 8, 2026
317764c
fix(anthropic): read the message id off the validated message
yucheng-berri Oct 8, 2026
85fc449
fix(batches): an unreadable error file no longer drops the output lin…
yucheng-berri Oct 8, 2026
21cd892
test(batches): pin billing for batch_parent_id on every endpoint and …
yucheng-berri Oct 8, 2026
7cf3024
test(batches): bill every request of a concurrent burst mixing forged…
yucheng-berri Oct 8, 2026
4bd5762
revert: keep the line-item fan-out all-or-nothing on an unreadable er…
yucheng-berri Oct 8, 2026
4cc9f56
test(batches): pin the all-or-nothing retry and warm the burst model …
yucheng-berri Oct 8, 2026
586b022
Merge remote-tracking branch 'origin/main' into fix41691
yucheng-berri Oct 8, 2026
f26f86b
Merge remote-tracking branch 'origin/main' into fix41691
yucheng-berri Oct 9, 2026
07d543c
fix(batches): run the line fan-out outside the aggregate event's dead…
yucheng-berri Oct 9, 2026
6e826b4
fix(batches): let running line fan-outs finish before proxy shutdown …
yucheng-berri Oct 10, 2026
fd7a099
Merge remote-tracking branch 'origin/main' into fix41691
yucheng-berri Oct 12, 2026
9ed3211
fix(batches): keep batch line fields off callback kwargs and skip fan…
yucheng-berri Oct 12, 2026
8a46101
fix(batches): log batch lines under the retrieve's callback settings …
yucheng-berri Oct 12, 2026
7ae8fec
test(batches): line events follow the key's message logging opt-out
yucheng-berri Oct 12, 2026
903c593
test(batches): line events follow team logging settings, keep the lin…
yucheng-berri Oct 12, 2026
2b30a09
fix(batches): keep in-memory line claims for 10,000 batches and pin m…
yucheng-berri Oct 12, 2026
0865123
Keep batch line unit tests in-process and drop repeated per-sink comm…
yucheng-berri Oct 12, 2026
56b60e6
Share one batch provider alias across batch_utils and line item logging
yucheng-berri Oct 12, 2026
0470177
Report Bedrock line status codes, skip unknown Bedrock lines without …
yucheng-berri Oct 12, 2026
8f2c935
Read a swallowed Redis claim failure as unavailable, price unpriceabl…
yucheng-berri Oct 12, 2026
d62c5f2
Call handle_completed_batch when line items are off, keep a cache tes…
yucheng-berri Oct 12, 2026
f6dc422
Hand the cost poller's credential snapshot to line item file reads, s…
yucheng-berri Oct 12, 2026
6125f5f
Log batch lines through the sync callbacks a direct async call runs, …
yucheng-berri Oct 12, 2026
cbdbbb5
fix(batches): log failed Bedrock embedding lines as embeddings with t…
yucheng-berri Oct 13, 2026
5460242
fix(batches): keep a Bedrock line's system prompt in its logged messages
yucheng-berri Oct 13, 2026
f010f96
Merge remote-tracking branch 'origin/main' into fix41691
yucheng-berri Oct 13, 2026
4c120da
feat(batches): store per-line batch requests and responses in S3/GCS …
yucheng-berri Oct 13, 2026
7ab9a3f
fix(batches): store batch line items after the batch is billed and re…
yucheng-berri Oct 13, 2026
5cad620
test(batches): cover team-level and deleted-key redaction of batch li…
yucheng-berri Oct 13, 2026
aa76a2e
fix(batches): store batch line items in the background so a hung buck…
yucheng-berri Oct 13, 2026
15f3d73
fix(batches): store an unbilled batch's line items only once it is re…
yucheng-berri Oct 13, 2026
21a7109
fix(batches): price and write batch line items off the event loop
yucheng-berri Oct 13, 2026
082a859
fix(batches): pair no request for a shared custom_id and wait for an …
yucheng-berri Oct 13, 2026
459234f
fix(batches): store batch line items only once the poll has billed ev…
yucheng-berri Oct 13, 2026
400a6f9
fix(batches): hash line-item objects off the event loop and keep line…
yucheng-berri Oct 13, 2026
ee61a60
fix(batches): keep request and response for batches created without a…
yucheng-berri Oct 13, 2026
85169fc
fix(batches): pair line items with the right request on every deploym…
yucheng-berri Oct 13, 2026
2875f03
fix(batches): let OAuth2 batches follow team and proxy message loggin…
yucheng-berri Oct 13, 2026
4ba1eaa
Merge branch 'main' into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 14, 2026
0ee34c9
fix(batches): hash the creator credential and write batch line items …
yucheng-berri Oct 14, 2026
a02fc23
chore: merge main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 14, 2026
bc925d4
docs(batches): say async_log_batch_line_items is called once per part
yucheng-berri Oct 15, 2026
315d705
fix(batches): log an error when a batch's deployment is gone before i…
yucheng-berri Oct 15, 2026
c75d257
Merge origin/main into litellm_batch_jsonl_line_item_callbacks
yucheng-berri Oct 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
226 changes: 216 additions & 10 deletions enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions litellm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ def _dev_env_hot_reload_enabled() -> bool:
failure_callback: List[CALLBACK_TYPES] = []
service_callback: List[CALLBACK_TYPES] = []
audit_log_callbacks: List[CALLBACK_TYPES] = []
batch_line_item_callbacks: Sequence[CALLBACK_TYPES] = ()
# logging_callback_manager is lazy-loaded via __getattr__
_custom_logger_compatible_callbacks_literal = Literal[
"lago",
Expand Down
192 changes: 192 additions & 0 deletions litellm/batches/batch_line_items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"""Per-line records of a finished batch for the loggers listed in batch_line_item_callbacks."""

import asyncio
from collections import Counter
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from itertools import chain
from typing import Final, Literal, TypeAlias

import litellm
from litellm._logging import verbose_logger
from litellm.batches.batch_utils import batch_cost_and_usage, get_file_content_as_dictionary
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.litellm_logging import init_custom_logger_compatible_class
from litellm.llms.vertex_ai.files.transformation import vertex_batch_row_custom_id
from litellm.types.utils import (
ModelInfo,
StandardBatchLineItem,
StandardBatchLineItemMetadata,
StandardBatchLineItemsPayload,
StandardBatchLineItemUsage,
)

BatchFileProvider: TypeAlias = Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "mistral"]

_VERTEX_AI_UNKNOWN_CUSTOM_ID: Final = "unknown" # what a Vertex AI batch row that carries no custom_id is read as


@dataclass(frozen=True, slots=True)
class BatchLineItemSource:
batch_id: str
finished_at: int
model: str
custom_llm_provider: str | None
cost_provider: BatchFileProvider
model_info: ModelInfo | None
metadata: StandardBatchLineItemMetadata


def line_item_metadata(attribution: Mapping[str, object]) -> StandardBatchLineItemMetadata:
return StandardBatchLineItemMetadata(
user_api_key_hash=_text(attribution, "user_api_key_hash"),
Comment thread
yucheng-berri marked this conversation as resolved.
Resolved
user_api_key_alias=_text(attribution, "user_api_key_alias"),
user_api_key_team_id=_text(attribution, "user_api_key_team_id"),
user_api_key_team_alias=_text(attribution, "user_api_key_team_alias"),
user_api_key_user_id=_text(attribution, "user_api_key_user_id"),
user_api_key_org_id=_text(attribution, "user_api_key_org_id"),
)


def _text(attribution: Mapping[str, object], name: str) -> str | None:
value: Final = attribution.get(name)
return value if isinstance(value, str) else None


def _line_key(entry: Mapping[str, object]) -> str | None:
"""A line's custom_id. Bedrock calls it recordId, and native Vertex rows carry it in the row key or request labels."""
key: Final = entry.get("custom_id", entry.get("recordId"))
return key if isinstance(key, str) else vertex_batch_row_custom_id(entry)


def build_batch_line_items(
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
source: BatchLineItemSource, input_content: bytes, result_contents: Iterable[bytes]
) -> StandardBatchLineItemsPayload:
"""Pair every output and error line with the input line that shares its custom_id, priced one line at a time."""
requests: Final = _requests_by_custom_id(input_content)
results: Final = chain.from_iterable(map(get_file_content_as_dictionary, result_contents))
return StandardBatchLineItemsPayload(
batch_id=source.batch_id,
finished_at=source.finished_at,
lines=tuple([_line_item(source, requests, entry) for entry in results]),
)


def _requests_by_custom_id(input_content: bytes) -> Mapping[str | None, Mapping[str, object]]:
"""Each input line by its custom_id. A custom_id that several input lines share, as when a Vertex AI embeddings
entry is split into one row per input, is paired with none of them."""
keyed: Final = tuple((_line_key(entry), entry) for entry in get_file_content_as_dictionary(input_content))
counts: Final = Counter(key for key, _ in keyed)
return {key: entry for key, entry in keyed if counts[key] == 1}


def _line_item(
source: BatchLineItemSource,
requests: Mapping[str | None, Mapping[str, object]],
entry: dict[str, object],
) -> StandardBatchLineItem:
priced: Final = batch_cost_and_usage(
(entry,), source.cost_provider, model_name=source.model, model_info=source.model_info
)
succeeded: Final = priced.successful_requests > 0
custom_id: Final = _line_key(entry)
return StandardBatchLineItem(
batch_id=source.batch_id,
custom_id=custom_id,
status="success" if succeeded else "failure",
request=_request_for(source, requests, custom_id),
response=entry,
usage=StandardBatchLineItemUsage(
prompt_tokens=priced.usage.prompt_tokens,
completion_tokens=priced.usage.completion_tokens,
total_tokens=priced.usage.total_tokens,
)
if succeeded
else None,
response_cost=priced.cost,
model=source.model,
custom_llm_provider=source.custom_llm_provider,
metadata=source.metadata,
)


def _request_for(
source: BatchLineItemSource, requests: Mapping[str | None, Mapping[str, object]], custom_id: str | None
) -> Mapping[str, object] | None:
"""The input line that shares a result line's custom_id. A Vertex AI line read as "unknown" pairs with none."""
if custom_id is None or (source.cost_provider == "vertex_ai" and custom_id == _VERTEX_AI_UNKNOWN_CUSTOM_ID):
return None
return requests.get(custom_id)


def without_request_and_response(payload: StandardBatchLineItemsPayload) -> StandardBatchLineItemsPayload:
return StandardBatchLineItemsPayload(
batch_id=payload["batch_id"],
finished_at=payload["finished_at"],
lines=tuple(
StandardBatchLineItem(
batch_id=line["batch_id"],
custom_id=line["custom_id"],
status=line["status"],
request=None,
response=None,
usage=line["usage"],
response_cost=line["response_cost"],
model=line["model"],
custom_llm_provider=line["custom_llm_provider"],
metadata=line["metadata"],
)
for line in payload["lines"]
),
)


async def dispatch_batch_line_items(payload: StandardBatchLineItemsPayload, redact_bodies: bool) -> None:
"""Hand the lines to every batch_line_item_callbacks logger. A failing logger is logged and never stops the rest."""
await asyncio.gather(
*(_deliver(callback, payload, redact_bodies) for callback in litellm.batch_line_item_callbacks)
)


async def _deliver(
callback: litellm.CALLBACK_TYPES, payload: StandardBatchLineItemsPayload, redact_bodies: bool
) -> None:
try:
logger: Final = _resolve_logger(callback)
if logger is None:
verbose_logger.error(
"batch_line_item_callbacks: %r cannot store batch line items, the lines of batch %s were not stored",
callback,
payload["batch_id"],
)
return
await logger.async_log_batch_line_items(
without_request_and_response(payload)
if redact_bodies or _logger_turned_off_message_logging(logger)
else payload
)
except Exception as error: # noqa: BLE001 # one failing sink must not stop the other sinks or the cost poller
verbose_logger.exception(
"batch_line_item_callbacks: %r failed to store the %d lines of batch %s: %s",
callback,
len(payload["lines"]),
payload["batch_id"],
error,
)


def _resolve_logger(callback: litellm.CALLBACK_TYPES) -> CustomLogger | None:
Comment thread
yucheng-berri marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · Custom loggers named in batch_line_item_callbacks proxy config are never resolved, so the new hook cannot be reached from config

This is still unfixed at head 315d705be7 (previously upheld; the author deferred it to a follow-up).

CustomLogger.async_log_batch_line_items is added as a general extension point. _resolve_logger, however, accepts only a CustomLogger instance or the literal strings "s3_v2" and "gcs_bucket".

On the proxy, litellm_settings.batch_line_item_callbacks has no dedicated branch in proxy_server.py. It falls through to the generic setattr(litellm, key, value), so dotted paths are never turned into instances by get_instance_fn. The callbacks and audit_log_callbacks settings do get that step (proxy_server.py:6744-6762).

Failure scenario:

  1. An operator sets batch_line_item_callbacks: ["custom_callbacks.proxy_handler_instance"].
  2. The CustomLogger subclass behind that path overrides async_log_batch_line_items.
  3. A managed batch completes.
  4. _deliver logs cannot store batch line items, part N of batch ... was not stored and drops every part. The override is never called.

Nothing rejects the entry at startup, so the operator only finds out from runtime error logs after the batch's lines are already lost.

Fix: either add an elif key == "batch_line_item_callbacks" branch that resolves dotted entries with get_instance_fn, as audit_log_callbacks does, or reject unsupported names when the config loads.

Evidence

litellm/batches/batch_line_items.py:236-243: the match statement handles CustomLogger() and "s3_v2" | "gcs_bucket"; every other value hits case _: return None.

litellm/batches/batch_line_items.py _deliver: when logger is None, it logs an error and returns, so that part is never stored.

grep batch_line_item_callbacks litellm/proxy returns nothing: the proxy has no resolution step for this setting, so it reaches the generic setattr at proxy_server.py:~6853.

Latest summary by full · View this review · Reviewed 315d705be711

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still a follow-up, same as the earlier thread. LIT-3395 asks only for S3 and GCS cold storage of batch lines, so this PR ships s3_v2 and gcs_bucket as the sinks, and the PR body lists module-path custom loggers under the Low caveats. Resolving dotted entries also means adding batch_line_item_callbacks to the DB config overlay's remote-module scrub next to audit_log_callbacks, so it belongs in its own PR with its own tests

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding still applies

At head 315d705be7, _resolve_logger still returns None for any callback other than a CustomLogger instance or the strings "s3_v2" / "gcs_bucket". The proxy has no branch that resolves dotted paths in batch_line_item_callbacks, so custom loggers configured by module path can't be reached and their parts are dropped at runtime. The author is deferring the fix to a follow-up for scope reasons. That is a scheduling decision, not evidence that the defect is gone.

Evidence

litellm/batches/batch_line_items.py:236-243: the match handles CustomLogger() and "s3_v2" | "gcs_bucket"; every other value hits case _: return None.

grep -rn batch_line_item_callbacks litellm/proxy returns no matches at head, so nothing resolves dotted entries with get_instance_fn.

The author's reply confirms the fix is deferred to a separate PR and does not claim it was fixed.

Reviewed 315d705be711 · View follow-up

match callback:
case CustomLogger():
return callback
case "s3_v2" | "gcs_bucket":
return init_custom_logger_compatible_class(callback, internal_usage_cache=None, llm_router=None)
case _:
return None


def _logger_turned_off_message_logging(logger: CustomLogger) -> bool:
return (
getattr(logger, "turn_off_message_logging", False) is True
or getattr(logger, "message_logging", True) is not True
)
19 changes: 16 additions & 3 deletions litellm/batches/batch_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from collections.abc import Iterable, Iterator, Mapping
from collections.abc import Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass
from dataclasses import replace as dataclasses_replace
from enum import Enum
Expand Down Expand Up @@ -70,7 +70,17 @@ def batch_cost_is_final(batch: Batch) -> bool:


async def calculate_batch_cost_and_usage(
file_content_dictionary: list[dict[str, object]],
file_content_dictionary: Sequence[dict[str, object]],
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "mistral"],
model_name: str | None = None,
model_info: ModelInfo | None = None,
) -> BatchCostUsageResult:
"""Calculate the cost and usage of a batch, see batch_cost_and_usage."""
return batch_cost_and_usage(file_content_dictionary, custom_llm_provider, model_name, model_info)


def batch_cost_and_usage(
file_content_dictionary: Sequence[dict[str, object]], # mutable-ok: the rows calculate_batch_cost_and_usage takes
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "mistral"],
model_name: str | None = None,
model_info: ModelInfo | None = None,
Expand Down Expand Up @@ -436,7 +446,7 @@ def _provider_output_file_id(output_file_id: str) -> str:
return extracted


async def _fetch_batch_managed_file_content(
async def fetch_batch_managed_file_content(
file_id: str,
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "mistral"] = "openai",
litellm_params: Mapping[str, object] | None = None,
Expand Down Expand Up @@ -467,6 +477,9 @@ async def _fetch_batch_managed_file_content(
return _file_content.content


_fetch_batch_managed_file_content: Final = fetch_batch_managed_file_content


async def _fetch_batch_output_file_content(
batch: Batch,
custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic", "mistral"] = "openai",
Expand Down
28 changes: 28 additions & 0 deletions litellm/integrations/batch_line_item_objects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""How the line items of one finished batch are laid out as a single object in a storage bucket."""

import json
from datetime import datetime, timezone
from typing import Final

from litellm.types.utils import StandardBatchLineItemsPayload


def batch_line_items_ndjson(payload: StandardBatchLineItemsPayload) -> str:
return "".join(f"{_ndjson_line(line)}\n" for line in payload["lines"])


def _ndjson_line(line: object) -> str:
"""One line as JSON, with non-ASCII text kept readable. A line holding a lone surrogate, which a provider's
JSON escapes can carry, has no UTF-8 form, so that line alone is written with every non-ASCII character escaped."""
text: Final = json.dumps(line, default=str, ensure_ascii=False)
try:
text.encode("utf-8")
except UnicodeEncodeError:
return json.dumps(line, default=str)
return text


def batch_line_items_object_name(payload: StandardBatchLineItemsPayload) -> str:
"""batch_line_items/<finished day, UTC>/<batch id>.jsonl, the same name on every retry so a rewrite replaces it."""
day: Final = datetime.fromtimestamp(payload["finished_at"], tz=timezone.utc).strftime("%Y-%m-%d")
return f"batch_line_items/{day}/{payload['batch_id'].replace('/', '_')}.jsonl"
4 changes: 4 additions & 0 deletions litellm/integrations/custom_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
ModelResponse,
ModelResponseStream,
StandardAuditLogPayload,
StandardBatchLineItemsPayload,
StandardCallbackDynamicParams,
StandardLoggingPayload,
)
Expand Down Expand Up @@ -195,6 +196,9 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti
async def async_log_audit_log_event(self, audit_log: "StandardAuditLogPayload"):
"""Called when an audit log is created. Override in subclasses to handle."""

async def async_log_batch_line_items(self, payload: StandardBatchLineItemsPayload) -> None:
"""Called once per finished batch with every line, when this logger is listed in batch_line_item_callbacks."""

#### PROMPT MANAGEMENT HOOKS ####

async def async_get_chat_completion_prompt(
Expand Down
17 changes: 16 additions & 1 deletion litellm/integrations/gcs_bucket/gcs_bucket.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@
from litellm._uuid import uuid
from litellm.constants import LITELLM_ASYNCIO_QUEUE_MAXSIZE
from litellm.integrations.additional_logging_utils import AdditionalLoggingUtils
from litellm.integrations.batch_line_item_objects import batch_line_items_ndjson, batch_line_items_object_name
from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
from litellm.litellm_core_utils.cloud_storage_security import (
sanitize_cloud_object_component,
)
from litellm.types.integrations.base_health_check import IntegrationHealthCheckStatus
from litellm.types.integrations.gcs_bucket import *
from litellm.types.utils import StandardLoggingPayload
from litellm.types.utils import StandardBatchLineItemsPayload, StandardLoggingPayload

if TYPE_CHECKING:
from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
Expand Down Expand Up @@ -95,6 +96,20 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti
except Exception as e:
verbose_logger.exception("GCS Bucket logging error: %s", e)

async def async_log_batch_line_items(self, payload: StandardBatchLineItemsPayload) -> None:
"""Write the batch's lines as one NDJSON object under batch_line_items/ in the default bucket."""
gcs_logging_config: Final = await self.get_gcs_logging_config()
headers: Final = await self.construct_request_headers(
vertex_instance=gcs_logging_config["vertex_instance"],
service_account_json=gcs_logging_config["path_service_account"],
)
await self._log_json_data_on_gcs(
headers=headers,
bucket_name=gcs_logging_config["bucket_name"],
object_name=batch_line_items_object_name(payload),
logging_payload=await asyncio.to_thread(batch_line_items_ndjson, payload),
)

def _drain_queue_batch(self) -> list[GCSLogQueueItem]:
"""
Drain items from the queue (non-blocking), respecting batch_size limit.
Expand Down
31 changes: 29 additions & 2 deletions litellm/integrations/s3_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
S3_PARTITION_GRANULARITY_ENV_VAR,
)
from litellm.integrations.adaptive_concurrency import AdaptiveConcurrencyLimiter, PutSample
from litellm.integrations.batch_line_item_objects import batch_line_items_ndjson, batch_line_items_object_name
from litellm.integrations.s3 import (
get_s3_object_download_filename,
get_s3_object_key,
Expand All @@ -57,7 +58,7 @@
httpxSpecialProvider,
)
from litellm.types.integrations.s3_v2 import S3PartitionGranularity, s3BatchLoggingElement
from litellm.types.utils import StandardAuditLogPayload, StandardLoggingPayload
from litellm.types.utils import StandardAuditLogPayload, StandardBatchLineItemsPayload, StandardLoggingPayload

from .custom_batch_logger import CustomBatchLogger

Expand Down Expand Up @@ -511,6 +512,31 @@ async def async_log_audit_log_event(self, audit_log: StandardAuditLogPayload) ->
except Exception as e:
verbose_logger.exception("S3 audit log error: %s", e)

async def async_log_batch_line_items(self, payload: StandardBatchLineItemsPayload) -> None:
"""Upload the batch's lines as one NDJSON object under <s3_path>/batch_line_items/."""
object_name: Final = batch_line_items_object_name(payload)
s3_path: Final = cast(str | None, self.s3_path) # cast-ok: s3_path is set from untyped callback params
s3_object_key: Final = (f"{s3_path.rstrip('/')}/" if s3_path else "") + object_name
element: Final = s3BatchLoggingElement(
payload={},
body=await asyncio.to_thread(batch_line_items_ndjson, payload),
content_type="application/x-ndjson",
s3_object_key=s3_object_key,
s3_object_download_filename=object_name.rsplit("/", 1)[-1],
)
# hashing a whole batch's object is CPU-bound too, so it is also prepared off the event loop
prepared_put: Final = await asyncio.to_thread(self._prepare_put, element)
delivered: Final = await self.async_upload_data_to_s3(element, prepared_put)
if not delivered:
# only a log-queue flush reads and clears the drop marks, and this upload is not part of one
self._flush_dropped.pop(id(element), None)
verbose_logger.error(
"s3 logging: the %d line items of batch %s were not stored at %s",
len(payload["lines"]),
payload["batch_id"],
s3_object_key,
)

async def _async_log_event_base(self, kwargs, response_obj, start_time, end_time):
try:
verbose_logger.debug("s3 Logging - Enters logging function for model %s", kwargs)
Expand Down Expand Up @@ -555,6 +581,7 @@ def _upload_semaphore(self, value: asyncio.Semaphore | AdaptiveConcurrencyLimite
async def async_upload_data_to_s3(
self,
batch_logging_element: s3BatchLoggingElement,
prepared_put: _PreparedPut | None = None,
) -> bool:
try:
from litellm.litellm_core_utils.asyncify import asyncify
Expand Down Expand Up @@ -587,7 +614,7 @@ async def signed_put(prepared: _PreparedPut) -> httpx.Response:
return error.response

max_retries: Final = 3
prepared: Final = self._prepare_put(batch_logging_element)
prepared: Final = prepared_put if prepared_put is not None else self._prepare_put(batch_logging_element)
for attempt in range(max_retries):
response = await self._recorded_put(partial(signed_put, prepared))
if (
Expand Down
Loading
Loading