Skip to content

Commit fe34e4b

Browse files
Kasper JungeRalphify
authored andcommitted
refactor: extract _iter_content_blocks to eliminate duplicated message-content iteration
_apply_assistant and _apply_user both repeated the same five-line boilerplate (get content from message, guard non-list, yield dicts). The new generator centralises that logic so each method focuses only on what it does with the blocks. Co-authored-by: Ralphify <noreply@ralphify.co>
1 parent 45d7e25 commit fe34e4b

1 file changed

Lines changed: 13 additions & 15 deletions

File tree

src/ralphify/_console_emitter.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import sys
1111
import threading
1212
import time
13-
from collections.abc import Callable
13+
from collections.abc import Callable, Iterator
1414
from dataclasses import dataclass
1515
from functools import partial
1616
from pathlib import Path
@@ -307,6 +307,16 @@ def _tool_display(name: str, tool_input: dict[str, Any]) -> tuple[str, str, str]
307307
return color, category, arg
308308

309309

310+
def _iter_content_blocks(raw: dict[str, Any]) -> Iterator[dict[str, Any]]:
311+
"""Yield each dict block from ``raw["message"]["content"]``."""
312+
content = raw.get("message", {}).get("content", [])
313+
if not isinstance(content, list):
314+
return
315+
for block in content:
316+
if isinstance(block, dict):
317+
yield block
318+
319+
310320
class _LivePanelBase:
311321
"""Shared scroll-buffer state for iteration Live renderables.
312322
@@ -484,13 +494,7 @@ def _apply_assistant(self, raw: dict[str, Any]) -> None:
484494
"cache_read_input_tokens", self._cache_read_tokens
485495
)
486496

487-
content = msg.get("content", [])
488-
if not isinstance(content, list):
489-
return
490-
491-
for block in content:
492-
if not isinstance(block, dict):
493-
continue
497+
for block in _iter_content_blocks(raw):
494498
block_type = block.get("type")
495499

496500
if block_type == "thinking":
@@ -534,13 +538,7 @@ def _apply_assistant(self, raw: dict[str, Any]) -> None:
534538
self.add_scroll_line(f"[bold {color}]{escape_markup(name)}[/]")
535539

536540
def _apply_user(self, raw: dict[str, Any]) -> None:
537-
msg = raw.get("message", {})
538-
content = msg.get("content", [])
539-
if not isinstance(content, list):
540-
return
541-
for block in content:
542-
if not isinstance(block, dict):
543-
continue
541+
for block in _iter_content_blocks(raw):
544542
if block.get("type") == "tool_result" and block.get("is_error"):
545543
snippet = _truncate(str(block.get("content", "")), _TRUNCATE_TOOL_ERROR)
546544
self.add_scroll_line(

0 commit comments

Comments
 (0)