加入「拾语」:首页 AI 近况摘要(流式)
- 汇总学习目录、博客分类与最近更新的 10 篇文章 - 调用本地 Ollama qwen3.8:27b 生成技术栈与最近在做 - 每次生成入库,10 天后首次打开首页自动重新生成 - 前端逐字展开缓存摘要,过期时读取 AI 流式响应 - 首页在开场引导结束后显示;拾脉目录页内嵌展示 - 修复摘要面板标题栏命中全局 header 定位的问题
This commit is contained in:
@@ -426,6 +426,71 @@ def chat_text(system, user, temperature=0.8, num_predict=200, timeout=30):
|
||||
return (message.get("content") or data.get("response") or "").strip()
|
||||
|
||||
|
||||
def chat_stream(system, user, model=None, temperature=0.7, num_predict=800, timeout=300):
|
||||
"""流式对话:逐段 yield 文本,给「拾语」的首页摘要用。"""
|
||||
payload = {
|
||||
"model": model or settings.OLLAMA_MODEL,
|
||||
"messages": [
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": user},
|
||||
],
|
||||
"stream": True,
|
||||
"options": {"temperature": temperature, "num_predict": num_predict},
|
||||
}
|
||||
if not getattr(settings, "OLLAMA_THINK", False):
|
||||
payload["think"] = False
|
||||
|
||||
url = settings.OLLAMA_BASE_URL + "/api/chat"
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=timeout)
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace")[:300]
|
||||
logger.warning("Ollama stream HTTP %s: %s", exc.code, detail)
|
||||
raise LLMUnavailable("模型服务返回了错误") from exc
|
||||
except (socket.timeout, TimeoutError) as exc:
|
||||
raise LLMTimeout() from exc
|
||||
except urllib.error.URLError as exc:
|
||||
if isinstance(exc.reason, (socket.timeout, TimeoutError)):
|
||||
raise LLMTimeout() from exc
|
||||
logger.warning("Ollama stream unreachable: %s", exc.reason)
|
||||
raise LLMUnavailable("连不上模型服务") from exc
|
||||
except OSError as exc:
|
||||
logger.warning("Ollama stream network error: %s", exc)
|
||||
raise LLMUnavailable("连不上模型服务") from exc
|
||||
|
||||
try:
|
||||
for raw_line in response:
|
||||
line = raw_line.decode("utf-8", "replace").strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if data.get("error"):
|
||||
raise LLMUnavailable(str(data.get("error"))[:200])
|
||||
message = data.get("message") or {}
|
||||
content = message.get("content") or data.get("response") or ""
|
||||
if content:
|
||||
yield content
|
||||
if data.get("done"):
|
||||
break
|
||||
except (socket.timeout, TimeoutError) as exc:
|
||||
raise LLMTimeout() from exc
|
||||
finally:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def extract_spec(idea):
|
||||
"""调模型 -> 结构化条件 -> 拼 GitHub 检索式。"""
|
||||
started = time.monotonic()
|
||||
|
||||
Reference in New Issue
Block a user