Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(proxy): preserve crlf line endings when injecting streamed usage cost

mateo-berrie7c8cff3b7c1
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 4e422ee49d7..10c54a25805 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -3107,8 +3107,7 @@ class ProxyBaseLLMRequestProcessing:
obj = json.loads(json_part)
maybe_modified = ProxyBaseLLMRequestProcessing._inject_cost_into_usage_dict(obj, model_name)
if maybe_modified is not None:
- # Replace just this line with updated JSON using safe_dumps
- lines[idx] = f"data: {safe_dumps(maybe_modified)}"
+ lines[idx] = "data: " + safe_dumps(maybe_modified) + ("\r" if ln.endswith("\r") else "")
return "\n".join(lines)
return None
except Exception:
diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py b/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py
index d559faba1c2..1d82a5dfc6e 100644
--- a/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py
@@ -454,6 +454,9 @@ async def test_chunk_processor_streams_crlf_delimited_frames_live_and_injects_co
assert len(received) == len(chunks)
assert received[0] == chunks[0]
+ injected_usage_frame = received[2]
+ assert injected_usage_frame.endswith(b"\r\n\r\n")
+ assert b"\n" not in injected_usage_frame.replace(b"\r\n", b"")
reassembled = b"".join(received).decode("utf-8")
usage_lines = [ln for ln in reassembled.replace("\r\n", "\n").split("\n") if '"total_tokens"' in ln]
assert len(usage_lines) == 1