Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/agents/util/_pretty_print.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
from typing import TYPE_CHECKING

from pydantic import BaseModel
Expand All @@ -8,10 +9,17 @@


def _indent(text: str, indent_level: int) -> str:
# Normalize ordinary CRLF breaks before escaping controls that splitlines consumes.
text = _escape_terminal_controls(text.replace("\r\n", "\n"))
indent_string = " " * indent_level
return "\n".join(f"{indent_string}{line}" for line in text.splitlines())


def _escape_terminal_controls(text: str) -> str:
"""Escape C0, DEL, and C1 controls, preserving tabs and diagnostic line breaks."""
return re.sub(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]", lambda m: f"\\x{ord(m[0]):02x}", text)
Comment thread
jbeckwith-oai marked this conversation as resolved.
Resolved


def _final_output_str(result: "RunResultBase") -> str:
if result.final_output is None:
return "None"
Expand All @@ -36,7 +44,7 @@ def pretty_print_result(result: "RunResult") -> str:
output += f"\n- {len(result.output_guardrail_results)} output guardrail result(s)"
output += "\n(See `RunResult` for more details)"

return output
return _escape_terminal_controls(output)
Comment thread
jbeckwith-oai marked this conversation as resolved.
Resolved


def pretty_print_run_error_details(result: "RunErrorDetails") -> str:
Expand Down Expand Up @@ -68,4 +76,4 @@ def pretty_print_run_result_streaming(result: "RunResultStreaming") -> str:
output += f"\n- {len(result.input_guardrail_results)} input guardrail result(s)"
output += f"\n- {len(result.output_guardrail_results)} output guardrail result(s)"
output += "\n(See `RunResultStreaming` for more details)"
return output
return _escape_terminal_controls(output)
76 changes: 76 additions & 0 deletions tests/test_pretty_print.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from dataclasses import dataclass

import pytest
from inline_snapshot import snapshot
Expand Down Expand Up @@ -120,6 +121,81 @@ class Foo(BaseModel):
bar: str


@dataclass
class TextOutput:
text: str

def __str__(self) -> str:
return self.text


@pytest.mark.asyncio
@pytest.mark.parametrize("streaming", [False, True])
@pytest.mark.parametrize("output_kind", ["text", "model", "dataclass"])
async def test_result_str_escapes_terminal_controls(streaming, output_kind):
payload = (
"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c\x0b\x0c\x1c\x1d\x1e\x85"
)
escaped = (
r"Hello\x1b[2J\x1b]0;title\x07\x08\x00\x7f\x9b31m\x9d0;title\x9c\x0b\x0c\x1c\x1d\x1e\x85"
)
model = ScriptedModel()
if output_kind == "model":
output_type = Foo
response = Foo(bar=payload).model_dump_json()
elif output_kind == "dataclass":
output_type = TextOutput
response = json.dumps({_WRAPPER_DICT_KEY: {"text": payload}})
else:
output_type = None
response = payload
model.enqueue([get_text_message(response)])
agent = Agent(name="agent\x1b[2J\x9b31m", model=model, output_type=output_type)

if streaming:
result = Runner.run_streamed(agent, input="Hello")
async for _ in result.stream_events():
pass
else:
result = await Runner.run(agent, input="Hello")

rendered = str(result)
assert r'Agent(name="agent\x1b[2J\x9b31m", ...)' in rendered
if output_kind == "model":
assert result.final_output.bar == payload
# JSON already escapes C0 controls; the diagnostic printer must also escape C1.
assert r"\u001b[2J" in rendered
assert r"\x9b31m\x9d0;title\x9c" in rendered
assert r"\x85" in rendered
elif output_kind == "dataclass":
assert result.final_output.text == payload
assert escaped in rendered
else:
assert result.final_output == payload
assert escaped in rendered
assert agent.name == "agent\x1b[2J\x9b31m"
assert all(char >= " " or char in "\n\t" for char in rendered)
assert not any("\x7f" <= char <= "\x9f" for char in rendered)


@pytest.mark.asyncio
@pytest.mark.parametrize("streaming", [False, True])
async def test_result_str_preserves_readable_multiline_output(streaming):
payload = "Hello, 世界 👋\r\n\tCafé\n\nlast line"
model = ScriptedModel()
model.enqueue([get_text_message(payload)])
agent = Agent(name="test_agent", model=model)
if streaming:
result = Runner.run_streamed(agent, input="Hello")
async for _ in result.stream_events():
pass
else:
result = await Runner.run(agent, input="Hello")

assert " Hello, 世界 👋\n \tCafé\n \n last line\n- 1 new item(s)" in str(result)
assert result.final_output == payload


@pytest.mark.asyncio
async def test_pretty_run_result_structured_output():
model = ScriptedModel()
Expand Down
Loading