fix(wechat-bot): ①对话时间统一北京时间 ②媒体内联发送(微信直看图片/视频) ③媒体生成计入Token驾驶舱 ④清空技能市场

This commit is contained in:
QihuAI Design committed 2026-07-15 23:37:30 +08:00
1 parent 7739f17594
commit da89a27bca
3 files changed
+166 -42

No files matched your search

+49 -13
View File
@@ -459,6 +459,9 @@ async def _generate_media_task(ai_msg_id: str, ai_model_id: str, prompt: str, us
msg.token_used = len(result) // 2
db.commit()
logger.info(f"[_generate_media_task] 消息 {ai_msg_id} 已回写内容")
# 媒体 Token 记账:把图片/视频真实消耗写入 TokenUsageLog,供驾驶舱统计。
# 主流程对媒体请求只写了占位文本的几 token,此处补写真实媒体消耗(模型名正确、数值合理)。
_write_media_token_log(db, ai_model, user_id, msg.conversation_id if msg else None, prompt)
except Exception as e:
logger.warning(f"[_generate_media_task] 后台生成异常: {e}")
finally:
@@ -468,6 +471,38 @@ async def _generate_media_task(ai_msg_id: str, ai_model_id: str, prompt: str, us
pass
def _write_media_token_log(db, ai_model, user_id: str, conversation_id: str, prompt: str):
"""媒体生成完成后补写 TokenUsageLog(图片/视频),修正此前只记占位文本的偏差。
媒体 API 不返回 token 用量,采用与 IM Bot 路径一致的估算:
视频基线 1200、图片基线 400,再加 prompt 长度的 1/4 作为提示词开销。
"""
if not user_id or not ai_model:
return
try:
is_video = "video" in (ai_model.capabilities or [])
base = 1200 if is_video else 400
est = base + (len(prompt or "") // 4)
db.add(TokenUsageLog(
id=gen_uuid(),
user_id=user_id,
model_id=ai_model.id,
model_name=ai_model.name,
conversation_id=conversation_id,
prompt_tokens=est,
completion_tokens=0,
total_tokens=est,
created_at=cst_now(),
))
db.commit()
except Exception as e:
logger.warning(f"[_write_media_token_log] 写入失败(忽略): {e}")
try:
db.rollback()
except Exception:
pass
# ============================================================
# 外部 Agent 远程调用 (Dify / n8n / Coze)
# ============================================================
@@ -2062,19 +2097,20 @@ async def send_message(
conv.knowledge_graph_count = (conv.knowledge_graph_count or 0) + 1
conv.updated_at = cst_now()
# 记录Token使用
token_usage = TokenUsageLog(
id=gen_uuid(),
user_id=current_user.id,
model_id=ai_model.id if ai_model else (req.model_id or conv.model_id),
model_name=ai_model.name if ai_model else None,
conversation_id=conv_id,
prompt_tokens=prompt_tokens or len(req.content) // 2,
completion_tokens=completion_tokens or ai_token_count,
total_tokens=total_tokens or (len(req.content) // 2 + ai_token_count),
created_at=cst_now(),
)
db.add(token_usage)
# 记录Token使用(媒体生成走 _generate_media_task 异步补写真实消耗,此处跳过避免占位文本重复记账)
if not media_generating:
token_usage = TokenUsageLog(
id=gen_uuid(),
user_id=current_user.id,
model_id=ai_model.id if ai_model else (req.model_id or conv.model_id),
model_name=ai_model.name if ai_model else None,
conversation_id=conv_id,
prompt_tokens=prompt_tokens or len(req.content) // 2,
completion_tokens=completion_tokens or ai_token_count,
total_tokens=total_tokens or (len(req.content) // 2 + ai_token_count),
created_at=cst_now(),
)
db.add(token_usage)
# 进化轨迹记录
try: