feat(blog): جدول — ستون‌ها قابل تغییر اندازه/افزودن و حذف؛ لینک کپشن تصویر؛ هدینگ‌های نسخه انگلیسی بزرگ‌تر

This commit is contained in:
aramesh-site deploy
2026-10-06 10:57:01 +00:00
parent 61a2e95278
commit 1b491357ab
45 changed files with 2341 additions and 81 deletions
+71
View File
@@ -66,6 +66,22 @@ def ensure_schema() -> None:
ON chatbot_chunks USING hnsw (embedding vector_cosine_ops)
"""
)
# گزارش گفتگوها — حلقه بازخورد برای کشف پرسش‌های بی‌پاسخ
conn.execute(
"""
CREATE TABLE IF NOT EXISTS chat_logs (
id BIGSERIAL PRIMARY KEY,
ts TIMESTAMPTZ NOT NULL DEFAULT now(),
thread_id TEXT NOT NULL,
question TEXT NOT NULL,
answer TEXT NOT NULL,
n_docs INTEGER NOT NULL DEFAULT 0,
is_fallback BOOLEAN NOT NULL DEFAULT FALSE,
latency_ms INTEGER NOT NULL DEFAULT 0
)
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS chat_logs_ts_idx ON chat_logs (ts DESC)")
def sync_chunks(chunks: list[dict], force: bool = False) -> dict:
@@ -168,6 +184,61 @@ def vector_count() -> int:
return 0
def log_chat(thread_id: str, question: str, answer: str, n_docs: int,
is_fallback: bool, latency_ms: int) -> None:
"""ثبت یک گفتگو در chat_logs — هرگز خطا نمی‌دهد (لاگ نباید جریان پاسخ را بشکند)."""
try:
import psycopg
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=5) as conn:
conn.execute(
"""
INSERT INTO chat_logs (thread_id, question, answer, n_docs, is_fallback, latency_ms)
VALUES (%s, %s, %s, %s, %s, %s)
""",
(thread_id, question, answer[:4000], n_docs, is_fallback, latency_ms),
)
except Exception as e:
log.warning("chat_logs insert failed: %s", e)
def chat_stats(days: int = 7) -> dict:
"""آمار تجمعی گفتگوها — بدون متن پرسش‌ها (متن‌ها فقط با توکن در /chat/stats)."""
try:
import psycopg
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=5) as conn:
total = int(conn.execute("SELECT count(*) FROM chat_logs").fetchone()[0])
row = conn.execute(
"""
SELECT count(*), count(*) FILTER (WHERE is_fallback)
FROM chat_logs WHERE ts > now() - (%s || ' days')::interval
""",
(str(days),),
).fetchone()
recent_fallbacks: list[str] = []
if row and row[1]:
recent_fallbacks = [
r[0] for r in conn.execute(
"""
SELECT question FROM chat_logs
WHERE is_fallback AND ts > now() - (%s || ' days')::interval
ORDER BY ts DESC LIMIT 20
""",
(str(days),),
).fetchall()
]
return {
"total_logged": total,
"last_7d": int(row[0]) if row else 0,
"fallback_7d": int(row[1]) if row else 0,
"recent_fallback_questions": recent_fallbacks,
}
except Exception as e:
log.warning("chat_stats failed: %s", e)
return {"total_logged": 0, "last_7d": 0, "fallback_7d": 0, "recent_fallback_questions": []}
def dense_search(query: str, top_k: int) -> list[tuple[dict, float]]:
"""جست‌وجوی معنایی SQL با فاصله کسینوسی — خروجی: (سند، شباهت).