llm.py
23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
"""DashScope(通义千问)封装:chat / chat_stream / chat_json / embed / rerank。
留空 LLM_BASE_URL 时用 DashScope SDK;填写则走 OpenAI 兼容接口。
v2 新增:
- chat_stream:流式作答。v1 用阻塞 chat(),用户要盯着空白等 20~30 秒。
- KVCache:按 messages 哈希缓存,抽取/检索共用,省额度且演示秒出。
- rerank:证据重排,检索精度提升性价比最高的一步。
- count_tokens:上下文预算控制用。刻意不引入 tiktoken —— 它首次使用要联网下载
BPE 词表,容器内会失败。这里用对中文足够准的启发式估算。
"""
from __future__ import annotations
import contextlib
import contextvars
import json
import logging
import re
import threading
import time
from typing import Any, Iterator
import numpy as np
import requests
from .config import get_settings
from . import db
from ..store.kv_cache import KVCache
log = logging.getLogger(__name__)
_settings = get_settings()
_cache = KVCache(_settings.data_path / "cache", "llm")
_embed_cache = KVCache(_settings.data_path / "cache", "embed")
# DashScope 有 QPS 限制,并发抽取时用信号量兜一下,避免整批 429
_sem = threading.Semaphore(16)
def _key() -> str:
return _settings.dashscope_api_key
def _cache_on() -> bool:
return db.get_config("LLM_CACHE", "1") == "1"
# ---------------- token 估算 ----------------
_CJK = re.compile(r"[一-鿿-ヿ가-]")
def count_tokens(text: str) -> int:
"""估算 token 数。中文按 1 字≈1 token,其余按 4 字符≈1 token。
对 qwen 系列,中文实测在 0.6~1.0 token/字之间,取 1 是保守估计 ——
上下文预算宁可估多也不要估少导致超长报错。
"""
if not text:
return 0
cjk = len(_CJK.findall(text))
rest = len(text) - cjk
return cjk + max(1, rest // 4) if rest else cjk
def truncate_to_tokens(text: str, max_tokens: int) -> str:
if max_tokens <= 0:
return ""
if count_tokens(text) <= max_tokens:
return text
# 二分裁剪到预算内,尽量贴着上限
lo, hi = 0, len(text)
while lo < hi:
mid = (lo + hi + 1) // 2
if count_tokens(text[:mid]) <= max_tokens:
lo = mid
else:
hi = mid - 1
return text[:lo].rstrip() + "…"
def _observe(kind: str, model: str, prompt: str, out: str, started: float,
cached: bool = False, ok: bool = True) -> None:
"""记一笔调用到可观测层。任何异常都吞掉 —— 统计不能影响主链路。"""
try:
from ..governance import llmlog
llmlog.record(kind, model, count_tokens(prompt), count_tokens(out),
int((time.time() - started) * 1000), cached=cached, ok=ok)
except Exception: # noqa: BLE001
pass
def _prompt_text(messages: list[dict]) -> str:
return "\n".join(str(m.get("content", "")) for m in messages)
# ---------------- 调用追踪 ----------------
class Cancelled(BaseException):
"""调用方要求中断正在进行的调用(如终止一次 AI 建模)。
继承 BaseException:各处兜底的 `except Exception` 不会把它吞掉,chat() 也不会拿它重试。"""
_trace: contextvars.ContextVar[tuple[Any, str] | None] = contextvars.ContextVar("llm_trace", default=None)
@contextlib.contextmanager
def tracing(sink: Any, label: str = ""):
"""在这个范围里的每次 chat() 都报给 sink:开始、思考过程与输出(流式,约每 1.5 秒一次)、结束。
sink 要有 begin(label, feature, model, prompt) -> handle、update(handle, reasoning, output)、
end(handle, **result) 三个方法;begin / update 里可以抛 Cancelled 或别的 BaseException 来停下。"""
tok = _trace.set((sink, label))
try:
yield
finally:
_trace.reset(tok)
# ---------------- 换模型 ----------------
DASHSCOPE_COMPAT = "https://dashscope.aliyuncs.com/compatible-mode/v1"
_model: contextvars.ContextVar[str] = contextvars.ContextVar("llm_model", default="")
@contextlib.contextmanager
def use_model(name: str):
"""这个范围里的 chat() 改用 name(AI 建模用自己的模型,不动全局的 QWEN_MODEL)。name 为空就什么也不改。"""
tok = _model.set((name or "").strip())
try:
yield
finally:
_model.reset(tok)
def _route() -> tuple[str, str]:
"""(模型, 兼容接口地址)。地址为空 = 走 DashScope SDK。
换过的模型一律走兼容接口:qwen3.7-plus 这类新模型 SDK 报 url error,兼容接口新老模型都认。"""
base_url = db.get_config("LLM_BASE_URL").strip()
over = _model.get()
if over:
return over, base_url or DASHSCOPE_COMPAT
return db.get_config("QWEN_MODEL"), base_url
def trace_label(label: str):
"""已经在追踪里时,只给接下来的调用换个名字(如「读文档 · 第 2/4 批」);没在追踪就什么也不做。"""
cur = _trace.get()
return tracing(cur[0], label) if cur else contextlib.nullcontext()
def _feature() -> str:
from ..governance import llmlog
return llmlog.current_feature()
# ---------------- Chat ----------------
def chat(messages: list[dict], temperature: float = 0.2, max_retries: int = 3,
use_cache: bool | None = None) -> str:
model, base_url = _route()
cache_on = _cache_on() if use_cache is None else use_cache
ck = KVCache.key({"m": model, "msgs": messages, "t": temperature, "u": base_url})
started = time.time()
traced = _trace.get()
if cache_on:
hit = _cache.get(ck)
if isinstance(hit, str):
_observe("chat", model, _prompt_text(messages), hit, started, cached=True)
if traced:
sink, label = traced
sink.end(sink.begin(label, _feature(), model, _prompt_text(messages)), output=hit, cached=True)
return hit
last_err = ""
for attempt in range(max_retries):
handle = None
try:
if traced:
sink, label = traced
handle = sink.begin(label + (f"(第 {attempt + 1} 次)" if attempt else ""), _feature(), model,
_prompt_text(messages))
with _sem:
if traced and base_url:
out, reasoning, usage = _chat_openai_traced(base_url, model, messages, temperature,
traced[0], handle)
elif traced:
out, reasoning, usage = _chat_dashscope_traced(model, messages, temperature, traced[0], handle)
else:
out = (_chat_openai(base_url, model, messages, temperature) if base_url
else _chat_dashscope(model, messages, temperature))
reasoning, usage = "", {}
if cache_on:
_cache.set(ck, out)
_observe("chat", model, _prompt_text(messages), out, started)
if handle is not None:
traced[0].end(handle, output=out, reasoning=reasoning, usage=usage)
return out
except Exception as e: # noqa: BLE001
last_err = str(e)
if handle is not None:
traced[0].end(handle, ok=False, error=last_err[:500])
log.warning("chat 第 %d 次失败:%s", attempt + 1, last_err[:200])
time.sleep(1.2 * (attempt + 1))
except BaseException:
if handle is not None:
traced[0].end(handle, ok=False, error="已终止")
raise
_observe("chat", model, _prompt_text(messages), "", started, ok=False)
raise RuntimeError(f"chat 调用失败:{last_err}")
def chat_stream(messages: list[dict], temperature: float = 0.3) -> Iterator[str]:
"""流式输出增量文本片段。失败时退回一次性 chat(),保证一定有内容。"""
model, base_url = _route()
started = time.time()
got: list[str] = []
try:
gen = (_stream_openai(base_url, model, messages, temperature) if base_url
else _stream_dashscope(model, messages, temperature))
for piece in gen:
got.append(piece)
yield piece
_observe("stream", model, _prompt_text(messages), "".join(got), started)
except Exception as e: # noqa: BLE001
if got: # 已经吐出去一部分就不能再整段重来,否则前端会看到重复内容
_observe("stream", model, _prompt_text(messages), "".join(got), started, ok=False)
raise
log.warning("流式失败,退回非流式:%s", str(e)[:200])
yield chat(messages, temperature=temperature)
def chat_stream_cached(messages: list[dict], temperature: float = 0.2) -> Iterator[str]:
"""带缓存的流式输出。
`chat_stream` 本身不走缓存 —— 但 SQL 起草这种「答案确定、还要看着它被写出来」
的场景两样都想要:第一次真流式(用户不用干等),重复问秒出(演示和评测都靠它)。
缓存键与 `chat()` 完全一致,所以两边的结果可以互相复用。
命中缓存时按小段吐出来,前端的打字机效果不用为此写第二套分支。
"""
model, base_url = _route()
ck = KVCache.key({"m": model, "msgs": messages, "t": temperature, "u": base_url})
if _cache_on():
hit = _cache.get(ck)
if isinstance(hit, str) and hit:
for i in range(0, len(hit), 24):
yield hit[i:i + 24]
return
buf: list[str] = []
for piece in chat_stream(messages, temperature=temperature):
buf.append(piece)
yield piece
out = "".join(buf)
if out and _cache_on():
_cache.set(ck, out)
# 这些步骤不思考会答错数、会凑数;其余(抽实体、写说明、找流程、对账、按校验错误改)有校验兜底或不要紧,直接答
_THINK = {"ask", "eval_judge", "ontology_propose", "ontology_dedupe", "ontology_draft", "modeling_action",
"sop_draft", "modeling_rules", "modeling_metric", "modeling_schedule"}
# 起草类步骤:要思考,但不让它无限斟酌 —— 不限时读一批文档能想出四五万字、三四分钟,结果并不更好。
# 提问(ask)不限,答对数比快重要。
_BUDGETED = {"ontology_propose", "ontology_dedupe", "ontology_draft", "modeling_action", "sop_draft",
"modeling_rules", "modeling_metric", "modeling_schedule"}
def _thinking() -> dict:
"""带思考能力的模型默认会先想一大段再答:回答问题时这样更准,但批量起草一批元素要七八分钟。
auto(默认):只在 _THINK 列出的步骤思考;on / off:总是 / 从不。
起草类步骤再加 LLM_THINKING_BUDGET 的上限(0 = 不限)。"""
mode = (db.get_config("LLM_THINKING") or "auto").strip().lower()
if mode in ("off", "0", "false"):
return {"enable_thinking": False}
from ..governance import llmlog
feat = llmlog.current_feature()
if mode not in ("on", "1", "true") and feat not in _THINK:
return {"enable_thinking": False}
try:
budget = int(db.get_config("LLM_THINKING_BUDGET") or "0")
except ValueError:
budget = 0
return {"thinking_budget": budget} if budget > 0 and feat in _BUDGETED else {}
def _chat_dashscope(model: str, messages: list[dict], temperature: float) -> str:
from dashscope import Generation
r = Generation.call(model=model, api_key=_key(), messages=messages,
result_format="message", temperature=temperature, **_thinking())
if getattr(r, "status_code", None) != 200:
raise RuntimeError(f"DashScope code={getattr(r, 'status_code', None)} msg={getattr(r, 'message', '')}")
return r.output.choices[0].message.content
def _chat_dashscope_traced(model: str, messages: list[dict], temperature: float,
sink: Any, handle: Any) -> tuple[str, str, dict]:
"""流式拿思考过程和输出,边收边报给 sink(它可以借机抛 Cancelled 打断)。返回 (输出, 思考, usage)。"""
from dashscope import Generation
resp = Generation.call(model=model, api_key=_key(), messages=messages,
result_format="message", temperature=temperature,
stream=True, incremental_output=True, **_thinking())
think: list[str] = []
out: list[str] = []
usage: dict = {}
last = time.time()
for chunk in resp:
if getattr(chunk, "status_code", None) != 200:
raise RuntimeError(f"DashScope code={getattr(chunk, 'status_code', None)} "
f"msg={getattr(chunk, 'message', '')}")
try:
msg = chunk.output.choices[0].message
except Exception: # noqa: BLE001
continue
think.append(getattr(msg, "reasoning_content", "") or "")
out.append(getattr(msg, "content", "") or "")
if getattr(chunk, "usage", None):
usage = dict(chunk.usage)
if time.time() - last > 1.5:
last = time.time()
sink.update(handle, "".join(think), "".join(out))
return "".join(out), "".join(think), usage
def _stream_dashscope(model: str, messages: list[dict], temperature: float) -> Iterator[str]:
from dashscope import Generation
resp = Generation.call(model=model, api_key=_key(), messages=messages,
result_format="message", temperature=temperature,
stream=True, incremental_output=True, **_thinking())
for chunk in resp:
if getattr(chunk, "status_code", None) != 200:
raise RuntimeError(f"DashScope stream code={getattr(chunk, 'status_code', None)}")
try:
piece = chunk.output.choices[0].message.content
except Exception:
continue
if piece:
yield piece
# ---------------- OpenAI 兼容接口 ----------------
# 有些模型(如 deepseek-v4.1-flash、qwen3.7-plus)在 DashScope 上只能走兼容接口,SDK 会报 url error。
# 这条路统一用流式:思考再长也不会撞整体超时(超时只算两个数据块之间的空档),思考过程也能边想边报给追踪。
def _is_dashscope(base_url: str) -> bool:
return "dashscope" in base_url.lower()
def _openai_deltas(base_url: str, model: str, messages: list[dict],
temperature: float) -> Iterator[tuple[str, str, dict]]:
"""逐块吐出 (思考增量, 输出增量, usage);usage 只在最后一块里有,没有就是空 dict。
enable_thinking / thinking_budget 与 stream_options 是 DashScope 的扩展参数,别家服务可能不认,只对它发。"""
body: dict[str, Any] = {"model": model, "messages": messages, "temperature": temperature, "stream": True}
if _is_dashscope(base_url):
body["stream_options"] = {"include_usage": True}
body.update(_thinking())
url = base_url.rstrip("/") + "/chat/completions"
with requests.post(url, headers={"Authorization": f"Bearer {_key()}"}, json=body,
timeout=(15, 180), stream=True) as resp:
if resp.status_code != 200:
raise RuntimeError(f"HTTP {resp.status_code} {(resp.text or '')[:200]}")
for raw in resp.iter_lines(decode_unicode=False):
if not raw:
continue
line = raw.decode("utf-8", errors="replace").strip()
if not line.startswith("data:"):
continue
payload = line[5:].strip()
if payload == "[DONE]":
break
try:
chunk = json.loads(payload)
except Exception: # noqa: BLE001
continue
u = chunk.get("usage") or {}
usage = {"input_tokens": u.get("prompt_tokens"), "output_tokens": u.get("completion_tokens"),
"output_tokens_details": {"reasoning_tokens": (u.get("completion_tokens_details") or {})
.get("reasoning_tokens")}} if u else {}
choices = chunk.get("choices") or []
delta = (choices[0].get("delta") or {}) if choices else {}
think, piece = delta.get("reasoning_content") or "", delta.get("content") or ""
if think or piece or usage:
yield think, piece, usage
def _chat_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> str:
return "".join(piece for _, piece, _ in _openai_deltas(base_url, model, messages, temperature))
def _chat_openai_traced(base_url: str, model: str, messages: list[dict], temperature: float,
sink: Any, handle: Any) -> tuple[str, str, dict]:
"""同 _chat_dashscope_traced:边收边报给 sink(它可以借机抛 Cancelled 打断)。返回 (输出, 思考, usage)。"""
think: list[str] = []
out: list[str] = []
usage: dict = {}
last = time.time()
for t, piece, u in _openai_deltas(base_url, model, messages, temperature):
think.append(t)
out.append(piece)
usage = u or usage
if time.time() - last > 1.5:
last = time.time()
sink.update(handle, "".join(think), "".join(out))
return "".join(out), "".join(think), usage
def _stream_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> Iterator[str]:
for _, piece, _ in _openai_deltas(base_url, model, messages, temperature):
if piece:
yield piece
def chat_json(messages: list[dict], temperature: float = 0.1) -> Any:
"""调用并把返回内容解析为 JSON(容忍 ```json 围栏与前后噪声)。
模型偶尔会吐出坏掉的 JSON(字符串没闭合之类):明明有内容却解析不出来时,绕过缓存重问一次,
不能悄悄当成「什么也没有」—— 那会让整批结果丢掉而没人知道。"""
txt = chat(messages, temperature=temperature)
out = parse_json(txt)
if out == {} and len((txt or "").strip()) > 20:
log.warning("模型返回的 JSON 解析不了(%d 字),绕过缓存重问一次", len(txt or ""))
out = parse_json(chat(messages, temperature=temperature, use_cache=False))
return out
def parse_json(txt: str) -> Any:
t = (txt or "").strip()
t = re.sub(r"^```(?:json)?\s*", "", t)
t = re.sub(r"\s*```$", "", t)
try:
return json.loads(t)
except Exception:
pass
# 兜底:截取第一个 { 到最后一个 }
i, j = t.find("{"), t.rfind("}")
if i != -1 and j > i:
try:
return json.loads(t[i:j + 1])
except Exception:
pass
# 再兜底:数组
i, j = t.find("["), t.rfind("]")
if i != -1 and j > i:
try:
return json.loads(t[i:j + 1])
except Exception:
pass
return {}
# ---------------- Embedding ----------------
def embed(texts: list[str], max_retries: int = 3, use_cache: bool = True) -> np.ndarray:
"""返回 (n, dim) 的 L2 归一化向量。空输入返回 (0, dim)。
带内容哈希缓存:重跑抽取时,内容没变的 chunk / 实体不会重复计费。
"""
dim = int(db.get_config("EMBED_DIM") or "1024")
if not texts:
return np.zeros((0, dim), dtype=np.float32)
model = db.get_config("EMBED_MODEL")
base_url = db.get_config("LLM_BASE_URL").strip()
concurrency = max(1, int(db.get_config("EMBED_CONCURRENCY") or "6"))
norm_texts = [t if (t and t.strip()) else "空" for t in texts]
out: list[list[float] | None] = [None] * len(norm_texts)
todo_idx: list[int] = []
keys: list[str] = []
for i, t in enumerate(norm_texts):
k = KVCache.key({"m": model, "t": t, "u": base_url})
keys.append(k)
hit = _embed_cache.get(k) if use_cache else None
if isinstance(hit, list):
out[i] = hit
else:
todo_idx.append(i)
if todo_idx:
pending = [norm_texts[i] for i in todo_idx]
batches = [pending[i:i + 10] for i in range(0, len(pending), 10)] # DashScope 批量上限 10
def _run_batch(batch: list[str]) -> list[list[float]]:
last_err = ""
for attempt in range(max_retries):
try:
with _sem:
return (_embed_openai(base_url, model, batch) if base_url
else _embed_dashscope(model, batch))
except Exception as e: # noqa: BLE001
last_err = str(e)
time.sleep(1.2 * (attempt + 1))
raise RuntimeError(f"embed 调用失败:{last_err}")
from concurrent.futures import ThreadPoolExecutor
if len(batches) <= 1 or concurrency <= 1:
results = [_run_batch(b) for b in batches]
else:
with ThreadPoolExecutor(max_workers=min(concurrency, len(batches))) as pool:
results = list(pool.map(_run_batch, batches)) # map 保持顺序
flat: list[list[float]] = []
for r in results:
flat.extend(r)
for pos, vec in zip(todo_idx, flat):
out[pos] = vec
if use_cache:
_embed_cache.set(keys[pos], vec)
arr = np.asarray([v if v is not None else [0.0] * dim for v in out], dtype=np.float32)
norms = np.linalg.norm(arr, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return arr / norms
def _embed_dashscope(model: str, batch: list[str]) -> list[list[float]]:
from dashscope import TextEmbedding
r = TextEmbedding.call(model=model, api_key=_key(), input=batch)
if getattr(r, "status_code", None) != 200:
raise RuntimeError(f"DashScope embed code={getattr(r, 'status_code', None)} msg={getattr(r, 'message', '')}")
items = sorted(r.output["embeddings"], key=lambda x: x["text_index"])
return [it["embedding"] for it in items]
def _embed_openai(base_url: str, model: str, batch: list[str]) -> list[list[float]]:
url = base_url.rstrip("/") + "/embeddings"
resp = requests.post(url, headers={"Authorization": f"Bearer {_key()}"},
json={"model": model, "input": batch}, timeout=120)
resp.raise_for_status()
data = sorted(resp.json()["data"], key=lambda x: x["index"])
return [d["embedding"] for d in data]
# ---------------- Rerank ----------------
def rerank(query: str, documents: list[str], top_n: int | None = None) -> list[tuple[int, float]]:
"""返回 [(原始下标, 相关度)],按相关度降序。失败或未配置模型时返回空列表(调用方退回原序)。"""
model = db.get_config("RERANK_MODEL").strip()
if not model or not documents:
return []
top_n = top_n or len(documents)
ck = KVCache.key({"rr": model, "q": query, "d": documents, "n": top_n})
if _cache_on():
hit = _cache.get(ck)
if isinstance(hit, list):
return [(int(i), float(s)) for i, s in hit]
try:
from dashscope import TextReRank
with _sem:
r = TextReRank.call(model=model, api_key=_key(), query=query,
documents=documents, top_n=top_n, return_documents=False)
if getattr(r, "status_code", None) != 200:
raise RuntimeError(f"rerank code={getattr(r, 'status_code', None)}")
pairs = [(int(it["index"]), float(it["relevance_score"])) for it in r.output["results"]]
pairs.sort(key=lambda x: -x[1])
if _cache_on():
_cache.set(ck, pairs)
return pairs
except Exception as e: # noqa: BLE001
log.warning("rerank 不可用,退回原排序:%s", str(e)[:200])
return []
def cache_stats() -> dict:
return {"llm": _cache.stats(), "embed": _embed_cache.stats()}
def clear_cache() -> None:
_cache.clear()
_embed_cache.clear()