Files
ssw-mvp/demo/_shared/llm.py
T
admin 66af651f6e demo: 安全合规检测 + 可信场景生成 接入大模型推理(DeepSeek 异步任务)
- 新增 _shared/llm.py:Anthropic 兼容端点客户端,支持 chat/chat_stream/extract_json(截断修复)
- 新增 _shared/jobs.py:内存任务表,支撑长耗时 LLM 异步轮询
- security_audit:审计引擎由静态正则升级为大模型 8 维审计;反面案例高风险远多于合规案例(验证 score=0/7Critical vs score=97)
- secure_scenario:场景描述输入框驱动大模型生成可跑 nax+TEE 代码
- server.py:注册 /api/job/<id> 全局轮询路由
- 前端两面板改为 async 提交 + 进度轮询(thinking 流式尾迹),避免长等待超时
2026-08-11 13:37:40 +08:00

295 lines
9.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""共享 LLM 客户端 · Anthropic Messages 兼容端点。
默认走 DeepSeek 的 Anthropic 兼容网关,可用环境变量覆盖::
LLM_BASE_URL 默认 https://api.deepseek.com/anthropic
LLM_API_KEY 默认内置演示 key
LLM_MODEL 默认 deepseek-v4-pro
仅依赖标准库 urllib,避免给 demo 增加第三方依赖。
"""
from __future__ import annotations
import json
import os
import re
import time
import urllib.error
import urllib.request
BASE_URL = os.environ.get("LLM_BASE_URL", "https://api.deepseek.com/anthropic").rstrip("/")
API_KEY = os.environ.get("LLM_API_KEY", "sk-08d05456b12345a9b7484b2d8073ff7f")
MODEL = os.environ.get("LLM_MODEL", "deepseek-v4-pro")
DEFAULT_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "600"))
class LLMError(RuntimeError):
"""LLM 调用失败。"""
def chat(
system: str,
user: str,
*,
max_tokens: int = 8000,
temperature: float = 0.2,
timeout: float | None = None,
retries: int = 2,
) -> dict:
"""调用 Anthropic Messages 接口,返回 ``{"text", "thinking", "usage", "model", "elapsed_ms"}``。"""
payload = {
"model": MODEL,
"max_tokens": max_tokens,
"temperature": temperature,
"system": system,
"messages": [{"role": "user", "content": user}],
}
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
url = f"{BASE_URL}/v1/messages"
last_err: Exception | None = None
for attempt in range(retries + 1):
t0 = time.perf_counter()
req = urllib.request.Request(
url,
data=body,
method="POST",
headers={
"content-type": "application/json",
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
},
)
try:
with urllib.request.urlopen(req, timeout=timeout or DEFAULT_TIMEOUT) as resp:
raw = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc: # noqa: PERF203
detail = exc.read().decode("utf-8", "replace")[:400]
last_err = LLMError(f"HTTP {exc.code}: {detail}")
except Exception as exc: # noqa: BLE001
last_err = LLMError(f"{type(exc).__name__}: {exc}")
else:
text_parts, think_parts = [], []
for blk in raw.get("content", []):
if blk.get("type") == "text":
text_parts.append(blk.get("text", ""))
elif blk.get("type") == "thinking":
think_parts.append(blk.get("thinking", ""))
return {
"text": "".join(text_parts).strip(),
"thinking": "\n".join(think_parts).strip(),
"usage": raw.get("usage", {}),
"model": raw.get("model", MODEL),
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 1),
}
if attempt < retries:
time.sleep(1.2 * (attempt + 1))
raise last_err or LLMError("unknown error")
def chat_stream(
system: str,
user: str,
on_delta=None,
*,
max_tokens: int = 8000,
temperature: float = 0.2,
timeout: float | None = None,
) -> dict:
"""流式调用,边收边回调 ``on_delta(kind, chunk)``,kind ∈ {"thinking","text"}。
返回结构与 :func:`chat` 一致。SSE 解析失败时自动回落到非流式。
"""
payload = {
"model": MODEL,
"max_tokens": max_tokens,
"temperature": temperature,
"system": system,
"messages": [{"role": "user", "content": user}],
"stream": True,
}
req = urllib.request.Request(
f"{BASE_URL}/v1/messages",
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
method="POST",
headers={
"content-type": "application/json",
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"accept": "text/event-stream",
},
)
t0 = time.perf_counter()
text_parts: list[str] = []
think_parts: list[str] = []
usage: dict = {}
block_kinds: dict[int, str] = {}
try:
with urllib.request.urlopen(req, timeout=timeout or DEFAULT_TIMEOUT) as resp:
for raw_line in resp:
line = raw_line.decode("utf-8", "replace").strip()
if not line.startswith("data:"):
continue
chunk = line[5:].strip()
if not chunk or chunk == "[DONE]":
continue
try:
ev = json.loads(chunk)
except Exception: # noqa: BLE001
continue
et = ev.get("type")
if et == "content_block_start":
block_kinds[ev.get("index", 0)] = (ev.get("content_block") or {}).get("type", "text")
elif et == "content_block_delta":
d = ev.get("delta") or {}
idx = ev.get("index", 0)
if d.get("type") == "thinking_delta" or block_kinds.get(idx) == "thinking":
piece = d.get("thinking") or d.get("text") or ""
if piece:
think_parts.append(piece)
if on_delta:
on_delta("thinking", piece)
else:
piece = d.get("text") or ""
if piece:
text_parts.append(piece)
if on_delta:
on_delta("text", piece)
elif et == "message_delta":
usage.update(ev.get("usage") or {})
elif et == "message_start":
usage.update(((ev.get("message") or {}).get("usage")) or {})
elif et == "error":
raise LLMError(str(ev.get("error"))[:300])
except LLMError:
raise
except Exception as exc: # noqa: BLE001
if text_parts:
pass # 已经拿到部分正文,按已有内容返回
else:
raise LLMError(f"stream {type(exc).__name__}: {exc}") from exc
if not text_parts:
# 流式没拿到正文,退回一次性调用
return chat(system, user, max_tokens=max_tokens, temperature=temperature,
timeout=timeout, retries=0)
return {
"text": "".join(text_parts).strip(),
"thinking": "".join(think_parts).strip(),
"usage": usage,
"model": MODEL,
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 1),
}
_FENCE = re.compile(r"```(?:json)?\s*(.*?)```", re.S)
def extract_json(text: str) -> dict:
"""从模型输出里稳健地抠出第一个 JSON 对象。
兼容三种情况:```json 围栏、原始裸 JSON、以及**被 max_tokens 截断**的半截 JSON
(模型 thinking 过长耗尽预算时常见)——对后者尝试补齐未闭合的引号与括号。
"""
candidates: list[str] = []
m = _FENCE.search(text)
if m:
candidates.append(m.group(1).strip())
# 括号配对扫描,支持字符串内的花括号
depth, start, in_str, esc = 0, -1, False, False
for i, ch in enumerate(text):
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
continue
if ch == '"':
in_str = True
elif ch == "{":
if depth == 0:
start = i
depth += 1
elif ch == "}":
depth -= 1
if depth == 0 and start >= 0:
candidates.append(text[start:i + 1])
break
candidates.append(text.strip())
for cand in candidates:
obj = _loads_or_none(cand)
if isinstance(obj, dict):
return obj
# 末班车:尝试修复被截断的 JSON(常见于 thinking 过长耗尽 max_tokens)
for cand in candidates:
if not cand.startswith("{"):
continue
repaired = _repair_json(cand)
if isinstance(repaired, dict):
return repaired
raise LLMError("模型返回内容无法解析为 JSON:" + text[:300])
def _loads_or_none(s: str):
try:
return json.loads(s)
except Exception: # noqa: BLE001
return None
def _repair_json(s: str):
"""补齐被截断 JSON 里未闭合的字符串引号与括号,成功返回对象否则 None。"""
obj = _loads_or_none(s)
if isinstance(obj, dict):
return obj
stack: list[str] = []
in_str = False
esc = False
for ch in s:
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
continue
if ch == '"':
in_str = True
elif ch == "{":
stack.append("}")
elif ch == "[":
stack.append("]")
elif ch in ("}", "]"):
if stack:
stack.pop()
tail = ""
if in_str:
tail += '"' # 闭合被截断的字符串
tail += "".join(reversed(stack)) # 闭合剩余括号
if tail:
return _loads_or_none(s + tail)
return None
def health() -> dict:
"""探活,供前端显示引擎状态。"""
try:
r = chat("你是探活探针。", "回复 OK 两个字符。", max_tokens=32, retries=0, timeout=25)
except Exception as exc: # noqa: BLE001
return {"ok": False, "model": MODEL, "base": BASE_URL, "msg": str(exc)[:200]}
return {"ok": True, "model": r["model"], "base": BASE_URL, "elapsed_ms": r["elapsed_ms"]}