feat(contract): 采购合同对比agent

Signed-off-by: sophie <sophie>

Signed-off-by: sophie <sophie>
This commit is contained in:
sophie committed 2026-07-27 14:47:09 +08:00
1 parent ffccf19ba2
commit 0503ff76a6
90 files changed
+16729 -1344

No files matched your search

+98
View File
@@ -1166,6 +1166,104 @@ class DifyService:
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n"
@staticmethod
def run_chatflow_once(
*,
agent,
query: str,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 120),
) -> dict[str, Any]:
"""
以单次、无持久会话方式调用 Dify Chatflow 并收集最终回答。
核心逻辑:复用 Chatflow 的 `/v1/chat-messages` 和 SSE 协议,但不写 chat_logs、
不传 conversation_id;适用于合同审核等后台结构化任务,返回 message_end 的 answer。
Args:
agent: 含 Dify API Key 的 Chatflow Agent。
query: 传给 Chatflow 的一次性任务提示。
inputs: Dify Start 节点声明的变量。
user: Dify 用户标识,不应使用真实业务用户 ID。
timeout: `(connect_seconds, read_seconds)`。
Returns:
包含 `answer`、`conversation_id`、`message_id` 的字典。
Raises:
RuntimeError: Dify 返回错误事件或未产出最终回答。
requests.RequestException: HTTP 连接、超时或状态码错误。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"query": str(query or "").strip(),
"response_mode": "streaming",
"user": str(user or "system"),
}
if current_app:
current_app.logger.info(
"[chatflow-once] start agent_id=%s url=%s query_len=%s",
getattr(agent, "id", None),
url,
len(payload["query"]),
)
answer_parts: list[str] = []
final_data: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as response:
if not response.ok and current_app:
current_app.logger.error(
"[chatflow-once] bad response status=%s url=%s body=%s",
response.status_code,
url,
response.text[:2000],
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded = line.decode("utf-8", errors="replace")
if not decoded.startswith("data: "):
continue
try:
data = json.loads(decoded[6:])
except json.JSONDecodeError:
continue
event = str(data.get("event") or "")
if event == "error":
raise RuntimeError(str(data.get("message") or data))
if event == "message" and data.get("answer"):
answer_parts.append(str(data["answer"]))
if event in {"message_end", "workflow_finished"}:
final_data = data
workflow_data = data.get("data") if isinstance(data.get("data"), dict) else {}
if event == "workflow_finished" and workflow_data.get("status") == "failed":
# Chatflow also emits workflow events; expose the canvas-node error to the review task.
error_text = str(workflow_data.get("error") or "Dify Chatflow workflow failed")
raise RuntimeError(error_text)
final_answer = str(data.get("answer") or "").strip()
if final_answer:
answer_parts = [final_answer]
if event == "message_end":
break
answer = "".join(answer_parts).strip()
if not answer:
raise RuntimeError("Dify Chatflow returned no final answer")
return {
"answer": answer,
"conversation_id": final_data.get("conversation_id"),
"message_id": final_data.get("message_id") or final_data.get("id"),
"event": final_data.get("event") or "message_end",
}
@staticmethod
def _log_chat(
user_id,