调整总结逻辑,支持流式回复,并且加入深度思考兼容
This commit is contained in:
@@ -219,7 +219,7 @@ class MessageSummaryPlugin(MessagePluginInterface):
|
||||
data = {
|
||||
"inputs": {},
|
||||
"query": f"请根据[{group_name}]群的群聊记录生成一份总结:\n\n{content_compress}",
|
||||
"response_mode": "blocking", # 使用阻塞模式,直接获取完整响应
|
||||
"response_mode": "streaming",
|
||||
"conversation_id": "",
|
||||
"user": group_name if group_name is not None else "message_summary_bot",
|
||||
"files": [] # 不包含文件
|
||||
@@ -233,63 +233,57 @@ class MessageSummaryPlugin(MessagePluginInterface):
|
||||
}
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
timeout = aiohttp.ClientTimeout(total=600, sock_read=120)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
async with session.post(self._api_url, headers=headers, json=data) as response:
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
response_data = await response.json()
|
||||
|
||||
response.raise_for_status()
|
||||
self.LOG.info(f"Dify API响应状态码: {response.status}")
|
||||
self.LOG.debug(f"响应数据: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
|
||||
|
||||
# 提取回答内容
|
||||
answer = response_data.get("answer", "")
|
||||
# 去除广告内容pollinations.ai 的广告
|
||||
# answer = remove_trailing_content(answer)
|
||||
spath = ""
|
||||
# 提取token使用情况
|
||||
metadata = response_data.get("metadata", {})
|
||||
usage = metadata.get("usage", {})
|
||||
|
||||
if usage:
|
||||
prompt_tokens = usage.get("prompt_tokens", 0)
|
||||
completion_tokens = usage.get("completion_tokens", 0)
|
||||
total_tokens = usage.get("total_tokens", 0)
|
||||
|
||||
# 添加token信息
|
||||
tokens_info = f"\n\n【tokens】输入: {prompt_tokens} 生成: {completion_tokens} 总: {total_tokens}"
|
||||
answer += tokens_info
|
||||
answer_parts = []
|
||||
current_event = None
|
||||
data_buffer = []
|
||||
async for raw_line in response.content:
|
||||
line = raw_line.decode("utf-8").rstrip("\n")
|
||||
if not line:
|
||||
if data_buffer:
|
||||
payload_str = "\n".join(data_buffer)
|
||||
try:
|
||||
payload = json.loads(payload_str)
|
||||
if current_event == "message":
|
||||
chunk = payload.get("answer") or ""
|
||||
if chunk:
|
||||
answer_parts.append(chunk)
|
||||
except Exception as e:
|
||||
self.LOG.debug(f"SSE数据解析失败: {e}")
|
||||
current_event = None
|
||||
data_buffer = []
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
continue
|
||||
if line.startswith("event:"):
|
||||
current_event = line.split(":", 1)[1].strip()
|
||||
continue
|
||||
if line.startswith("data:"):
|
||||
data_buffer.append(line[5:].strip())
|
||||
continue
|
||||
answer = "".join(answer_parts)
|
||||
spath = None
|
||||
if answer:
|
||||
try:
|
||||
# 使用唯一文件名并指定完整路径
|
||||
timestamp = int(time.time())
|
||||
output_path = f"summary_{timestamp}.png"
|
||||
# 构建完整的输出路径
|
||||
self.LOG.info(f"开始生成图片: {output_path}")
|
||||
spath = await convert_md_str_to_image(answer, output_path)
|
||||
self.LOG.info(f"成功生成图片: {spath}")
|
||||
except Exception as e:
|
||||
self.LOG.error(f"生成图片失败: {e}", exc_info=True)
|
||||
# 如果图片生成失败,尝试发送纯文本消息
|
||||
try:
|
||||
# 截断过长的文本,避免消息太长
|
||||
max_length = 2000
|
||||
if len(answer) > max_length:
|
||||
answer = answer[:max_length] + "\n\n... (内容过长,已截断)"
|
||||
self.LOG.info("图片生成失败,将发送文本消息作为备选方案")
|
||||
spath = None # 设置为None,让调用方知道需要发送文本
|
||||
except Exception as fallback_error:
|
||||
self.LOG.error(f"备选文本发送也失败: {fallback_error}")
|
||||
spath = None
|
||||
# 返回文本内容和图片路径
|
||||
max_length = 2000
|
||||
if len(answer) > max_length:
|
||||
answer = answer[:max_length] + "\n\n... (内容过长,已截断)"
|
||||
spath = None
|
||||
return answer, spath
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
self.LOG.error(f"请求Dify API时出错: {e}")
|
||||
return f"生成总结时出错", None
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
self.LOG.error(f"解析Dify API响应时出错: {e}")
|
||||
return "解析API响应时出错", None
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理总结时出现未知错误: {e}")
|
||||
return f"生成总结时出现未知错误", None
|
||||
|
||||
Reference in New Issue
Block a user