streaming.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # utils/streaming.py
  2. """流式输出工具函数"""
  3. import sys
  4. from typing import List
  5. from hello_agents import HelloAgentsLLM
  6. def should_stream(streaming: bool = None) -> bool:
  7. """
  8. 判断是否应该使用流式输出
  9. Args:
  10. streaming: 手动指定的流式输出设置(None = 自动检测)
  11. Returns:
  12. 是否使用流式输出
  13. """
  14. if streaming is None:
  15. # 自动检测:交互式终端使用流式输出
  16. return sys.stdout.isatty()
  17. return streaming
  18. def stream_response(llm: HelloAgentsLLM, messages: List[dict], silent: bool = False) -> str:
  19. """
  20. 执行流式 LLM 调用并打印结果
  21. Args:
  22. llm: HelloAgentsLLM 实例
  23. messages: LLM 消息列表
  24. silent: 是否静默模式(不打印输出)
  25. Returns:
  26. 完整的响应文本
  27. """
  28. full_response = ""
  29. previous_length = 0
  30. try:
  31. for chunk in llm.stream_invoke(messages):
  32. # chunk 是累积式的,只打印新增部分
  33. if len(chunk) > previous_length:
  34. new_content = chunk[previous_length:]
  35. if not silent:
  36. print(new_content, end='', flush=True)
  37. previous_length = len(chunk)
  38. # 保存完整响应
  39. full_response = chunk
  40. if not silent:
  41. print() # 换行
  42. return full_response
  43. except Exception as e:
  44. # 如果流式输出失败,降级到普通输出
  45. if not silent:
  46. print(f"\n[流式输出失败,使用普通输出: {e}]")
  47. return llm.invoke(messages)