Fixed RPG
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import json
|
||||
import base64
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import aiosqlite
|
||||
from database.db import DB_PATH
|
||||
@@ -110,8 +111,8 @@ async def save_character(card: dict, lora_name: str = "", lora_weight: float = 0
|
||||
await db.execute(
|
||||
"""INSERT OR REPLACE INTO characters
|
||||
(card_id, name, description, personality, scenario, first_mes,
|
||||
mes_example, raw_json, lora_name, lora_weight, appearance_tags, lorebook_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
mes_example, raw_json, lora_name, lora_weight, appearance_tags, lorebook_json, avatar_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
card_id,
|
||||
card["name"],
|
||||
@@ -125,6 +126,7 @@ async def save_character(card: dict, lora_name: str = "", lora_weight: float = 0
|
||||
lora_weight,
|
||||
card.get("appearance_tags", ""),
|
||||
card["lorebook_json"],
|
||||
card.get("avatar_path", ""),
|
||||
),
|
||||
)
|
||||
await db.commit()
|
||||
@@ -171,7 +173,7 @@ async def update_appearance_tags(card_id: str, appearance_tags: str):
|
||||
|
||||
async def update_character(card_id: str, fields: dict) -> bool:
|
||||
allowed = {"name", "description", "personality", "scenario", "first_mes",
|
||||
"mes_example", "appearance_tags", "lora_name", "lora_weight"}
|
||||
"mes_example", "appearance_tags", "lora_name", "lora_weight", "avatar_path"}
|
||||
updates = {k: v for k, v in fields.items() if k in allowed}
|
||||
if not updates:
|
||||
return False
|
||||
@@ -190,6 +192,9 @@ async def import_card_file(content: bytes, filename: str, lora_name: str = "", l
|
||||
card = parse_png_card(content)
|
||||
if not card:
|
||||
raise ValueError("PNG does not contain character card metadata")
|
||||
# Use the PNG itself as avatar
|
||||
avatar_rel = _save_avatar_bytes(content, f"card_{card['card_id']}")
|
||||
card["avatar_path"] = avatar_rel
|
||||
else:
|
||||
card = parse_card_v2(json.loads(content.decode("utf-8")))
|
||||
|
||||
@@ -210,5 +215,15 @@ async def import_card_file(content: bytes, filename: str, lora_name: str = "", l
|
||||
lora_name=lora_name,
|
||||
lora_weight=lora_weight,
|
||||
appearance_tags=saved.get("appearance_tags", ""),
|
||||
avatar_path=saved.get("avatar_path", ""),
|
||||
)
|
||||
return saved
|
||||
|
||||
|
||||
def _save_avatar_bytes(png_bytes: bytes, prefix: str) -> str:
|
||||
avatars_dir = Path("static/avatars")
|
||||
avatars_dir.mkdir(parents=True, exist_ok=True)
|
||||
fname = f"{prefix}_{uuid.uuid4().hex[:8]}.png"
|
||||
path = avatars_dir / fname
|
||||
path.write_bytes(png_bytes)
|
||||
return f"avatars/{fname}"
|
||||
|
||||
@@ -31,6 +31,22 @@ async def send_message(messages: list) -> str:
|
||||
return data["choices"][0]["message"]["content"]
|
||||
|
||||
|
||||
async def send_message_with_model(messages: list, model: str) -> str:
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=90) as client:
|
||||
response = await client.post(
|
||||
OPENROUTER_URL,
|
||||
headers=HEADERS,
|
||||
json=payload
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data["choices"][0]["message"]["content"]
|
||||
|
||||
|
||||
async def stream_message(messages: list):
|
||||
"""Стриминг — отдаём чанки по мере получения"""
|
||||
payload = {
|
||||
|
||||
+290
-1
@@ -36,6 +36,17 @@ async def get_all_sessions() -> list:
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def get_session(session_id: str) -> dict | None:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"SELECT * FROM sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
async def update_session_title(session_id: str, title: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
@@ -47,16 +58,118 @@ async def update_session_title(session_id: str, title: str):
|
||||
|
||||
async def update_session_persona(session_id: str, persona_id: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"SELECT persona_id FROM sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
) as cur:
|
||||
row = await cur.fetchone()
|
||||
prev = row["persona_id"] if row else None
|
||||
|
||||
await db.execute(
|
||||
"UPDATE sessions SET persona_id = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(persona_id, session_id),
|
||||
)
|
||||
|
||||
# If persona changed, reset RPG state bound to the persona/arc.
|
||||
if prev is not None and prev != persona_id:
|
||||
await db.execute(
|
||||
"""UPDATE sessions
|
||||
SET facts_json = '[]',
|
||||
global_plot = '',
|
||||
status_quo = '',
|
||||
plot_arc_json = '{}'
|
||||
WHERE session_id = ?""",
|
||||
(session_id,),
|
||||
)
|
||||
await db.execute(
|
||||
"DELETE FROM action_resolutions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_rpg(session_id: str, rpg_enabled: bool):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET rpg_enabled = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(1 if rpg_enabled else 0, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_facts(session_id: str, facts_json: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET facts_json = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(facts_json, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_global_plot(session_id: str, global_plot: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET global_plot = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(global_plot, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_status_quo(session_id: str, status_quo: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET status_quo = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(status_quo, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_plot_arc(session_id: str, plot_arc_json: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET plot_arc_json = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(plot_arc_json, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def add_action_resolution(
|
||||
session_id: str,
|
||||
intent_text: str,
|
||||
roll: int,
|
||||
outcome: str,
|
||||
resolution_text: str,
|
||||
message_id: int | None = None,
|
||||
):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"""INSERT INTO action_resolutions
|
||||
(session_id, message_id, intent_text, roll, outcome, resolution_text)
|
||||
VALUES (?, ?, ?, ?, ?, ?)""",
|
||||
(session_id, message_id, intent_text, roll, outcome, resolution_text),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_last_action_resolution(session_id: str) -> dict | None:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"""SELECT * FROM action_resolutions
|
||||
WHERE session_id = ?
|
||||
ORDER BY id DESC LIMIT 1""",
|
||||
(session_id,),
|
||||
) as cur:
|
||||
row = await cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
async def delete_session(session_id: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))
|
||||
await db.execute("DELETE FROM rpg_quests WHERE session_id = ?", (session_id,))
|
||||
await db.execute("DELETE FROM action_resolutions WHERE session_id = ?", (session_id,))
|
||||
await db.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
|
||||
await db.commit()
|
||||
|
||||
@@ -65,13 +178,14 @@ async def get_history(session_id: str) -> list:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"""SELECT role, content, image_prompt, image_path
|
||||
"""SELECT id, role, content, image_prompt, image_path
|
||||
FROM messages WHERE session_id = ? ORDER BY id""",
|
||||
(session_id,),
|
||||
) as cursor:
|
||||
rows = await cursor.fetchall()
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"role": r["role"],
|
||||
"content": r["content"],
|
||||
"image_prompt": r["image_prompt"],
|
||||
@@ -81,6 +195,114 @@ async def get_history(session_id: str) -> list:
|
||||
]
|
||||
|
||||
|
||||
async def get_message(message_id: int) -> dict | None:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"SELECT id, session_id, role, content FROM messages WHERE id = ?",
|
||||
(message_id,),
|
||||
) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
async def update_message_content(message_id: int, content: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE messages SET content = ? WHERE id = ?",
|
||||
(content, message_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def delete_messages_after(session_id: str, message_id: int):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"DELETE FROM messages WHERE session_id = ? AND id > ?",
|
||||
(session_id, message_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def delete_message(message_id: int):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute("DELETE FROM messages WHERE id = ?", (message_id,))
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_last_message_preview(session_id: str, max_len: int = 80) -> str:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"""SELECT content, role FROM messages
|
||||
WHERE session_id = ? AND role IN ('user', 'assistant')
|
||||
ORDER BY id DESC LIMIT 1""",
|
||||
(session_id,),
|
||||
) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
if not row:
|
||||
return ""
|
||||
prefix = "Вы: " if row["role"] == "user" else "AI: "
|
||||
text = (row["content"] or "").replace("\n", " ").strip()
|
||||
if len(text) > max_len:
|
||||
text = text[:max_len] + "…"
|
||||
return prefix + text
|
||||
|
||||
|
||||
async def fork_session(source_session_id: str, until_message_id: int) -> str | None:
|
||||
source = await get_session(source_session_id)
|
||||
if not source:
|
||||
return None
|
||||
|
||||
import uuid
|
||||
new_id = "sess_" + uuid.uuid4().hex[:8]
|
||||
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"""INSERT INTO sessions
|
||||
(session_id, persona_id, title, rpg_enabled, facts_json, global_plot,
|
||||
status_quo, plot_arc_json, genre, rpg_settings_json, affinity)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
new_id,
|
||||
source["persona_id"],
|
||||
(source.get("title") or "Новый чат") + " (ветка)",
|
||||
source.get("rpg_enabled", 0),
|
||||
source.get("facts_json", "[]"),
|
||||
source.get("global_plot", ""),
|
||||
source.get("status_quo", ""),
|
||||
source.get("plot_arc_json", "{}"),
|
||||
source.get("genre", "adventure"),
|
||||
source.get("rpg_settings_json", "{}"),
|
||||
source.get("affinity", 0),
|
||||
),
|
||||
)
|
||||
async with db.execute(
|
||||
"""SELECT role, content, image_prompt, image_path FROM messages
|
||||
WHERE session_id = ? AND id <= ? ORDER BY id""",
|
||||
(source_session_id, until_message_id),
|
||||
) as cur:
|
||||
rows = await cur.fetchall()
|
||||
for r in rows:
|
||||
await db.execute(
|
||||
"""INSERT INTO messages (session_id, role, content, image_prompt, image_path)
|
||||
VALUES (?, ?, ?, ?, ?)""",
|
||||
(new_id, r[0], r[1], r[2], r[3]),
|
||||
)
|
||||
async with db.execute(
|
||||
"SELECT title, status FROM rpg_quests WHERE session_id = ?",
|
||||
(source_session_id,),
|
||||
) as cur:
|
||||
quests = await cur.fetchall()
|
||||
for q in quests:
|
||||
await db.execute(
|
||||
"INSERT INTO rpg_quests (session_id, title, status) VALUES (?, ?, ?)",
|
||||
(new_id, q[0], q[1]),
|
||||
)
|
||||
await db.commit()
|
||||
return new_id
|
||||
|
||||
|
||||
async def add_message(
|
||||
session_id: str,
|
||||
role: str,
|
||||
@@ -131,6 +353,73 @@ async def clear_history(session_id: str):
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_affinity(session_id: str, delta: int):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET affinity = affinity + ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(delta, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_genre(session_id: str, genre: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET genre = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(genre, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def update_session_rpg_settings(session_id: str, settings_json: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE sessions SET rpg_settings_json = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
|
||||
(settings_json, session_id),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def upsert_quest(session_id: str, title: str, status: str = "active"):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
async with db.execute(
|
||||
"SELECT id FROM rpg_quests WHERE session_id = ? AND title = ?",
|
||||
(session_id, title),
|
||||
) as cur:
|
||||
row = await cur.fetchone()
|
||||
if row:
|
||||
await db.execute(
|
||||
"UPDATE rpg_quests SET status = ? WHERE id = ?",
|
||||
(status, row[0]),
|
||||
)
|
||||
else:
|
||||
await db.execute(
|
||||
"INSERT INTO rpg_quests (session_id, title, status) VALUES (?, ?, ?)",
|
||||
(session_id, title, status),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_quests(session_id: str) -> list:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
async with db.execute(
|
||||
"SELECT id, title, status FROM rpg_quests WHERE session_id = ? ORDER BY id",
|
||||
(session_id,),
|
||||
) as cur:
|
||||
rows = await cur.fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def update_quest_status(session_id: str, title: str, status: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"UPDATE rpg_quests SET status = ? WHERE session_id = ? AND title = ?",
|
||||
(status, session_id, title),
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_message_count(session_id: str) -> int:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
|
||||
+95
-4
@@ -63,9 +63,29 @@ def _row_to_persona(row: dict) -> dict:
|
||||
"lora_name": row["lora_name"] or "",
|
||||
"lora_weight": row["lora_weight"] if row["lora_weight"] is not None else 0.8,
|
||||
"appearance_tags": row["appearance_tags"] or "",
|
||||
"personality": row.get("personality", "") or "",
|
||||
"scenario": row.get("scenario", "") or "",
|
||||
"first_mes": row.get("first_mes", "") or "",
|
||||
"mes_example": row.get("mes_example", "") or "",
|
||||
"lorebook_json": row.get("lorebook_json", "[]") or "[]",
|
||||
"avatar_path": row.get("avatar_path", "") or "",
|
||||
}
|
||||
|
||||
|
||||
def build_persona_prompt(data: dict) -> str:
|
||||
parts = [
|
||||
f"You are {data.get('name', '').strip()}." if data.get("name") else "",
|
||||
f"Description: {data.get('description', '').strip()}",
|
||||
f"Personality: {data.get('personality', '').strip()}",
|
||||
f"Scenario: {data.get('scenario', '').strip()}",
|
||||
]
|
||||
ex = (data.get("mes_example") or "").strip()
|
||||
if ex:
|
||||
parts.append(f"Example dialogue:\n{ex}")
|
||||
parts.append("Stay in character. Reply as the character. Do not add image tags.")
|
||||
return "\n\n".join(p for p in parts if p and p.split(": ", 1)[-1].strip())
|
||||
|
||||
|
||||
async def get_all_personas() -> dict:
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
@@ -96,16 +116,33 @@ async def create_persona(
|
||||
lora_name: str = "",
|
||||
lora_weight: float = 0.8,
|
||||
appearance_tags: str = "",
|
||||
personality: str = "",
|
||||
scenario: str = "",
|
||||
first_mes: str = "",
|
||||
mes_example: str = "",
|
||||
lorebook_json: str = "[]",
|
||||
avatar_path: str = "",
|
||||
) -> dict:
|
||||
final_prompt = prompt.strip() or build_persona_prompt(
|
||||
{
|
||||
"name": name,
|
||||
"description": description,
|
||||
"personality": personality,
|
||||
"scenario": scenario,
|
||||
"mes_example": mes_example,
|
||||
}
|
||||
)
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute(
|
||||
"""INSERT INTO personas
|
||||
(persona_id, name, emoji, description, prompt, custom,
|
||||
sd_enabled, lora_name, lora_weight, appearance_tags)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?)""",
|
||||
sd_enabled, lora_name, lora_weight, appearance_tags,
|
||||
personality, scenario, first_mes, mes_example, lorebook_json, avatar_path)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
persona_id, name, emoji, description, prompt,
|
||||
persona_id, name, emoji, description, final_prompt,
|
||||
1 if sd_enabled else 0, lora_name, lora_weight, appearance_tags,
|
||||
personality, scenario, first_mes, mes_example, lorebook_json, avatar_path,
|
||||
),
|
||||
)
|
||||
await db.commit()
|
||||
@@ -113,12 +150,18 @@ async def create_persona(
|
||||
"name": name,
|
||||
"emoji": emoji,
|
||||
"description": description,
|
||||
"prompt": prompt,
|
||||
"prompt": final_prompt,
|
||||
"custom": True,
|
||||
"sd_enabled": sd_enabled,
|
||||
"lora_name": lora_name,
|
||||
"lora_weight": lora_weight,
|
||||
"appearance_tags": appearance_tags,
|
||||
"personality": personality,
|
||||
"scenario": scenario,
|
||||
"first_mes": first_mes,
|
||||
"mes_example": mes_example,
|
||||
"lorebook_json": lorebook_json,
|
||||
"avatar_path": avatar_path,
|
||||
}
|
||||
|
||||
|
||||
@@ -166,3 +209,51 @@ async def update_persona_prompt(persona_id: str, prompt: str):
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
await db.execute("UPDATE personas SET prompt = ? WHERE persona_id = ?", (prompt, persona_id))
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def patch_persona(persona_id: str, fields: dict) -> bool:
|
||||
allowed = {
|
||||
"name",
|
||||
"emoji",
|
||||
"description",
|
||||
"prompt",
|
||||
"sd_enabled",
|
||||
"lora_name",
|
||||
"lora_weight",
|
||||
"appearance_tags",
|
||||
"personality",
|
||||
"scenario",
|
||||
"first_mes",
|
||||
"mes_example",
|
||||
"lorebook_json",
|
||||
"avatar_path",
|
||||
}
|
||||
updates = {k: v for k, v in fields.items() if k in allowed}
|
||||
if not updates:
|
||||
return False
|
||||
|
||||
async with aiosqlite.connect(DB_PATH) as db:
|
||||
db.row_factory = aiosqlite.Row
|
||||
# disallow editing built-in personas
|
||||
async with db.execute("SELECT custom FROM personas WHERE persona_id = ?", (persona_id,)) as cur:
|
||||
row = await cur.fetchone()
|
||||
if not row or not row[0]:
|
||||
return False
|
||||
|
||||
# rebuild prompt if user didn't explicitly set it
|
||||
raw_fields = {"name", "description", "personality", "scenario", "mes_example"}
|
||||
if "prompt" not in updates and (raw_fields & updates.keys()):
|
||||
async with db.execute("SELECT * FROM personas WHERE persona_id = ?", (persona_id,)) as cur:
|
||||
existing = await cur.fetchone()
|
||||
if existing:
|
||||
merged = dict(existing)
|
||||
merged.update(updates)
|
||||
updates["prompt"] = build_persona_prompt(merged)
|
||||
|
||||
cols = ", ".join(f"{k} = ?" for k in updates)
|
||||
cur2 = await db.execute(
|
||||
f"UPDATE personas SET {cols} WHERE persona_id = ?",
|
||||
(*updates.values(), persona_id),
|
||||
)
|
||||
await db.commit()
|
||||
return cur2.rowcount > 0
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from services.llm import send_message_with_model, send_message
|
||||
|
||||
FACTS_MODEL = os.getenv("RPG_FACTS_MODEL", "").strip() or "deepseek/deepseek-chat-v3"
|
||||
|
||||
FACTS_SYSTEM = """Extract stable facts from the conversation.
|
||||
Return ONLY valid JSON (no markdown), as an array of short strings.
|
||||
Rules:
|
||||
- Facts must be durable (names, relations, inventory, locations, world rules).
|
||||
- Do not include ephemeral actions unless they change state.
|
||||
- Avoid duplicates.
|
||||
- Keep each fact <= 120 chars.
|
||||
Example output:
|
||||
["User name is Alex", "We are in a ruined castle", "NPC Mira distrusts the user"]"""
|
||||
|
||||
|
||||
def merge_facts(existing_json: str, new_facts: list[str], limit: int = 80) -> str:
|
||||
try:
|
||||
existing = json.loads(existing_json or "[]")
|
||||
if not isinstance(existing, list):
|
||||
existing = []
|
||||
except json.JSONDecodeError:
|
||||
existing = []
|
||||
|
||||
seen = {str(x).strip() for x in existing if str(x).strip()}
|
||||
merged = [str(x).strip() for x in existing if str(x).strip()]
|
||||
for f in new_facts:
|
||||
s = str(f).strip()
|
||||
if not s or s in seen:
|
||||
continue
|
||||
seen.add(s)
|
||||
merged.append(s)
|
||||
|
||||
if len(merged) > limit:
|
||||
merged = merged[-limit:]
|
||||
return json.dumps(merged, ensure_ascii=False)
|
||||
|
||||
|
||||
async def extract_facts(context_messages: list[dict]) -> list[str]:
|
||||
# Build a compact transcript
|
||||
transcript = "\n".join(
|
||||
f"{m.get('role')}: {m.get('content','')}".strip()
|
||||
for m in context_messages
|
||||
if m.get("role") in ("user", "assistant")
|
||||
)[-6000:]
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": FACTS_SYSTEM},
|
||||
{"role": "user", "content": transcript},
|
||||
]
|
||||
|
||||
raw = await (send_message_with_model(messages, FACTS_MODEL) if FACTS_MODEL else send_message(messages))
|
||||
try:
|
||||
data = json.loads(raw.strip())
|
||||
if isinstance(data, list):
|
||||
return [str(x) for x in data][:40]
|
||||
except Exception:
|
||||
return []
|
||||
return []
|
||||
|
||||
|
||||
def facts_to_prompt(facts_json: str, max_items: int = 20) -> str:
|
||||
try:
|
||||
facts = json.loads(facts_json or "[]")
|
||||
if not isinstance(facts, list):
|
||||
return ""
|
||||
except json.JSONDecodeError:
|
||||
return ""
|
||||
facts = [str(x).strip() for x in facts if str(x).strip()]
|
||||
if not facts:
|
||||
return ""
|
||||
block = "\n".join(f"- {x}" for x in facts[-max_items:])
|
||||
return f"--- Facts (persistent memory) ---\n{block}\n---"
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
from services.llm import send_message_with_model
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NARRATOR_MODEL = os.getenv("RPG_NARRATOR_MODEL", "").strip() or "deepseek/deepseek-chat-v3"
|
||||
|
||||
NARRATOR_PRE_SYSTEM = """You are the System/Narrator of an RPG chat.
|
||||
Decide if the user's action requires a skill/ability check (physical action, persuasion, deception, stealth, combat, etc.).
|
||||
Pure dialogue, questions, or passive observation do NOT require a check.
|
||||
Return ONLY valid JSON (no markdown):
|
||||
{
|
||||
"needs_check": true,
|
||||
"check_reason": "brief reason why a check is needed (e.g. 'jumping over a pit')",
|
||||
"directives": ["short imperative rules for the next character reply"],
|
||||
"resolution_text": "what actually happens as result of the action — written as narrator prose (1-2 sentences). Only if needs_check=true and roll/outcome provided.",
|
||||
"status_quo_update": "optional short update about the world state"
|
||||
}
|
||||
If needs_check=false: directives may still guide tone/pacing, resolution_text must be empty string.
|
||||
If needs_check=true and roll/outcome are provided: resolution_text MUST reflect the outcome.
|
||||
- critical failure (1): embarrassing or painful failure with extra complication
|
||||
- failure (2-8): action fails, partial or no progress
|
||||
- success (9-19): action succeeds as intended
|
||||
- critical success (20): spectacular success with bonus effect"""
|
||||
|
||||
NARRATOR_POST_SYSTEM = """You are the System/Narrator of an RPG chat.
|
||||
After the character replied, update persistent state.
|
||||
Return ONLY valid JSON (no markdown):
|
||||
{
|
||||
"status_quo_update": "what changed in the world/state (1-3 sentences)",
|
||||
"facts": ["durable facts only"],
|
||||
"choices": [{"id":"a","label":"..."}, ...],
|
||||
"affinity_delta": 0,
|
||||
"quest_updates": [{"title": "quest title", "status": "active|done|failed"}]
|
||||
}
|
||||
Rules:
|
||||
- affinity_delta: integer -2..+2. Positive if character warmed up to player, negative if pushed away. 0 if neutral.
|
||||
- quest_updates: only include if a quest was clearly started, completed, or failed. Empty array otherwise.
|
||||
- choices: 0-4 options for what the player can do next."""
|
||||
|
||||
|
||||
async def narrator_pre(
|
||||
persona_name: str,
|
||||
context: str,
|
||||
global_plot: str,
|
||||
facts_block: str,
|
||||
user_message: str,
|
||||
roll: int | None = None,
|
||||
outcome: str | None = None,
|
||||
) -> dict:
|
||||
roll_block = f"Roll d20={roll}\nOutcome={outcome}\n\n" if roll is not None else ""
|
||||
user = (
|
||||
f"Persona: {persona_name}\n"
|
||||
f"{roll_block}"
|
||||
f"User action: {user_message}\n\n"
|
||||
f"Global plot:\n{global_plot}\n\n"
|
||||
f"Facts:\n{facts_block}\n\n"
|
||||
f"Recent context:\n{context}\n"
|
||||
)
|
||||
raw = await send_message_with_model(
|
||||
[{"role": "system", "content": NARRATOR_PRE_SYSTEM}, {"role": "user", "content": user}],
|
||||
NARRATOR_MODEL,
|
||||
)
|
||||
cleaned = raw.strip()
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned.split("\n", 1)[1] if "\n" in cleaned else cleaned
|
||||
if cleaned.endswith("```"):
|
||||
cleaned = cleaned.rsplit("```", 1)[0]
|
||||
cleaned = cleaned.strip()
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
except Exception:
|
||||
logger.warning("Narrator-pre JSON parse failed. Raw=%.500s", raw)
|
||||
return {"needs_check": False, "directives": [], "status_quo_update": "", "resolution_text": ""}
|
||||
|
||||
|
||||
async def narrator_post(
|
||||
persona_name: str,
|
||||
context: str,
|
||||
global_plot: str,
|
||||
facts_block: str,
|
||||
) -> dict:
|
||||
user = (
|
||||
f"Persona: {persona_name}\n\n"
|
||||
f"Global plot:\n{global_plot}\n\n"
|
||||
f"Facts:\n{facts_block}\n\n"
|
||||
f"Recent context:\n{context}\n"
|
||||
)
|
||||
raw = await send_message_with_model(
|
||||
[{"role": "system", "content": NARRATOR_POST_SYSTEM}, {"role": "user", "content": user}],
|
||||
NARRATOR_MODEL,
|
||||
)
|
||||
cleaned = raw.strip()
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned.split("\n", 1)[1] if "\n" in cleaned else cleaned
|
||||
if cleaned.endswith("```"):
|
||||
cleaned = cleaned.rsplit("```", 1)[0]
|
||||
cleaned = cleaned.strip()
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
except Exception:
|
||||
logger.warning("Narrator-post JSON parse failed. Raw=%.500s", raw)
|
||||
return {"status_quo_update": "", "facts": [], "choices": [], "affinity_delta": 0, "quest_updates": []}
|
||||
@@ -0,0 +1,105 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from services.llm import send_message_with_model, send_message
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PLOT_MODEL = os.getenv("RPG_PLOT_MODEL", "").strip() or "deepseek/deepseek-chat-v3"
|
||||
|
||||
GENRE_LABELS = {
|
||||
"adventure": "Adventure",
|
||||
"horror": "Horror",
|
||||
"romance": "Romance",
|
||||
"slice_of_life": "Slice of Life",
|
||||
"fantasy": "Fantasy",
|
||||
"sci_fi": "Sci-Fi",
|
||||
}
|
||||
|
||||
ARC_SYSTEM = """You are a narrative designer for an RPG chat.
|
||||
Given the opening scene (greeting), character info, current facts, and genre(s), produce a STRUCTURED PLOT ARC.
|
||||
Return ONLY valid JSON (no markdown):
|
||||
{
|
||||
"title": "short arc title",
|
||||
"boundaries": ["things that must remain true to preserve immersion"],
|
||||
"phase": "opening|hook|complication|reveal|climax|aftermath",
|
||||
"cast": [{"name":"NPC name","role":"helper|antagonist|bystander","motivation":"..."}],
|
||||
"secrets": ["hidden truths not revealed yet"],
|
||||
"beats": [
|
||||
{"id":"b1","trigger":"event_driven:rest|event_driven:travel|event_driven:help_request|event_driven:after_fail|event_driven:after_success",
|
||||
"injection":"1-3 sentences to introduce the beat WITHOUT breaking current scene",
|
||||
"choices":[{"id":"a","label":"..."},{"id":"b","label":"..."}]}
|
||||
],
|
||||
"next_beat_hint": "short hint for narrator what to push next"
|
||||
}
|
||||
Rules:
|
||||
- Respect the opening scene. Do not jump to unrelated characters immediately.
|
||||
- Beats must feel like natural developments fitting the genre(s). For cross-genre, blend tropes organically.
|
||||
- Keep injections immersive (in-world narration)."""
|
||||
|
||||
|
||||
def format_genres(genre: str) -> str:
|
||||
parts = [g.strip() for g in genre.replace("+", ",").split(",") if g.strip()]
|
||||
if not parts:
|
||||
return "Adventure"
|
||||
labels = [GENRE_LABELS.get(g, g.replace("_", " ").title()) for g in parts]
|
||||
if len(labels) == 1:
|
||||
return labels[0]
|
||||
return " + ".join(labels) + " (cross-genre blend)"
|
||||
|
||||
|
||||
async def generate_plot_arc(persona_name: str, persona_desc: str, persona_scenario: str, greeting: str, facts_block: str = "", genre: str = "adventure") -> dict:
|
||||
user = (
|
||||
f"Character: {persona_name}\n"
|
||||
f"Description: {persona_desc}\n"
|
||||
f"Scenario: {persona_scenario}\n"
|
||||
f"Greeting: {greeting}\n"
|
||||
f"Genre: {format_genres(genre)}\n"
|
||||
f"Facts:\n{facts_block}\n"
|
||||
).strip()
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": ARC_SYSTEM},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
raw = await (send_message_with_model(messages, PLOT_MODEL) if PLOT_MODEL else send_message(messages))
|
||||
cleaned = raw.strip()
|
||||
# common OpenRouter formatting: fenced json
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned.split("\n", 1)[1] if "\n" in cleaned else cleaned
|
||||
if cleaned.endswith("```"):
|
||||
cleaned = cleaned.rsplit("```", 1)[0]
|
||||
cleaned = cleaned.strip()
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
logger.warning("PlotArc JSON parse failed. Raw=%.500s", raw)
|
||||
return {}
|
||||
|
||||
|
||||
def should_advance_arc(user_text: str) -> str | None:
|
||||
t = (user_text or "").lower()
|
||||
if any(x in t for x in ["отдыха", "ночлег", "спим", "сон", "разбить лагерь", "лагерь", "отдохн"]):
|
||||
return "event_driven:rest"
|
||||
if any(x in t for x in ["идем дальше", "пойдем дальше", "в путь", "продолжаем путь", "уходим", "возвращаемся", "переходим"]):
|
||||
return "event_driven:travel"
|
||||
if any(x in t for x in ["помоги", "помочь", "нужна помощь", "спасите", "help"]):
|
||||
return "event_driven:help_request"
|
||||
return None
|
||||
|
||||
|
||||
def pop_matching_beats(arc: dict, trigger: str, max_beats: int = 1) -> tuple[dict, list[dict]]:
|
||||
beats = arc.get("beats", [])
|
||||
if not isinstance(beats, list):
|
||||
return arc, []
|
||||
matched, remaining = [], []
|
||||
for b in beats:
|
||||
if len(matched) < max_beats and isinstance(b, dict) and b.get("trigger") == trigger:
|
||||
matched.append(b)
|
||||
else:
|
||||
remaining.append(b)
|
||||
arc["beats"] = remaining
|
||||
return arc, matched
|
||||
|
||||
Reference in New Issue
Block a user