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,11 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "frontend-dev",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["--prefix", "frontend", "run", "dev"],
|
||||
"port": 5173
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -16,6 +16,11 @@ AWS_BEARER_TOKEN_BEDROCK=
|
||||
# デバッグ (true にすると LiteLLM の詳細ログが出力される)
|
||||
DEBUG=false
|
||||
|
||||
# GUIの「設定」画面(APIキー等の変更)を保護する簡易パスワード。
|
||||
# 未設定だと設定画面は常に403で拒否される(=GUIからのAPIキー変更機能を使わないなら空でよい)。
|
||||
# HTTPS化していない環境ではBasic認証の資格情報が平文で流れるため、公開環境ではHTTPS化とセットで使うこと。
|
||||
SETTINGS_PASSWORD=
|
||||
|
||||
# Tavily Web検索(未設定だとweb_searchツールは何も検索せず空振りする)
|
||||
TAVILY_API_KEY=
|
||||
# 蓄積知識をシステムプロンプトに注入する際の最大件数
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from app.core.auth import require_settings_password
|
||||
from app.db.database import get_db
|
||||
from app.db.models import ModelPreset
|
||||
|
||||
router = APIRouter(prefix="/api/models", tags=["models"])
|
||||
|
||||
|
||||
class ModelPresetResponse(BaseModel):
|
||||
id: int
|
||||
label: str
|
||||
value: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ModelPresetRequest(BaseModel):
|
||||
label: str
|
||||
value: str
|
||||
|
||||
|
||||
@router.get("", response_model=list[ModelPresetResponse])
|
||||
def list_model_presets(db: DBSession = Depends(get_db)):
|
||||
"""モデル選択プルダウンの表示に使うため認証不要(誰でも読める)。"""
|
||||
return db.query(ModelPreset).order_by(ModelPreset.id).all()
|
||||
|
||||
|
||||
@router.post("", response_model=ModelPresetResponse, dependencies=[Depends(require_settings_password)])
|
||||
def create_model_preset(req: ModelPresetRequest, db: DBSession = Depends(get_db)):
|
||||
preset = ModelPreset(label=req.label, value=req.value)
|
||||
db.add(preset)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail=f"モデル文字列が重複しています: {req.value}") from e
|
||||
db.refresh(preset)
|
||||
return preset
|
||||
|
||||
|
||||
@router.put("/{preset_id}", response_model=ModelPresetResponse, dependencies=[Depends(require_settings_password)])
|
||||
def update_model_preset(preset_id: int, req: ModelPresetRequest, db: DBSession = Depends(get_db)):
|
||||
preset = db.get(ModelPreset, preset_id)
|
||||
if not preset:
|
||||
raise HTTPException(status_code=404, detail="Model preset not found")
|
||||
preset.label = req.label
|
||||
preset.value = req.value
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=400, detail=f"モデル文字列が重複しています: {req.value}") from e
|
||||
db.refresh(preset)
|
||||
return preset
|
||||
|
||||
|
||||
@router.delete("/{preset_id}", status_code=204, dependencies=[Depends(require_settings_password)])
|
||||
def delete_model_preset(preset_id: int, db: DBSession = Depends(get_db)):
|
||||
preset = db.get(ModelPreset, preset_id)
|
||||
if preset:
|
||||
db.delete(preset)
|
||||
db.commit()
|
||||
@@ -0,0 +1,46 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from app.core import settings_store
|
||||
from app.core.auth import require_settings_password
|
||||
from app.db.database import get_db
|
||||
|
||||
router = APIRouter(prefix="/api/settings", tags=["settings"], dependencies=[Depends(require_settings_password)])
|
||||
|
||||
|
||||
class SettingEntry(BaseModel):
|
||||
key: str
|
||||
is_set: bool
|
||||
masked: str | None
|
||||
overridden: bool
|
||||
|
||||
|
||||
class SaveSettingsRequest(BaseModel):
|
||||
values: dict[str, str]
|
||||
|
||||
|
||||
@router.get("", response_model=list[SettingEntry])
|
||||
def list_settings(db: DBSession = Depends(get_db)):
|
||||
return settings_store.list_masked(db)
|
||||
|
||||
|
||||
@router.put("", response_model=list[SettingEntry])
|
||||
def save_settings(req: SaveSettingsRequest, db: DBSession = Depends(get_db)):
|
||||
try:
|
||||
for key, value in req.values.items():
|
||||
if not value:
|
||||
continue # 空欄は「変更なし」として無視する
|
||||
settings_store.save(db, key, value)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
return settings_store.list_masked(db)
|
||||
|
||||
|
||||
@router.delete("/{key}", response_model=list[SettingEntry])
|
||||
def clear_setting(key: str, db: DBSession = Depends(get_db)):
|
||||
try:
|
||||
settings_store.clear(db, key)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
return settings_store.list_masked(db)
|
||||
@@ -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
|
||||
@@ -104,6 +104,25 @@ class LocalKnowledgeDoc(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""GUIの設定画面から編集する接続情報(APIキー等)。app.core.settings_store が読み書きする。"""
|
||||
__tablename__ = "app_settings"
|
||||
|
||||
key: Mapped[str] = mapped_column(String, primary_key=True)
|
||||
value: Mapped[str] = mapped_column(Text)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ModelPreset(Base):
|
||||
"""モデル選択プルダウン(ModelSelector.vue)に表示するプリセット。GUIの設定画面から編集する。"""
|
||||
__tablename__ = "model_presets"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
label: Mapped[str] = mapped_column(String)
|
||||
value: Mapped[str] = mapped_column(String, unique=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ApiLog(Base):
|
||||
__tablename__ = "api_logs"
|
||||
|
||||
|
||||
+44
-2
@@ -4,13 +4,31 @@ from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api import chat, logs, memory, system
|
||||
from app.api import models as models_api
|
||||
from app.api import settings as settings_api
|
||||
from app.core import settings_store
|
||||
from app.core.config import CORS_ORIGINS
|
||||
from app.core.discord.discord_bot import start_discord_bot
|
||||
from app.core.discord.scheduler import start_scheduler
|
||||
from app.core.memory_kb.word_memory import seed_from_history
|
||||
from app.db.database import SessionLocal, init_db
|
||||
from app.db.models import Message
|
||||
from app.api import chat, memory, logs, system
|
||||
from app.db.models import Message, ModelPreset
|
||||
|
||||
# ModelSelector.vue に元々ハードコードされていたプリセット。初回起動時のみDBへシードする。
|
||||
_DEFAULT_MODEL_PRESETS = [
|
||||
("GPT-5.5", "gpt-5.5"),
|
||||
("GPT-5.4", "gpt-5.4"),
|
||||
("GPT-5.4 mini", "gpt-5.4-mini"),
|
||||
("Claude Sonnet 4.6", "claude-sonnet-4-6"),
|
||||
("Claude Haiku 4.5", "claude-haiku-4-5-20251001"),
|
||||
("Ollama llama3", "ollama/llama3"),
|
||||
("Ollama Gemma4", "ollama/gemma4"),
|
||||
("Gemma 4 12B (llama-server)", "gpt-3.5-turbo"),
|
||||
("Claude Sonnet 4.6 (Bedrock)", "bedrock/jp.anthropic.claude-sonnet-4-6"),
|
||||
("Llama 3 70B (Bedrock)", "bedrock/meta.llama3-70b-instruct-v1:0"),
|
||||
("Nova 2 Lite (Bedrock)", "bedrock/jp.amazon.nova-2-lite-v1:0"),
|
||||
]
|
||||
|
||||
|
||||
def _seed_word_memory_from_db() -> None:
|
||||
@@ -28,9 +46,31 @@ def _seed_word_memory_from_db() -> None:
|
||||
db.close()
|
||||
|
||||
|
||||
def _load_settings_into_env() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
settings_store.load_into_env(db)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _seed_default_models() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if db.query(ModelPreset).first() is not None:
|
||||
return
|
||||
for label, value in _DEFAULT_MODEL_PRESETS:
|
||||
db.add(ModelPreset(label=label, value=value))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_db()
|
||||
_load_settings_into_env()
|
||||
_seed_default_models()
|
||||
_seed_word_memory_from_db()
|
||||
start_scheduler()
|
||||
asyncio.create_task(start_discord_bot())
|
||||
@@ -52,6 +92,8 @@ app.include_router(chat.router)
|
||||
app.include_router(memory.router)
|
||||
app.include_router(logs.router)
|
||||
app.include_router(system.router)
|
||||
app.include_router(settings_api.router)
|
||||
app.include_router(models_api.router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
|
||||
@@ -59,10 +59,40 @@ docker compose version
|
||||
|
||||
## 3. リポジトリの取得と設定
|
||||
|
||||
```bash
|
||||
git clone <このリポジトリのURL> playchat
|
||||
cd playchat
|
||||
リポジトリは自前の Git サーバー(`colc-git.duckdns.org`、Gitea/Forgejo系)でホストしている。
|
||||
DuckDNS 経由の公開IPで、HTTPS(443)・SSH(22) とも外部から到達可能なので、Lightsail インスタンスからも
|
||||
VPN 等は不要で直接クローンできる。認証方法は以下のどちらか。
|
||||
|
||||
### 方法A: SSH デプロイキー(推奨・pull専用なら安全)
|
||||
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -C "lightsail-playchat" -f ~/.ssh/id_ed25519 -N ""
|
||||
cat ~/.ssh/id_ed25519.pub
|
||||
```
|
||||
|
||||
表示された公開鍵を colc-git.duckdns.org 側のリポジトリ設定の **Deploy Keys** に **Read only** で登録してから:
|
||||
|
||||
```bash
|
||||
git clone git@colc-git.duckdns.org:colcaroli/playchat.git
|
||||
cd playchat
|
||||
```
|
||||
|
||||
### 方法B: HTTPS + アクセストークン
|
||||
|
||||
colc-git.duckdns.org 側で個人アクセストークン(PAT)を発行し:
|
||||
|
||||
```bash
|
||||
git clone https://colc-git.duckdns.org/colcaroli/playchat.git
|
||||
cd playchat
|
||||
# Username / Password 入力を求められたら、Password 欄に発行したトークンを入力
|
||||
```
|
||||
|
||||
トークンをキャッシュしたい場合は `git config credential.helper cache`(メモリに一時保存。
|
||||
`store` は平文保存になるため非推奨)。
|
||||
|
||||
### .env の設定
|
||||
|
||||
```bash
|
||||
cp backend/.env.example backend/.env
|
||||
nano backend/.env # APIキーやモデル名など本番用の値を設定
|
||||
```
|
||||
@@ -76,9 +106,19 @@ nano backend/.env # APIキーやモデル名など本番用の値を設定
|
||||
| `CORS_ORIGINS` | `http://<静的IP>` またはドメイン(nginx が同一オリジンで配信するので基本は素通りするが念のため合わせておく) |
|
||||
| `DATABASE_URL` | **編集不要**(`docker-compose.yml` が `/app/data/playchat.db` に上書きし、Docker Volume に永続化する) |
|
||||
| `DISCORD_BOT_TOKEN` 等 | Discord Bot / 通知機能を使うなら設定。不要なら空のままでよい(未設定時は該当機能が無効) |
|
||||
| `SETTINGS_PASSWORD` | GUIの「設定」画面(後述)を使うなら必ず設定する。未設定だと設定画面は403で拒否される |
|
||||
|
||||
`backend/.env` はコンテナに `env_file` として渡され、Git 管理対象外(`.gitignore` 済み)なので直接編集してよい。
|
||||
|
||||
### GUIからのAPIキー管理
|
||||
|
||||
初回起動後は、`OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / AWS認証情報などをSSHで`.env`を編集し直さなくても、
|
||||
アプリ右上の「設定」ボタン(`SETTINGS_PASSWORD` によるBasic認証で保護)から変更できる。GUIで保存した値は
|
||||
SQLite(`AppSetting`テーブル、`backend_data`ボリュームで永続化)に保存され、`.env`の値より優先される。
|
||||
|
||||
**注意:** このパスワード保護は簡易的なものであり、HTTP平文通信の場合はBasic認証の資格情報がネットワーク上に
|
||||
そのまま流れてしまう。この機能を使うなら[6. HTTPS化](#6-https-化ドメインがある場合)と合わせて運用すること。
|
||||
|
||||
## 4. ビルド & 起動
|
||||
|
||||
```bash
|
||||
|
||||
+15
-3
@@ -5,12 +5,18 @@ import ChatWindow from './components/ChatWindow.vue'
|
||||
import MessageInput from './components/MessageInput.vue'
|
||||
import ModelSelector from './components/ModelSelector.vue'
|
||||
import LogViewer from './components/LogViewer.vue'
|
||||
import SettingsPanel from './components/SettingsPanel.vue'
|
||||
import ToastList from './components/ToastList.vue'
|
||||
import MemoryMonitor from './components/MemoryMonitor.vue'
|
||||
import Clock from './components/Clock.vue'
|
||||
import WordPool from './components/WordPool.vue'
|
||||
|
||||
const showLogs = ref(false)
|
||||
type SidePanel = 'none' | 'logs' | 'settings'
|
||||
const activePanel = ref<SidePanel>('none')
|
||||
|
||||
function togglePanel(panel: SidePanel) {
|
||||
activePanel.value = activePanel.value === panel ? 'none' : panel
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -25,7 +31,10 @@ const showLogs = ref(false)
|
||||
<span class="title">PlayChat</span>
|
||||
<ModelSelector />
|
||||
<Clock />
|
||||
<button class="log-toggle" :class="{ active: showLogs }" @click="showLogs = !showLogs">
|
||||
<button class="log-toggle" :class="{ active: activePanel === 'settings' }" @click="togglePanel('settings')">
|
||||
設定
|
||||
</button>
|
||||
<button class="log-toggle" :class="{ active: activePanel === 'logs' }" @click="togglePanel('logs')">
|
||||
ログ
|
||||
</button>
|
||||
</header>
|
||||
@@ -34,9 +43,12 @@ const showLogs = ref(false)
|
||||
<ChatWindow />
|
||||
<MessageInput />
|
||||
</div>
|
||||
<div v-if="showLogs" class="log-pane">
|
||||
<div v-if="activePanel === 'logs'" class="log-pane">
|
||||
<LogViewer />
|
||||
</div>
|
||||
<div v-else-if="activePanel === 'settings'" class="log-pane">
|
||||
<SettingsPanel />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -81,6 +81,72 @@ export async function deleteLog(logId: number): Promise<void> {
|
||||
await fetch(`${BASE}/logs/${logId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export interface SettingEntry {
|
||||
key: string
|
||||
is_set: boolean
|
||||
masked: string | null
|
||||
overridden: boolean
|
||||
}
|
||||
|
||||
function authHeader(password: string): HeadersInit {
|
||||
return { Authorization: `Basic ${btoa(`x:${password}`)}` }
|
||||
}
|
||||
|
||||
export async function fetchSettings(password: string): Promise<SettingEntry[]> {
|
||||
const res = await fetch(`${BASE}/api/settings`, { headers: authHeader(password) })
|
||||
return parseJson<SettingEntry[]>(res, '設定取得')
|
||||
}
|
||||
|
||||
export async function saveSettings(values: Record<string, string>, password: string): Promise<SettingEntry[]> {
|
||||
const res = await fetch(`${BASE}/api/settings`, {
|
||||
method: 'PUT',
|
||||
headers: { ...authHeader(password), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ values }),
|
||||
})
|
||||
return parseJson<SettingEntry[]>(res, '設定保存')
|
||||
}
|
||||
|
||||
export async function clearSetting(key: string, password: string): Promise<SettingEntry[]> {
|
||||
const res = await fetch(`${BASE}/api/settings/${key}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeader(password),
|
||||
})
|
||||
return parseJson<SettingEntry[]>(res, '設定クリア')
|
||||
}
|
||||
|
||||
export interface ModelPreset {
|
||||
id: number
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export async function fetchModelPresets(): Promise<ModelPreset[]> {
|
||||
const res = await fetch(`${BASE}/api/models`)
|
||||
return parseJson<ModelPreset[]>(res, 'モデル一覧取得')
|
||||
}
|
||||
|
||||
export async function createModelPreset(label: string, value: string, password: string): Promise<ModelPreset> {
|
||||
const res = await fetch(`${BASE}/api/models`, {
|
||||
method: 'POST',
|
||||
headers: { ...authHeader(password), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ label, value }),
|
||||
})
|
||||
return parseJson<ModelPreset>(res, 'モデル追加')
|
||||
}
|
||||
|
||||
export async function updateModelPreset(id: number, label: string, value: string, password: string): Promise<ModelPreset> {
|
||||
const res = await fetch(`${BASE}/api/models/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { ...authHeader(password), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ label, value }),
|
||||
})
|
||||
return parseJson<ModelPreset>(res, 'モデル更新')
|
||||
}
|
||||
|
||||
export async function deleteModelPreset(id: number, password: string): Promise<void> {
|
||||
await fetch(`${BASE}/api/models/${id}`, { method: 'DELETE', headers: authHeader(password) })
|
||||
}
|
||||
|
||||
export function streamChat(
|
||||
message: string,
|
||||
sessionId: string | null,
|
||||
|
||||
@@ -1,28 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { useChatStore } from '../stores/chat'
|
||||
import { useSettingsStore } from '../stores/settings'
|
||||
|
||||
const store = useChatStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
const presets = [
|
||||
{ label: 'GPT-5.5', value: 'gpt-5.5' },
|
||||
{ label: 'GPT-5.4', value: 'gpt-5.4' },
|
||||
{ label: 'GPT-5.4 mini', value: 'gpt-5.4-mini' },
|
||||
{ label: 'Claude Sonnet 4.6', value: 'claude-sonnet-4-6' },
|
||||
{ label: 'Claude Haiku 4.5', value: 'claude-haiku-4-5-20251001' },
|
||||
{ label: 'Ollama llama3', value: 'ollama/llama3' },
|
||||
{ label: 'Ollama Gemma4', value: 'ollama/gemma4' },
|
||||
{ label: 'Gemma 4 12B (llama-server)', value: 'gpt-3.5-turbo' },
|
||||
{ label: 'Claude Sonnet 4.6 (Bedrock)', value: 'bedrock/jp.anthropic.claude-sonnet-4-6' },
|
||||
{ label: 'Llama 3 70B (Bedrock)', value: 'bedrock/meta.llama3-70b-instruct-v1:0' },
|
||||
{ label: 'Nova 2 Lite (Bedrock)', value: 'bedrock/jp.amazon.nova-2-lite-v1:0' },
|
||||
]
|
||||
// 選択中のモデルがプリセット一覧に無い場合(削除された/カスタム値)も表示が壊れないよう、
|
||||
// その場で追加のoptionとして補う。
|
||||
const options = computed(() => {
|
||||
const presets = settingsStore.modelPresets
|
||||
if (presets.some((p) => p.value === store.selectedModel)) return presets
|
||||
return [...presets, { id: -1, label: store.selectedModel, value: store.selectedModel }]
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
settingsStore.loadModelPresets()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="model-selector">
|
||||
<label>モデル</label>
|
||||
<select v-model="store.selectedModel">
|
||||
<option v-for="p in presets" :key="p.value" :value="p.value">{{ p.label }}</option>
|
||||
<option v-for="p in options" :key="p.value" :value="p.value">{{ p.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted, watch } from 'vue'
|
||||
import { useSettingsStore } from '../stores/settings'
|
||||
|
||||
const store = useSettingsStore()
|
||||
|
||||
const passwordInput = ref('')
|
||||
const drafts = reactive<Record<string, string>>({})
|
||||
|
||||
const presetDrafts = reactive<Record<number, { label: string; value: string }>>({})
|
||||
const newLabel = ref('')
|
||||
const newValue = ref('')
|
||||
|
||||
watch(
|
||||
() => store.modelPresets,
|
||||
(presets) => {
|
||||
for (const key of Object.keys(presetDrafts)) delete presetDrafts[Number(key)]
|
||||
for (const p of presets) presetDrafts[p.id] = { label: p.label, value: p.value }
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
async function saveModelPreset(id: number) {
|
||||
const draft = presetDrafts[id]
|
||||
if (!draft || !draft.label || !draft.value) return
|
||||
await store.editModelPreset(id, draft.label, draft.value)
|
||||
}
|
||||
|
||||
async function addModelPreset() {
|
||||
if (!newLabel.value || !newValue.value) return
|
||||
const ok = await store.addModelPreset(newLabel.value, newValue.value)
|
||||
if (ok) {
|
||||
newLabel.value = ''
|
||||
newValue.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const KEY_LABELS: Record<string, string> = {
|
||||
OPENAI_API_KEY: 'OpenAI APIキー',
|
||||
ANTHROPIC_API_KEY: 'Anthropic APIキー',
|
||||
AWS_ACCESS_KEY_ID: 'AWS Access Key ID',
|
||||
AWS_SECRET_ACCESS_KEY: 'AWS Secret Access Key',
|
||||
AWS_SESSION_TOKEN: 'AWS Session Token',
|
||||
AWS_BEARER_TOKEN_BEDROCK: 'AWS Bedrock Bearer Token',
|
||||
AWS_REGION_NAME: 'AWS Region',
|
||||
OLLAMA_API_BASE: 'Ollama API Base URL',
|
||||
TAVILY_API_KEY: 'Tavily APIキー',
|
||||
LOCAL_KB_EMBEDDING_MODEL: '埋め込みモデル(ローカルナレッジベース検索用)',
|
||||
}
|
||||
|
||||
// 秘匿情報ではないため、マスクせず通常のテキスト入力として表示するキー
|
||||
const PLAIN_TEXT_KEYS = new Set(['LOCAL_KB_EMBEDDING_MODEL', 'OLLAMA_API_BASE', 'AWS_REGION_NAME'])
|
||||
|
||||
async function submitPassword() {
|
||||
const ok = await store.unlock(passwordInput.value)
|
||||
if (ok) passwordInput.value = ''
|
||||
}
|
||||
|
||||
async function saveAll() {
|
||||
const values: Record<string, string> = {}
|
||||
for (const [key, value] of Object.entries(drafts)) {
|
||||
if (value) values[key] = value
|
||||
}
|
||||
if (Object.keys(values).length === 0) return
|
||||
const ok = await store.save(values)
|
||||
if (ok) {
|
||||
for (const key of Object.keys(drafts)) drafts[key] = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function clearOne(key: string) {
|
||||
await store.clear(key)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
store.tryAutoUnlock()
|
||||
store.loadModelPresets()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="settings-panel">
|
||||
<div class="toolbar">
|
||||
<span class="title">API接続設定</span>
|
||||
<button v-if="store.unlocked" class="lock-btn" @click="store.lock()">ロック</button>
|
||||
</div>
|
||||
|
||||
<form v-if="!store.unlocked" class="login" @submit.prevent="submitPassword">
|
||||
<p class="hint">APIキーを表示・変更するにはパスワードが必要です。</p>
|
||||
<input
|
||||
v-model="passwordInput"
|
||||
type="password"
|
||||
placeholder="パスワード"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
<button type="submit" :disabled="store.loading || !passwordInput">
|
||||
{{ store.loading ? '確認中...' : 'ロック解除' }}
|
||||
</button>
|
||||
<p v-if="store.error" class="error">{{ store.error }}</p>
|
||||
</form>
|
||||
|
||||
<div v-else class="entries">
|
||||
<p v-if="store.error" class="error">{{ store.error }}</p>
|
||||
<div v-for="entry in store.entries" :key="entry.key" class="entry">
|
||||
<label>{{ KEY_LABELS[entry.key] ?? entry.key }}</label>
|
||||
<div class="row">
|
||||
<input
|
||||
v-model="drafts[entry.key]"
|
||||
:type="PLAIN_TEXT_KEYS.has(entry.key) ? 'text' : 'password'"
|
||||
:placeholder="entry.is_set ? `設定済み ${entry.masked}` : '未設定'"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<button
|
||||
v-if="entry.overridden"
|
||||
class="clear-btn"
|
||||
title="GUIで設定した値をクリアして.envの値に戻す"
|
||||
@click="clearOne(entry.key)"
|
||||
>
|
||||
クリア
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="save-btn" :disabled="store.loading" @click="saveAll">
|
||||
{{ store.loading ? '保存中...' : '保存' }}
|
||||
</button>
|
||||
|
||||
<hr />
|
||||
|
||||
<h3 class="section-title">モデル管理</h3>
|
||||
<div v-for="p in store.modelPresets" :key="p.id" class="preset-row">
|
||||
<input v-model="presetDrafts[p.id].label" placeholder="表示名" />
|
||||
<input v-model="presetDrafts[p.id].value" placeholder="モデル文字列" />
|
||||
<button class="mini-btn" @click="saveModelPreset(p.id)">保存</button>
|
||||
<button class="mini-btn danger" @click="store.removeModelPreset(p.id)">削除</button>
|
||||
</div>
|
||||
|
||||
<div class="preset-row new-preset">
|
||||
<input v-model="newLabel" placeholder="表示名(例: GPT-5.5)" />
|
||||
<input v-model="newValue" placeholder="モデル文字列(例: gpt-5.5)" />
|
||||
<button class="mini-btn" @click="addModelPreset">追加</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.settings-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
background: #111;
|
||||
}
|
||||
.toolbar {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 10px 12px; border-bottom: 1px solid #2a2a2a; flex-shrink: 0;
|
||||
}
|
||||
.title { font-size: 13px; font-weight: 600; color: #aaa; }
|
||||
.lock-btn {
|
||||
background: none; border: 1px solid #444; color: #aaa;
|
||||
border-radius: 5px; padding: 2px 10px; font-size: 12px; cursor: pointer;
|
||||
}
|
||||
.login { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.hint { font-size: 12px; color: #888; }
|
||||
.error { font-size: 12px; color: #f87171; }
|
||||
input {
|
||||
background: #2a2a2a; color: #eee; border: 1px solid #444;
|
||||
border-radius: 6px; padding: 6px 10px; font-size: 13px; width: 100%;
|
||||
}
|
||||
button {
|
||||
background: #1d3557; color: #93c5fd; border: 1px solid #2563eb;
|
||||
border-radius: 6px; padding: 6px 10px; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
button:disabled { opacity: 0.5; cursor: default; }
|
||||
.entries { padding: 12px; display: flex; flex-direction: column; gap: 14px; }
|
||||
.entry { display: flex; flex-direction: column; gap: 4px; }
|
||||
.entry label { font-size: 12px; color: #888; }
|
||||
.row { display: flex; gap: 6px; }
|
||||
.row input { flex: 1; }
|
||||
.clear-btn {
|
||||
background: none; border: 1px solid #444; color: #aaa;
|
||||
font-size: 12px; padding: 4px 8px; white-space: nowrap;
|
||||
}
|
||||
.save-btn { align-self: flex-start; padding: 6px 18px; }
|
||||
hr { border: none; border-top: 1px solid #2a2a2a; margin: 4px 0; }
|
||||
.section-title { font-size: 12px; color: #888; text-transform: uppercase; }
|
||||
.preset-row { display: flex; gap: 6px; align-items: center; }
|
||||
.preset-row input { flex: 1; min-width: 0; }
|
||||
.mini-btn {
|
||||
background: none; border: 1px solid #444; color: #aaa;
|
||||
font-size: 12px; padding: 6px 10px; white-space: nowrap;
|
||||
}
|
||||
.mini-btn.danger { border-color: #7f1d1d; color: #f87171; }
|
||||
.new-preset { padding-top: 4px; }
|
||||
</style>
|
||||
@@ -0,0 +1,138 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
fetchSettings,
|
||||
saveSettings,
|
||||
clearSetting,
|
||||
fetchModelPresets,
|
||||
createModelPreset,
|
||||
updateModelPreset,
|
||||
deleteModelPreset,
|
||||
type SettingEntry,
|
||||
type ModelPreset,
|
||||
} from '../api/client'
|
||||
|
||||
const STORAGE_KEY = 'playchat_settings_password'
|
||||
|
||||
export const useSettingsStore = defineStore('settings', () => {
|
||||
const password = ref(sessionStorage.getItem(STORAGE_KEY) ?? '')
|
||||
const unlocked = ref(false)
|
||||
const entries = ref<SettingEntry[]>([])
|
||||
const modelPresets = ref<ModelPreset[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
async function unlock(candidatePassword: string): Promise<boolean> {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
entries.value = await fetchSettings(candidatePassword)
|
||||
password.value = candidatePassword
|
||||
sessionStorage.setItem(STORAGE_KEY, candidatePassword)
|
||||
unlocked.value = true
|
||||
return true
|
||||
} catch (e) {
|
||||
unlocked.value = false
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** ページ再読み込み時などに、保存済みパスワードで自動的に再認証を試みる。 */
|
||||
async function tryAutoUnlock(): Promise<void> {
|
||||
if (!password.value || unlocked.value) return
|
||||
await unlock(password.value)
|
||||
}
|
||||
|
||||
async function save(values: Record<string, string>): Promise<boolean> {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
entries.value = await saveSettings(values, password.value)
|
||||
return true
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function clear(key: string): Promise<void> {
|
||||
error.value = null
|
||||
try {
|
||||
entries.value = await clearSetting(key, password.value)
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
}
|
||||
}
|
||||
|
||||
function lock() {
|
||||
unlocked.value = false
|
||||
password.value = ''
|
||||
sessionStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
|
||||
/** モデル一覧は認証不要で誰でも取得できる(ModelSelectorから直接呼ばれる想定)。 */
|
||||
async function loadModelPresets(): Promise<void> {
|
||||
try {
|
||||
modelPresets.value = await fetchModelPresets()
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
}
|
||||
}
|
||||
|
||||
async function addModelPreset(label: string, value: string): Promise<boolean> {
|
||||
error.value = null
|
||||
try {
|
||||
const created = await createModelPreset(label, value, password.value)
|
||||
modelPresets.value = [...modelPresets.value, created]
|
||||
return true
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function editModelPreset(id: number, label: string, value: string): Promise<boolean> {
|
||||
error.value = null
|
||||
try {
|
||||
const updated = await updateModelPreset(id, label, value, password.value)
|
||||
modelPresets.value = modelPresets.value.map((p) => (p.id === id ? updated : p))
|
||||
return true
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeModelPreset(id: number): Promise<void> {
|
||||
error.value = null
|
||||
try {
|
||||
await deleteModelPreset(id, password.value)
|
||||
modelPresets.value = modelPresets.value.filter((p) => p.id !== id)
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : 'エラーが発生しました'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
password,
|
||||
unlocked,
|
||||
entries,
|
||||
modelPresets,
|
||||
loading,
|
||||
error,
|
||||
unlock,
|
||||
tryAutoUnlock,
|
||||
save,
|
||||
clear,
|
||||
lock,
|
||||
loadModelPresets,
|
||||
addModelPreset,
|
||||
editModelPreset,
|
||||
removeModelPreset,
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user