ForcePilot/backend/package/yuxi/channel/extensions/wechat-kf/streaming.py

110 lines
3.3 KiB
Python
Raw Normal View History

feat(channel): 添加微信客服、微信公众号和微信支付通知渠道扩展 新增微信客服、微信公众号、微信支付通知三个渠道扩展。 微信客服渠道扩展功能模块: - account: 账户管理 - config: 渠道配置管理 - gateway: SSE/WebSocket 网关接入 - webhook: Webhook 事件处理 - outbound: 外发消息管理 - streaming: 流式消息处理 - pairing: 用户配对与绑定 - security: 安全校验 - crypto: 加解密处理 - dedupe: 消息去重 - customer: 客户管理 - servicer: 客服管理 - session: 会话管理 - status: 会话状态管理 - media: 媒体资源处理 - statistics: 统计功能 - sync: 数据同步 - upgrade: 升级处理 微信公众号渠道扩展功能模块: - config: 渠道配置管理 - gateway: SSE/WebSocket 网关接入 - webhook: Webhook 事件处理 - outbound: 外发消息管理 - streaming: 流式消息处理 - pairing: 用户配对与绑定 - security: 安全校验 - crypto: 加解密处理 - dedupe: 消息去重 - passive_reply: 被动回复 - message: 消息处理 - broadcast: 群发消息 - template: 模板消息 - menu: 菜单管理 - qrcode: 二维码管理 - user: 用户管理 - media: 媒体资源处理 - status: 会话状态管理 微信支付通知渠道扩展功能模块: - config: 渠道配置管理 - webhook: Webhook 事件处理 - crypto: 加解密与签名校验 - cert_manager: 证书管理 - event_router: 事件路由 - dedupe: 消息去重 - pay_repo: 支付数据仓库 - query_client: 查询客户端 - arq_tasks: 异步任务 - callback_compensator: 回调补偿
2026-05-21 12:00:30 +08:00
import asyncio
import random
class WeChatKFStreaming:
streaming_mode = "block"
preview_stream_throttle_ms = 160
preview_min_initial_chars = 18
block_streaming_enabled = True
block_streaming_break = "text_end"
block_streaming_chunk_min_chars = 200
block_streaming_chunk_max_chars = 1200
block_streaming_chunk_break_preference = "paragraph"
block_streaming_coalesce_defaults = {
"min_chars": 80,
"max_chars": 400,
"idle_ms": 500,
}
ENABLED = True
STRATEGY = "block"
MIN_CHARS = 200
MAX_INTERVAL_MS = 500
MAX_BLOCKS = 5
FINISH_MARK = "[↓]"
def __init__(self, outbound=None):
self._outbound = outbound
def create_draft_stream_session(self, target_id: str) -> object:
return {"target_id": target_id, "mode": "block"}
def create_block_chunker(self) -> object:
return {"mode": "length", "min_chars": 200, "max_chars": 1200}
@classmethod
def should_stream(cls, estimated_length: int) -> bool:
return estimated_length > cls.MIN_CHARS
@classmethod
def build_chunk(cls, text: str, is_final: bool) -> str:
if is_final:
return text
return f"{text}\n{cls.FINISH_MARK}"
async def send_block_stream(self, external_user_id: str, open_kfid: str, full_text: str, session_manager) -> list:
if not self._outbound:
return []
MAX_CHUNK_CHARS = 1000
COALESCE_THRESHOLD = 500
MIN_DELAY_MS = 300
MAX_DELAY_MS = 800
session = session_manager.get_session(open_kfid, external_user_id)
remaining = 5 - (session.msg_count_in_round if session else 0)
chunks = self._split_content(full_text, max_chunks=remaining)
results = []
for chunk in chunks:
delay = random.uniform(MIN_DELAY_MS / 1000, MAX_DELAY_MS / 1000)
await asyncio.sleep(delay)
result = await self._outbound.send_text(external_user_id, open_kfid, chunk)
results.append(result)
return results
def _split_content(self, text: str, max_chunks: int = 5) -> list[str]:
if not text:
return []
char_count = len(text)
MAX_CHUNK_CHARS = 1000
COALESCE_THRESHOLD = 500
if char_count <= COALESCE_THRESHOLD:
return [text]
if max_chunks <= 1:
return [text[:MAX_CHUNK_CHARS]]
paragraphs = text.split("\n\n")
chunks = []
current = ""
for para in paragraphs:
if len(current) + len(para) + 1 <= MAX_CHUNK_CHARS:
current = f"{current}\n\n{para}" if current else para
else:
if current:
chunks.append(current)
if len(chunks) >= max_chunks - 1:
remaining_text = "\n\n".join([current, para] + paragraphs[paragraphs.index(para) + 1 :])
chunks.append(remaining_text[:MAX_CHUNK_CHARS])
return chunks
current = para
if current:
chunks.append(current)
if len(chunks) > max_chunks:
merged = ""
for chunk in chunks[max_chunks - 1 :]:
merged += chunk
chunks = chunks[: max_chunks - 1] + [merged[:MAX_CHUNK_CHARS]]
return chunks