Files
ai-agent/internal/ai/tooling/reply_safety.go
T
t 18c9354095 refactor: 将客服后端重构为宿主可嵌入模块
- 注入数据库、运行时配置、统一响应、文件存储和平台 AI 能力,补充业务读写工具与客户快捷操作契约。

- 移除模块内重复的组织、客户、工单、标签、技能、旧工作流、MCP 和迁移实现,将身份权限与业务主体交由宿主管理。

- 使用 libSQL 重构向量存储,并完善图片消息、访客身份、排队调度、企业微信和支持聊天页面。

- 统一 HTTP、DTO 与 WebSocket 的 snake_case 协议,补齐模块初始化、业务动作和公共载荷等回归测试。
2026-08-28 22:23:13 +08:00

72 lines
2.3 KiB
Go

package tooling
import (
"fmt"
"regexp"
"strings"
"unicode"
)
const maxCustomerReplyRunes = 8000
const restrictedNetworkPolicyFallback = "当前网络状态请以实际使用情况为准。如无法联网,请使用“智能检测”或联系人工客服。"
var restrictedNetworkPolicyPattern = regexp.MustCompile(`(?i)限速|降速|速率限制|带宽限制|speed[ _-]?limit|throttl|traffic[ _-]?shap|(?:^|[^a-z0-9])\d+(?:\.\d+)?\s*(?:k|m|g)?bps(?:[^a-z0-9]|$)`)
// NormalizeCustomerReply applies the final plain-text boundary before an AI
// response enters a customer conversation. It rejects likely credential
// assignments instead of masking them, because a masked secret is not useful
// customer-facing content.
func NormalizeCustomerReply(value string) (string, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("ai reply is empty")
}
if secretAssignmentPattern.MatchString(value) {
return "", fmt.Errorf("ai reply contains sensitive credential data")
}
var builder strings.Builder
for _, r := range value {
if unicode.IsControl(r) && r != '\n' && r != '\t' {
continue
}
builder.WriteRune(r)
}
value = strings.TrimSpace(builder.String())
for strings.Contains(value, "\n\n\n") {
value = strings.ReplaceAll(value, "\n\n\n", "\n\n")
}
value = redactRestrictedNetworkPolicy(value)
if value == "" {
return "", fmt.Errorf("ai reply is empty")
}
if len([]rune(value)) > maxCustomerReplyRunes {
return "", fmt.Errorf("ai reply exceeds maximum length")
}
return value, nil
}
// redactRestrictedNetworkPolicy is a final customer-visible safety boundary.
// The model may still ignore its system prompt, so any line that confirms,
// denies, or quantifies an internal network speed policy is removed before the
// message is persisted. Other useful lines are preserved.
func redactRestrictedNetworkPolicy(value string) string {
if !restrictedNetworkPolicyPattern.MatchString(value) {
return value
}
lines := strings.Split(value, "\n")
safe := make([]string, 0, len(lines)+1)
redacted := false
for _, line := range lines {
if restrictedNetworkPolicyPattern.MatchString(line) {
redacted = true
continue
}
safe = append(safe, line)
}
if redacted {
safe = append(safe, restrictedNetworkPolicyFallback)
}
return strings.TrimSpace(strings.Join(safe, "\n"))
}