MaxKB是否有敏感词拦截的功能?

本篇文章将讨论通过函数库或者知识库引用的方式去拦截,实现方式有三种,可以根据场景自行决定使用那种方式比较合适。

一、调用第三方服务商或接口进行拦截

例如使用百度智能云的内容审核平台(有很多第三方服务商接口可以调用)

对接“内容审核平台-文本”接口函数:

接口调用

import requests

API_KEY = "tCDe********"

SECRET_KEY = "DO9**************"

def get_access_token():

    """

    使用 AK,SK 生成鉴权签名(Access Token)

    :return: access_token,或是None(如果错误)

    """

    url = "https://aip.baidubce.com/oauth/2.0/token"

    params = {"grant_type""client_credentials""client_id": API_KEY, "client_secret": SECRET_KEY}

    return str(requests.post(url, params=params).json().get("access_token"))

def sensitive_words(text):

    url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + get_access_token()

    payload = 'text='+text+''

    headers = {

        'Content-Type''application/x-www-form-urlencoded',

        'Accept''application/json'

    }

    response = requests.request("POST", url, headers=headers, data=payload.encode('utf-8'))

    # 解析并打印JSON响应

    weather_data = response.json()

    return weather_data['conclusion']

在函数库中配置输入变量:

read-normal-img

read-normal-img

效果预览:

read-normal-img

二、通过数据字典进行拦截

采用的是读取数据库中记录的敏感词汇判断是否匹配进行拦截

创建敏感词表结构并插入数据:

表结构

CREATE TABLE sensitive_words (

    id INT AUTO_INCREMENT PRIMARY KEY,

    word VARCHAR(255) NOT NULL

);

INSERT INTO sensitive_words (word) VALUES ('独家新闻'), ('经济'), ('政治');

创建查询数据字典的函数:

接口调用

import re

import mysql.connector

from mysql.connector import Error

  

  

def check_sensitive_words(text):

    """

    :param query: 要执行的SQL查询

    :return: 查询结果

    """

    connection = None

    result = None

    try:

        connection = mysql.connector.connect(

            host= "10.1.xx.xx",

            user= "xxxx",

            passwd= "xxxxx",

            database= "xxxxxx"

        )

        if connection.is_connected():

            cursor = connection.cursor()

            query = "SELECT word FROM sensitive_words;"

            cursor.execute(query)

            sensitive_words = cursor.fetchall()

            cursor.close()

            result = [word[0for word in sensitive_words]

            pattern = re.compile('|'.join(re.escape(word) for word in result))

            # 查找所有匹配项

            matches = pattern.findall(text)

            # 如果找到敏感词,返回匹配的词;否则,返回 None

            if matches:

                result = "不合规"

            else:

                result = "合规"

    except Error as e:

        print(f"Error while connecting to MySQL {e}")

    finally:

        if connection.is_connected():

            cursor.close()

            connection.close()

            print("MySQL connection is closed")

    return result

在函数库中配置输入变量:

read-normal-img

read-normal-img

效果预览:

read-normal-img

三、通过匹配敏感词汇的知识库进行拦截

创建敏感词汇的知识库,并在知识库中添加对于分段:

read-normal-img

效果预览:

read-normal-img

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