Skip to content
32 changes: 21 additions & 11 deletions openhands-sdk/openhands/sdk/llm/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,21 +170,12 @@ class TextContent(BaseContent):
model_config: ClassVar[ConfigDict] = ConfigDict(
extra="forbid", populate_by_name=True
)
enable_truncation: bool = True

def to_llm_dict(self) -> list[dict[str, str | dict[str, str]]]:
"""Convert to LLM API format."""
text = self.text
if self.enable_truncation and len(text) > DEFAULT_TEXT_CONTENT_LIMIT:
logger.warning(
f"TextContent text length ({len(text)}) exceeds limit "
f"({DEFAULT_TEXT_CONTENT_LIMIT}), truncating"
)
text = maybe_truncate(text, DEFAULT_TEXT_CONTENT_LIMIT)

data: dict[str, str | dict[str, str]] = {
"type": self.type,
"text": text,
"text": self.text,
}
if self.cache_prompt:
data["cache_control"] = {"type": "ephemeral"}
Expand Down Expand Up @@ -342,6 +333,8 @@ def _string_serializer(self) -> dict[str, Any]:
content = "\n".join(
item.text for item in self.content if isinstance(item, TextContent)
)
if self.role == "tool":
content = self._maybe_truncate_tool_text(content)
message_dict: dict[str, Any] = {"content": content, "role": self.role}

# tool call keys are added in to_chat_dict to centralize behavior
Expand All @@ -366,6 +359,12 @@ def _list_serializer(self, *, vision_enabled: bool) -> dict[str, Any]:
# All content types now return list[dict[str, Any]]
item_dicts = item.to_llm_dict()

if self.role == "tool" and item_dicts:
for d in item_dicts:
text_val = d.get("text")
if d.get("type") == "text" and isinstance(text_val, str):
d["text"] = self._maybe_truncate_tool_text(text_val)

# We have to remove cache_prompt for tool content and move it up to the
# message level
# See discussion here for details: https://github.com/BerriAI/litellm/issues/6422#issuecomment-2438765472
Expand Down Expand Up @@ -551,17 +550,28 @@ def to_responses_dict(self, *, vision_enabled: bool) -> list[dict[str, Any]]:
)
for c in self.content:
if isinstance(c, TextContent):
output_text = self._maybe_truncate_tool_text(c.text)
items.append(
{
"type": "function_call_output",
"call_id": resp_call_id,
"output": c.text,
"output": output_text,
}
)
return items

return items

def _maybe_truncate_tool_text(self, text: str) -> str:
if not text or len(text) <= DEFAULT_TEXT_CONTENT_LIMIT:
return text
logger.warning(
"Tool TextContent text length (%s) exceeds limit (%s), truncating",
len(text),
DEFAULT_TEXT_CONTENT_LIMIT,
)
return maybe_truncate(text, DEFAULT_TEXT_CONTENT_LIMIT)

