幻觉防护栏
Hallucination Guardrail 是一项企业功能,用于验证 AI 生成内容是否有事实依据且不包含幻觉。它会将 task 输出与参考上下文进行比对,并在检测到可能的幻觉内容时提供详细反馈。
什么是幻觉?
Section titled “什么是幻觉?”当语言模型生成看起来合理、但事实上错误或并未得到所提供上下文支持的内容时,就会出现 AI 幻觉。Hallucination Guardrail 通过以下方式帮助避免这些问题:
- 将输出与参考上下文进行比较
- 评估对源材料的忠实度
- 针对有问题的内容提供详细反馈
- 支持用于验证严格程度的自定义阈值
设置 Guardrail
Section titled “设置 Guardrail”from crewai.tasks.hallucination_guardrail import HallucinationGuardrailfrom crewai import LLM
# Basic usage - will use task's expected_output as contextguardrail = HallucinationGuardrail( llm=LLM(model="gpt-4o-mini"))
# With explicit reference contextcontext_guardrail = HallucinationGuardrail( context="AI helps with various tasks including analysis and generation.", llm=LLM(model="gpt-4o-mini"))from crewai import Task
# Create your task with the guardrailtask = Task( description="Write a summary about AI capabilities", expected_output="A factual summary based on the provided context", agent=my_agent, guardrail=guardrail # Add the guardrail to validate output)自定义阈值验证
Section titled “自定义阈值验证”如果需要更严格的验证,可以设置自定义的 faithfulness 阈值(0-10 量表):
# Strict guardrail requiring high faithfulness scorestrict_guardrail = HallucinationGuardrail( context="Quantum computing uses qubits that exist in superposition states.", llm=LLM(model="gpt-4o-mini"), threshold=8.0 # Requires score >= 8 to pass validation)包含工具响应上下文
Section titled “包含工具响应上下文”当你的任务使用工具时,可以把工具响应也纳入验证,以获得更准确的判断:
# Guardrail with tool response contextweather_guardrail = HallucinationGuardrail( context="Current weather information for the requested location", llm=LLM(model="gpt-4o-mini"), tool_response="Weather API returned: Temperature 22°C, Humidity 65%, Clear skies")- 上下文分析:Guardrail 将 task 输出与提供的参考上下文进行比较
- Faithfulness 评分:使用内部评估器分配一个 faithfulness 分数(0-10)
- Verdict 判定:判断内容是否忠实或包含幻觉
- 阈值检查:如果设置了自定义阈值,则按该分数进行验证
- 反馈生成:验证失败时提供详细原因
- 默认模式:使用基于 verdict 的验证(FAITHFUL vs HALLUCINATED)
- 阈值模式:要求 faithfulness 分数达到或超过指定阈值
- 错误处理:优雅处理评估错误并提供信息丰富的反馈
Guardrail 结果
Section titled “Guardrail 结果”Guardrail 会返回结构化结果,表示验证状态:
# Example of guardrail result structure{ "valid": False, "feedback": "Content appears to be hallucinated (score: 4.2/10, verdict: HALLUCINATED). The output contains information not supported by the provided context."}- valid:布尔值,表示输出是否通过验证
- feedback:验证失败时的详细说明,包括:
- Faithfulness 分数
- Verdict 分类
- 失败的具体原因
与任务系统集成
Section titled “与任务系统集成”当你把 guardrail 加到任务上时,它会在任务被标记为完成前自动验证输出:
# Task output validation flowtask_output = agent.execute_task(task)validation_result = guardrail(task_output)
if validation_result.valid: # Task completes successfully return task_outputelse: # Task fails with validation feedback raise ValidationError(validation_result.feedback)Guardrail 会与 CrewAI 的事件系统集成,以提供可观测性:
- Validation Started:开始评估 guardrail 时
- Validation Completed:评估完成并返回结果时
- Validation Failed:评估过程中发生技术错误时
- 提供完整上下文
包含 AI 输出应当依据的所有相关事实信息:
context = """Company XYZ was founded in 2020 and specializes in renewable energy solutions.They have 150 employees and generated $50M revenue in 2023.Their main products include solar panels and wind turbines.""" - 保持上下文相关
只包含与任务直接相关的信息,以避免混淆:
# Good: Focused contextcontext = "The current weather in New York is 18°C with light rain."# Avoid: Unrelated informationcontext = "The weather is 18°C. The city has 8 million people. Traffic is heavy." - 定期更新上下文
确保参考上下文反映的是当前、准确的信息。
- 从默认验证开始
先不要使用自定义阈值,了解基线表现。
- 根据需求调整
- 高风险内容:使用 8-10 的阈值以获得最高准确度
- 通用内容:使用 6-7 的阈值以获得平衡验证
- 创意内容:使用 4-5 的阈值或默认基于 verdict 的验证
- 监控并迭代
跟踪验证结果,并根据假阳性/假阴性调整阈值。
对执行时间的影响
Section titled “对执行时间的影响”- 验证开销:每个 guardrail 大约增加 1-3 秒
- LLM 效率:为评估选择高效模型(例如 gpt-4o-mini)
- 模型选择:Guardrail 评估尽量使用更小、更高效的模型
- 上下文大小:保持参考上下文简洁但完整
- 缓存:对于重复内容,考虑缓存验证结果
Validation Always Fails
可能原因:
- 上下文过于严格,或与任务输出无关
- 阈值对该类内容设置得过高
- 参考上下文包含过时信息
解决办法:
- 检查并更新上下文,使其符合任务要求
- 降低阈值,或使用默认基于 verdict 的验证
- 确保上下文是当前且准确的
False Positives (Valid Content Marked Invalid)
可能原因:
- 对创意或解释型任务设置了过高的阈值
- 上下文没有覆盖输出中的所有合法方面
- 评估模型过于保守
解决办法:
- 降低阈值,或使用默认验证
- 扩展上下文,涵盖更广泛的可接受内容
- 使用不同的评估模型进行测试
Evaluation Errors
可能原因:
- 网络连接问题
- LLM 模型不可用或被限流
- 任务输出或上下文格式不正确
解决办法:
- 检查网络连接和 LLM 服务状态
- 为瞬时失败实现重试逻辑
- 在 guardrail 评估前验证 task 输出格式
需要帮助?
联系我们的支持团队,获取 hallucination guardrail 配置或故障排查方面的帮助。