新增快手(Kuaishou)渠道扩展,支持在 Yuxi 平台中集成快手客服渠道。 包含以下功能模块: - api: 快手 API 客户端封装 - accounts: 账户管理 - config: 渠道配置管理 - gateway: SSE/WebSocket 网关接入 - webhook: Webhook 事件处理 - outbound: 外发消息管理 - streaming: 流式消息处理 - pairing: 用户配对与绑定 - security: 安全校验 - signature: 请求签名验证 - dedupe: 消息去重 - monitor: 渠道状态监控 - status: 会话状态管理 - media: 媒体资源处理 - types: 类型定义
59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import logging
|
||
|
||
from .types import OutboundResult
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# 默认块级流式参数(经验值,P2-2 阶段需根据官方频率限制调整)
|
||
DEFAULT_MIN_CHARS = 800
|
||
DEFAULT_MAX_CHARS = 1200
|
||
DEFAULT_BLOCK_DELAY_MS = 400
|
||
|
||
|
||
class KuaishouBlockStreaming:
|
||
def __init__(
|
||
self,
|
||
outbound,
|
||
min_chars: int = DEFAULT_MIN_CHARS,
|
||
max_chars: int = DEFAULT_MAX_CHARS,
|
||
block_delay_ms: int = DEFAULT_BLOCK_DELAY_MS,
|
||
):
|
||
self._outbound = outbound
|
||
self._min_chars = min_chars
|
||
self._max_chars = max_chars
|
||
self._block_delay_ms = block_delay_ms
|
||
|
||
async def stream_text(
|
||
self,
|
||
to_user_id: str,
|
||
content: str,
|
||
) -> list[OutboundResult]:
|
||
results: list[OutboundResult] = []
|
||
pos = 0
|
||
|
||
while pos < len(content):
|
||
chunk_end = min(pos + self._max_chars, len(content))
|
||
|
||
if chunk_end < len(content):
|
||
break_point = content.rfind("\n", pos, chunk_end)
|
||
if break_point > pos + self._min_chars:
|
||
chunk_end = break_point
|
||
|
||
chunk = content[pos:chunk_end]
|
||
try:
|
||
result = await self._outbound.send_text(to_user_id, chunk)
|
||
results.append(result)
|
||
except Exception:
|
||
logger.exception("流式发送块失败")
|
||
# TODO(P2-2): 收到 429 时实现指数退避重试
|
||
raise
|
||
|
||
pos = chunk_end
|
||
if pos < len(content):
|
||
await asyncio.sleep(self._block_delay_ms / 1000)
|
||
|
||
return results
|