Repository navigation
feat(batches): store each batch line's request and response in S3 and GCS #41691
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 110 commits
b38b867
0ea8ce7
7fa8c92
c7edcce
7f06708
8908023
8aca0c3
ff9d30b
feea6f2
775d851
8484b2f
b4cb884
61d5ab0
bc53e23
4b6efef
ed23e2e
096ba84
a8fafaf
c746e57
45b7509
bef2f04
6cbad5c
a760991
271b6c6
c0b69ae
67d4471
ee8dcfc
a2fd2a8
fe11251
05d6977
f5670e0
0ca85b4
dd9d4fd
4c86f0b
5777f7e
87d82b9
f4a6e12
f3ba65d
f65b5b1
cffa640
a7c9ded
f69d5c5
5f35c25
a891065
ff77170
1388dbc
ee21adb
4d96efc
64c514c
aebde2a
06fb342
eac1ed0
e1b9449
60a47e2
a7f1978
9ca41c9
9c71dae
8ec50a2
a35d4ee
c9f67ff
1b02cb6
6348a7d
b139924
db33862
15fa86c
1b63787
235019d
6b8fb29
0632fdd
b57e4f0
c653e2e
e00471b
317764c
85fc449
21cd892
7cf3024
4bd5762
4cc9f56
586b022
f26f86b
07d543c
6e826b4
fd7a099
9ed3211
8a46101
7ae8fec
903c593
2b30a09
0865123
56b60e6
0470177
8f2c935
d62c5f2
f6dc422
6125f5f
cbdbbb5
5460242
f010f96
4c120da
7ab9a3f
5cad620
aa76a2e
15f3d73
21a7109
082a859
459234f
400a6f9
ee61a60
85169fc
2875f03
4ba1eaa
0ee34c9
a02fc23
bc925d4
315d705
c75d257
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| 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"), | ||
| 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( | ||
|
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: | ||
|
yucheng-berri marked this conversation as resolved.
Resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Low · Custom loggers named in
|
||
| 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 | ||
| ) | ||
| 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" |
Uh oh!
There was an error while loading. Please reload this page.