Skip to content

Commit fb67680

Browse files
authored
fix: #2856 stop recursive trace preview truncation (#2860)
1 parent c06cd45 commit fb67680

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/agents/tracing/processors.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,11 @@ def _truncate_json_value_for_limit(self, value: Any, max_bytes: int) -> Any:
296296
if isinstance(value, list):
297297
return self._truncate_list_for_json_limit(value, max_bytes)
298298

299-
return self._truncated_preview(value)
299+
preview = self._truncated_preview(value)
300+
if self._value_json_size_bytes(preview) <= max_bytes:
301+
return preview
302+
303+
return value
300304

301305
def _truncate_mapping_for_json_limit(
302306
self, value: dict[str, Any], max_bytes: int

tests/test_trace_processor.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,48 @@ def test_sanitize_for_openai_tracing_api_replaces_unserializable_output():
920920
exporter.close()
921921

922922

923+
def test_truncate_json_value_for_limit_terminates_preview_dict_under_zero_budget():
924+
exporter = BackendSpanExporter(api_key="test_key")
925+
preview = exporter._truncated_preview(None)
926+
927+
truncated = exporter._truncate_json_value_for_limit(preview, 0)
928+
929+
assert truncated == {}
930+
exporter.close()
931+
932+
933+
def test_sanitize_for_openai_tracing_api_handles_none_content_under_tight_budget():
934+
exporter = BackendSpanExporter(api_key="test_key")
935+
payload: dict[str, Any] = {
936+
"object": "trace.span",
937+
"span_data": {
938+
"type": "generation",
939+
"output": [
940+
{
941+
"role": "assistant",
942+
"content": None,
943+
"name": "a" * 25_000,
944+
"tool_calls": [],
945+
}
946+
for _ in range(8)
947+
],
948+
"usage": {"input_tokens": 1, "output_tokens": 1},
949+
},
950+
}
951+
952+
sanitized = exporter._sanitize_for_openai_tracing_api(payload)
953+
sanitized_output = cast(list[Any], sanitized["span_data"]["output"])
954+
955+
assert isinstance(sanitized_output, list)
956+
assert sanitized_output != payload["span_data"]["output"]
957+
assert (
958+
exporter._value_json_size_bytes(sanitized_output)
959+
<= exporter._OPENAI_TRACING_MAX_FIELD_BYTES
960+
)
961+
assert any(item == {} for item in sanitized_output)
962+
exporter.close()
963+
964+
923965
def test_truncate_string_for_json_limit_returns_original_when_within_limit():
924966
exporter = BackendSpanExporter(api_key="test_key")
925967
value = "hello"

0 commit comments

Comments
 (0)