streamParser.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. from typing import AsyncGenerator
  3. from digitalHuman.protocol import *
  4. __all__ = ['resonableStreamingParser']
  5. async def resonableStreamingParser(generator: AsyncGenerator[str, None]):
  6. chunkBuffer: str = ""
  7. thinkFlag = False
  8. async for eventType, chunk in generator:
  9. # 只有text做解析
  10. if eventType != EVENT_TYPE.TEXT:
  11. yield eventStreamResponse(eventType, chunk)
  12. continue
  13. chunkBuffer += chunk
  14. # 缓存10个字符
  15. if len(chunkBuffer) < 10:
  16. continue
  17. if not thinkFlag and '<think>' in chunkBuffer:
  18. # 开始标志位判断
  19. thinkFlag = True
  20. textContent, thinkContent = chunkBuffer.split('<think>')
  21. if thinkContent: yield eventStreamThink(thinkContent)
  22. if textContent: yield eventStreamText(textContent)
  23. chunkBuffer = ""
  24. continue
  25. if thinkFlag and '</think>' in chunkBuffer:
  26. # 结束标志位判断
  27. thinkFlag = False
  28. thinkContent, textContent = chunkBuffer.split('</think>')
  29. if thinkContent: yield eventStreamThink(thinkContent)
  30. if textContent: yield eventStreamText(textContent)
  31. chunkBuffer = ""
  32. continue
  33. chunkBuffer, content = chunkBuffer[-10:], chunkBuffer[:-10]
  34. if thinkFlag:
  35. yield eventStreamThink(content)
  36. else:
  37. yield eventStreamText(content)
  38. if chunkBuffer:
  39. if thinkFlag:
  40. # 结束标志位判断
  41. if '</think>' in chunkBuffer:
  42. thinkFlag = False
  43. thinkContent, textContent = content.split('</think>')
  44. yield eventStreamThink(thinkContent)
  45. yield eventStreamText(textContent)
  46. else:
  47. yield eventStreamThink(chunkBuffer)
  48. else:
  49. yield eventStreamText(chunkBuffer)