You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于RAG与NeMo Guardrails的聊天机器人集成输入输出Rails报错排查

问题解决方案

针对你在集成NeMo Guardrails输入/输出Rails时遇到的input rails token not found和COLANG解析错误,以下是具体排查和修复步骤:

1. 确认NeMo Guardrails版本兼容性

self_check_input是NeMo Guardrails的内置输入检查Rail,部分旧版本可能未包含该内置功能。执行以下命令升级到最新稳定版:

pip install nemoguardrails --upgrade

2. 修正COLANG配置语法

COLANG解析报错未知token“self_check_input”,通常是因为未正确声明内置flow或错误直接调用token。正确的COLANG配置示例:

# 声明输入检查流程
define flow self_check_input
  execute self_check_input
  if not allowed:
    respond with "你的输入违反了安全规范,请调整后重试。"
    stop

# 声明输出检查流程
define flow self_check_output
  execute self_check_output
  if not allowed:
    respond with "我无法提供符合该要求的回复。"
    stop

3. 规范配置文件结构

避免将YAML和COLANG配置混在单个文件中(易导致解析冲突),建议拆分文件:

  • config.yml(核心配置):
models:
  - type: main
    engine: openai
    model: gpt-3.5-turbo-instruct
rails:
  input:
    flows:
      - self_check_input
  output:
    flows:
      - self_check_output
  • rules.co(COLANG规则):
    将上述修正后的COLANG代码单独放入此文件。

4. 正确初始化Rails实例

确保代码中正确加载配置目录而非单个文件:

from nemoguardrails import RailsConfig, LLMRails
from langchain.llms import OpenAI

# 初始化OpenAI LLM
openai_llm = OpenAI(model_name="gpt-3.5-turbo-instruct")

# 加载配置目录(包含config.yml和rules.co)
config = RailsConfig.from_path("./guardrails_config")
rails = LLMRails(config, llm=openai_llm)

5. 自定义替代方案(若内置Rail不可用)

如果升级版本后仍无法使用self_check_input,可自定义输入检查逻辑:

  1. 在COLANG中声明自定义flow:
define flow custom_input_check
  execute check_input_violations
  if not allowed:
    respond with "你的输入不符合安全要求,请重新输入。"
    stop
  1. 在Python中实现对应的检查函数:
from nemoguardrails.actions import action

@action()
async def check_input_violations(context: dict):
    user_input = context.get("user_message", "")
    # 自定义检查逻辑(如关键词过滤、敏感内容检测)
    forbidden_words = ["敏感词1", "敏感词2"]
    if any(word in user_input for word in forbidden_words):
        return {"allowed": False}
    return {"allowed": True}
  1. 在config.yml中配置自定义flow:
rails:
  input:
    flows:
      - custom_input_check

内容的提问来源于stack exchange,提问作者Aryan Sirdesai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 07:45:00