assistant.py
7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""智能助手:助手设置(助手名称、通用提示词、对话参数)、技能(开关 / 参数 / 提示词片段)、试聊。
每句话的处理过程在「消息通道 → 消息记录」里看(/api/wecom/logs/{id}/trace);群里 @ 的机器人昵称在「消息通道 → 接收对象」里配。
话术(发给计划员的消息)只在代码里维护;后台能改的只有提示词:通用提示词 assistant.prompt 和各技能的提示词片段,
保存后下一条消息生效。
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from ..features import skills
from ..services import agent, audit, im, settings, texts
from .deps import Scope, current_store
router = APIRouter(prefix="/api/assistant", tags=["assistant"])
PROMPT_KEY = "assistant.prompt"
SETTING_FIELDS = ("name", "use_emoji", "free_reply", "history_limit", "history_chars")
class SettingsIn(BaseModel):
values: dict = {}
prompt: str | None = None # None = 不改;"" 或与默认一致 = 恢复默认
class PromptPreviewIn(BaseModel):
content: str | None = None # 未保存的通用提示词;None = 用当前生效的
class SkillIn(BaseModel):
enabled: bool | None = None # None = 不改
config: dict | None = None # None = 不改;只传要改的字段,和现有参数合并后整体校验
prompt: str | None = None # None = 不改;"" 或与默认一致 = 恢复默认
class RehearseIn(BaseModel):
text: str
session: str = "default"
def _prompt_info() -> dict:
return texts.info(PROMPT_KEY)
def _save_prompt(s: Scope, key: str, prompt: str, action: str) -> None:
"""保存 / 恢复默认一段可改的提示词(通用提示词或技能片段),写审计。"""
before, _ = texts.source(key)
content = prompt.strip()
if not content or content == texts.DEFAULTS[key].content.strip():
texts.reset(key)
audit.record(s.store_id, s.actor, f"{action}.reset", target_type="text", target_id=key,
before={"content": before})
return
try:
texts.save(key, content, s.actor.name)
except ValueError as e:
raise HTTPException(400, str(e))
audit.record(s.store_id, s.actor, f"{action}.save", target_type="text", target_id=key,
before={"content": before}, after={"content": content})
@router.get("/settings")
def get_settings(s: Scope = Depends(current_store)):
a = settings.public("assistant")
return {"values": {k: a.get(k) for k in SETTING_FIELDS}, "prompt": _prompt_info(),
"llm": {"model": settings.get().llm_model, "ready": bool(settings.get().llm_key)}}
@router.put("/settings")
def put_settings(body: SettingsIn, s: Scope = Depends(current_store)):
vals = {k: v for k, v in (body.values or {}).items() if k in SETTING_FIELDS}
if vals:
try:
before, after = settings.save("assistant", settings.get("assistant").model_dump() | vals, s.actor.name)
except Exception as e: # noqa: BLE001
raise HTTPException(400, f"设置不合法:{e}")
audit.record(s.store_id, s.actor, "assistant.update", target_type="settings", target_id="assistant",
before=before, after=after)
if body.prompt is not None:
_save_prompt(s, PROMPT_KEY, body.prompt, "assistant.prompt")
return get_settings(s)
@router.post("/prompt/preview")
def preview_prompt(body: PromptPreviewIn, s: Scope = Depends(current_store)):
"""模型实际收到的内容:系统提示词(通用提示词 + 技能片段 + 工具清单)+ 上下文(当前状态 + 最近聊天记录 + 这句话)。"""
try:
system = agent.system_prompt(s.store_id, body.content)
except Exception as e: # noqa: BLE001
return {"ok": False, "error": f"提示词渲染出错:{e}", "system": "", "context": ""}
targets = im.chat_targets(s.store_id)
ctxs = agent._contexts(s.store_id, "", "计划员", target_id=targets[0]["id"] if targets else None)
rows = im.recent_chat(s.store_id, targets[0]["contact_id"], None, agent.history_limit()) if targets else []
ctx = agent.context_text(agent.state_text(ctxs, "计划员"),
agent.history_text(rows, settings.get("assistant").name), "计划员", "(计划员说的话)")
return {"ok": True, "error": "", "system": system, "context": ctx}
# ---------------------------------------------------------------- 技能
def _skill_out(store_id: int, sk: skills.Skill) -> dict:
from .. import features
feature_on = features.is_enabled(store_id, sk.feature)
switched = skills.switched_on(store_id, sk.key)
cfg = skills.config(store_id, sk.key)
return {"key": sk.key, "name": sk.name, "summary": sk.description,
"feature": sk.feature, "feature_name": features.get(sk.feature).name, "feature_enabled": feature_on,
"enabled": switched, "active": feature_on and switched,
"tools": [{"name": t.name, "description": t.description} for t in sk.tools()],
"schema": sk.config_model.model_json_schema() if sk.config_model else None,
"config": cfg.model_dump(mode="json") if cfg is not None else None,
"prompt": texts.info(sk.prompt_key) if sk.prompt_key else None}
def _skill(key: str) -> skills.Skill:
try:
return skills.get(key)
except KeyError:
raise HTTPException(404, "技能不存在")
@router.get("/skills")
def list_skills(s: Scope = Depends(current_store)):
return {"skills": [_skill_out(s.store_id, sk) for sk in skills.all_skills()]}
@router.put("/skills/{key}")
def put_skill(key: str, body: SkillIn, s: Scope = Depends(current_store)):
sk = _skill(key)
if body.enabled is not None or body.config is not None:
try:
before, after = skills.save(s.store_id, key, enabled=body.enabled, values=body.config)
except Exception as e: # noqa: BLE001
raise HTTPException(400, f"参数不合法:{e}")
if before != after:
audit.record(s.store_id, s.actor, "assistant.skill.update", target_type="skill", target_id=key,
before=before, after=after)
if body.prompt is not None:
if not sk.prompt_key:
raise HTTPException(400, "这个技能没有提示词片段")
_save_prompt(s, sk.prompt_key, body.prompt, "assistant.skill_prompt")
return _skill_out(s.store_id, sk)
# ---------------------------------------------------------------- 试聊
def _session(s: Scope, sid: str) -> str:
return f"{s.user['id']}:{(sid or 'default')[:40]}" # 每个后台用户各自的试聊会话
@router.post("/rehearse")
async def rehearse(body: RehearseIn, s: Scope = Depends(current_store)):
if not body.text.strip():
raise HTTPException(400, "请输入一句话")
return await agent.assistant.rehearse(s.store_id, _session(s, body.session), body.text.strip()[:500])
@router.delete("/rehearse/{sid}")
def reset_rehearse(sid: str, s: Scope = Depends(current_store)):
agent.assistant.reset_rehearse(_session(s, sid))
return {"ok": True}