fix(agent): 外部Dify Agent 手动跟随http->https 301重定向并保持POST(测试连接+运行期);qihuyun.com直连

This commit is contained in:
deploy committed 2026-07-15 14:30:24 +08:00
1 parent d274733fb3
commit 4d57987aa5
2 files changed
+111 -46

No files matched your search

+69 -45
View File
@@ -146,6 +146,9 @@ def _proxy_for_url(url: str) -> str | None:
host = (urlparse(url).hostname or "").lower()
if "agnes-ai.com" in host or "agnes-ai.space" in host:
return None
# 平台自有域名(含自建 Dify/n8n 等)必须直连,不经出网代理。
if "qihuyun.com" in host:
return None
return _outbound_proxy()
@@ -352,52 +355,73 @@ async def _call_dify_agent(endpoint: str, api_key: str, query: str,
new_conv_id = ext_conv_id
err_msg = None
wf_outputs = None
async with httpx.AsyncClient(timeout=180, proxy=_proxy_for_url(url), trust_env=False) as client:
async with client.stream("POST", url, headers=headers, json=payload) as resp:
if resp.status_code != 200:
body = (await resp.aread()).decode("utf-8", "replace")
raise RuntimeError(f"Dify HTTP {resp.status_code}: {body[:300]}")
async for line in resp.aiter_lines():
if not line:
# httpx 默认 follow_redirects=False;stream POST 若遇 301/302 会直接返回该状态码。
# 且 httpx 自动跟随会把 POST 降级为 GET(对 /v1/chat-messages 变 405)。
# 因此手动跟随 301/302/307/308,保持 POST 与请求体不变(最多 4 跳)。
async with httpx.AsyncClient(timeout=180, proxy=_proxy_for_url(url), trust_env=False,
follow_redirects=False) as client:
cur_url = url
for _redir in range(4):
async with client.stream("POST", cur_url, headers=headers, json=payload) as resp:
if resp.status_code in (301, 302, 307, 308):
loc = resp.headers.get("location") or resp.headers.get("Location")
await resp.aclose()
if not loc:
raise RuntimeError(f"Dify HTTP {resp.status_code}: 缺少重定向地址")
# 处理相对地址
if loc.startswith("/"):
from urllib.parse import urlsplit, urlunsplit
p = urlsplit(cur_url)
loc = urlunsplit((p.scheme, p.netloc, loc, "", ""))
cur_url = loc
continue
line = line.strip()
if not line.startswith("data:"):
continue
data_str = line[5:].strip()
if not data_str or data_str == "[DONE]":
continue
try:
evt = json.loads(data_str)
except Exception:
continue
ev = evt.get("event")
if evt.get("conversation_id"):
new_conv_id = evt["conversation_id"]
data = evt.get("data") or {}
# 兼容三类 Dify 应用:
# 1) Chat/Agent 应用: message / agent_message 事件带增量 answer
# 2) Chatflow/Workflow 应用: text_chunk 事件带 data.text;
# 结束时 workflow_finished 带 status / outputs / error
if ev in ("message", "agent_message"):
answer_parts.append(evt.get("answer", "") or "")
elif ev == "message_replace":
# 内容审查替换:以替换后的完整 answer 为准
answer_parts = [evt.get("answer", "") or ""]
elif ev == "text_chunk":
answer_parts.append((data.get("text") or ""))
elif ev == "node_finished":
# answer / end 节点的 outputs 可能含最终文本
if data.get("node_type") in ("answer", "end") and data.get("outputs"):
wf_outputs = data.get("outputs")
if data.get("status") == "failed" and data.get("error"):
err_msg = str(data.get("error"))
elif ev == "workflow_finished":
if data.get("status") == "failed":
err_msg = str(data.get("error") or "Dify 工作流执行失败")
elif data.get("outputs"):
wf_outputs = data.get("outputs")
elif ev == "error":
err_msg = evt.get("message") or evt.get("code") or "Dify 流式返回错误"
if resp.status_code != 200:
body = (await resp.aread()).decode("utf-8", "replace")
raise RuntimeError(f"Dify HTTP {resp.status_code}: {body[:300]}")
async for line in resp.aiter_lines():
if not line:
continue
line = line.strip()
if not line.startswith("data:"):
continue
data_str = line[5:].strip()
if not data_str or data_str == "[DONE]":
continue
try:
evt = json.loads(data_str)
except Exception:
continue
ev = evt.get("event")
if evt.get("conversation_id"):
new_conv_id = evt["conversation_id"]
data = evt.get("data") or {}
# 兼容三类 Dify 应用:
# 1) Chat/Agent 应用: message / agent_message 事件带增量 answer
# 2) Chatflow/Workflow 应用: text_chunk 事件带 data.text;
# 结束时 workflow_finished 带 status / outputs / error
if ev in ("message", "agent_message"):
answer_parts.append(evt.get("answer", "") or "")
elif ev == "message_replace":
# 内容审查替换:以替换后的完整 answer 为准
answer_parts = [evt.get("answer", "") or ""]
elif ev == "text_chunk":
answer_parts.append((data.get("text") or ""))
elif ev == "node_finished":
# answer / end 节点的 outputs 可能含最终文本
if data.get("node_type") in ("answer", "end") and data.get("outputs"):
wf_outputs = data.get("outputs")
if data.get("status") == "failed" and data.get("error"):
err_msg = str(data.get("error"))
elif ev == "workflow_finished":
if data.get("status") == "failed":
err_msg = str(data.get("error") or "Dify 工作流执行失败")
elif data.get("outputs"):
wf_outputs = data.get("outputs")
elif ev == "error":
err_msg = evt.get("message") or evt.get("code") or "Dify 流式返回错误"
break
else:
raise RuntimeError("Dify 重定向次数过多(>4),请直接填写重定向后的地址")
answer = "".join(answer_parts).strip()
# 流式无增量文本时,尝试从 workflow 结束 outputs 兜底提取
if not answer and wf_outputs: