| 664 | |
| 665 | |
| 666 | def stream_usage_tracking_updates( |
| 667 | data: Mapping[str, object], |
| 668 | general_settings: Mapping[str, object], |
| 669 | route_type: str, |
| 670 | supports_stream_options: Callable[[], bool], |
| 671 | ) -> Mapping[str, object]: |
| 672 | scrub: Final = {flag: False for flag in _STREAM_USAGE_FLAGS if flag in data} |
| 673 | if data.get("stream", False) is not True: |
| 674 | return scrub |
| 675 | always_include: Final = general_settings.get("always_include_stream_usage") |
| 676 | stream_options: Final = data.get("stream_options") |
| 677 | if always_include is True: |
| 678 | if "stream_options" not in data: |
| 679 | return {**scrub, "stream_options": {"include_usage": True}, STREAM_USAGE_INJECTED_FIELD: True} |
| 680 | if isinstance(stream_options, dict) and "include_usage" not in stream_options: |
| 681 | return { |
| 682 | **scrub, |
| 683 | "stream_options": {**stream_options, "include_usage": True}, |
| 684 | STREAM_USAGE_INJECTED_FIELD: True, |
| 685 | } |
| 686 | return scrub |
| 687 | if always_include is False and route_type == "agenerate_content_stream" and "stream_options" not in data: |
| 688 | return {**scrub, "stream_options": {"include_usage": False}} |
| 689 | if always_include is False or route_type not in _STREAM_USAGE_TRACKED_ROUTES: |
| 690 | return scrub |
| 691 | if isinstance(stream_options, dict) and stream_options.get("include_usage") is True: |
| 692 | return scrub |
| 693 | if not supports_stream_options(): |
| 694 | return scrub |
| 695 | merged_stream_options: Final = {**stream_options} if isinstance(stream_options, dict) else {} |
| 696 | return { |
| 697 | "stream_options": {**merged_stream_options, "include_usage": True}, |
| 698 | "_litellm_strip_stream_usage": True, |
| 699 | STREAM_USAGE_INJECTED_FIELD: True, |
| 700 | } |
| 701 | |
| 702 | |
| 703 | @runtime_checkable |