@classmethod
def from_llm_chat_message(cls, message: LiteLLMMessage) -> "Message":
"""Convert a LiteLLMMessage (Chat Completions) to our Message class.
Expand Down
6 changes: 1 addition & 5 deletions tests/integration/utils/llm_judge.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,7 @@ def judge_agent_behavior(

try:
# Get LLM response with tool calling
messages = [
Message(
role="user", content=[TextContent(text=prompt, enable_truncation=False)]
)
]
messages = [Message(role="user", content=[TextContent(text=prompt)])]
response = llm.completion(
messages=messages,
tools=[judgment_tool], # type: ignore[arg-type]
Expand Down
94 changes: 77 additions & 17 deletions tests/sdk/llm/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,35 +234,95 @@ def test_text_content_truncation_under_limit():
assert result[0]["text"] == "Short text"


def test_text_content_truncation_over_limit():
"""Test TextContent truncates when over limit."""
def test_text_content_no_truncation_over_limit():
"""TextContent itself should not truncate; truncation is role=tool only."""
from openhands.sdk.llm.message import TextContent
from openhands.sdk.utils import DEFAULT_TEXT_CONTENT_LIMIT

# Create text that exceeds the limit
long_text = "A" * (DEFAULT_TEXT_CONTENT_LIMIT + 1000)

with patch("openhands.sdk.llm.message.logger") as mock_logger:
content = TextContent(text=long_text)
result = content.to_llm_dict()

# Check that warning was logged
mock_logger.warning.assert_called_once()
warning_call = mock_logger.warning.call_args[0][0]
assert "exceeds limit" in warning_call
assert str(DEFAULT_TEXT_CONTENT_LIMIT + 1000) in warning_call
assert str(DEFAULT_TEXT_CONTENT_LIMIT) in warning_call

# Check that text was truncated
mock_logger.warning.assert_not_called()
assert len(result) == 1
text_result = result[0]["text"]
assert result[0]["text"] == long_text


def test_tool_message_truncates_text_over_limit():
"""Tool-role messages should truncate huge TextContent blocks."""
from openhands.sdk.llm.message import Message, TextContent
from openhands.sdk.utils import DEFAULT_TEXT_CONTENT_LIMIT

long_text = "A" * (DEFAULT_TEXT_CONTENT_LIMIT + 1000)

with patch("openhands.sdk.llm.message.logger") as mock_logger:
msg = Message(role="tool", content=[TextContent(text=long_text)])
result = msg.to_chat_dict(
cache_enabled=True,
vision_enabled=False,
function_calling_enabled=False,
force_string_serializer=False,
send_reasoning_content=False,
)

mock_logger.warning.assert_called_once()
args = mock_logger.warning.call_args[0]
assert "Tool TextContent text length" in args[0]
assert args[1] == DEFAULT_TEXT_CONTENT_LIMIT + 1000
assert args[2] == DEFAULT_TEXT_CONTENT_LIMIT

content_item = result["content"][0]
assert content_item["type"] == "text"
text_result = content_item["text"]
assert isinstance(text_result, str)
assert len(text_result) < len(long_text)
assert len(text_result) == DEFAULT_TEXT_CONTENT_LIMIT
# With head-and-tail truncation, should start and end with original content
assert text_result.startswith("A") # Should start with original content
assert text_result.endswith("A") # Should end with original content
assert "<response clipped>" in text_result # Should contain truncation notice
assert "<response clipped>" in text_result


def test_user_message_does_not_truncate_text_over_limit():
"""User-role messages should not truncate at serialization."""
from openhands.sdk.llm.message import Message, TextContent
from openhands.sdk.utils import DEFAULT_TEXT_CONTENT_LIMIT

long_text = "A" * (DEFAULT_TEXT_CONTENT_LIMIT + 1000)

with patch("openhands.sdk.llm.message.logger") as mock_logger:
msg = Message(role="user", content=[TextContent(text=long_text)])
result = msg.to_chat_dict(
cache_enabled=False,
vision_enabled=False,
function_calling_enabled=False,
force_string_serializer=True,
send_reasoning_content=False,
)

mock_logger.warning.assert_not_called()
assert result["content"] == long_text


def test_tool_message_truncates_text_over_limit_with_string_serializer():
"""Tool-role truncation must also apply on the string-serializer path."""
from openhands.sdk.llm.message import Message, TextContent
from openhands.sdk.utils import DEFAULT_TEXT_CONTENT_LIMIT

long_text = "A" * (DEFAULT_TEXT_CONTENT_LIMIT + 1000)

with patch("openhands.sdk.llm.message.logger") as mock_logger:
msg = Message(role="tool", content=[TextContent(text=long_text)])
result = msg.to_chat_dict(
cache_enabled=False,
vision_enabled=False,
function_calling_enabled=False,
force_string_serializer=True,
send_reasoning_content=False,
)

mock_logger.warning.assert_called_once()
assert result["content"] != long_text
assert len(result["content"]) == DEFAULT_TEXT_CONTENT_LIMIT
assert "<response clipped>" in result["content"]


def test_text_content_truncation_exact_limit():
Expand Down
22 changes: 22 additions & 0 deletions tests/sdk/llm/test_responses_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,28 @@ def test_tool_to_responses_emits_function_call_output_with_fc_prefix():
assert all(item["call_id"].startswith("fc_") for item in out)


def test_tool_to_responses_truncates_output_over_limit():
from unittest.mock import patch

from openhands.sdk.utils import DEFAULT_TEXT_CONTENT_LIMIT

long_text = "A" * (DEFAULT_TEXT_CONTENT_LIMIT + 1000)
m = Message(
role="tool",
tool_call_id="abc",
name="foo",
content=[TextContent(text=long_text)],
)

with patch("openhands.sdk.llm.message.logger") as mock_logger:
out = m.to_responses_dict(vision_enabled=False)

mock_logger.warning.assert_called_once()
assert out[0]["type"] == "function_call_output"
assert len(out[0]["output"]) == DEFAULT_TEXT_CONTENT_LIMIT
assert "<response clipped>" in out[0]["output"]


def test_assistant_includes_reasoning_passthrough():
ri = ReasoningItemModel(
id="rid1",
Expand Down
Loading