You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
2.0 KiB

import requests
import json
from Config import *
# Dify API 配置
url = DIFY_URL + "/chat-messages"
headers = {
'Authorization': 'Bearer ' + DIFY_API_KEY,
'Content-Type': 'application/json'
}
# 请求数据
payload = json.dumps({
"inputs": {},
"query": "你是谁?",
"response_mode": "streaming", # 启用流式输出
"conversation_id": "",
"user": "abc-123"
})
# 发送请求并处理流式响应
try:
with requests.post(url, headers=headers, data=payload, stream=True) as response:
response.raise_for_status() # 检查请求是否成功
showed_task_id = False
# 逐行处理流式响应
for line in response.iter_lines():
if line: # 过滤掉空行
decoded_line = line.decode('utf-8') # 解码为 UTF-8
if decoded_line.startswith("data: "): # 处理以 "data: " 开头的行
json_str = decoded_line[len("data: "):] # 去掉 "data: " 前缀
if json_str == "[DONE]": # 流式响应结束
break
try:
# 解析 JSON 数据
json_data = json.loads(json_str)
# 首次显示task_id
if not showed_task_id:
print('task_id=' + json_data['task_id'])
print('message_id=' + json_data['message_id'] )
print('conversation_id=' + json_data['conversation_id'] + '\n')
showed_task_id = True
# 提取并输出流式内容
if "answer" in json_data:
print(json_data["answer"], end="", flush=True) # 实时输出
except json.JSONDecodeError:
pass # 忽略解析错误
except requests.exceptions.RequestException as e:
print("请求失败:", e)