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.
43 lines
1.6 KiB
43 lines
1.6 KiB
5 months ago
|
import requests
|
||
|
import json
|
||
|
|
||
|
# Dify API 配置
|
||
|
url = "http://10.10.14.207/v1/chat-messages"
|
||
|
headers = {
|
||
|
'Authorization': 'Bearer app-E0r9SOtMQ14P9OHrPCbIHvJ5',
|
||
|
'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() # 检查请求是否成功
|
||
|
|
||
|
# 逐行处理流式响应
|
||
|
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)
|
||
|
# 提取并输出流式内容
|
||
|
if "answer" in json_data:
|
||
|
print(json_data["answer"], end="", flush=True) # 实时输出
|
||
|
except json.JSONDecodeError:
|
||
|
pass # 忽略解析错误
|
||
|
|
||
|
except requests.exceptions.RequestException as e:
|
||
|
print("请求失败:", e)
|