helper.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from __future__ import annotations
  2. import re
  3. import logging
  4. from typing import AsyncIterator, Iterator, AsyncGenerator, Optional
  5. def filter_json(text: str) -> str:
  6. """
  7. Parses JSON code block from a string.
  8. Args:
  9. text (str): A string containing a JSON code block.
  10. Returns:
  11. dict: A dictionary parsed from the JSON code block.
  12. """
  13. match = re.search(r"```(json|)\n(?P<code>[\S\s]+?)\n```", text)
  14. if match:
  15. return match.group("code")
  16. return text
  17. def find_stop(stop: Optional[list[str]], content: str, chunk: str = None):
  18. first = -1
  19. word = None
  20. if stop is not None:
  21. for word in list(stop):
  22. first = content.find(word)
  23. if first != -1:
  24. content = content[:first]
  25. break
  26. if chunk is not None and first != -1:
  27. first = chunk.find(word)
  28. if first != -1:
  29. chunk = chunk[:first]
  30. else:
  31. first = 0
  32. return first, content, chunk
  33. def filter_none(**kwargs) -> dict:
  34. return {
  35. key: value
  36. for key, value in kwargs.items()
  37. if value is not None
  38. }
  39. async def safe_aclose(generator: AsyncGenerator) -> None:
  40. try:
  41. await generator.aclose()
  42. except Exception as e:
  43. logging.warning(f"Error while closing generator: {e}")
  44. # Helper function to convert a synchronous iterator to an async iterator
  45. async def to_async_iterator(iterator: Iterator) -> AsyncIterator:
  46. for item in iterator:
  47. yield item