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(batch_utils.py): improve batch utils to handle newlines within batch content

Krrish Dholakia7ad6abeb1c6a
diff --git a/litellm/router_utils/batch_utils.py b/litellm/router_utils/batch_utils.py
index 6c5d80afc1b..0baad322fa9 100644
--- a/litellm/router_utils/batch_utils.py
+++ b/litellm/router_utils/batch_utils.py
@@ -3,16 +3,66 @@ import json
from os import PathLike
from typing import Optional
+from litellm._logging import verbose_logger
from litellm.types.llms.openai import FileTypes, OpenAIFilesPurpose
class InMemoryFile(io.BytesIO):
- def __init__(self, content: bytes, name: str, content_type: str = "application/jsonl"):
+ def __init__(
+ self, content: bytes, name: str, content_type: str = "application/jsonl"
+ ):
super().__init__(content)
self.name = name
self.content_type = content_type
+def parse_jsonl_with_embedded_newlines(content: str) -> list[dict]:
+ """
+ Parse JSONL content that may contain JSON objects with embedded newlines in string values.
+
+ Unlike splitlines(), this function properly handles cases where JSON string values
+ contain literal newline characters, which would otherwise break simple line-based parsing.
+
+ Args:
+ content: The JSONL file content as a string
+
+ Returns:
+ List of parsed JSON objects
+
+ Example:
+ >>> content = '{"id":1,"msg":"Line 1\\nLine 2"}\\n{"id":2,"msg":"test"}'
+ >>> parse_jsonl_with_embedded_newlines(content)
+ [{"id":1,"msg":"Line 1\\nLine 2"}, {"id":2,"msg":"test"}]
+ """
+ json_objects = []
+ buffer = ""
+
+ for char in content:
+ buffer += char
+ if char == "\n":
+ # Try to parse what we have so far
+ try:
+ json_object = json.loads(buffer.strip())
+ json_objects.append(json_object)
+ buffer = "" # Reset buffer for next JSON object
+ except json.JSONDecodeError:
+ # Not a complete JSON object yet, keep accumulating
+ continue
+
+ # Handle any remaining content in buffer
+ if buffer.strip():
+ try:
+ json_object = json.loads(buffer.strip())
+ json_objects.append(json_object)
+ except json.JSONDecodeError as e:
+ verbose_logger.error(
+ f"error parsing final buffer: {buffer[:100]}..., error: {e}"
+ )
+ raise e
+
+ return json_objects
+
+
def should_replace_model_in_jsonl(
purpose: OpenAIFilesPurpose,
) -> bool:
@@ -47,14 +97,18 @@ def replace_model_in_jsonl(file_content: FileTypes, new_model_name: str) -> File
elif isinstance(file_content_bytes, str):
file_content_str = file_content_bytes
else:
+
return file_content
- lines = file_content_str.splitlines()
- modified_lines = []
- for line in lines:
- # Parse each line as a JSON object
- json_object = json.loads(line.strip())
+ # Parse JSONL properly, handling potential multiline JSON objects
+ json_objects = parse_jsonl_with_embedded_newlines(file_content_str)
+ # If no valid JSON objects were found, return the original content
+ if len(json_objects) == 0:
+ return file_content
+
+ modified_lines = []
+ for json_object in json_objects:
# Replace the model name if it exists
if "body" in json_object:
json_object["body"]["model"] = new_model_name
@@ -64,6 +118,7 @@ def replace_model_in_jsonl(file_content: FileTypes, new_model_name: str) -> File
# Reassemble the modified lines and return as bytes
modified_file_content = "\n".join(modified_lines).encode("utf-8")
+
return InMemoryFile(modified_file_content, name="modified_file.jsonl", content_type="application/jsonl") # type: ignore
except (json.JSONDecodeError, UnicodeDecodeError, TypeError):
@@ -80,7 +135,13 @@ def _get_router_metadata_variable_name(function_name: Optional[str]) -> str:
For ALL other endpoints we call this "metadata
"""
ROUTER_METHODS_USING_LITELLM_METADATA = set(
- ["batch", "generic_api_call", "_acreate_batch", "file", "_ageneric_api_call_with_fallbacks"]
+ [
+ "batch",
+ "generic_api_call",
+ "_acreate_batch",
+ "file",
+ "_ageneric_api_call_with_fallbacks",
+ ]
)
if function_name and any(
method in function_name for method in ROUTER_METHODS_USING_LITELLM_METADATA
diff --git a/tests/router_unit_tests/test_router_batch_utils.py b/tests/router_unit_tests/test_router_batch_utils.py
index adbab7ce881..afa5c8ef646 100644
--- a/tests/router_unit_tests/test_router_batch_utils.py
+++ b/tests/router_unit_tests/test_router_batch_utils.py
@@ -18,7 +18,9 @@ from io import BytesIO
from typing import Dict, List
from litellm.router_utils.batch_utils import (
replace_model_in_jsonl,
- _get_router_metadata_variable_name, InMemoryFile,
+ _get_router_metadata_variable_name,
+ InMemoryFile,
+ parse_jsonl_with_embedded_newlines,
)
@@ -126,5 +128,117 @@ def test_should_replace_model_in_jsonl():
assert should_replace_model_in_jsonl(purpose="batch") == True
assert should_replace_model_in_jsonl(purpose="test") == False
assert should_replace_model_in_jsonl(purpose="user_data") == False
+
+
+def test_parse_jsonl_with_embedded_newlines_simple():
+ """Test parsing simple JSONL without embedded newlines"""
+ content = '{"id": 1, "name": "test"}\n{"id": 2, "name": "test2"}'
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 2
+ assert result[0] == {"id": 1, "name": "test"}
+ assert result[1] == {"id": 2, "name": "test2"}
+
+
+def test_parse_jsonl_with_embedded_newlines_in_strings():
+ """Test parsing JSONL with newlines embedded in string values"""
+ content = '{"id": 1, "message": "Line 1\\nLine 2\\nLine 3"}\n{"id": 2, "message": "test"}'
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 2
+ assert result[0] == {"id": 1, "message": "Line 1\nLine 2\nLine 3"}
+ assert result[1] == {"id": 2, "message": "test"}
+
+
+def test_parse_jsonl_with_embedded_newlines_real_world_example():
+ """Test with the real-world example from the Cooler Master Shark X case"""
+ # This simulates the actual problem case from the user's log
+ content = '''{"custom_id":"16546277850245725","method":"POST","url":"/v1/chat/completions","body":{"model":"openai-gpt-4o-mini-dp-items-translation-dag","messages":[{"role":"system","content":"Translate the product title and description for an e-commerce marketplace in Saudi Arabia and the UAE. Text may be in English or Arabic.\\n"},{"role":"user","content":"\\nOriginal Title: ```Cooler Master Shark X PC Case```\\nOriginal Description: ```UNIQUE MASTERPIECEShark X is a system that provides an impressive unique alternative to traditional PC systems. Shark X will stand out and can be the ultimate trophy or conversation piece for people looking for a unique setup that stands head and fins above the res.```\\nStore Name: ```geekay```\\n"}]}}'''
+
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 1
+ assert result[0]["custom_id"] == "16546277850245725"
+ assert result[0]["method"] == "POST"
+ assert result[0]["body"]["model"] == "openai-gpt-4o-mini-dp-items-translation-dag"
+ assert len(result[0]["body"]["messages"]) == 2
+ assert "Translate the product title" in result[0]["body"]["messages"][0]["content"]
+ assert "Cooler Master Shark X PC Case" in result[0]["body"]["messages"][1]["content"]
+ assert "UNIQUE MASTERPIECEShark X" in result[0]["body"]["messages"][1]["content"]
+
+
+def test_parse_jsonl_with_embedded_newlines_multiple_complex_objects():
+ """Test parsing multiple complex JSON objects with embedded newlines"""
+ content = '''{"id":1,"text":"Line 1\\nLine 2"}
+{"id":2,"nested":{"field":"Value\\nWith\\nNewlines"}}
+{"id":3,"simple":"test"}'''
+
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 3
+ assert result[0]["id"] == 1
+ assert result[0]["text"] == "Line 1\nLine 2"
+ assert result[1]["id"] == 2
+ assert result[1]["nested"]["field"] == "Value\nWith\nNewlines"
+ assert result[2]["id"] == 3
+ assert result[2]["simple"] == "test"
+
+
+def test_parse_jsonl_with_embedded_newlines_no_trailing_newline():
+ """Test parsing JSONL without trailing newline"""
+ content = '{"id": 1, "name": "test"}'
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 1
+ assert result[0] == {"id": 1, "name": "test"}
+
+
+def test_parse_jsonl_with_embedded_newlines_empty_string():
+ """Test parsing empty string"""
+ content = ''
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 0
+
+
+def test_parse_jsonl_with_embedded_newlines_whitespace_only():
+ """Test parsing whitespace-only content"""
+ content = ' \n \n '
+ result = parse_jsonl_with_embedded_newlines(content)
+
+ assert len(result) == 0
+
+
+def test_replace_model_in_jsonl_with_embedded_newlines():
+ """Test that replace_model_in_jsonl works correctly with embedded newlines in content"""
+ # Create a JSONL with embedded newlines in the message content
+ jsonl_data = {
+ "custom_id": "test123",
+ "body": {
+ "model": "old-model",
+ "messages": [
+ {
+ "role": "user",
+ "content": "This is a message\nwith multiple\nlines"
+ }
+ ]
+ }
+ }
+
+ jsonl_bytes = json.dumps(jsonl_data).encode("utf-8")
+ new_model = "new-model"
+
+ result = replace_model_in_jsonl(jsonl_bytes, new_model)
+
+ assert isinstance(result, InMemoryFile)
+
+ # Read and parse the result
+ result_content = result.read().decode("utf-8")
+ result_json = json.loads(result_content)
+ # Verify the model was replaced
+ assert result_json["body"]["model"] == "new-model"
+ # Verify the content with newlines is preserved
+ assert result_json["body"]["messages"][0]["content"] == "This is a message\nwith multiple\nlines"
+ assert result_json["custom_id"] == "test123"
\ No newline at end of file