stream_consumer_fences.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Code-fence helpers shared by the stream consumer and the gateway final send."""
  2. from __future__ import annotations
  3. import re
  4. def escape_code_fences_for_display(text: str) -> str:
  5. """Replace each ``` with \\`\\`\\` so text can be wrapped in an outer ``` block.
  6. Reasoning content that quotes code would otherwise break the outer fence.
  7. """
  8. return text.replace("```", "\\`\\`\\`") if isinstance(text, str) else text
  9. def ensure_closed_code_fences(text: str) -> str:
  10. """Append a closing ``` and/or ` if the text has orphaned code markers.
  11. Output truncated mid-code-block (finish_reason="length") would otherwise render
  12. everything after the orphan as one code block / inline span; a spurious close is
  13. far less harmful. Odd ``` count → fence on its own line; then, with complete
  14. ```…``` regions stripped, odd ` count → a backtick.
  15. """
  16. if not isinstance(text, str) or not text:
  17. return text
  18. if text.count("```") % 2 == 1:
  19. text = text.rstrip("\n") + "\n```"
  20. # Strip complete fenced regions (and any trailing unclosed ``` that leaks
  21. # through) so their internal backticks don't pollute the standalone count.
  22. without_fences = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
  23. without_fences = re.sub(r"```[^`]*$", "", without_fences)
  24. if without_fences.count("`") % 2 == 1:
  25. text = text + "`"
  26. return text