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