TravelContentCreator/examples/README_streaming.md

103 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 流式处理功能说明
本文档介绍了Travel Content Creator中新增的三种流式输出处理方式以及如何使用它们来优化内容生成体验。
## 新增的流式处理方式
我们在`AI_Agent`类中实现了三种不同的流式处理方式:
1. **同步流式响应** (`generate_text_stream`)
- 已修改为返回完整响应,不再是生成器
- 内部仍使用流式请求以获得更好的超时控制
- 适用于简单的API调用场景
2. **基于回调的流式响应** (`generate_text_stream_with_callback`)
- 通过回调函数处理每个文本块
- 可在回调中实现实时显示、分析或保存
- 最灵活的选项,适合需要自定义处理流程的场景
3. **异步流式响应** (`async_generate_text_stream`)
- 基于`asyncio`的异步生成器
- 适用于需要与其他异步操作集成的场景
- 可在保持响应性的同时处理长时间运行的请求
## 演示脚本
我们提供了一个示例脚本`test_stream.py`,演示了如何使用这三种流式处理方式:
```bash
# 从项目根目录运行
python examples/test_stream.py
```
## 回调函数示例
以下是使用回调函数处理流式响应的例子:
```python
def handle_chunk(chunk, is_last=False, is_timeout=False, is_error=False, error=None):
# 处理文本块
if chunk:
print(chunk, end="", flush=True) # 实时显示
# 处理结束状态
if is_last:
if is_timeout:
print("\n流式响应超时")
if is_error:
print(f"\n发生错误: {error}")
# 使用回调函数进行流式处理
response = agent.generate_text_stream_with_callback(
system_prompt,
user_prompt,
handle_chunk, # 传入回调函数
temperature=0.7
)
```
## 异步流式处理示例
以下是使用异步方式处理流式响应的例子:
```python
async def process_stream():
async for chunk in agent.async_generate_text_stream(
system_prompt,
user_prompt,
temperature=0.7
):
print(chunk, end="", flush=True) # 实时显示
# 可以同时执行其他异步操作
await other_async_task()
# 在异步环境中运行
asyncio.run(process_stream())
```
## 超时处理
所有流式处理方法都支持超时控制:
1. **全局请求超时**:控制整个请求的最长等待时间
2. **流式块超时**:控制两个连续文本块之间的最长等待时间
这些参数可以在创建`AI_Agent`实例时设置:
```python
agent = AI_Agent(
api_url="http://localhost:8000/v1/",
model="qwen",
api_key="EMPTY",
timeout=30, # 全局请求超时(秒)
stream_chunk_timeout=10 # 流式块超时(秒)
)
```
## 注意事项
1. 新的流式处理方法内置了重试机制和错误处理
2. 回调方式提供了最佳的灵活性和控制
3. 异步方式最适合需要保持UI响应性的应用
4. 所有方法都会在完成时自动关闭流式请求