加入「拾语」:首页 AI 近况摘要(流式)

- 汇总学习目录、博客分类与最近更新的 10 篇文章
- 调用本地 Ollama qwen3.8:27b 生成技术栈与最近在做
- 每次生成入库,10 天后首次打开首页自动重新生成
- 前端逐字展开缓存摘要,过期时读取 AI 流式响应
- 首页在开场引导结束后显示;拾脉目录页内嵌展示
- 修复摘要面板标题栏命中全局 header 定位的问题
This commit is contained in:
2026-11-21 13:56:53 +08:00
parent 7c6e5d45d1
commit e3270bcd94
19 changed files with 951 additions and 3 deletions
+5 -1
View File
@@ -4,6 +4,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="csrf-token" content="{{ csrf_token }}">
<title>思维导航 · 我的博客</title>
<!-- <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> -->
@@ -13,6 +14,7 @@
<link href="https://fonts.loli.net/css2?family=Noto+Serif+SC:wght@500;700;900&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet">
<!-- 全局基础样式(项目级) -->
<link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
<link rel="stylesheet" href="{% static 'digest/digest.css' %}">
<!-- 让子模板可以追加自己的 CSS -->
{% block extra_css %}{% endblock %}
@@ -186,7 +188,8 @@
<span class="dot"></span>
<a class="footer-link" href="/manage/">写作台</a>
</footer>
{% include "digest/_panel.html" %}
<script src="{% static 'blog/js/d3.min.js' %}"></script>
<script src="{% static 'blog/js/index.js' %}"></script>
@@ -199,6 +202,7 @@
<script src="https://cdn.jsdmirror.com/npm/markmap-view@0.18.10/dist/browser/index.js"></script>
<script src="https://cdn.jsdmirror.com/npm/markmap-lib@0.18.12/dist/browser/index.iife.js"></script> -->
<script type="module" src="{% static 'blog/js/main.js' %}"></script>
<script src="{% static 'digest/digest.js' %}"></script>
<!-- 让子模板可以追加自己的 JS -->
{% block extra_js %}{% endblock %}
</body>
+8 -2
View File
@@ -8,6 +8,7 @@ from django.utils.html import strip_tags
from .models import Category, Post, Tag , SiteInfo
from explore.models import Idea, Repository
from mindmaps.models import MindMap
from digest.services import DIGEST_DAYS, DIGEST_MODEL, digest_is_stale, latest_digest
def category_list(request):
# """首页:展示所有分类"""
@@ -39,12 +40,17 @@ def category_list(request):
digest = latest_digest()
return render(request, 'base2.html', {
# 'categories': categories,
'total_posts': total_posts, # 文章总数
'total_categories': total_categories, # 分类总数
'mindmap_count' : mindmap_count
'mindmap_count' : mindmap_count,
'digest': digest,
'digest_stale': digest_is_stale(digest),
'digest_days': DIGEST_DAYS,
'digest_model': DIGEST_MODEL,
})
+5
View File
@@ -46,6 +46,7 @@ INSTALLED_APPS = [
"reflections",
"moments",
"studio",
"digest",
"rest_framework",
]
@@ -212,6 +213,10 @@ OLLAMA_TIMEOUT = int(os.environ.get("OLLAMA_TIMEOUT", "90"))
# qwen3.5 默认会先输出思考过程;关掉才能稳定拿到 JSON
OLLAMA_THINK = os.environ.get("OLLAMA_THINK", "0") == "1"
# ===== 拾语:首页 AI 近况摘要 =====
DIGEST_MODEL = os.environ.get("DIGEST_MODEL", "qwen3.8:27b")
DIGEST_INTERVAL_DAYS = int(os.environ.get("DIGEST_INTERVAL_DAYS", "10"))
# ===== GitHub 仓库搜索 =====
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "")
GITHUB_TIMEOUT = int(os.environ.get("GITHUB_TIMEOUT", "20"))
+1
View File
@@ -37,6 +37,7 @@ urlpatterns = [
path('reflections/', include('reflections.urls')),
path('moments/', include('moments.urls')),
path('manage/', include('studio.urls')),
path('digest/', include('digest.urls')),
path('', include('blog.urls')),
path("mindmaps/", include("mindmaps.urls")),
path("api/",include("api.urls")),
View File
+15
View File
@@ -0,0 +1,15 @@
from django.contrib import admin
from .models import Digest
@admin.register(Digest)
class DigestAdmin(admin.ModelAdmin):
list_display = ("id", "model", "complete", "created_at", "short_content")
list_filter = ("complete", "model", "created_at")
readonly_fields = ("created_at",)
search_fields = ("content",)
@admin.display(description="摘要")
def short_content(self, obj):
return obj.content[:80]
+7
View File
@@ -0,0 +1,7 @@
from django.apps import AppConfig
class DigestConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "digest"
verbose_name = "拾语"
+55
View File
@@ -0,0 +1,55 @@
# Generated by Django 5.2.18 on 2026-11-21 05:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Digest",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("content", models.TextField(verbose_name="摘要")),
(
"model",
models.CharField(
default="qwen3.8:27b", max_length=100, verbose_name="模型"
),
),
(
"snapshot",
models.JSONField(blank=True, default=dict, verbose_name="数据快照"),
),
(
"complete",
models.BooleanField(default=True, verbose_name="完整生成"),
),
(
"error",
models.TextField(blank=True, default="", verbose_name="错误"),
),
(
"created_at",
models.DateTimeField(auto_now_add=True, verbose_name="生成时间"),
),
],
options={
"verbose_name": "近况摘要",
"verbose_name_plural": "近况摘要",
"ordering": ["-created_at"],
},
),
]
View File
+20
View File
@@ -0,0 +1,20 @@
from django.db import models
class Digest(models.Model):
"""一次 AI 近况摘要的生成结果。"""
content = models.TextField("摘要")
model = models.CharField("模型", max_length=100, default="qwen3.8:27b")
snapshot = models.JSONField("数据快照", default=dict, blank=True)
complete = models.BooleanField("完整生成", default=True)
error = models.TextField("错误", blank=True, default="")
created_at = models.DateTimeField("生成时间", auto_now_add=True)
class Meta:
ordering = ["-created_at"]
verbose_name = "近况摘要"
verbose_name_plural = "近况摘要"
def __str__(self):
return self.content[:60]
+177
View File
@@ -0,0 +1,177 @@
from datetime import timedelta
from django.conf import settings
from django.db.models import Count, Q
from django.utils import timezone
from blog.models import Category, Post
from mindmaps.models import MindFolder, MindMap
from .models import Digest
DIGEST_DAYS = max(1, int(getattr(settings, "DIGEST_INTERVAL_DAYS", 10)))
DIGEST_MODEL = getattr(settings, "DIGEST_MODEL", "qwen3.8:27b")
SYSTEM_PROMPT = """你是「拾语」,一个熟悉这个技术博客的整理者。请根据给出的站点数据,用中文写一份近况摘要。
请严格按下面两段输出,不要使用 Markdown 标题、列表符号或代码块:
技术栈:用 3-6 个短语概括主要技术方向,不超过 100 字,不要罗列所有文章标题。
最近在做:写 2-4 句话,像博客主人自己在更新近况,具体提到最近在学、在做的方向;不要编造数据,不要把技术栈逐条重复。
总字数控制在 250-450 字,不要输出 JSON 或额外解释。"""
def latest_digest():
return Digest.objects.filter(complete=True).order_by("-created_at").first()
def digest_is_stale(digest=None):
if digest is None:
return True
return timezone.now() - digest.created_at >= timedelta(days=DIGEST_DAYS)
def _folder_path(folder):
parts = []
seen = set()
node = folder
while node is not None and node.pk not in seen:
seen.add(node.pk)
parts.append(node.name)
node = node.parent
return " / ".join(reversed(parts))
def _map_info(item):
root = ""
data = item.mindmap_data or {}
if isinstance(data, dict):
root = ((data.get("data") or {}).get("text") or "").strip()
return {
"title": (item.title or "").strip()[:200],
"root": root[:100],
"description": (item.description or "").strip()[:200],
}
def build_snapshot():
folders = MindFolder.objects.prefetch_related("maps").order_by("name")
directories = []
for folder in folders:
directories.append({
"path": _folder_path(folder),
"description": (folder.description or "").strip()[:300],
"maps": [_map_info(item) for item in folder.maps.all()],
})
unfiled = [
_map_info(item)
for item in MindMap.objects.filter(folder__isnull=True).order_by("created_at")
]
categories = (
Category.objects.annotate(
published=Count(
"posts", filter=Q(posts__status="published"), distinct=True
)
)
.filter(published__gt=0)
.order_by("-published", "name")
)
latest_posts = (
Post.objects.filter(status="published")
.prefetch_related("categories")
.order_by("-updated_at", "-published_at")[:10]
)
return {
"generated_at": timezone.now().isoformat(),
"stats": {
"published_posts": Post.objects.filter(status="published").count(),
"categories": Category.objects.count(),
"folders": MindFolder.objects.count(),
"maps": MindMap.objects.count(),
},
"directories": directories,
"unfiled_maps": unfiled,
"blog_categories": [
{"name": category.name, "published": category.published}
for category in categories
],
"latest_posts": [
{
"title": post.title,
"categories": [category.name for category in post.categories.all()],
"published_at": post.published_at.isoformat() if post.published_at else "",
"updated_at": post.updated_at.isoformat() if post.updated_at else "",
}
for post in latest_posts
],
}
def snapshot_prompt(snapshot):
stats = snapshot.get("stats") or {}
lines = [
"站点概况:已发布文章 {} 篇,分类 {} 个,拾脉目录 {} 个,脑图 {} 份。".format(
stats.get("published_posts", 0),
stats.get("categories", 0),
stats.get("folders", 0),
stats.get("maps", 0),
),
"",
"## 学习目录(拾脉)",
]
directories = snapshot.get("directories") or []
if directories:
for directory in directories:
description = directory.get("description") or ""
maps = ";".join(
item.get("root") or item.get("title") or ""
for item in directory.get("maps") or []
)
line = "- {}".format(directory.get("path") or "未命名目录")
if description:
line += ":{}".format(description)
if maps:
line += ";脑图:{}".format(maps)
lines.append(line)
else:
lines.append("- 暂无目录")
unfiled = snapshot.get("unfiled_maps") or []
if unfiled:
lines.append(
"未归档脑图:{}".format(
";".join(item.get("root") or item.get("title") or "" for item in unfiled)
)
)
lines.extend(["", "## 博客分类(已发布数量)"])
categories = snapshot.get("blog_categories") or []
if categories:
for category in categories:
lines.append("- {}:{} 篇".format(category["name"], category["published"]))
else:
lines.append("- 暂无分类")
lines.extend(["", "## 最近更新的 10 篇文章"])
posts = snapshot.get("latest_posts") or []
if posts:
for index, post in enumerate(posts, 1):
category_names = "、".join(post.get("categories") or []) or "未分类"
updated = (post.get("updated_at") or "")[:10]
lines.append(
"{}. 《{}》({},更新于 {})".format(
index, post.get("title") or "", category_names, updated
)
)
else:
lines.append("- 暂无文章")
lines.extend([
"",
"请据此写出:技术栈,以及最近在做什么。",
])
return "\n".join(lines)
+165
View File
@@ -0,0 +1,165 @@
/* =========================================================
拾语 · 首页 AI 近况摘要
========================================================= */
.dg-panel {
position: fixed;
left: 20px;
bottom: 54px;
z-index: 30;
display: flex;
flex-direction: column;
width: 340px;
max-height: 42vh;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--card);
box-shadow: var(--card-shadow);
font-family: Inter, 'Noto Sans SC', -apple-system, 'PingFang SC', sans-serif;
transition: width .25s ease, box-shadow .25s ease,
opacity .45s ease, visibility .45s ease;
}
/* 首页:开场引导层结束、脑图展开后才显示 */
body:not(.intro-done) .dg-panel:not(.dg-panel-inline) {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
body.intro-done .dg-panel:not(.dg-panel-inline) {
opacity: 1;
visibility: visible;
}
.dg-panel:hover { box-shadow: 0 20px 44px -28px rgba(0, 0, 0, .5); }
.dg-head {
display: flex;
align-items: center;
gap: 7px;
flex: none;
padding: 9px 11px 9px 13px;
cursor: pointer;
user-select: none;
border-bottom: 1px solid var(--line);
}
.dg-spark { color: var(--c2); font-size: 10px; }
.dg-title {
color: var(--ink);
font-family: 'Noto Serif SC', serif;
font-size: 12.5px;
font-weight: 700;
letter-spacing: .05em;
}
.dg-badge {
margin-left: auto;
padding: 1px 6px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--ink-faint);
font-size: 8.5px;
letter-spacing: .04em;
white-space: nowrap;
}
.dg-toggle {
display: grid;
place-items: center;
width: 20px; height: 20px;
padding: 0;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--bg);
color: var(--ink-faint);
font-family: inherit;
font-size: 12px;
line-height: 1;
cursor: pointer;
transition: color .18s ease, border-color .18s ease;
}
.dg-toggle:hover { color: var(--accent); border-color: var(--accent); }
.dg-body {
min-height: 0;
padding: 10px 14px 12px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.dg-text {
margin: 0;
color: var(--ink-soft);
font-family: 'Noto Serif SC', serif;
font-size: 12.2px;
line-height: 1.92;
white-space: pre-wrap;
word-break: break-word;
text-wrap: pretty;
}
.dg-text:empty::before {
content: '正在整理最近的目录和文章…';
color: var(--ink-faint);
}
.dg-meta {
margin: 8px 0 0;
padding-top: 7px;
border-top: 1px dashed var(--line);
color: var(--ink-faint);
font-family: Inter, sans-serif;
font-size: 9.5px;
line-height: 1.7;
}
.dg-panel.is-streaming .dg-text::after {
content: '▍';
margin-left: 1px;
color: var(--accent);
animation: dg-blink 1s steps(1) infinite;
}
.dg-panel.is-streaming .dg-badge {
color: var(--accent);
border-color: color-mix(in srgb, var(--accent) 35%, var(--line));
}
.dg-panel.is-collapsed { width: 220px; }
.dg-panel.is-collapsed .dg-body { display: none; }
/* 拾脉目录页:内嵌卡片,不悬浮遮挡目录 */
.dg-panel.dg-panel-inline {
position: static;
left: auto;
right: auto;
bottom: auto;
width: auto;
max-height: none;
margin: 22px 0 4px;
box-shadow: var(--shadow-sm);
}
.dg-panel.dg-panel-inline.is-collapsed { width: auto; }
.dg-panel.dg-panel-inline .dg-body { max-height: 340px; }
.dg-panel.is-collapsed .dg-head { border-bottom-color: transparent; }
.dg-panel.is-collapsed .dg-badge { display: none; }
@keyframes dg-blink {
0%, 49% { opacity: 1; }
50%, 100% { opacity: 0; }
}
@media (max-width: 720px) {
.dg-panel {
left: 12px;
right: 12px;
bottom: 72px;
width: auto;
max-height: 34vh;
}
.dg-panel.is-collapsed {
left: 12px;
right: auto;
width: 210px;
}
}
@media (prefers-reduced-motion: reduce) {
.dg-panel { transition: none; }
.dg-panel.is-streaming .dg-text::after { animation: none; }
}
+262
View File
@@ -0,0 +1,262 @@
/* =========================================================
拾语 · 首页 / 拾脉目录页 AI 近况摘要
- 首页:开场引导层结束后才出现
- 缓存摘要由前端逐字展开,不是一次性塞入
- 过期时真正流式生成
========================================================= */
(function () {
'use strict';
var panel = document.getElementById('digestPanel');
if (!panel) return;
var textEl = document.getElementById('digestText');
var metaEl = document.getElementById('digestMeta');
var head = document.getElementById('digestHead');
var toggle = document.getElementById('digestToggle');
var csrfMeta = document.querySelector('meta[name="csrf-token"]');
var CSRF = csrfMeta ? csrfMeta.getAttribute('content') || '' : '';
var streamUrl = panel.getAttribute('data-stream-url');
var stale = panel.getAttribute('data-stale') === 'true';
var days = panel.getAttribute('data-days') || '10';
var model = panel.getAttribute('data-model') || 'qwen3.8:27b';
var isInline = panel.classList.contains('dg-panel-inline');
var reduced = window.matchMedia
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var initialMeta = metaEl ? metaEl.textContent.trim() : '';
var attempts = 0;
var maxAttempts = 20;
var initialContent = '';
var initialScript = document.getElementById('digest-initial');
if (initialScript) {
try {
initialContent = JSON.parse(initialScript.textContent);
} catch (error) {
initialContent = '';
}
}
/* ---------- 折叠 ---------- */
function setCollapsed(collapsed) {
panel.classList.toggle('is-collapsed', collapsed);
if (toggle) toggle.textContent = collapsed ? '+' : '−';
if (head) head.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
try {
localStorage.setItem('digest-collapsed-v2', collapsed ? '1' : '0');
} catch (error) {}
}
try {
if (localStorage.getItem('digest-collapsed-v2') === '1') {
panel.classList.add('is-collapsed');
if (toggle) toggle.textContent = '+';
if (head) head.setAttribute('aria-expanded', 'false');
}
} catch (error) {}
function flip() {
setCollapsed(!panel.classList.contains('is-collapsed'));
}
if (head) {
head.addEventListener('click', function (event) {
if (event.target.closest('button')) return;
flip();
});
head.addEventListener('keydown', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
flip();
}
});
}
if (toggle) {
toggle.addEventListener('click', function (event) {
event.stopPropagation();
flip();
});
}
/* ---------- 等首页引导层结束 ---------- */
function waitForIntro() {
if (isInline) return Promise.resolve();
var intro = document.getElementById('intro');
if (!intro || document.body.classList.contains('intro-done')) {
return Promise.resolve();
}
return new Promise(function (resolve) {
var done = false;
var poll = null;
function finish() {
if (done) return;
done = true;
observer.disconnect();
if (poll) clearInterval(poll);
resolve();
}
var observer = new MutationObserver(function () {
if (document.body.classList.contains('intro-done')) finish();
});
observer.observe(document.body, {
attributes: true,
attributeFilter: ['class']
});
poll = setInterval(function () {
if (!document.getElementById('intro') || document.body.classList.contains('intro-done')) {
finish();
}
}, 350);
});
}
waitForIntro().then(function () {
if (stale) {
startStream();
} else if (initialContent) {
typewrite(initialContent);
}
});
/* ---------- 前端逐字展开 ---------- */
function typewrite(text) {
if (!textEl || !text) return;
if (reduced) {
textEl.textContent = text;
return;
}
textEl.textContent = '';
panel.classList.add('is-streaming');
if (metaEl) metaEl.textContent = '展开摘要…';
var index = 0;
var timer = setInterval(function () {
index += 2;
textEl.textContent = text.slice(0, index);
scrollBody();
if (index >= text.length) {
clearInterval(timer);
textEl.textContent = text;
panel.classList.remove('is-streaming');
if (metaEl) metaEl.textContent = initialMeta;
}
}, 18);
}
function scrollBody() {
var body = document.getElementById('digestBody');
if (body) body.scrollTop = body.scrollHeight;
}
/* ---------- 过期后真正流式生成 ---------- */
async function startStream() {
if (!streamUrl) return;
attempts += 1;
panel.classList.add('is-streaming');
if (attempts === 1 && textEl) textEl.textContent = '';
if (metaEl) {
metaEl.textContent = attempts === 1
? '正在整理最近的目录和文章…'
: '其他窗口正在整理,稍后继续…';
}
var response;
try {
response = await fetch(streamUrl, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'text/plain',
'X-CSRFToken': CSRF
}
});
} catch (error) {
finishError('网络中断,刷新页面重试');
return;
}
if (response.status === 409) {
panel.classList.remove('is-streaming');
if (attempts < maxAttempts) {
if (metaEl) metaEl.textContent = '其他窗口正在整理,稍后继续…';
setTimeout(startStream, 6000);
} else {
finishError('整理排队超时,刷新页面重试');
}
return;
}
if (!response.ok) {
var message = '整理失败,刷新页面重试';
try {
var data = await response.json();
if (data && data.error) message = data.error;
} catch (error) {}
finishError(message);
return;
}
if (!response.body || !response.body.getReader) {
try {
var fullText = await response.text();
if (textEl) textEl.textContent = fullText.trim();
if (fullText.indexOf('[整理中断') !== -1) {
finishError('AI 整理中断,刷新页面重试');
} else {
finishOk();
}
} catch (error) {
finishError('整理失败,刷新页面重试');
}
return;
}
var reader = response.body.getReader();
var decoder = new TextDecoder();
var full = '';
try {
while (true) {
var result = await reader.read();
if (result.done) break;
full += decoder.decode(result.value, { stream: true });
if (textEl) {
textEl.textContent = full;
scrollBody();
}
}
full += decoder.decode();
if (textEl) textEl.textContent = full.trim();
if (full.indexOf('[整理中断') !== -1) {
finishError('AI 整理中断,刷新页面重试');
} else {
finishOk();
}
} catch (error) {
finishError('整理中断,刷新页面重试');
}
}
function finishOk() {
panel.classList.remove('is-streaming');
panel.classList.remove('is-stale');
panel.setAttribute('data-stale', 'false');
if (metaEl) {
metaEl.textContent = '刚刚更新 · ' + model + ' · 每 ' + days + ' 天更新';
}
}
function finishError(message) {
panel.classList.remove('is-streaming');
if (metaEl) metaEl.textContent = message;
}
})();
+29
View File
@@ -0,0 +1,29 @@
{% comment %}拾语:AI 近况摘要。homepage 用固定浮层;拾脉目录页用内嵌卡片。{% endcomment %}
<aside class="dg-panel{% if digest_inline %} dg-panel-inline{% endif %}{% if digest_stale %} is-stale{% endif %}"
id="digestPanel"
data-stale="{{ digest_stale|yesno:'true,false' }}"
data-stream-url="{% url 'digest:stream' %}"
data-has-digest="{{ digest|yesno:'true,false' }}"
data-model="{{ digest_model }}"
data-days="{{ digest_days }}"
aria-label="最近在做">
<div class="dg-head" id="digestHead" role="button" tabindex="0" aria-expanded="true">
<span class="dg-spark" aria-hidden="true">✦</span>
<span class="dg-title">最近在做</span>
<span class="dg-badge">拾语 · AI</span>
<button class="dg-toggle" id="digestToggle" type="button" aria-label="收起或展开">−</button>
</div>
<div class="dg-body" id="digestBody">
<div class="dg-text" id="digestText"></div>
<p class="dg-meta" id="digestMeta">
{% if digest and not digest_stale %}
更新于 {{ digest.created_at|date:"Y-m-d H:i" }} · {{ digest.model }} · 每 {{ digest_days }} 天更新
{% elif digest_stale %}
正在整理最近的目录与文章…
{% else %}
第一次整理 · 读取目录与最近文章…
{% endif %}
</p>
</div>
{% if digest %}{{ digest.content|json_script:"digest-initial" }}{% endif %}
</aside>
+9
View File
@@ -0,0 +1,9 @@
from django.urls import path
from . import views
app_name = "digest"
urlpatterns = [
path("stream/", views.stream, name="stream"),
]
+117
View File
@@ -0,0 +1,117 @@
from django.core.cache import cache
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
from django.views.decorators.http import require_POST
from explore.llm import LLMError, chat_stream
from .models import Digest
from .services import (
DIGEST_MODEL,
SYSTEM_PROMPT,
build_snapshot,
digest_is_stale,
latest_digest,
snapshot_prompt,
)
LOCK_KEY = "digest_generating"
LOCK_SECONDS = 600
@require_POST
def stream(request):
latest = latest_digest()
if latest and not digest_is_stale(latest):
return HttpResponse(latest.content, content_type="text/plain; charset=utf-8")
if not cache.add(LOCK_KEY, "1", LOCK_SECONDS):
return JsonResponse(
{"error": "正在整理,请稍后再试", "code": "busy"},
status=409,
)
latest = latest_digest()
if latest and not digest_is_stale(latest):
cache.delete(LOCK_KEY)
return HttpResponse(latest.content, content_type="text/plain; charset=utf-8")
try:
snapshot = build_snapshot()
user_prompt = snapshot_prompt(snapshot)
except Exception as exc:
cache.delete(LOCK_KEY)
return JsonResponse(
{"error": "整理数据失败:{}".format(exc), "code": "snapshot_failed"},
status=500,
)
def generate():
chunks = []
saved = False
error_text = ""
try:
for chunk in chat_stream(
SYSTEM_PROMPT,
user_prompt,
model=DIGEST_MODEL,
temperature=0.7,
num_predict=800,
timeout=300,
):
chunks.append(chunk)
yield chunk
content = "".join(chunks).strip()
if not content:
raise LLMError("AI 没有返回内容")
Digest.objects.create(
content=content,
model=DIGEST_MODEL,
snapshot=snapshot,
complete=True,
)
saved = True
except GeneratorExit:
raise
except Exception as exc:
error_text = str(exc)[:500]
partial = "".join(chunks).strip()
try:
Digest.objects.create(
content=partial,
model=DIGEST_MODEL,
snapshot=snapshot,
complete=False,
error=error_text,
)
saved = True
except Exception:
pass
try:
yield "\n\n[整理中断:{}]".format(error_text)
except Exception:
pass
finally:
if not saved:
partial = "".join(chunks).strip()
try:
Digest.objects.create(
content=partial,
model=DIGEST_MODEL,
snapshot=snapshot,
complete=False,
error=error_text or "stream closed",
)
except Exception:
pass
cache.delete(LOCK_KEY)
response = StreamingHttpResponse(
generate(),
content_type="text/plain; charset=utf-8",
)
response["Cache-Control"] = "no-cache"
response["X-Accel-Buffering"] = "no"
return response
+65
View File
@@ -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()
+4
View File
@@ -22,6 +22,8 @@
<div class="mm-stat"><b>{{ stats.nodes }}</b><span>节点</span></div>
</div>
{% include "digest/_panel.html" %}
<div class="mm-toolbar">
{% if unlocked %}
<button class="mm-btn mm-btn-primary" id="mmNewFolderBtn" type="button">+ 新建目录</button>
@@ -115,8 +117,10 @@
{% block extra_css %}
<link rel="stylesheet" href="{% static 'mindmaps/mindmaps.css' %}">
<link rel="stylesheet" href="{% static 'digest/digest.css' %}">
{% endblock %}
{% block extra_js %}
<script src="{% static 'mindmaps/mindmaps.js' %}"></script>
<script src="{% static 'digest/digest.js' %}"></script>
{% endblock %}
+7
View File
@@ -9,6 +9,7 @@ from django.utils.text import slugify
from django.views.decorators.http import require_POST
from cabinet.access import is_unlocked, minutes_left, unlock_minutes
from digest.services import DIGEST_DAYS, DIGEST_MODEL, digest_is_stale, latest_digest
from .forms import MindFolderForm, MindMapEditForm, MindMapUploadForm, descendant_ids
from .models import MindFolder, MindMap, make_slug, unique_slug
@@ -57,10 +58,16 @@ def index(request):
)
unfiled = MindMap.objects.filter(folder__isnull=True).order_by("created_at", "id")
all_maps = MindMap.objects.all()
digest = latest_digest()
context = {
"folders": folders,
"unfiled": unfiled,
"digest": digest,
"digest_stale": digest_is_stale(digest),
"digest_days": DIGEST_DAYS,
"digest_model": DIGEST_MODEL,
"digest_inline": True,
"stats": {
"folders": MindFolder.objects.count(),
"maps": all_maps.count(),