排程管理及排程记录查看功能
This commit is contained in:
1 parent
3b31867319
commit
08776feef2
28 files changed
+3040
-8
No files matched your search
@@ -87,6 +87,207 @@ class DifyService:
|
||||
return f"{base}/chat-messages"
|
||||
return f"{base}/v1/chat-messages"
|
||||
|
||||
@staticmethod
|
||||
def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]:
|
||||
def _convert(v):
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, dict):
|
||||
return {kk: _convert(vv) for kk, vv in v.items()}
|
||||
if isinstance(v, list):
|
||||
return [_convert(i) for i in v]
|
||||
return str(v)
|
||||
return {k: _convert(v) for k, v in (inputs or {}).items()}
|
||||
|
||||
@staticmethod
|
||||
def _build_workflow_url(base_url: str) -> str:
|
||||
base = str(base_url or "").strip().rstrip("/")
|
||||
if not base:
|
||||
return "/v1/workflows/run"
|
||||
if base.endswith("/v1/workflows/run"):
|
||||
base = base[: -len("/v1/workflows/run")].rstrip("/")
|
||||
elif base.endswith("/workflows/run"):
|
||||
base = base[: -len("/workflows/run")].rstrip("/")
|
||||
if base.endswith("/v1"):
|
||||
return f"{base}/workflows/run"
|
||||
return f"{base}/v1/workflows/run"
|
||||
|
||||
@staticmethod
|
||||
def run_workflow_streaming(
|
||||
*,
|
||||
agent,
|
||||
inputs: dict[str, Any] | None = None,
|
||||
user: str = "system",
|
||||
timeout: tuple[int, int] = (5, 300),
|
||||
) -> dict[str, Any]:
|
||||
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
||||
url = DifyService._build_workflow_url(base_url)
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {agent.dify_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
payload = {
|
||||
"inputs": DifyService._stringify_inputs(inputs),
|
||||
"response_mode": "streaming",
|
||||
"user": str(user or "system"),
|
||||
}
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] start user=%s agent_id=%s url=%s",
|
||||
user,
|
||||
getattr(agent, "id", None),
|
||||
url,
|
||||
)
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
workflow_run_id: str | None = None
|
||||
|
||||
try:
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
|
||||
if not resp.ok:
|
||||
body = resp.text[:2000]
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] dify error status=%s url=%s body=%s",
|
||||
resp.status_code, url, body,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
for line in resp.iter_lines(decode_unicode=True):
|
||||
if not line:
|
||||
continue
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
raw = line[len("data:"):].strip()
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
evt = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event_type = evt.get("event", "")
|
||||
|
||||
if event_type == "workflow_started":
|
||||
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] started run_id=%s",
|
||||
workflow_run_id,
|
||||
)
|
||||
|
||||
elif event_type == "workflow_finished":
|
||||
result = evt.get("data") or {}
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] finished status=%s",
|
||||
result.get("status"),
|
||||
)
|
||||
|
||||
elif event_type == "error":
|
||||
err_msg = evt.get("message") or str(evt)
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] dify stream error: %s",
|
||||
err_msg,
|
||||
)
|
||||
raise RuntimeError(f"Dify workflow error: {err_msg}")
|
||||
|
||||
except requests.exceptions.RequestException as exc:
|
||||
if result:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] connection dropped but result already captured",
|
||||
)
|
||||
elif workflow_run_id:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-streaming] connection dropped, polling result for run_id=%s",
|
||||
workflow_run_id,
|
||||
)
|
||||
result = DifyService._poll_workflow_result(
|
||||
agent=agent,
|
||||
workflow_run_id=workflow_run_id,
|
||||
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
|
||||
)
|
||||
else:
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] request error (no run_id): %s",
|
||||
exc,
|
||||
)
|
||||
raise
|
||||
|
||||
return result if isinstance(result, dict) else {}
|
||||
|
||||
@staticmethod
|
||||
def _poll_workflow_result(
|
||||
*,
|
||||
agent,
|
||||
workflow_run_id: str,
|
||||
max_wait: int = 300,
|
||||
interval: int = 10,
|
||||
) -> dict[str, Any]:
|
||||
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
||||
base = str(base_url).strip().rstrip("/")
|
||||
if base.endswith("/v1/workflows/run"):
|
||||
base = base[: -len("/v1/workflows/run")].rstrip("/")
|
||||
elif base.endswith("/workflows/run"):
|
||||
base = base[: -len("/workflows/run")].rstrip("/")
|
||||
if base.endswith("/v1"):
|
||||
poll_url = f"{base}/workflows/run/{workflow_run_id}"
|
||||
else:
|
||||
poll_url = f"{base}/v1/workflows/run/{workflow_run_id}"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {agent.dify_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
elapsed = 0
|
||||
while elapsed < max_wait:
|
||||
time.sleep(interval)
|
||||
elapsed += interval
|
||||
|
||||
try:
|
||||
resp = requests.get(poll_url, headers=headers, timeout=(5, 30))
|
||||
if not resp.ok:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-poll] status=%s url=%s",
|
||||
resp.status_code, poll_url,
|
||||
)
|
||||
continue
|
||||
|
||||
data = resp.json() if resp.content else {}
|
||||
status = data.get("status", "")
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-poll] run_id=%s status=%s elapsed=%ds",
|
||||
workflow_run_id, status, elapsed,
|
||||
)
|
||||
|
||||
if status in ("succeeded", "failed", "stopped"):
|
||||
return data
|
||||
|
||||
except requests.exceptions.RequestException as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-poll] request error: %s",
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-poll] timed out after %ds run_id=%s",
|
||||
max_wait, workflow_run_id,
|
||||
)
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
||||
"""
|
||||
|
||||
Reference in new issue
Block a user