Pin notes to a chat, and import notes from files
Two additions to the shared notes, both about getting content in and out of the prompt. Per-chat pinning. Notes normally reach the model as a title list only, and the body arrives just if the model decides to call read_note. A 📌 on the tab now puts a page's full body in the system prompt for the chat that is open, every turn, no tool round trip. The selection is per session (new table session_note_pages, unique on session_id + page_id), so different conversations carry different pages. The title list marks pinned pages so the model does not read them twice, and bodies are capped per page by SESSION_NOTES_CONTENT_LIMIT. A new chat has no session row until its first message, so the front end cannot PUT the selection yet. POST /chat/stream therefore accepts note_page_ids and applies it before building the context, which makes the pins count from the very first turn. File import. Dropping .md/.txt on the editor - or picking them with the new ⬆ button - creates pages, and a .zip is unpacked into one page per text entry with the first path component as the section. That is exactly the shape the export writes, so a downloaded zip round-trips back in. Titles that collide get a " (2)" suffix rather than overwriting, since restoring a backup into a live workspace should not destroy anything. UploadFile needs python-multipart, added to the lockfile. Toasts grew a kind: the import success message was rendering in the red error toast, as was the existing session-import message. Both are green now. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
+178
-4
@@ -2,14 +2,25 @@
|
||||
|
||||
システムプロンプトにはページの「タイトル一覧」だけを注入し、本文はモデルが
|
||||
read_note ツールで必要なときだけ読み出す。書き込みは write_note ツールで行う。
|
||||
|
||||
例外として、ユーザーがセッションに紐付けたページ(SessionNotePage)は本文も
|
||||
毎回そのままシステムプロンプトに載る。ツールの往復を待たずに確実に参照させたい
|
||||
資料のための仕組みで、指定はセッション単位なので会話ごとに組み合わせを変えられる。
|
||||
"""
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from app.core.config import NOTES_TOOL_CONTENT_LIMIT
|
||||
from app.db.models import NotePage
|
||||
from app.core.config import (
|
||||
NOTES_IMPORT_MAX_BYTES,
|
||||
NOTES_IMPORT_MAX_PAGES,
|
||||
NOTES_TOOL_CONTENT_LIMIT,
|
||||
SESSION_NOTES_CONTENT_LIMIT,
|
||||
)
|
||||
from app.db.models import NotePage, SessionNotePage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -138,9 +149,169 @@ def rename_section(db: DBSession, old_name: str, new_name: str | None) -> int:
|
||||
return len(pages)
|
||||
|
||||
|
||||
def get_notes_context(db: DBSession) -> str | None:
|
||||
"""共有ノートのタイトル一覧をシステムプロンプト用のテキストとして返す。セクションごとに見出しを付ける。"""
|
||||
# 取り込めるテキストファイルの拡張子。これ以外はZIP内でも単体でも無視する
|
||||
_TEXT_SUFFIXES = (".md", ".markdown", ".txt", ".text")
|
||||
# ダウンロードしたZIPのファイル名に付く並び順の通し番号(01_タイトル.md)
|
||||
_EXPORT_PREFIX = re.compile(r"^\d{2,}_")
|
||||
|
||||
|
||||
def _decode(raw: bytes) -> str:
|
||||
"""取り込んだファイルを文字列にする。UTF-8優先、日本語Windows由来のCP932も拾う。"""
|
||||
for encoding in ("utf-8-sig", "utf-8", "cp932"):
|
||||
try:
|
||||
return raw.decode(encoding)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def _title_from_filename(filename: str) -> str:
|
||||
"""ファイル名からページタイトルを作る。拡張子とエクスポート時の通し番号を落とす。"""
|
||||
stem = filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
|
||||
for suffix in _TEXT_SUFFIXES:
|
||||
if stem.lower().endswith(suffix):
|
||||
stem = stem[: -len(suffix)]
|
||||
break
|
||||
return _EXPORT_PREFIX.sub("", stem).strip() or "無題のページ"
|
||||
|
||||
|
||||
def _unique_title(db: DBSession, title: str, taken: set[str]) -> str:
|
||||
"""既存ページや同時取り込み分とタイトルがぶつかったら「(2)」を付けてずらす。
|
||||
|
||||
上書きせずに増やすのは、エクスポートしたZIPを既存のノートに投げ戻したときに
|
||||
元のページを壊さないため。要らない方は後からタブの × で消せる。
|
||||
"""
|
||||
existing = {p.title for p in db.query(NotePage.title).all()} | taken
|
||||
if title not in existing:
|
||||
return title
|
||||
n = 2
|
||||
while f"{title} ({n})" in existing:
|
||||
n += 1
|
||||
return f"{title} ({n})"
|
||||
|
||||
|
||||
def _create_imported_page(db: DBSession, title: str, content: str, section: str | None) -> NotePage:
|
||||
page = NotePage(title=title, content=content, position=next_position(db))
|
||||
db.add(page)
|
||||
db.commit()
|
||||
db.refresh(page)
|
||||
if section:
|
||||
# 同じセクションの末尾に並べ直す(連続配置の前提を保つ)
|
||||
page = set_section(db, page.id, section) or page
|
||||
return page
|
||||
|
||||
|
||||
def import_files(db: DBSession, files: list[tuple[str, bytes]]) -> list[NotePage]:
|
||||
"""アップロードされたファイルをノートのページとして取り込む。
|
||||
|
||||
files は (ファイル名, 中身) のリスト。.md / .txt はそのまま1ページになり、.zip は
|
||||
中のテキストファイルを1つずつページにする(ZIP内のフォルダ名がセクションになる)。
|
||||
エクスポートで出したZIPをそのまま投げ戻せば、セクションと並び順ごと復元できる。
|
||||
|
||||
取り込めないファイル(拡張子が対象外・大きすぎる)は黙って飛ばす。作成したページを返す。
|
||||
"""
|
||||
created: list[NotePage] = []
|
||||
taken: set[str] = set()
|
||||
|
||||
def add(filename: str, raw: bytes, section: str | None) -> None:
|
||||
if len(created) >= NOTES_IMPORT_MAX_PAGES or len(raw) > NOTES_IMPORT_MAX_BYTES:
|
||||
logger.info("Skipped note import: %s (%d bytes)", filename, len(raw))
|
||||
return
|
||||
title = _unique_title(db, _title_from_filename(filename), taken)
|
||||
taken.add(title)
|
||||
created.append(_create_imported_page(db, title, _decode(raw), section))
|
||||
|
||||
for filename, raw in files:
|
||||
if filename.lower().endswith(".zip"):
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||
for info in archive.infolist():
|
||||
if info.is_dir() or not info.filename.lower().endswith(_TEXT_SUFFIXES):
|
||||
continue
|
||||
if info.file_size > NOTES_IMPORT_MAX_BYTES:
|
||||
logger.info("Skipped zip entry: %s (%d bytes)", info.filename, info.file_size)
|
||||
continue
|
||||
# ZIP内のフォルダ名をセクションにする(ネストは最初の階層だけ見る)
|
||||
parts = info.filename.replace("\\", "/").split("/")
|
||||
section = parts[0] if len(parts) > 1 and parts[0] not in ("", ".", "..") else None
|
||||
add(info.filename, archive.read(info), section)
|
||||
except zipfile.BadZipFile:
|
||||
logger.warning("Not a valid zip: %s", filename)
|
||||
elif filename.lower().endswith(_TEXT_SUFFIXES):
|
||||
add(filename, raw, None)
|
||||
else:
|
||||
logger.info("Skipped unsupported file: %s", filename)
|
||||
|
||||
return created
|
||||
|
||||
|
||||
def get_attached_page_ids(db: DBSession, session_id: str) -> list[int]:
|
||||
"""セッションに紐付けられた(本文をプロンプトに載せる)ページIDを position 順で返す。"""
|
||||
rows = (
|
||||
db.query(SessionNotePage.page_id)
|
||||
.join(NotePage, NotePage.id == SessionNotePage.page_id)
|
||||
.filter(SessionNotePage.session_id == session_id)
|
||||
.order_by(NotePage.position, NotePage.id)
|
||||
.all()
|
||||
)
|
||||
return [row[0] for row in rows]
|
||||
|
||||
|
||||
def set_attached_pages(db: DBSession, session_id: str, page_ids: list[int]) -> list[int]:
|
||||
"""セッションに紐付けるページを page_ids で置き換える。存在しないIDは黙って捨てる。
|
||||
|
||||
戻り値は実際に紐付いたページIDを position 順で並べたもの。
|
||||
"""
|
||||
valid = {p.id for p in db.query(NotePage.id).filter(NotePage.id.in_(page_ids)).all()} if page_ids else set()
|
||||
|
||||
existing = db.query(SessionNotePage).filter(SessionNotePage.session_id == session_id).all()
|
||||
for link in existing:
|
||||
if link.page_id not in valid:
|
||||
db.delete(link)
|
||||
already = {link.page_id for link in existing if link.page_id in valid}
|
||||
for page_id in valid - already:
|
||||
db.add(SessionNotePage(session_id=session_id, page_id=page_id))
|
||||
db.commit()
|
||||
return get_attached_page_ids(db, session_id)
|
||||
|
||||
|
||||
def get_session_notes_context(db: DBSession, session_id: str) -> str | None:
|
||||
"""セッションに紐付けられたページの本文を、システムプロンプト用のテキストとして返す。
|
||||
|
||||
1ページも紐付いていなければ None。1ページあたり SESSION_NOTES_CONTENT_LIMIT 文字で切る。
|
||||
"""
|
||||
pages = (
|
||||
db.query(NotePage)
|
||||
.join(SessionNotePage, SessionNotePage.page_id == NotePage.id)
|
||||
.filter(SessionNotePage.session_id == session_id)
|
||||
.order_by(NotePage.position, NotePage.id)
|
||||
.all()
|
||||
)
|
||||
if not pages:
|
||||
return None
|
||||
|
||||
lines = [
|
||||
"【この会話で参照するノート】",
|
||||
"ユーザーがこの会話に紐付けたページです。本文をそのまま載せているので、"
|
||||
"これらのページに read_note を使う必要はありません。",
|
||||
"",
|
||||
]
|
||||
for page in pages:
|
||||
content = page.content.strip() or "(空)"
|
||||
if len(content) > SESSION_NOTES_CONTENT_LIMIT:
|
||||
content = content[:SESSION_NOTES_CONTENT_LIMIT] + "\n…(以下省略。全文は read_note で読めます)"
|
||||
lines += [f"## {page.title}", content, ""]
|
||||
return "\n".join(lines).rstrip()
|
||||
|
||||
|
||||
def get_notes_context(db: DBSession, session_id: str | None = None) -> str | None:
|
||||
"""共有ノートのタイトル一覧をシステムプロンプト用のテキストとして返す。セクションごとに見出しを付ける。
|
||||
|
||||
session_id を渡すと、そのセッションに紐付いた(本文が別途プロンプトに載る)ページに
|
||||
印を付ける。同じ本文を read_note で読み直させないため。
|
||||
"""
|
||||
pages = db.query(NotePage).order_by(NotePage.position, NotePage.id).all()
|
||||
attached = set(get_attached_page_ids(db, session_id)) if session_id else set()
|
||||
|
||||
lines = [
|
||||
"【共有ノート】",
|
||||
@@ -155,6 +326,9 @@ def get_notes_context(db: DBSession) -> str | None:
|
||||
current_section = page.section
|
||||
if current_section:
|
||||
lines.append(f"## {current_section}")
|
||||
if page.id in attached:
|
||||
lines.append(f"- {page.title} — (本文は「この会話で参照するノート」に全文あり)")
|
||||
continue
|
||||
preview = " ".join(page.content.split())[:40]
|
||||
suffix = f" — {preview}…" if preview else " — (空)"
|
||||
lines.append(f"- {page.title}{suffix}")
|
||||
|
||||
Reference in New Issue
Block a user