message_content.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from __future__ import annotations
  2. from collections.abc import Mapping
  3. from typing import Any
  4. _NON_TEXT_PART_TYPES = {"image", "image_url", "input_image", "audio", "input_audio"}
  5. _TEXT_KEYS = ("text", "content", "input_text", "output_text", "summary_text")
  6. def _field(value: Any, key: str) -> Any:
  7. return value.get(key) if isinstance(value, Mapping) else getattr(value, key, None)
  8. def _text_from_part(part: Any) -> str:
  9. if part is None:
  10. return ""
  11. if isinstance(part, str):
  12. return part
  13. if str(_field(part, "type") or "").strip().lower() in _NON_TEXT_PART_TYPES:
  14. return ""
  15. for key in _TEXT_KEYS:
  16. text = _field(part, key)
  17. if isinstance(text, str):
  18. return text
  19. return ""
  20. def flatten_message_text(content: Any, *, sep: str = "\n") -> str:
  21. """Return the visible text from common chat/Responses message content shapes."""
  22. if content is None:
  23. return ""
  24. if isinstance(content, str):
  25. return content
  26. if isinstance(content, list):
  27. return sep.join(chunk for chunk in map(_text_from_part, content) if chunk)
  28. text = _text_from_part(content)
  29. if text:
  30. return text
  31. try:
  32. return str(content)
  33. except Exception:
  34. return ""