llm.py
13.4 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
"""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 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() + "…"
# ---------------- Chat ----------------
def chat(messages: list[dict], temperature: float = 0.2, max_retries: int = 3,
use_cache: bool | None = None) -> str:
model = db.get_config("QWEN_MODEL")
base_url = db.get_config("LLM_BASE_URL").strip()
cache_on = _cache_on() if use_cache is None else use_cache
ck = KVCache.key({"m": model, "msgs": messages, "t": temperature, "u": base_url})
if cache_on:
hit = _cache.get(ck)
if isinstance(hit, str):
return hit
last_err = ""
for attempt in range(max_retries):
try:
with _sem:
out = (_chat_openai(base_url, model, messages, temperature) if base_url
else _chat_dashscope(model, messages, temperature))
if cache_on:
_cache.set(ck, out)
return out
except Exception as e: # noqa: BLE001
last_err = str(e)
log.warning("chat 第 %d 次失败:%s", attempt + 1, last_err[:200])
time.sleep(1.2 * (attempt + 1))
raise RuntimeError(f"chat 调用失败:{last_err}")
def chat_stream(messages: list[dict], temperature: float = 0.3) -> Iterator[str]:
"""流式输出增量文本片段。失败时退回一次性 chat(),保证一定有内容。"""
model = db.get_config("QWEN_MODEL")
base_url = db.get_config("LLM_BASE_URL").strip()
try:
if base_url:
yield from _stream_openai(base_url, model, messages, temperature)
else:
yield from _stream_dashscope(model, messages, temperature)
except Exception as e: # noqa: BLE001
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 = db.get_config("QWEN_MODEL")
base_url = db.get_config("LLM_BASE_URL").strip()
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)
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)
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 _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)
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
def _chat_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> str:
url = base_url.rstrip("/") + "/chat/completions"
resp = requests.post(url, headers={"Authorization": f"Bearer {_key()}"},
json={"model": model, "messages": messages, "temperature": temperature},
timeout=180)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]
def _stream_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> Iterator[str]:
url = base_url.rstrip("/") + "/chat/completions"
with requests.post(url, headers={"Authorization": f"Bearer {_key()}"},
json={"model": model, "messages": messages,
"temperature": temperature, "stream": True},
timeout=180, stream=True) as resp:
resp.raise_for_status()
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:
delta = json.loads(payload)["choices"][0].get("delta", {})
except Exception:
continue
piece = delta.get("content")
if piece:
yield piece
def chat_json(messages: list[dict], temperature: float = 0.1) -> Any:
"""调用并把返回内容解析为 JSON(容忍 ```json 围栏与前后噪声)。"""
return parse_json(chat(messages, temperature=temperature))
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()