Compare commits
6
Commits
388e9a5605
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
572f0529fb | ||
|
|
ae83d0d948 | ||
|
|
9f90de0541 | ||
|
|
6aa3559033 | ||
|
|
195099a214 | ||
|
|
2ec5c8cb9c |
@@ -32,6 +32,22 @@ async def preset():
|
||||
return STEP_PRESET
|
||||
|
||||
|
||||
@router.post("/preset/apply")
|
||||
async def apply_preset(user: User = Depends(current_user), db=Depends(get_db)):
|
||||
"""一键把 Step Plan 预设落成渠道(已有同名渠道则跳过)。"""
|
||||
from ...core.config import settings
|
||||
rows = await repos.ChannelRepo.visible_to(db, user)
|
||||
for r in rows:
|
||||
if r.name == STEP_PRESET["name"]:
|
||||
return {"applied": False, "reason": "已存在同名渠道"}
|
||||
c = Channel(name=STEP_PRESET["name"], base_url=STEP_PRESET["base_url"],
|
||||
api_key_enc=settings.step_api_key or "", models=STEP_PRESET["models"],
|
||||
owner_id=user.id if not user.is_admin else None, visibility="admin")
|
||||
db.add(c)
|
||||
await db.commit()
|
||||
return {"applied": True, "channel": _view(c)}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_channels(user: User = Depends(current_user), db=Depends(get_db)):
|
||||
rows = await repos.ChannelRepo.visible_to(db, user)
|
||||
|
||||
@@ -15,7 +15,7 @@ class CharacterIn(BaseModel):
|
||||
name: str
|
||||
persona: str = ""
|
||||
greeting: str = ""
|
||||
voice: str = "tongtong"
|
||||
voice: str = "elegantgentle-female"
|
||||
avatar_url: str = ""
|
||||
|
||||
|
||||
|
||||
+16
-5
@@ -39,6 +39,14 @@ class MessageIn(BaseModel):
|
||||
content: str
|
||||
|
||||
|
||||
PACE_GUIDE = """
|
||||
【对话节奏(重要)】
|
||||
- 像真人聊天:每次回复 1~3 句话(约 20~60 字),只推进一小步对话,把接话空间留给对方。
|
||||
- 禁止大段独白与成段描写;神态动作用极简括注(不超过一句)。
|
||||
- 不要复述对方的话,不要替对方回应,不要一次把话说完说透——留悬念等对方接。
|
||||
- 结尾尽量落在能让对方接话的位置(提问/行动/目光)。"""
|
||||
|
||||
|
||||
def _key(user):
|
||||
return security.key_cache.get(user.id)
|
||||
|
||||
@@ -77,7 +85,8 @@ async def build_context(db, user, session, history) -> list[dict]:
|
||||
msgs = []
|
||||
if session.mode == "roleplay":
|
||||
ch = await db.get(Character, session.character_id)
|
||||
persona = f"你扮演角色「{ch.name}」。人设:\n{_dec(user, ch.persona)}\n始终以该角色的口吻回复,不要出戏。"
|
||||
persona = (f"你扮演角色「{ch.name}」。人设:\n{_dec(user, ch.persona)}\n"
|
||||
"始终以该角色的口吻回复,不要出戏。" + PACE_GUIDE)
|
||||
mems = await repos.MemoryRepo.list_for(db, user.id, ch.id)
|
||||
key = _key(user)
|
||||
mem_text = "\n".join(f"- [{m.kind}] {_dec(user, m.content_enc)}" for m in mems)
|
||||
@@ -91,7 +100,9 @@ async def build_context(db, user, session, history) -> list[dict]:
|
||||
"content": ("你是小说编剧,与用户共创一部小说。用户可以控制主角行动,"
|
||||
"你负责推进剧情、描写场景与其他角色的言行。剧情需要时,"
|
||||
"你可以自主引入新的配角,给他们完整的性格与名字。\n"
|
||||
f"小说设定:\n{setting}")})
|
||||
f"小说设定:\n{setting}"
|
||||
"\n【行文节奏】每段回复 2~4 句(80 字内),画面感靠细节不靠堆字,"
|
||||
"在剧情关键处停笔,把下一步行动交给用户。")})
|
||||
scope_hits = []
|
||||
# 世界书:角色模式查 character scope,小说模式查 novel scope
|
||||
scope = "character" if session.mode == "roleplay" else "novel"
|
||||
@@ -271,11 +282,11 @@ async def tts(sid: int, mid: int, user: User = Depends(current_user),
|
||||
raise HTTPException(404, "消息不存在")
|
||||
client, models = await _channel_for(db, user, s)
|
||||
model = models.get("tts") or "stepaudio-2.5-tts"
|
||||
voice = "tongtong"
|
||||
voice = "elegantgentle-female"
|
||||
if s.character_id:
|
||||
ch = await db.get(Character, s.character_id)
|
||||
if ch:
|
||||
voice = ch.voice
|
||||
if ch and ch.voice:
|
||||
voice = ch.voice # 非法音色由 client.fix_voice 兜底
|
||||
try:
|
||||
audio = await client.tts(model, _dec(user, m.content_enc), voice)
|
||||
except Exception as e:
|
||||
|
||||
@@ -60,7 +60,8 @@ async def create_group(body: GroupIn, user: User = Depends(current_user),
|
||||
|
||||
GROUP_SYSTEM = """这是群聊场景。参与角色:{roster}。
|
||||
你控制角色「{name}」发言。其他角色的话会以【角色名】标注。
|
||||
只在轮到你说话或被@时发言,保持角色人设,不要替其他角色说话。回复保持简短口语化。"""
|
||||
只在轮到你说话或被@时发言,保持角色人设,不要替其他角色说话。
|
||||
回复必须口语化、简短:1~2 句话(30 字内),像微信群聊插话,禁止大段描写或独白。"""
|
||||
|
||||
|
||||
@router.post("/sessions/{sid}/send_group")
|
||||
@@ -101,6 +102,8 @@ async def send_group(sid: int, body: dict, user: User = Depends(current_user),
|
||||
reply = await client.chat(models.get("narrative") or "step-3.5-flash",
|
||||
[{"role": "system", "content": sysmsg}] + msgs,
|
||||
temperature=0.95)
|
||||
import re as _re
|
||||
reply = _re.sub(r"^【[^】]*】\s*", "", reply) # 剥掉模型学舌的【角色名】前缀
|
||||
m = Message(session_id=sid, user_id=user.id, role="assistant",
|
||||
speaker=c.name, content_enc=_enc(user, reply),
|
||||
swipes_enc=_enc(user, json.dumps([reply])))
|
||||
|
||||
@@ -8,6 +8,8 @@ class Settings(BaseSettings):
|
||||
jwt_expire_minutes: int = 60 * 24 * 7
|
||||
first_admin_user: str = "admin"
|
||||
first_admin_pass: str = "maopaoya-admin"
|
||||
# 默认 Step Plan 渠道的 key(为空则种渠道但不填 key,到后台补)
|
||||
step_api_key: str = ""
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
|
||||
+7
-1
@@ -12,7 +12,13 @@ def enc(key: bytes | None, text: str) -> str:
|
||||
|
||||
def dec(key: bytes | None, stored: str) -> str:
|
||||
from ..core.security import decrypt_text
|
||||
return decrypt_text(key, stored) if key else stored
|
||||
if not key:
|
||||
return stored
|
||||
try:
|
||||
return decrypt_text(key, stored)
|
||||
except Exception:
|
||||
# 密码重置/盐变更导致的旧密文:降级显示,不让整个请求 500
|
||||
return "[旧加密内容已失效]"
|
||||
|
||||
|
||||
class UserRepo:
|
||||
|
||||
@@ -38,6 +38,15 @@ async def startup():
|
||||
password_hash=security.hash_password(settings.first_admin_pass),
|
||||
kdf_salt=salt.hex(), is_admin=True))
|
||||
await db.commit()
|
||||
# 默认渠道:空库时种 Step Plan 预设(key 走 OMO_STEP_API_KEY)
|
||||
from .models.entities import Channel
|
||||
from .core.config import STEP_PRESET
|
||||
chans = (await db.execute(__import__('sqlalchemy').select(Channel))).scalars().all()
|
||||
if not chans:
|
||||
db.add(Channel(name=STEP_PRESET["name"], base_url=STEP_PRESET["base_url"],
|
||||
api_key_enc=settings.step_api_key, models=STEP_PRESET["models"],
|
||||
owner_id=None, visibility="admin"))
|
||||
await db.commit()
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
|
||||
+19
-11
@@ -44,19 +44,27 @@ class LLMClient:
|
||||
d = r.json()["data"][0]
|
||||
return d.get("url") or ("data:image/png;base64," + d.get("b64_json", ""))
|
||||
|
||||
# 阶跃 stepaudio 系合法音色(system_voices 实测 + 官方文档)
|
||||
TTS_VOICES = {"elegantgentle-female", "livelybreezy-female", "lively-girl",
|
||||
"cixingnansheng", "wenrounansheng", "shenchennanyin",
|
||||
"zhengpaiqingnian", "shuangkuainansheng", "ganliannvsheng",
|
||||
"qinhenvsheng", "huolinvsheng"}
|
||||
|
||||
@staticmethod
|
||||
def fix_voice(voice: str) -> str:
|
||||
return voice if voice in LLMClient.TTS_VOICES else "elegantgentle-female"
|
||||
|
||||
async def tts(self, model: str, text: str, voice: str) -> bytes:
|
||||
"""优先 OpenAI 兼容 /audio/speech;失败回落阶跃 stepaudio TTS 格式。"""
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
try:
|
||||
r = await get_http().post(f"{self.base_url}/audio/speech", headers=headers,
|
||||
json={"model": model, "input": text, "voice": voice})
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except httpx.HTTPError:
|
||||
r = await get_http().post(f"{self.base_url}/audio/speech", headers=headers,
|
||||
json={"model": model, "text": text, "voice": voice,
|
||||
"""OpenAI 兼容 /audio/speech;input 上限 1000 字符(stepaudio-2.5-tts)。"""
|
||||
voice = self.fix_voice(voice)
|
||||
r = await get_http().post(
|
||||
f"{self.base_url}/audio/speech",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json={"model": model, "input": text[:1000], "voice": voice,
|
||||
"response_format": "wav"})
|
||||
r.raise_for_status()
|
||||
if r.status_code >= 400:
|
||||
detail = r.text[:150]
|
||||
raise RuntimeError(f"{r.status_code}: {detail}")
|
||||
return r.content
|
||||
|
||||
async def ping(self, model: str) -> tuple[bool, str]:
|
||||
|
||||
@@ -19,4 +19,21 @@ input, textarea, select { background: rgba(255,255,255,.06); border: 1px solid r
|
||||
.spread { justify-content: space-between; }
|
||||
.tag { background: rgba(124,154,255,.18); border-radius: 8px; padding: 1px 8px;
|
||||
font-size: 11px; color: #7c9aff; }
|
||||
|
||||
/* #ifdef H5 */
|
||||
uni-input, uni-textarea { display: block; width: 100%; height: 46px; margin-bottom: 10px;
|
||||
background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.2);
|
||||
border-radius: 12px; box-sizing: border-box; }
|
||||
uni-textarea { height: 100px; }
|
||||
uni-input .uni-input-wrapper, uni-textarea .uni-textarea-wrapper {
|
||||
display: flex; flex-direction: column; justify-content: center; width: 100%; height: 100%; }
|
||||
uni-input .uni-input-input, uni-input .uni-input-placeholder,
|
||||
uni-textarea .uni-textarea-textarea, uni-textarea .uni-textarea-placeholder {
|
||||
width: 100%; height: 100%; padding: 10px 12px; font-size: 15px; color: #f2f4ff;
|
||||
box-sizing: border-box; outline: none; border: none; background: transparent;
|
||||
margin: 0; font-family: inherit; }
|
||||
uni-input .uni-input-placeholder, uni-textarea .uni-textarea-placeholder {
|
||||
color: rgba(242,244,255,.45); }
|
||||
uni-button, button { -webkit-appearance: none; }
|
||||
/* #endif */
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user