问题
我们搭建了一个Agent的知识库问题,希望调用接口进行返回,但是Agent模型只支持streaming格式,不支持blocking模式。

而流式输出是字节码,我们是不能直接看懂它的意思,因此需要通过下面代码去实现转换。
python
import requests
import json
def stream_to_text(url, headers, data):
"""
将流式API响应转换为完整的文字输出
参数:
url: API端点URL
headers: 请求头
data: 请求数据(字典格式)
返回:
完整的响应文本
"""
full_response = ""
try:
# 发送POST请求,设置stream=True来接收流式响应
response = requests.post(url, headers=headers, json=data, stream=True)
response.raise_for_status()
# 逐行读取流式响应
for line in response.iter_lines():
if line:
# 解码字节为字符串
line_str = line.decode('utf-8')
# 流式响应通常以"data: "开头
if line_str.startswith('data: '):
json_str = line_str[6:] # 移除"data: "前缀
try:
# 解析JSON数据
data_obj = json.loads(json_str)
# 根据实际API响应结构提取文本
# 这里可能需要根据你的API实际返回格式调整
if 'answer' in data_obj:
full_response += data_obj['answer']
elif 'message' in data_obj:
full_response += data_obj['message']
elif 'text' in data_obj:
full_response += data_obj['text']
except json.JSONDecodeError:
# 如果不是JSON格式,直接添加文本
if json_str != '[DONE]': # 忽略结束标记
full_response += json_str
return full_response
except requests.exceptions.RequestException as e:
return f"请求错误: {str(e)}"
# 使用示例
if __name__ == "__main__":
url = "http://xxx/v1/chat-messages"
headers = {
"Authorization": "Bearer your-api-key",
"Content-Type": "application/json"
}
data = {
"inputs": {},
"query": "卷纸属于哪一类的费用报销",
"response_mode": "streaming",
"conversation_id": "",
"user": "abc-123"
}
print("正在请求API...")
result = stream_to_text(url, headers, data)
print("\n完整响应:")
print(result)
运行后会得到以下结果:
