门户估价对话、会员与智能体账号,以及生产 Docker 部署一直停在工作区,远端主分支还没有这些改动。 Co-authored-by: Cursor <cursoragent@cursor.com>
250 lines
8.7 KiB
Python
250 lines
8.7 KiB
Python
import json
|
||
from collections.abc import Iterator
|
||
|
||
import httpx
|
||
|
||
from app.core.config import get_settings
|
||
|
||
|
||
class DifyNotConfigured(RuntimeError):
|
||
pass
|
||
|
||
|
||
class DifyChatError(RuntimeError):
|
||
pass
|
||
|
||
|
||
_THINK_OPEN = "<think>"
|
||
_THINK_CLOSE = "</think>"
|
||
_REASON_MARK = "<!--dify-deepseek-reasoning-->"
|
||
|
||
|
||
def _ensure_parse_state(state: dict) -> None:
|
||
state.setdefault("answer", "")
|
||
state.setdefault("thoughts", {})
|
||
state.setdefault("in_think", False)
|
||
state.setdefault("carry", "")
|
||
state.setdefault("think_text", "")
|
||
|
||
|
||
def _clean_thought(text: str) -> str:
|
||
return (text or "").replace(_REASON_MARK, "").strip()
|
||
|
||
|
||
def joined_thought(state: dict) -> str:
|
||
_ensure_parse_state(state)
|
||
parts = [_clean_thought(item) for item in state["thoughts"].values()]
|
||
extra = _clean_thought(state["think_text"])
|
||
return "\n\n".join(part for part in (*parts, extra) if part)
|
||
|
||
|
||
def _hold_partial(text: str, token: str) -> tuple[str, str]:
|
||
limit = min(len(token) - 1, len(text))
|
||
for size in range(limit, 0, -1):
|
||
if text.endswith(token[:size]):
|
||
return text[:-size], text[-size:]
|
||
return text, ""
|
||
|
||
|
||
def feed_answer_chunk(state: dict, chunk: str, *, flush: bool = False) -> list[dict]:
|
||
"""把模型夹在 think 标签里的推理从可见回答中拆出。"""
|
||
_ensure_parse_state(state)
|
||
buf = state["carry"] + chunk
|
||
state["carry"] = ""
|
||
out: list[dict] = []
|
||
while True:
|
||
if state["in_think"]:
|
||
close_at = buf.find(_THINK_CLOSE)
|
||
if close_at < 0:
|
||
body, hold = (buf, "") if flush else _hold_partial(buf, _THINK_CLOSE)
|
||
state["carry"] = hold
|
||
if body:
|
||
state["think_text"] += body
|
||
out.append({"type": "thought", "text": joined_thought(state)})
|
||
break
|
||
state["think_text"] += buf[:close_at]
|
||
out.append({"type": "thought", "text": joined_thought(state)})
|
||
state["in_think"] = False
|
||
buf = buf[close_at + len(_THINK_CLOSE) :]
|
||
continue
|
||
open_at = buf.find(_THINK_OPEN)
|
||
if open_at < 0:
|
||
body, hold = (buf, "") if flush else _hold_partial(buf, _THINK_OPEN)
|
||
state["carry"] = hold
|
||
if body:
|
||
state["answer"] += body
|
||
out.append({"type": "delta", "text": body})
|
||
break
|
||
visible = buf[:open_at]
|
||
if visible:
|
||
state["answer"] += visible
|
||
out.append({"type": "delta", "text": visible})
|
||
state["in_think"] = True
|
||
buf = buf[open_at + len(_THINK_OPEN) :]
|
||
return out
|
||
|
||
|
||
def split_stored_reasoning(content: str, thought: str = "") -> tuple[str, str]:
|
||
state = {"answer": "", "thoughts": {}, "in_think": False, "carry": "", "think_text": ""}
|
||
feed_answer_chunk(state, content or "", flush=True)
|
||
extra = _clean_thought(state["think_text"])
|
||
prior = _clean_thought(thought)
|
||
merged = "\n\n".join(part for part in (prior, extra) if part)
|
||
return state["answer"].strip(), merged
|
||
|
||
|
||
def apply_dify_event(event: dict, state: dict) -> list[dict]:
|
||
_ensure_parse_state(state)
|
||
kind = event.get("event")
|
||
if event.get("conversation_id"):
|
||
state["conversation_id"] = event["conversation_id"]
|
||
out: list[dict] = []
|
||
if kind in ("message", "agent_message"):
|
||
chunk = event.get("answer") or ""
|
||
if chunk:
|
||
out.extend(feed_answer_chunk(state, chunk))
|
||
elif kind == "message_replace":
|
||
state["answer"] = ""
|
||
state["in_think"] = False
|
||
state["carry"] = ""
|
||
state["think_text"] = ""
|
||
feed_answer_chunk(state, event.get("answer") or "", flush=True)
|
||
out.append({"type": "replace", "text": state["answer"]})
|
||
thought = joined_thought(state)
|
||
if thought:
|
||
out.append({"type": "thought", "text": thought})
|
||
elif kind == "agent_thought":
|
||
thought = (event.get("thought") or "").strip()
|
||
if thought:
|
||
key = str(event.get("id") or len(state["thoughts"]) + 1)
|
||
state["thoughts"][key] = thought
|
||
out.append({"type": "thought", "text": joined_thought(state)})
|
||
elif kind == "error":
|
||
raise DifyChatError(event.get("message") or "Dify 返回错误")
|
||
elif kind == "message_end":
|
||
out.extend(feed_answer_chunk(state, "", flush=True))
|
||
documents = source_documents(event.get("metadata"))
|
||
if documents:
|
||
state["sources"] = documents
|
||
out.append({"type": "sources", "documents": documents})
|
||
out.append({"type": "done", "conversationId": state.get("conversation_id") or ""})
|
||
return out
|
||
|
||
|
||
def cited_documents(attachments: list[str], retrieved: list[str]) -> list[dict[str, str]]:
|
||
items: list[dict[str, str]] = []
|
||
seen: set[tuple[str, str]] = set()
|
||
attachment_names: set[str] = set()
|
||
for name in _unique_names(attachments):
|
||
items.append({"name": name, "kind": "attachment"})
|
||
seen.add(("attachment", name))
|
||
attachment_names.add(name)
|
||
for name in _unique_names(retrieved):
|
||
if name in attachment_names or ("knowledge", name) in seen:
|
||
continue
|
||
items.append({"name": name, "kind": "knowledge"})
|
||
seen.add(("knowledge", name))
|
||
return items
|
||
|
||
|
||
def _unique_names(items: list[str]) -> list[str]:
|
||
names: list[str] = []
|
||
seen: set[str] = set()
|
||
for item in items:
|
||
name = str(item or "").strip()
|
||
if not name or name in seen:
|
||
continue
|
||
seen.add(name)
|
||
names.append(name)
|
||
return names
|
||
|
||
|
||
def source_documents(metadata: object) -> list[str]:
|
||
if not isinstance(metadata, dict):
|
||
return []
|
||
resources = metadata.get("retriever_resources") or []
|
||
if not isinstance(resources, list):
|
||
return []
|
||
names: list[str] = []
|
||
seen: set[str] = set()
|
||
for item in resources:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
name = str(item.get("document_name") or "").strip()
|
||
if not name or name in seen:
|
||
continue
|
||
seen.add(name)
|
||
names.append(name)
|
||
return names
|
||
|
||
|
||
def upload_dify_file(*, filename: str, content: bytes, content_type: str, user: str) -> str:
|
||
settings = get_settings()
|
||
key = (settings.dify_valuation_api_key or "").strip()
|
||
if not key:
|
||
raise DifyNotConfigured("未配置估价智能体 API Key")
|
||
base = (settings.dify_api_base or "http://127.0.0.1:13080/v1").rstrip("/")
|
||
timeout = httpx.Timeout(60.0, connect=10.0)
|
||
with httpx.Client(timeout=timeout) as client:
|
||
response = client.post(
|
||
f"{base}/files/upload",
|
||
headers={"Authorization": f"Bearer {key}"},
|
||
data={"user": user},
|
||
files={"file": (filename, content, content_type or "application/octet-stream")},
|
||
)
|
||
if response.status_code >= 400:
|
||
raise DifyChatError("附件未能交给估价智能体")
|
||
file_id = (response.json() or {}).get("id")
|
||
if not file_id:
|
||
raise DifyChatError("附件未能交给估价智能体")
|
||
return str(file_id)
|
||
|
||
|
||
def iter_dify_chat(
|
||
*,
|
||
query: str,
|
||
conversation_id: str,
|
||
user: str,
|
||
files: list[dict] | None = None,
|
||
) -> Iterator[dict]:
|
||
settings = get_settings()
|
||
key = (settings.dify_valuation_api_key or "").strip()
|
||
if not key:
|
||
raise DifyNotConfigured("未配置估价智能体 API Key")
|
||
base = (settings.dify_api_base or "http://127.0.0.1:13080/v1").rstrip("/")
|
||
payload = {
|
||
"inputs": {},
|
||
"query": query,
|
||
"response_mode": "streaming",
|
||
"conversation_id": conversation_id or "",
|
||
"user": user,
|
||
}
|
||
if files:
|
||
payload["files"] = files
|
||
state = {"answer": "", "thoughts": {}, "conversation_id": conversation_id or ""}
|
||
timeout = httpx.Timeout(120.0, connect=10.0)
|
||
with httpx.Client(timeout=timeout) as client:
|
||
with client.stream(
|
||
"POST",
|
||
f"{base}/chat-messages",
|
||
headers={"Authorization": f"Bearer {key}"},
|
||
json=payload,
|
||
) as response:
|
||
if response.status_code >= 400:
|
||
response.read()
|
||
raise DifyChatError(f"Dify 拒绝请求({response.status_code})")
|
||
for raw in response.iter_lines():
|
||
line = raw.decode() if isinstance(raw, bytes) else raw
|
||
if not line or not line.startswith("data:"):
|
||
continue
|
||
body = line[5:].strip()
|
||
if not body or body == "[DONE]":
|
||
continue
|
||
try:
|
||
event = json.loads(body)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
yield from apply_dify_event(event, state)
|
||
if not state["answer"]:
|
||
raise DifyChatError("Dify 没有返回回答")
|