Add GUI settings panel for API keys, model presets, and embedding model
- Add a password-protected /api/settings endpoint (HTTP Basic auth, backend/app/core/auth.py) backed by a DB-stored allowlist of connection settings (OPENAI_API_KEY, ANTHROPIC_API_KEY, AWS creds, OLLAMA_API_BASE, TAVILY_API_KEY, LOCAL_KB_EMBEDDING_MODEL). Saved values override .env and apply immediately via os.environ, so Lightsail deployments no longer need SSH + `.env` edits to rotate keys. Values are always returned masked to the frontend. - Replace ModelSelector.vue's hardcoded model list with a DB-backed /api/models CRUD API (read is public, writes reuse the settings password) so the chat model dropdown can be edited from the GUI; seed it once with the previous hardcoded presets on first boot. - Fix local_knowledge.py reading LOCAL_KB_EMBEDDING_MODEL once at import time instead of per-call, which would have silently ignored GUI/DB overrides for the embedding model. - Add SettingsPanel.vue (API keys + model management UI) and document the new SETTINGS_PASSWORD env var in .env.example and the Lightsail deploy guide. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import secrets
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
|
||||
from app.core.config import SETTINGS_PASSWORD
|
||||
|
||||
_security = HTTPBasic()
|
||||
|
||||
|
||||
def require_settings_password(credentials: HTTPBasicCredentials = Depends(_security)) -> None:
|
||||
"""設定画面(/api/settings)専用の簡易パスワード認証。ユーザー名は見ない。
|
||||
|
||||
SETTINGS_PASSWORD が未設定の場合は、空パスワードでの突破を防ぐため常に拒否する。
|
||||
"""
|
||||
if not SETTINGS_PASSWORD:
|
||||
raise HTTPException(status_code=403, detail="SETTINGS_PASSWORD is not configured on the server")
|
||||
if not secrets.compare_digest(credentials.password, SETTINGS_PASSWORD):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Invalid password",
|
||||
headers={"WWW-Authenticate": "Basic"},
|
||||
)
|
||||
@@ -9,6 +9,9 @@ MEMORY_SUMMARIZE_THRESHOLD: int = int(os.getenv("MEMORY_SUMMARIZE_THRESHOLD", "2
|
||||
CORS_ORIGINS: list[str] = os.getenv("CORS_ORIGINS", "http://localhost:5173").split(",")
|
||||
DEBUG: bool = os.getenv("DEBUG", "false").lower() in ("1", "true", "yes")
|
||||
|
||||
# GUI設定画面(/api/settings)を保護する簡易パスワード。未設定の場合、設定画面は常に403で拒否する。
|
||||
SETTINGS_PASSWORD: str | None = os.getenv("SETTINGS_PASSWORD")
|
||||
|
||||
# メッセージへの自動タグ付けに使うモデル(未設定ならDEFAULT_MODELを使用)
|
||||
TAGGING_MODEL: str | None = os.getenv("TAGGING_MODEL")
|
||||
|
||||
|
||||
@@ -7,12 +7,13 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from app.core import llm
|
||||
from app.core.config import LOCAL_KB_DIR, LOCAL_KB_EMBEDDING_MODEL, LOCAL_KB_MIN_SCORE, LOCAL_KB_TOP_K
|
||||
from app.core.config import LOCAL_KB_DIR, LOCAL_KB_MIN_SCORE, LOCAL_KB_TOP_K
|
||||
from app.db.models import KnowledgeEntry, LocalKnowledgeDoc
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -22,6 +23,11 @@ def _kb_dir() -> Path:
|
||||
return Path(LOCAL_KB_DIR)
|
||||
|
||||
|
||||
def _embedding_model() -> str:
|
||||
"""GUIの設定画面から実行時に変更できるよう、起動時定数ではなく都度 os.environ を見に行く。"""
|
||||
return os.environ.get("LOCAL_KB_EMBEDDING_MODEL", "text-embedding-3-small")
|
||||
|
||||
|
||||
def _hash(content: str) -> str:
|
||||
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||
|
||||
@@ -104,7 +110,7 @@ async def sync_local_kb(db: DBSession) -> None:
|
||||
continue
|
||||
|
||||
try:
|
||||
[embedding] = await llm.embed([content], model=LOCAL_KB_EMBEDDING_MODEL)
|
||||
[embedding] = await llm.embed([content], model=_embedding_model())
|
||||
except Exception:
|
||||
logger.exception("Failed to embed local knowledge file: %s", rel_path)
|
||||
continue
|
||||
@@ -142,7 +148,7 @@ async def get_local_kb_context(db: DBSession, query_text: str) -> str | None:
|
||||
return None
|
||||
|
||||
try:
|
||||
[query_embedding] = await llm.embed([query_text], model=LOCAL_KB_EMBEDDING_MODEL)
|
||||
[query_embedding] = await llm.embed([query_text], model=_embedding_model())
|
||||
except Exception:
|
||||
logger.exception("Failed to embed query for local knowledge search")
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import os
|
||||
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from app.db.models import AppSetting
|
||||
|
||||
# GUIから編集可能な環境変数の許可リスト。ここに無いキーは save()/clear() で拒否する。
|
||||
CONFIGURABLE_KEYS = [
|
||||
"OPENAI_API_KEY",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_SECRET_ACCESS_KEY",
|
||||
"AWS_SESSION_TOKEN",
|
||||
"AWS_BEARER_TOKEN_BEDROCK",
|
||||
"AWS_REGION_NAME",
|
||||
"OLLAMA_API_BASE",
|
||||
"TAVILY_API_KEY",
|
||||
"LOCAL_KB_EMBEDDING_MODEL",
|
||||
]
|
||||
|
||||
# .env由来の起動時の値のスナップショット。clear() で戻す先として使う。
|
||||
_env_defaults: dict[str, str | None] = {}
|
||||
_snapshot_taken = False
|
||||
|
||||
|
||||
def _ensure_snapshot() -> None:
|
||||
global _snapshot_taken
|
||||
if _snapshot_taken:
|
||||
return
|
||||
for key in CONFIGURABLE_KEYS:
|
||||
_env_defaults[key] = os.environ.get(key)
|
||||
_snapshot_taken = True
|
||||
|
||||
|
||||
def _mask(value: str) -> str:
|
||||
if len(value) <= 4:
|
||||
return "••••"
|
||||
return f"••••{value[-4:]}"
|
||||
|
||||
|
||||
def load_into_env(db: DBSession) -> None:
|
||||
"""DBに保存済みの値をos.environに適用する。起動時に一度呼ぶ。"""
|
||||
_ensure_snapshot()
|
||||
for row in db.query(AppSetting).all():
|
||||
if row.key in CONFIGURABLE_KEYS:
|
||||
os.environ[row.key] = row.value
|
||||
|
||||
|
||||
def list_masked(db: DBSession) -> list[dict]:
|
||||
_ensure_snapshot()
|
||||
saved = {row.key: row.value for row in db.query(AppSetting).all()}
|
||||
result = []
|
||||
for key in CONFIGURABLE_KEYS:
|
||||
current = os.environ.get(key)
|
||||
result.append({
|
||||
"key": key,
|
||||
"is_set": bool(current),
|
||||
"masked": _mask(current) if current else None,
|
||||
"overridden": key in saved,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def save(db: DBSession, key: str, value: str) -> None:
|
||||
if key not in CONFIGURABLE_KEYS:
|
||||
raise ValueError(f"Unknown setting key: {key}")
|
||||
_ensure_snapshot()
|
||||
row = db.get(AppSetting, key)
|
||||
if row:
|
||||
row.value = value
|
||||
else:
|
||||
db.add(AppSetting(key=key, value=value))
|
||||
db.commit()
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
def clear(db: DBSession, key: str) -> None:
|
||||
if key not in CONFIGURABLE_KEYS:
|
||||
raise ValueError(f"Unknown setting key: {key}")
|
||||
_ensure_snapshot()
|
||||
row = db.get(AppSetting, key)
|
||||
if row:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
original = _env_defaults.get(key)
|
||||
if original is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = original
|
||||
Reference in New Issue
Block a user