added chat history

This commit is contained in:
2026-09-08 09:18:25 +03:00
parent 82953f0fe9
commit 8397f09de4
11 changed files with 635 additions and 30 deletions
+2
View File
@@ -18,6 +18,8 @@ class Settings(BaseSettings):
# SOCKS5 proxy for OpenRouter, e.g. socks5://user:pass@host:1080
openrouter_proxy: str = ""
llm_max_context_rows: int = 80
# Soft context window for the usage meter (tokens). Trim history if exceeded.
llm_context_limit: int = 64000
cors_origins: str = "*"
+72
View File
@@ -0,0 +1,72 @@
"""Lightweight schema patches for deployments without Alembic migrations."""
from __future__ import annotations
from sqlalchemy import inspect, text
from sqlalchemy.engine import Engine
def ensure_schema(engine: Engine) -> None:
"""Add llm_chats / chat_id if missing (create_all does not ALTER existing tables)."""
insp = inspect(engine)
tables = set(insp.get_table_names())
if "llm_messages" not in tables:
return
cols = {c["name"] for c in insp.get_columns("llm_messages")}
if "chat_id" in cols:
_migrate_orphan_messages(engine)
return
with engine.begin() as conn:
if "llm_chats" not in tables:
conn.execute(
text(
"""
CREATE TABLE llm_chats (
id SERIAL PRIMARY KEY,
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
title VARCHAR(255) DEFAULT 'Новый чат',
table_type VARCHAR(64),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
)
"""
)
)
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_llm_chats_project_id ON llm_chats (project_id)"))
conn.execute(
text(
"ALTER TABLE llm_messages ADD COLUMN chat_id INTEGER "
"REFERENCES llm_chats(id) ON DELETE CASCADE"
)
)
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_llm_messages_chat_id ON llm_messages (chat_id)"))
_migrate_orphan_messages(engine)
def _migrate_orphan_messages(engine: Engine) -> None:
"""Put legacy messages (no chat_id) into one chat per project."""
with engine.begin() as conn:
projects = conn.execute(
text(
"SELECT DISTINCT project_id FROM llm_messages WHERE chat_id IS NULL"
)
).fetchall()
for (project_id,) in projects:
chat_id = conn.execute(
text(
"INSERT INTO llm_chats (project_id, title, table_type) "
"VALUES (:pid, 'История', NULL) RETURNING id"
),
{"pid": project_id},
).scalar_one()
conn.execute(
text(
"UPDATE llm_messages SET chat_id = :cid "
"WHERE project_id = :pid AND chat_id IS NULL"
),
{"cid": chat_id, "pid": project_id},
)