{
  "canonical_name": "guardrails-ai/guardrails",
  "compilation_id": "pack_2b699465cee04c8d83f29bbe39104757",
  "created_at": "2026-05-22T03:47:17.676302+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=skill, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=skill, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install guardrails-ai` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install guardrails-ai",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_30eca47d4c774492a3214c468ad9b477"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_85e45fa2bef2a40f01fa3b66fcd9a8d9",
    "canonical_name": "guardrails-ai/guardrails",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/guardrails-ai/guardrails",
    "slug": "guardrails",
    "source_packet_id": "phit_e9ea46b293f64b34915485deb0d15835",
    "source_validation_id": "dval_4e8dcba9fe0c48c2ac835e2e5a64cd86"
  },
  "merchandising": {
    "best_for": "需要安全审查与权限治理能力，并使用 chatgpt的用户",
    "github_forks": 599,
    "github_stars": 6843,
    "one_liner_en": "Adding guardrails to large language models.",
    "one_liner_zh": "Adding guardrails to large language models.",
    "primary_category": {
      "category_id": "security-permissions",
      "confidence": "high",
      "name_en": "Security & Permissions",
      "name_zh": "安全审查与权限治理",
      "reason": "curated popular coverage category matched project identity"
    },
    "target_user": "使用 chatgpt 等宿主 AI 的用户",
    "title_en": "guardrails",
    "title_zh": "guardrails 能力包",
    "visible_tags": [
      {
        "label_en": "Knowledge Retrieval",
        "label_zh": "知识检索",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-knowledge-retrieval",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_e9ea46b293f64b34915485deb0d15835",
  "page_model": {
    "artifacts": {
      "artifact_slug": "guardrails",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install guardrails-ai",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/guardrails-ai/guardrails#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "知识检索",
        "知识库问答",
        "结构化数据提取",
        "断点恢复流程",
        "开源工具"
      ],
      "eyebrow": "安全审查与权限治理",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要安全审查与权限治理能力，并使用 chatgpt的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Adding guardrails to large language models."
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "chatgpt",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "skill, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_69600563346341a386aa86c6af5d1274 | https://github.com/guardrails-ai/guardrails/issues/1448 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature request: OWASP ASI06 memory poisoning guard validator",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_e44b7cdf7b674acf9789c9feddc13dbc | https://github.com/guardrails-ai/guardrails/issues/1488 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Feature request: OWASP ASI06 memory poisoning guard validator",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Portable evidence artifacts for validation outcomes",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_ef2970465bbe44c89b513edd115b682c | https://github.com/guardrails-ai/guardrails/issues/1457 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Portable evidence artifacts for validation outcomes",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: Agent Threat Rules detection integration",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_64ae6a0aa3324a3a9af980f2f61a5c30 | https://github.com/guardrails-ai/guardrails/issues/1471 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Proposal: Agent Threat Rules detection integration",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_d7163e193eb54aab837d87b3ecd73991 | https://github.com/guardrails-ai/guardrails/issues/1453 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[bug] 429 Rate Limit Error from Opting into Metrics",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_3c9ae4fdd14547eea3c3a4be6ac6fb23 | https://github.com/guardrails-ai/guardrails/issues/1385 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[bug] 429 Rate Limit Error from Opting into Metrics",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：[docs] Fix double logo display in pypi",
            "category": "能力坑",
            "evidence": [
              "community_evidence:github | cevd_084985c7cb4d4238a44e452b14b2eaf9 | https://github.com/guardrails-ai/guardrails/issues/1362 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[docs] Fix double logo display in pypi",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "Developers should check this security_permissions risk before relying on the project: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation",
            "category": "安全/权限坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_819ae3bfce09ed33a4655a81cf59dd44 | https://github.com/guardrails-ai/guardrails/issues/1485 | Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation"
            ],
            "severity": "high",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation. Context: Observed when using python",
            "title": "失败模式：security_permissions: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication,...",
            "user_impact": "Developers may expose sensitive permissions or credentials: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation"
          },
          {
            "body": "Developers should check this security_permissions risk before relying on the project: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard",
            "category": "安全/权限坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_2c7b3b6f6709cc847b37fb56bc9973d3 | https://github.com/guardrails-ai/guardrails/issues/1476 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard",
              "failure_mode_cluster:github_issue | fmev_77887b77c9dabcdbce93e8b20c9a7c57 | https://github.com/guardrails-ai/guardrails/issues/1475 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard"
            ],
            "severity": "high",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard. Context: Observed when using python",
            "title": "失败模式：security_permissions: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard",
            "user_impact": "Developers may expose sensitive permissions or credentials: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard"
          },
          {
            "body": "Developers should check this security_permissions risk before relying on the project: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub",
            "category": "安全/权限坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_70a43b34234fca351363180353991f27 | https://github.com/guardrails-ai/guardrails/issues/1479 | [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub"
            ],
            "severity": "high",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub. Context: Observed when using python, docker, cuda",
            "title": "失败模式：security_permissions: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator wit...",
            "user_impact": "Developers may expose sensitive permissions or credentials: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_0f957598a5044976a69cdd1925dd9483 | https://github.com/guardrails-ai/guardrails/issues/1476 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: Cryptographic audit trail validator with asqav",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_8db542ceccff4a71bc11c254ce3abfde | https://github.com/guardrails-ai/guardrails/issues/1446 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Integration proposal: Cryptographic audit trail validator with asqav",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_da275c0a112848ed920af00c76fd3e1b | https://github.com/guardrails-ai/guardrails/issues/1463 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_3f90fdd47b014d488f2782f04c75b37c | https://github.com/guardrails-ai/guardrails/issues/1479 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_2a7dfe1829e559543fd3177ac3a0ace3 | https://github.com/guardrails-ai/guardrails/issues/1463 | Integration proposal: styxx hallucination validator (8-benchmark cross-validated)"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: styxx hallucination validator (8-benchmark cross-validated). Context: Observed when using python, cuda",
            "title": "失败模式：installation: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)",
            "user_impact": "Developers may fail before the first successful local run: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_b8ff8a254ff16e4d23faa27660558c49 | https://github.com/guardrails-ai/guardrails/issues/1483 | Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+). Context: Observed during installation or first-run setup.",
            "title": "失败模式：installation: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)",
            "user_impact": "Developers may fail before the first successful local run: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 38 个潜在踩坑项，其中 14 个为 high/blocking；最高优先级：安装坑 - 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 77,
        "forks": 599,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 6843
      },
      "source_url": "https://github.com/guardrails-ai/guardrails",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Adding guardrails to large language models.",
      "title": "guardrails 能力包",
      "trial_prompt": "# guardrails - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for guardrails-ai/guardrails.\n\nProject:\n- Name: guardrails\n- Repository: https://github.com/guardrails-ai/guardrails\n- Summary: Adding guardrails to large language models.\n- Host target: chatgpt\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Adding guardrails to large language models.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Adding guardrails to large language models.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. getting-started: Getting Started with Guardrails. Produce one small intermediate artifact and wait for confirmation.\n2. system-architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. guard-class: Guard Class Reference. Produce one small intermediate artifact and wait for confirmation.\n4. validators: Validators System. Produce one small intermediate artifact and wait for confirmation.\n5. schema-processing: Schema Processing. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/guardrails-ai/guardrails\n- https://github.com/guardrails-ai/guardrails#readme\n- README.md\n- guardrails/__init__.py\n- guardrails/version.py\n- guardrails/guard.py\n- guardrails/async_guard.py\n- guardrails/validator_service/validator_service_base.py\n- guardrails/classes/schema/processed_schema.py\n- guardrails/schema/pydantic_schema.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: Feature request: OWASP ASI06 memory poisoning guard validator（https://github.com/guardrails-ai/guardrails/issues/1488）；github/github_issue: Proposal: Agent Threat Rules detection integration（https://github.com/guardrails-ai/guardrails/issues/1471）；github/github_issue: Proposal: Agent Threat Rules detection integration（https://github.com/guardrails-ai/guardrails/issues/1471）；github/github_issue: Proposal: Agent Threat Rules detection integration（https://github.com/guardrails-ai/guardrails/issues/1471）；github/github_issue: Proposal: Agent Threat Rules detection integration（https://github.com/guardrails-ai/guardrails/issues/1471）；github/github_issue: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt（https://github.com/guardrails-ai/guardrails/issues/1485）；github/github_issue: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)（https://github.com/guardrails-ai/guardrails/issues/1483）；github/github_issue: [SECURITY] Supply Chain Compromise in guardrails-ai v0.10.1 on PyPI（https://github.com/guardrails-ai/guardrails/issues/1473）；github/github_issue: [bug] 429 Rate Limit Error from Opting into Metrics（https://github.com/guardrails-ai/guardrails/issues/1385）；github/github_issue: [bug] Failures and Delayed Responses from guard.validate Method Using Di（https://github.com/guardrails-ai/guardrails/issues/1479）；github/github_issue: [feat] Attempt to repair JSON before triggering NonParseableReAsk（https://github.com/guardrails-ai/guardrails/issues/1380）；github/github_issue: Feature Request: OWASP ASI06 memory write validation via Agent Memory Gu（https://github.com/guardrails-ai/guardrails/issues/1476）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Feature request: OWASP ASI06 memory poisoning guard validator",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1488"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Proposal: Agent Threat Rules detection integration",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1471"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Proposal: Agent Threat Rules detection integration",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1471"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Proposal: Agent Threat Rules detection integration",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1471"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Proposal: Agent Threat Rules detection integration",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1471"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Best-practice: litellm pin excludes patched CVE versions, unverified-jwt",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1485"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1483"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[SECURITY] Supply Chain Compromise in guardrails-ai v0.10.1 on PyPI",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1473"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[bug] 429 Rate Limit Error from Opting into Metrics",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1385"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[bug] Failures and Delayed Responses from guard.validate Method Using Di",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1479"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[feat] Attempt to repair JSON before triggering NonParseableReAsk",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1380"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Feature Request: OWASP ASI06 memory write validation via Agent Memory Gu",
              "url": "https://github.com/guardrails-ai/guardrails/issues/1476"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "安全审查与权限治理",
      "desc": "Adding guardrails to large language models.",
      "effort": "安装已验证",
      "forks": 599,
      "icon": "shield",
      "name": "guardrails 能力包",
      "risk": "可发布",
      "slug": "guardrails",
      "stars": 6843,
      "tags": [
        "知识检索",
        "知识库问答",
        "结构化数据提取",
        "断点恢复流程",
        "开源工具"
      ],
      "thumb": "purple",
      "type": "Skill Pack"
    },
    "manual": {
      "markdown": "# https://github.com/guardrails-ai/guardrails 项目说明书\n\n生成时间：2026-05-15 16:49:27 UTC\n\n## 目录\n\n- [Getting Started with Guardrails](#getting-started)\n- [System Architecture](#system-architecture)\n- [Guard Class Reference](#guard-class)\n- [Validators System](#validators)\n- [Schema Processing](#schema-processing)\n- [Execution Pipeline](#execution-pipeline)\n- [Async and Streaming Support](#async-streaming)\n- [LLM Provider Integration](#llm-providers)\n- [Framework Integrations](#framework-integrations)\n- [Creating Custom Validators](#custom-validators)\n\n<a id='getting-started'></a>\n\n## Getting Started with Guardrails\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Validators System](#validators)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md)\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/cli/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/install.py)\n- [guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n</details>\n\n# Getting Started with Guardrails\n\n## Overview\n\nGuardrails is an open-source Python library that provides validation, correction, and structural guarantees for AI/LLM applications. It enables developers to define constraints on LLM outputs and automatically validates, corrects, or re-asks the model when outputs violate those constraints. 资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\nThe library serves as a critical layer between LLM outputs and application logic, ensuring that AI-generated content meets specified quality, safety, and structural requirements.\n\n## Installation\n\n### Prerequisites\n\n- Python 3.8 or higher\n- pip or pipx\n\n### Standard Installation\n\nInstall Guardrails from PyPI:\n\n```bash\npip install guardrails-ai\n```\n\n### Development Installation\n\nFor contributors or those who want the latest features from the main branch:\n\n```bash\n# Clone the repository\ngit clone https://github.com/guardrails-ai/guardrails.git\ncd guardrails\n\n# Install in development mode\nmake dev\n\n# Install pre-commit hooks\npre-commit install\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md), [CONTRIBUTING.md](https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md)\n\n## Core Concepts\n\n### Guard\n\nThe `Guard` is the central component in Guardrails. It wraps LLM calls and applies validation rules to ensure outputs meet specified constraints.\n\n```python\nfrom guardrails import Guard, OnFailAction\n\nguard = Guard().use(\n    RegexMatch, regex=\"\\(?\\d{3}\\)?-? *\\d{3}-? *-?\\d{4}\", on_fail=OnFailAction.EXCEPTION\n)\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n### Validators\n\nValidators are individual constraint checks that can be applied to LLM outputs. They are installed from the Guardrails Hub or created as custom validators.\n\n```python\nfrom guardrails.hub import RegexMatch, CompetitorCheck, ToxicLanguage\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n### OnFailAction\n\nActions to take when validation fails:\n\n| Action | Description |\n|--------|-------------|\n| `EXCEPTION` | Raise an exception |\n| `REASK` | Re-ask the LLM to produce valid output |\n| `FIX` | Attempt to auto-fix the output |\n| `FILTER` | Filter out invalid parts |\n| `REFRAIN` | Return nothing for invalid fields |\n\n## Quick Start Guide\n\n### Step 1: Configure Guardrails Hub CLI\n\nAfter installation, configure the Guardrails CLI:\n\n```bash\nguardrails configure\n```\n\n### Step 2: Install Required Validators\n\nInstall validators from Guardrails Hub based on your use case:\n\n```bash\n# Example: Install validators for phone number validation and competitor checking\nguardrails hub install hub://guardrails/regex_match\nguardrails hub install hub://guardrails/competitor_check\nguardrails hub install hub://guardrails/toxic_language\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n### Step 3: Create a Guard\n\nCreate a Guard instance with your desired validators:\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import CompetitorCheck, ToxicLanguage\n\nguard = Guard().use(\n    CompetitorCheck([\"Apple\", \"Microsoft\", \"Google\"], on_fail=OnFailAction.EXCEPTION),\n    ToxicLanguage(threshold=0.5, validation_method=\"sentence\", on_fail=OnFailAction.EXCEPTION)\n)\n```\n\n### Step 4: Validate LLM Output\n\nApply the Guard to validate outputs:\n\n```python\n# Valid output - passes all validations\nguard.validate(\n    \"\"\"An apple a day keeps a doctor away.\n    This is good advice for keeping your health.\"\"\"\n)\n\n# Invalid output - fails validations\ntry:\n    guard.validate(\n        \"\"\"Shut the hell up! Apple just released a new iPhone.\"\"\"\n    )\nexcept Exception as e:\n    print(e)\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Application] --> B[Guard Instance]\n    B --> C[Validators Stack]\n    C --> D[LLM Call]\n    D --> E{Validation Pass?}\n    E -->|Yes| F[Return Validated Output]\n    E -->|No| G[OnFailAction Handler]\n    G --> H[EXCEPTION / REASK / FIX / FILTER / REFRAIN]\n    H --> I[Retry if REASK]\n    I --> D\n```\n\n## Creating Guards\n\n### From RAIL String\n\nRAIL (Reliable AI Abstraction Language) is an XML-based specification for defining output constraints:\n\n```python\nfrom guardrails import Guard\n\nrail_string = '''\n<rail version=\"0.1\">\n    <output>\n        <!-- Define output structure and validators -->\n    </output>\n    <prompt>\n        <!-- Define the prompt -->\n    </prompt>\n</rail>\n'''\n\nguard = Guard.from_rail_string(rail_string)\n```\n\n资料来源：[guardrails/guard.py:45-60](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### From Pydantic Model\n\nDefine output structure using Pydantic BaseModel:\n\n```python\nfrom pydantic import BaseModel, Field\nfrom guardrails import Guard\n\nclass Pet(BaseModel):\n    pet_type: str = Field(description=\"Species of pet\")\n    name: str = Field(description=\"a unique pet name\")\n\nguard = Guard.for_pydantic(Pet)\n```\n\nThe Guard uses two methods to generate structured data:\n1. **Function calling**: For LLMs that support function calling\n2. **Prompt optimization**: For LLMs that don't support function calling (schema added to prompt)\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md), [guardrails/guard.py:85-115](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n## Guardrails Hub Validators\n\nThe Guardrails Hub provides pre-built validators for common use cases:\n\n| Validator | Purpose | Example Usage |\n|-----------|---------|---------------|\n| `RegexMatch` | Validate string against regex pattern | Phone number format |\n| `CompetitorCheck` | Detect mentions of competitors | Brand safety |\n| `ToxicLanguage` | Detect toxic/offensive content | Content moderation |\n| `LowerCase` | Ensure text is lowercase | Normalization |\n| `UpperCase` | Ensure text is uppercase | Normalization |\n\n### Installing Validators\n\n```bash\n# From Guardrails Hub\nguardrails hub install hub://guardrails/<validator_name>\n\n# With specific version\nguardrails hub install hub://guardrails/regex_match~=1.4\n```\n\n资料来源：[guardrails/hub/install.py:45-60](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n\n## Validation Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant Validators\n    participant LLM\n    \n    User->>Guard: validate(input)\n    Guard->>Validators: Check constraints\n    alt Validation Failed\n        Validators-->>Guard: ValidationError\n        Guard->>Guard: Handle OnFailAction\n        alt OnFailAction.REASK\n            Guard->>LLM: Request correction\n            LLM-->>Guard: New response\n            Guard->>Validators: Re-validate\n        end\n    end\n    Guard-->>User: Validated output / Exception\n```\n\n## Creating Custom Validators\n\nUse the CLI to scaffold a new validator:\n\n```bash\nguardrails hub create-validator MyValidator\n```\n\nThis creates a template file with the required structure:\n\n```python\nfrom guardrails import Validator\nfrom guardrails.validators import ValidationResult, PassResult\n\nclass MyValidator(Validator):\n    \"\"\"Description of what your validator does.\"\"\"\n    \n    def __init__(self, arg_1: str, **kwargs):\n        # Initialize with custom arguments\n        super().__init__(**kwargs)\n    \n    def validate(self, value: Any, **kwargs) -> ValidationResult:\n        # Implement validation logic\n        if valid:\n            return PassResult()\n        else:\n            return FailResult()\n```\n\n资料来源：[guardrails/cli/hub/create_validator.py:35-70](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n\n## Development Workflow\n\nFor contributing to Guardrails:\n\n1. **Clone and setup**:\n   ```bash\n   git clone https://github.com/guardrails-ai/guardrails.git\n   cd guardrails\n   make dev\n   ```\n\n2. **Run tests**:\n   ```bash\n   make test\n   ```\n\n3. **Format code**:\n   ```bash\n   make autoformat\n   ```\n\n4. **Type checking**:\n   ```bash\n   make type\n   ```\n\n5. **Update documentation**:\n   ```bash\n   make docs-gen\n   ```\n\n资料来源：[CONTRIBUTING.md](https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md)\n\n## Call History and Debugging\n\nThe Guard maintains a history of all calls, useful for debugging and monitoring:\n\n```python\ncall = guard.validate(\"123-456-7890\")\nprint(call.iterations)  # View all iterations\nprint(call.id)          # Unique call identifier\n```\n\nEach `Call` object contains:\n- `iterations`: Stack of validation iterations\n- `inputs`: Original inputs to the Guard\n- `exception`: Any exception that occurred\n\n资料来源：[guardrails/classes/history/call.py:15-35](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n\n## CLI Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| `guardrails configure` | Configure Guardrails Hub CLI |\n| `guardrails hub install <package>` | Install a validator from Hub |\n| `guardrails hub create-validator <name>` | Create a new validator template |\n| `guardrails start` | Start the Guardrails API server |\n\n资料来源：[guardrails/cli/start.py:25-50](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/start.py), [guardrails/cli/hub/install.py:20-45](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/install.py)\n\n## Common Patterns\n\n### Input and Output Guards\n\nApply different validators to input and output:\n\n```python\nguard = Guard()\n\n# Input validation\nguard.use(InputValidator(CompetitorCheck, competitors=[...]))\n\n# Output validation  \nguard.use(OutputValidator(ToxicLanguage))\n```\n\n### Multiple Validators\n\nChain multiple validators on a single Guard:\n\n```python\nguard = Guard().use(\n    Validator1(param1=value1),\n    Validator2(param2=value2),\n    Validator3()\n)\n```\n\n### Streaming Support\n\nGuardrails supports streaming responses:\n\n```python\nguard.validate(\n    llm_output,\n    metadata={\"stream\": True}\n)\n```\n\n## Next Steps\n\n- Explore the [Guardrails Hub](https://guardrailsai.com/hub/) for available validators\n- Read the API documentation for detailed parameter descriptions\n- Join the [Discord community](https://discord.gg/Jsey3mX98B) for support\n- Check existing issues and contribute to the project\n\n---\n\n<a id='system-architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Getting Started with Guardrails](#getting-started), [Execution Pipeline](#execution-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/async_guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/async_guard.py)\n- [guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n- [guardrails/classes/schema/processed_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/schema/processed_schema.py)\n</details>\n\n# System Architecture\n\n## Overview\n\nGuardrails is a Python library for validating and constraining outputs from Large Language Models (LLMs). The system provides a flexible framework for defining validation rules (validators), composing them into Guards, and applying them to LLM outputs to ensure they meet specified quality and safety criteria.\n\n资料来源：[README.md:1-20]()\n\n## High-Level Architecture\n\nThe Guardrails system consists of several key layers that work together to provide LLM output validation:\n\n```mermaid\ngraph TB\n    subgraph \"Presentation Layer\"\n        Guard[\"Guard Class\"]\n        AsyncGuard[\"AsyncGuard Class\"]\n    end\n    \n    subgraph \"Schema Layer\"\n        ProcessedSchema[\"ProcessedSchema\"]\n        RailSchema[\"RailSchema\"]\n    end\n    \n    subgraph \"Validation Layer\"\n        ValidatorService[\"ValidatorService\"]\n        Validators[\"Validators\"]\n    end\n    \n    subgraph \"Integration Layer\"\n        LLMProviders[\"LLM Providers\"]\n        APIClient[\"APIClient\"]\n    end\n    \n    Guard --> ProcessedSchema\n    AsyncGuard --> ProcessedSchema\n    ProcessedSchema --> ValidatorService\n    ValidatorService --> Validators\n    Guard --> LLMProviders\n    Guard --> APIClient\n```\n\n资料来源：[guardrails/guard.py:1-50]()\n\n## Core Components\n\n### Guard Class\n\nThe `Guard` class is the primary entry point for using Guardrails. It serves as a container for validators and provides methods for validating LLM outputs.\n\n#### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Validator Composition** | Chain multiple validators using `.use()` method |\n| **Schema Support** | Support for RAIL, Pydantic, and JSON Schema |\n| **LLM Integration** | Built-in support for various LLM providers |\n| **History Tracking** | Records all validation iterations and outcomes |\n| **Async Support** | Separate `AsyncGuard` class for async operations |\n\n#### Factory Methods\n\n```python\n@classmethod\ndef from_rail(cls, rail_string: str, ...) -> Guard\n@classmethod\ndef for_pydantic(cls, output_class: ModelOrListOfModels, ...) -> Guard\n```\n\nThe `Guard` class provides multiple ways to create instances:\n\n1. **`from_rail()`** - Creates a Guard from a RAIL (Rich Application Information Language) string\n2. **`for_pydantic()`** - Creates a Guard using Pydantic models to define output structure\n\n资料来源：[guardrails/guard.py:200-280]()\n\n### AsyncGuard Class\n\nThe `AsyncGuard` class provides asynchronous validation capabilities, enabling non-blocking LLM output validation for high-throughput applications.\n\n#### Key Differences from Guard\n\n| Aspect | Guard | AsyncGuard |\n|--------|-------|------------|\n| Execution | Synchronous | Asynchronous (async/await) |\n| Use Case | Standard applications | High-performance async apps |\n| API | `guard.validate()` | `await guard.avalidate()` |\n\n### Validator Service\n\nThe `ValidatorService` is the core validation engine that executes validators against input data.\n\n#### Responsibilities\n\n- Load and initialize validators\n- Execute validation pipeline\n- Handle validation failures and reasks\n- Collect and aggregate validation results\n\n```mermaid\ngraph LR\n    Input[\"Input Data\"] --> ValidatorService\n    ValidatorService --> V1[\"Validator 1\"]\n    ValidatorService --> V2[\"Validator 2\"]\n    ValidatorService --> VN[\"Validator N\"]\n    V1 --> Result1[\"Result 1\"]\n    V2 --> Result2[\"Result 2\"]\n    VN --> ResultN[\"Result N\"]\n    Result1 --> Aggregated[\"Aggregated Result\"]\n    Result2 --> Aggregated\n    ResultN --> Aggregated\n```\n\n资料来源：[guardrails/validator_service/validator_service_base.py:1-50]()\n\n### ProcessedSchema\n\nThe `ProcessedSchema` class handles the parsing and processing of validation schemas into an internal format that can be executed by the validator service.\n\n#### Schema Processing Flow\n\n```mermaid\ngraph TD\n    RawSchema[\"Raw Schema Input\"] --> Parser[\"Schema Parser\"]\n    Parser --> Processed[\"ProcessedSchema\"]\n    Processed --> Serialization[\"Serialization\"]\n    Serialization --> Storage[\"Storage/Caching\"]\n    Processed --> Execution[\"Validation Execution\"]\n```\n\n资料来源：[guardrails/classes/schema/processed_schema.py:1-40]()\n\n## Validation Flow\n\n### Standard Validation Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant ProcessedSchema\n    participant ValidatorService\n    participant Validator\n    participant LLM\n\n    User->>Guard: validate(output)\n    Guard->>ProcessedSchema: parse_and_validate()\n    ProcessedSchema->>ValidatorService: run_validators()\n    ValidatorService->>Validator: validate()\n    Validator-->>ValidatorService: ValidationResult\n    ValidatorService-->>ProcessedSchema: AggregatedResult\n    ProcessedSchema-->>Guard: FinalResult\n    Guard-->>User: Result/Exception\n```\n\n### ReAsk Flow\n\nWhen initial validation fails, the system can trigger a reask mechanism:\n\n1. Validation fails for field\n2. System generates reask prompt\n3. LLM receives reask prompt\n4. New output is validated\n5. Process repeats until valid or max iterations reached\n\n资料来源：[guardrails/guard.py:300-400]()\n\n## Schema System\n\n### Supported Schema Formats\n\n| Format | Method | Description |\n|--------|--------|-------------|\n| RAIL | `Guard.from_rail()` | XML-based schema with validators |\n| Pydantic | `Guard.for_pydantic()` | Python class-based schema |\n| JSON Schema | `json_schema_to_rail_output()` | JSON schema conversion |\n\n### RAIL Schema Processing\n\nThe `rail_schema.py` module handles conversion between different schema formats:\n\n```python\ndef json_schema_to_rail_output(\n    json_schema: Dict[str, Any], \n    validator_map: ValidatorMap\n) -> str:\n    \"\"\"Takes a JSON Schema and converts it to the RAIL output specification.\"\"\"\n```\n\n资料来源：[guardrails/schema/rail_schema.py:60-80]()\n\n## History and Call Tracking\n\nThe `Call` class tracks each execution of a Guard, maintaining a history of all iterations:\n\n```python\nclass Call:\n    iterations: Stack[Iteration]  # Stack of iterations for reasks\n    inputs: CallInputs             # Original inputs to Guard\n    exception: Optional[Exception] # Any exceptions during execution\n```\n\n#### Call Structure\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| `iterations` | `Stack[Iteration]` | Each validation round and reask |\n| `inputs` | `CallInputs` | Original prompt, parameters, etc. |\n| `exception` | `Exception` | Exception if Guard execution failed |\n\n资料来源：[guardrails/classes/history/call.py:10-50]()\n\n## Integration Architecture\n\n### LLM Provider Integration\n\nGuardrails integrates with multiple LLM providers through a unified interface:\n\n```mermaid\ngraph TB\n    Guard[\"Guard Class\"]\n    ManifestCallable[\"ManifestCallable\"]\n    LiteLLMCallable[\"LiteLLMCallable\"]\n    CustomCallable[\"Custom Provider\"]\n    \n    Guard --> ManifestCallable\n    Guard --> LiteLLMCallable\n    Guard --> CustomCallable\n```\n\nSupported providers include:\n- OpenAI\n- Anthropic\n- LiteLLM (unified interface)\n- Manifest (local models)\n\n资料来源：[guardrails/llm_providers.py:1-100]()\n\n### API Client Integration\n\nThe `APIClient` enables remote Guard management:\n\n| Method | Purpose |\n|--------|---------|\n| `upsert_guard()` | Create or update a Guard on the server |\n| `fetch_guard()` | Retrieve a Guard by name |\n| `aupsert_guard()` | Async version of upsert |\n\n```python\nasync def aupsert_guard(self, guard: Guard) -> Guard:\n    existing_guard = await self.afetch_guard(guard.name)\n    if existing_guard:\n        response = await self.ahttp_client.put(...)\n    else:\n        response = await self.ahttp_client.post(...)\n```\n\n资料来源：[guardrails/api_client.py:1-80]()\n\n## Hub Integration\n\n### Validator Installation\n\nThe Hub system allows dynamic installation of validators:\n\n```python\ndef install(package_uri: str, ...) -> ModuleType:\n    # 1. Validate package URI\n    # 2. Fetch manifest\n    # 3. Download dependencies\n    # 4. Install via pip\n```\n\n#### Installation Flow\n\n```mermaid\ngraph LR\n    A[\"hub://guardrails/regex_match\"] --> B[\"ValidatorPackageService\"]\n    B --> C[\"Fetch Manifest\"]\n    C --> D[\"Install Dependencies\"]\n    D --> E[\"Load Module\"]\n```\n\n资料来源：[guardrails/hub/install.py:20-60]()\n\n## CLI Architecture\n\n### Command Structure\n\n| Command | File | Purpose |\n|---------|------|---------|\n| `guardrails configure` | CLI setup | Configure Guardrails settings |\n| `guardrails hub install` | `cli/hub/install.py` | Install validators from Hub |\n| `guardrails hub create-validator` | `cli/hub/create_validator.py` | Scaffold new validators |\n| `guardrails start` | `cli/start.py` | Start Guardrails API server |\n\n资料来源：[guardrails/cli/start.py:1-50]()\n\n## Error Handling and Logging\n\n### Log Levels\n\n| Level | Value | Usage |\n|-------|-------|-------|\n| `SPAM` | 5 | Verbose debug information |\n| `VERBOSE` | 15 | Detailed execution info |\n| `NOTICE` | 25 | Important events |\n| `SUCCESS` | 35 | Successful operations |\n\n资料来源：[guardrails/cli/logger.py:1-30]()\n\n## Summary\n\nThe Guardrails architecture follows a layered approach:\n\n1. **Presentation Layer** - `Guard` and `AsyncGuard` classes provide the user-facing API\n2. **Schema Layer** - `ProcessedSchema` and `RailSchema` handle input parsing and validation rules\n3. **Validation Layer** - `ValidatorService` executes validators and aggregates results\n4. **Integration Layer** - LLM providers and API client enable seamless integration with external services\n\nThis separation of concerns allows for:\n- Flexible validator composition\n- Multiple schema format support\n- Both sync and async operation modes\n- Extensible provider integrations\n\n---\n\n<a id='guard-class'></a>\n\n## Guard Class Reference\n\n### 相关页面\n\n相关主题：[Validators System](#validators), [Schema Processing](#schema-processing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/pydantic_schema.py)\n- [guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/rail_schema.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n- [guardrails/classes/history/call_inputs.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call_inputs.py)\n- [guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n- [guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n</details>\n\n# Guard Class Reference\n\nThe `Guard` class is the central orchestrator in the Guardrails library, serving as the primary interface for validating, parsing, and constraining LLM outputs. It acts as a container that manages validators, output schemas, and validation outcomes while maintaining execution history.\n\n## Overview\n\nThe Guard class provides a unified API for:\n\n- Defining validation rules through RAIL XML strings or Pydantic models\n- Validating LLM outputs against specified schemas and constraints\n- Parsing raw LLM responses into structured data\n- Tracking validation history across multiple iterations and reasks\n- Configuring behavior on validation failure through `OnFailAction` strategies\n\n```mermaid\ngraph TD\n    A[LLM Output] --> B[Guard Instance]\n    B --> C{Validation}\n    C -->|Pass| D[Validated Output]\n    C -->|Fail| E{OnFailAction}\n    E -->|EXCEPTION| F[Raise Exception]\n    E -->|REASK| G[Reask LLM]\n    E -->|FIX| H[Return Fixed Value]\n    E -->|[None]| I[Return None]\n    G --> A\n```\n\n## Creating Guard Instances\n\n### Factory Methods\n\nThe Guard class provides two primary factory methods for instantiation:\n\n| Method | Input Type | Use Case |\n|--------|------------|----------|\n| `Guard.from_rail()` | RAIL XML string | Complex schemas with validators |\n| `Guard.for_pydantic()` | Pydantic BaseModel | Structured data generation |\n\n### Creating from RAIL Strings\n\n```python\n@classmethod\ndef from_rail(cls, rail_string: str, *, name: str = None, description: str = None) -> \"Guard\"\n```\n\nA RAIL (Rich AI Language) string is an XML-based specification that defines:\n\n- Output schema structure\n- Field-level validators\n- Error handling behaviors\n\n```python\nfrom guardrails import Guard\n\nrail_string = \"\"\"\n<rail version=\"0.1\">\n    <output>\n        <string name=\"response\" />\n    </output>\n</rail>\n\"\"\"\n\nguard = Guard.from_rail(rail_string, name=\"my-guard\")\n```\n\n资料来源：[guardrails/guard.py:from_rail-method](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### Creating from Pydantic Models\n\n```python\n@classmethod\ndef for_pydantic(\n    cls,\n    output_class: ModelOrListOfModels,\n    *,\n    reask_messages: Optional[List[Dict]] = None,\n    messages: Optional[List[Dict]] = None,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n    output_formatter: Optional[Union[str, BaseFormatter]] = None,\n) -> \"Guard\"\n```\n\nThis method accepts Pydantic `BaseModel` classes and internally converts them to RAIL format for validation.\n\n```python\nfrom guardrails import Guard\nfrom pydantic import BaseModel, Field\n\nclass Pet(BaseModel):\n    pet_type: str = Field(description=\"Species of pet\")\n    name: str = Field(description=\"a unique pet name\")\n\nguard = Guard.for_pydantic(Pet)\n```\n\n资料来源：[guardrails/guard.py:for_pydantic-method](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### Internal Schema Processing\n\nBoth factory methods ultimately convert their input to an internal RAIL schema representation:\n\n```mermaid\ngraph LR\n    A[Pydantic Model] -->|for_pydantic| B[JSON Schema]\n    C[RAIL String] -->|from_rail| D[Schema Parser]\n    B --> D\n    D --> E[RAIL Schema]\n    E --> F[Guard Instance]\n```\n\n资料来源：[guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/rail_schema.py)\n\n## Guard Configuration\n\n### Using Validators with `Guard.use()`\n\nValidators are added to a Guard instance using the `.use()` method, which chains multiple validators onto the same instance.\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import RegexMatch, CompetitorCheck\n\nguard = Guard().use(\n    RegexMatch(regex=r\"\\d{4}\", on_fail=OnFailAction.EXCEPTION),\n    CompetitorCheck([\"Apple\", \"Google\"], on_fail=OnFailAction.REASK)\n)\n```\n\n资料来源：[README.md:example-code](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n## Validation Process\n\n### Core Validation Methods\n\n| Method | Purpose | Returns |\n|--------|---------|---------|\n| `validate()` | Validates LLM output against schema | `ValidationOutcome` |\n| `parse()` | Parses raw output without full validation | Parsed result |\n| `__call__()` | Combined call and validation | LLM response + validated output |\n\n### ValidationOutcome Class\n\nThe `ValidationOutcome` class encapsulates the results of validation:\n\n```python\n@dataclass\nclass ValidationOutcome:\n    validation_passed: bool\n    corrected_output: Any\n    error_message: Optional[str]\n    reasks: List[ReAsk]\n```\n\n资料来源：[guardrails/classes/validation_outcome.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/validation_outcome.py)\n\n### OnFailAction Enum\n\nWhen validation fails, the configured `OnFailAction` determines the behavior:\n\n| Action | Behavior |\n|--------|----------|\n| `EXCEPTION` | Raises an exception with error details |\n| `REASK` | Attempts to regenerate the LLM output with feedback |\n| `FIX` | Returns a corrected/fallback value |\n| `REFRAIN` | Returns `None` instead of output |\n| `NOOP` | Returns the original output unchanged |\n| `CUSTOM` | Uses a custom handler function |\n\n资料来源：[guardrails/types/on_fail.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/types/on_fail.py)\n\n## Call History and Iteration Tracking\n\n### Call Class Structure\n\nThe `Call` class maintains a complete history of Guard executions:\n\n```python\nclass Call:\n    _id: str | None = None\n    iterations: Stack[Iteration] = Field(default_factory=Stack)\n    inputs: CallInputs = Field(default_factory=CallInputs)\n    exception: Optional[Exception] = None\n    \n    @computed_field\n    @property\n    def id(self) -> str:\n        \"\"\"Unique identifier for this Call execution.\"\"\"\n        if not self._id:\n            self._id = str(object_id(self))\n        return self._id\n```\n\n资料来源：[guardrails/classes/history/call.py:Call-class](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n\n### Iteration Stack\n\nEach `Call` contains a stack of `Iteration` objects representing:\n\n1. The initial validation round\n2. Each subsequent reask iteration\n\n```mermaid\ngraph TD\n    A[Call] --> B[Iteration 1: Initial Call]\n    A --> C[Iteration 2: Reask 1]\n    A --> D[Iteration N: Reask N-1]\n    B --> E[Step 1: LLM Call]\n    B --> F[Step 2: Validation]\n    C --> G[Step: LLM Reask]\n    C --> H[Step: Validation]\n```\n\n### CallInputs Data Model\n\nThe `CallInputs` class captures all inputs passed to a Guard execution:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `prompt_params` | Dict | Parameters formatted into messages |\n| `num_reasks` | int | Maximum reask attempts |\n| `metadata` | Dict | Additional runtime data |\n| `full_schema_reask` | bool | Reask entire schema vs individual fields |\n| `stream` | bool | Streaming mode flag |\n| `args` | List[Any] | Additional positional arguments |\n| `kwargs` | Dict[str, Any] | Additional keyword arguments |\n\n资料来源：[guardrails/classes/history/call_inputs.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call_inputs.py)\n\n## LLM Provider Integration\n\n### PromptCallableBase Interface\n\nThe Guard class integrates with multiple LLM providers through the `PromptCallableBase` interface:\n\n```python\nclass PromptCallableBase:\n    def _invoke_llm(\n        self,\n        text: Optional[str] = None,\n        model: str = \"gpt-3.5-turbo\",\n        messages: Optional[List[Dict]] = None,\n        *args,\n        **kwargs\n    ) -> LLMResponse:\n        \"\"\"Abstract method to invoke LLM.\"\"\"\n```\n\nSupported providers include:\n\n- **LiteLLM** - Unified interface to multiple LLMs\n- **Manifest** - ML model inference client\n- **OpenAI** - Direct OpenAI API integration\n\n资料来源：[guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n\n### LLM Response Structure\n\n```python\n@dataclass\nclass LLMResponse:\n    output: Any  # The raw LLM response\n    token_usage: Optional[Dict] = None  # Token consumption metrics\n    model_name: Optional[str] = None  # Model identifier\n```\n\n## Validator Installation via Hub\n\n### Installing Validators\n\nValidators from Guardrails Hub can be installed programmatically:\n\n```python\nfrom guardrails.hub.install import install\n\nRegexMatch = install(\"hub://guardrails/regex_match\").RegexMatch\n```\n\nThe installation process:\n\n1. Validates the package URI format\n2. Fetches the module manifest\n3. Downloads dependencies via pip\n4. Installs to site-packages\n\n资料来源：[guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n\n## Complete Usage Example\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import RegexMatch, CompetitorCheck\n\n# Create a Guard with multiple validators\nguard = Guard().use(\n    RegexMatch(\n        regex=r\"\\d{3}-\\d{3}-\\d{4}\",\n        on_fail=OnFailAction.EXCEPTION\n    ),\n    CompetitorCheck(\n        competitors=[\"Apple\", \"Microsoft\"],\n        on_fail=OnFailAction.REASK\n    )\n)\n\n# Validate output\ntry:\n    result = guard.validate(\"123-456-7890\")\n    print(f\"Validation passed: {result.validation_passed}\")\nexcept Exception as e:\n    print(f\"Validation failed: {e}\")\n\n# Access call history\ncall_history = guard.history  # List of Call objects\n```\n\n## Summary\n\nThe `Guard` class serves as the central orchestrator for LLM output validation in the Guardrails library. Key responsibilities include:\n\n- **Schema Management**: Creating Guards from RAIL strings or Pydantic models\n- **Validation Orchestration**: Running validators and applying OnFailAction strategies\n- **History Tracking**: Maintaining complete execution history with iterations and steps\n- **LLM Integration**: Supporting multiple LLM providers through a unified interface\n- **Extensibility**: Allowing composition of multiple validators through the `.use()` method\n\n资料来源：[guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py), [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py), [guardrails/types/on_fail.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/types/on_fail.py)\n\n---\n\n<a id='validators'></a>\n\n## Validators System\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Creating Custom Validators](#custom-validators)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n- [guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n- [guardrails/cli/hub/create_validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n- [guardrails/telemetry/validator_tracing.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/telemetry/validator_tracing.py)\n- [guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n</details>\n\n# Validators System\n\n## Overview\n\nThe Validators System is a core component of the Guardrails framework that provides validation capabilities for LLM (Large Language Model) outputs. Validators are modular, composable validation units that can be attached to a `Guard` instance to enforce constraints on data before, during, or after LLM inference.\n\nValidators enable developers to:\n\n- Validate string, structured (JSON), and typed outputs from LLMs\n- Define custom failure handling policies via the `on_fail` mechanism\n- Chain multiple validators to create complex validation pipelines\n- Track validation history and results through the Call/Iteration data model\n\n## Architecture\n\n### High-Level Component Flow\n\n```mermaid\ngraph TD\n    A[LLM Output] --> B[Guard.validate]\n    B --> C[ValidatorService]\n    C --> D[Validator 1]\n    C --> E[Validator 2]\n    C --> F[Validator N]\n    D --> G[ValidationResult]\n    E --> H[ValidationResult]\n    F --> I[ValidationResult]\n    G --> J[ValidationOutcome]\n    H --> J\n    I --> J\n    J --> K[Pass or Fail with Corrections]\n```\n\n### Validator Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Initialized\n    Initialized --> Running: before_run_validator\n    Running --> Success: validate returns PassResult\n    Running --> Failed: validate returns FailResult\n    Success --> Completed: after_run_validator\n    Failed --> Completed: on_fail handler applied\n    Completed --> [*]\n```\n\n## Core Components\n\n### Validator Base Class\n\nValidators inherit from the base `Validator` class which provides:\n\n- Standard initialization with `on_fail` policy configuration\n- `validate(value, metadata)` method implementation contract\n- Integration with the validator service infrastructure\n- Telemetry and tracing capabilities\n\n### Validation Result Classes\n\nThe system uses two primary result types:\n\n| Class | Purpose |\n|-------|---------|\n| `PassResult` | Indicates validation succeeded |\n| `FailResult` | Indicates validation failed with error details |\n\n```mermaid\nclassDiagram\n    class ValidationResult {\n        <<abstract>>\n    }\n    class PassResult {\n        +str error_message = None\n        +ValidationResult fix_value = None\n    }\n    class FailResult {\n        +str error_message\n        +Any fix_value\n    }\n    ValidationResult <|-- PassResult\n    ValidationResult <|-- FailResult\n```\n\n### OnFailAction Policies\n\nWhen validation fails, the `on_fail` parameter determines the behavior:\n\n| Policy | Behavior |\n|--------|----------|\n| `REASK` | Trigger a reask to the LLM |\n| `FIX` | Attempt to fix the value automatically |\n| `FILTER` | Remove invalid elements |\n| `REFRAIN` | Return empty/null value |\n| `NOOP` | Return the original value unchanged |\n| `EXCEPTION` | Raise an exception |\n\n资料来源：[guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n\n## Validator Service\n\n### Sequential Validator Service\n\nThe `SequentialValidatorService` executes validators in order, one after another, stopping on the first failure unless configured otherwise.\n\nKey methods:\n\n| Method | Description |\n|--------|-------------|\n| `before_run_validator` | Prepares logging and tracking before validation |\n| `after_run_validator` | Records results and timing after validation |\n| `run_validator` | Executes a single validator's validation logic |\n\n资料来源：[guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n\n### Validation Logging\n\nThe `ValidatorLogs` class tracks each validator execution:\n\n```python\nvalidator_logs = ValidatorLogs(\n    validatorName=validator_class_name,\n    valueBeforeValidation=value,\n    registeredName=validator.rail_alias,\n    propertyPath=absolute_property_path,\n    instanceId=id(validator),\n)\n```\n\n| Field | Description |\n|-------|-------------|\n| `validatorName` | Class name of the validator |\n| `valueBeforeValidation` | Original value before validation |\n| `registeredName` | RAIL alias for the validator |\n| `propertyPath` | JSON path to the validated property |\n| `instanceId` | Memory address of validator instance |\n| `start_time` | Timestamp when validation began |\n| `end_time` | Timestamp when validation completed |\n| `validation_result` | Result of the validation |\n\n资料来源：[guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n\n## Guard Integration\n\n### Attaching Validators to Guard\n\nValidators are attached to a `Guard` instance using the `.use()` method:\n\n```python\nguard = Guard().use(\n    RegexMatch, regex=\"\\\\(?\\\\d{3}\\\\)?-? *\\\\d{3}-? *-?\\\\d{4}\"\n)\n```\n\nThe `use()` method signature:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `*validators` | Validator | Positional args for validators |\n| `on` | str | Property path (\"output\", \"messages\", \"$.property\") |\n\n```python\ndef use(\n    self,\n    *validators: Validator,\n    on: str = \"output\",\n    **kwargs,\n) -> \"Guard\":\n```\n\n资料来源：[guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### Validation Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant ValidatorService\n    participant Validator\n    participant LLM\n\n    User->>Guard: validate(llm_output)\n    Guard->>Guard: parse(llm_output)\n    Guard->>ValidatorService: run_validators()\n    ValidatorService->>Validator: before_run_validator()\n    Validator->>Validator: validate(value, metadata)\n    Validator-->>ValidatorService: ValidationResult\n    ValidatorService->>Validator: after_run_validator()\n    ValidatorService-->>Guard: ValidationOutcome\n    Guard-->>User: Pass/Fail with corrections\n```\n\n### Getting Attached Validators\n\nRetrieve validators attached to a specific property:\n\n```python\nvalidators = guard.get_validators(on=\"output\")\n```\n\n| Parameter | Valid Options | Description |\n|-----------|---------------|-------------|\n| `on` | `\"output\"`, `\"messages\"`, `\"$.path\"` | Property to query |\n\n资料来源：[guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n## Validation History Tracking\n\n### Call and Iteration Model\n\nValidation history is tracked through a hierarchical model:\n\n```mermaid\nclassDiagram\n    class Call {\n        +str id\n        +Stack~Iteration~ iterations\n        +CallInputs inputs\n        +Exception exception\n    }\n    class Iteration {\n        +Step[] steps\n        +IterationOutputs outputs\n    }\n    class Step {\n        +ValidatorLogs[] validator_logs\n    }\n    Call \"1\" --> \"*\" Iteration\n    Iteration \"1\" --> \"*\" Step\n```\n\n| Class | Purpose |\n|-------|---------|\n| `Call` | Represents a single Guard execution (validate/parse/call) |\n| `Iteration` | A single validation round, including reasks |\n| `Step` | Contains validator execution logs |\n\n资料来源：[guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n\n### Call Inputs\n\nThe `CallInputs` class captures the original inputs to each Guard invocation:\n\n- `llm_output`: Raw LLM response\n- ` Prompt parameters and messages\n- Configuration options passed during validation\n\n## Telemetry and Tracing\n\n### Validator Tracing\n\nThe validator tracing system provides observability into validation execution:\n\n```mermaid\ngraph TD\n    A[Validate Request] --> B[trace_validator_decorator]\n    B --> C[Create Span]\n    C --> D[Execute Validator]\n    D --> E{Success?}\n    E -->|Yes| F[Record PassResult]\n    E -->|No| G[Record FailResult]\n    F --> H[Add Attributes]\n    G --> H\n    H --> I[Close Span]\n    I --> J[Return Result]\n```\n\nKey tracing attributes:\n\n| Attribute | Description |\n|-----------|-------------|\n| `validator_name` | Name of the validator class |\n| `validator_span` | OpenTelemetry span reference |\n| `obj_id` | Object identifier |\n| `on_fail_descriptor` | Policy applied on failure |\n| `init_kwargs` | Validator initialization arguments |\n| `validation_session_id` | Session identifier |\n\n资料来源：[guardrails/telemetry/validator_tracing.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/telemetry/validator_tracing.py)\n\n## Creating Custom Validators\n\n### Validator Template\n\nThe CLI command `guardrails create-validator` generates a template:\n\n```bash\nguardrails create-validator MyValidator\n```\n\nGenerated template structure:\n\n```python\nfrom guardrails import Validator\nfrom guardrails.properties import register_validator\nfrom guardrails.classes import ValidationResult\n\n@register_validator(name=\"my_validator\", fmt=\"native\")\nclass MyValidator(Validator):\n    \"\"\"Validator description.\n    \n    Args:\n        arg_1: Description of the argument.\n        on_fail: Policy when validation fails.\n    \"\"\"\n    \n    def __init__(\n        self,\n        arg_1: str,\n        on_fail: Optional[Callable] = None,\n    ):\n        super().__init__(on_fail=on_fail, arg_1=arg_1)\n        self._arg_1 = arg_1\n\n    def validate(self, value: Any, metadata: Dict) -> ValidationResult:\n        \"\"\"Validates the input value.\n        \n        Args:\n            value: The value to validate.\n            metadata: Additional context for validation.\n        \"\"\"\n        if value != \"pass\":\n            return FailResult(\n                error_message=\"Value must be 'pass'\",\n                fix_value=\"fails\"\n            )\n        return PassResult()\n```\n\n资料来源：[guardrails/cli/hub/create_validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n\n### Validator Registration\n\nValidators are registered using the `@register_validator` decorator:\n\n| Parameter | Description |\n|-----------|-------------|\n| `name` | Unique identifier for the validator |\n| `fmt` | Format (\"native\" or \"raw\") |\n| `rail_alias` | RAIL XML alias |\n\n## Hub Installation\n\n### Installing Validators from Hub\n\nValidators can be installed from Guardrails Hub:\n\n```bash\nguardrails hub install hub://guardrails/regex_match\n```\n\nThe `install()` function:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `package_uri` | str | Hub package URI (e.g., `hub://guardrails/regex_match`) |\n| `quiet` | bool | Suppress output |\n| `upgrade` | bool | Force upgrade to latest |\n\n```python\n>>> RegexMatch = install(\"hub://guardrails/regex_match\").RegexMatch\n>>> RegexMatch = install(\"hub://guard://guardrails/regex_match~=1.4\").RegexMatch\n```\n\n资料来源：[guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n\n### Installation Process\n\n```mermaid\ngraph LR\n    A[Install Request] --> B[Get Validator ID]\n    B --> C[Fetch Manifest]\n    C --> D[Download Dependencies]\n    D --> E[Install via Pip]\n    E --> F[Register Validator]\n```\n\n## Usage Examples\n\n### Basic String Validation\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import RegexMatch\n\nguard = Guard().use(\n    RegexMatch, \n    regex=\"\\\\(?\\\\d{3}\\\\)?-? *\\\\d{3}-? *-?\\\\d{4}\",\n    on_fail=OnFailAction.EXCEPTION\n)\n\nguard.validate(\"123-456-7890\")  # Passes\n```\n\n### Multiple Validators\n\n```python\nfrom guardrails import Guard\nfrom guardrails.hub import CompetitorCheck, ToxicLanguage\n\nguard = Guard().use(\n    CompetitorCheck([\"Apple\", \"Microsoft\"]),\n    on_fail=OnFailAction.EXCEPTION\n).use(\n    ToxicLanguage(threshold=0.5),\n    on_fail=OnFailAction.FILTER\n)\n```\n\n### Custom Validator\n\n```python\nfrom guardrails import Validator\nfrom guardrails.classes import ValidationResult, PassResult, FailResult\n\nclass UppercaseValidator(Validator):\n    def validate(self, value, metadata):\n        if value.isupper():\n            return PassResult()\n        return FailResult(\n            error_message=\"Value must be uppercase\",\n            fix_value=value.upper()\n        )\n\nguard = Guard().use(UppercaseValidator)\n```\n\n## Best Practices\n\n1. **Error Messages**: Provide clear, actionable error messages in `FailResult`\n2. **Fix Values**: Always provide sensible `fix_value` when possible\n3. **Metadata**: Use metadata for context-aware validation (e.g., schema info)\n4. **Ordering**: Place more restrictive validators first for early failure\n5. **Testing**: Test both passing and failing cases for each validator\n\n## Related Components\n\n| Component | File | Role |\n|-----------|------|------|\n| Guard | `guardrails/guard.py` | Main entry point for validation |\n| ValidatorService | `validator_service_base.py` | Orchestrates validation execution |\n| Call History | `classes/history/call.py` | Tracks validation execution history |\n| Hub Install | `hub/install.py` | Handles validator distribution |\n| Telemetry | `telemetry/validator_tracing.py` | Observability into validation |\n\n---\n\n<a id='schema-processing'></a>\n\n## Schema Processing\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Execution Pipeline](#execution-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/rail_schema.py)\n- [guardrails/schema/pydantic_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/pydantic_schema.py)\n- [guardrails/schema/primitive_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/primitive_schema.py)\n- [guardrails/schema/validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/validator.py)\n</details>\n\n# Schema Processing\n\nSchema Processing is the core system within Guardrails that handles conversion, validation, and transformation of data structures between different schema formats. It provides the foundational infrastructure for validating LLM outputs against defined schemas, supporting multiple schema specification formats including RAIL (Rich AI Language), Pydantic models, and JSON Schema.\n\n## Overview\n\nThe Schema Processing module enables Guardrails to:\n\n- Convert JSON Schema to RAIL output specifications\n- Build element hierarchies from JSON Schema definitions\n- Support multiple data types including primitives, dates, times, and enums\n- Map validators to schema elements\n- Generate structured output from LLM responses\n\n资料来源：[guardrails/schema/rail_schema.py:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[JSON Schema / Pydantic / RAIL] --> B[Schema Processing Module]\n    B --> C[rail_schema.py]\n    B --> D[pydantic_schema.py]\n    B --> E[primitive_schema.py]\n    B --> F[validator.py]\n    C --> G[build_element]\n    C --> H[json_schema_to_rail_output]\n    D --> I[Schema Generation]\n    E --> J[Type Handling]\n    F --> K[Validator Mapping]\n    G --> L[XML Element Tree]\n    H --> M[RAIL Output String]\n```\n\n## Core Components\n\n### Schema Type System\n\nThe schema processing system uses a dual type classification system:\n\n| Type Category | Values | Description |\n|---------------|--------|-------------|\n| **SimpleTypes** | STRING, INTEGER, NUMBER, BOOLEAN, ARRAY, OBJECT, NULL | JSON Schema primitive types |\n| **RailTypes** | STRING, INTEGER, FLOAT, BOOL, DATE, TIME, DATETIME, PERCENTAGE, ENUM | RAIL-specific type representations |\n\n资料来源：[guardrails/schema/rail_schema.py:30-45]()\n\n### Type Mapping Matrix\n\n```mermaid\ngraph LR\n    A[JSON Schema Type] -->|Mapping| B[Internal Schema Type]\n    A1[STRING] --> B1[SimpleTypes.STRING]\n    A2[integer] --> A2a[integer] --> B2[SimpleTypes.INTEGER]\n    A3[number] --> A3a[number] --> B3[SimpleTypes.NUMBER]\n    A4[boolean] --> B4[SimpleTypes.BOOLEAN]\n    A5[array] --> B5[SimpleTypes.ARRAY]\n    A6[object] --> B6[SimpleTypes.OBJECT]\n```\n\n### build_element Function\n\nThe `build_element` function is the central dispatcher for converting JSON Schema definitions into XML element structures:\n\n```python\ndef build_element(\n    json_schema: Dict[str, Any],\n    validator_map: ValidatorMap,\n    *,\n    json_path: str = \"$\",\n    elem: Callable[..., _Element] = SubElement,\n    tag_override: Optional[str] = None,\n    parent: Optional[_Element] = None,\n    required: Optional[str] = \"true\",\n    attributes: Optional[Dict[str, Any]] = None,\n) -> _Element:\n```\n\n**Parameters:**\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `json_schema` | Dict[str, Any] | required | The JSON Schema definition to process |\n| `validator_map` | ValidatorMap | required | Mapping of validator names to implementations |\n| `json_path` | str | \"$\" | Current path in the JSON structure for tracking |\n| `elem` | Callable | SubElement | Element construction function |\n| `tag_override` | Optional[str] | None | Override the XML tag name |\n| `parent` | Optional[_Element] | None | Parent element for nesting |\n| `required` | Optional[str] | \"true\" | Whether field is required |\n| `attributes` | Optional[Dict[str, Any]] | None | Additional XML attributes |\n\n资料来源：[guardrails/schema/rail_schema.py:100-130]()\n\n### json_schema_to_rail_output Function\n\nConverts a JSON Schema back to RAIL XML format for interoperability:\n\n```python\ndef json_schema_to_rail_output(\n    json_schema: Dict[str, Any], validator_map: ValidatorMap\n) -> str:\n```\n\n**Process Flow:**\n\n```mermaid\ngraph TD\n    A[JSON Schema Input] --> B[jsonref.replace_refs]\n    B --> C[dereferenced_json_schema]\n    C --> D[build_element with tag_override='output']\n    D --> E[ET.tostring with pretty_print]\n    E --> F[canonicalize output]\n    F --> G[Replace &#xA; entities]\n    G --> H[RAIL XML String]\n```\n\n资料来源：[guardrails/schema/rail_schema.py:60-75]()\n\n## Type-Specific Processing\n\n### String Element Builder\n\nThe `build_string_element` function handles all string-based types with special formatting:\n\n```mermaid\ngraph TD\n    A[String Type Detected] --> B{format.internal_type}\n    B -->|DATE| C[Set date-format attribute]\n    B -->|TIME| D[Set time-format attribute]\n    B -->|DATETIME| E[Set datetime-format attribute]\n    B -->|PERCENTAGE| F[Set percentage handling]\n    B -->|STRING| G[Standard string processing]\n    C --> H[Return Element with attributes]\n    D --> H\n    E --> H\n    F --> H\n    G --> H\n```\n\n**Date/Time Format Handling:**\n\n| Internal Type | XML Attribute | Purpose |\n|---------------|---------------|---------|\n| `RailTypes.DATE` | `date-format` | Custom date patterns |\n| `RailTypes.TIME` | `time-format` | Custom time patterns |\n| `RailTypes.DATETIME` | `datetime-format` | Custom datetime patterns |\n\n资料来源：[guardrails/schema/rail_schema.py:140-180]()\n\n### Format Extraction\n\nThe format extraction system maps JSON Schema formats to internal RAIL types:\n\n```python\ndef extract_format(\n    element,\n    internal_type: RailTypes,\n    internal_format_attr: str,\n) -> Optional[Format]:\n```\n\n**Supported Format Mappings:**\n\n| JSON Schema Format | RailTypes Value | Internal Format Attr |\n|--------------------|-----------------|---------------------|\n| date | DATE | date-format |\n| date-time | DATETIME | datetime-format |\n| time | TIME | time-format |\n| percentage | PERCENTAGE | (empty string) |\n| email | STRING | - |\n| uri | STRING | - |\n| uuid | STRING | - |\n\n资料来源：[guardrails/schema/rail_schema.py:200-250]()\n\n## Integration with Guard Class\n\nThe Schema Processing module integrates with the Guard class through multiple factory methods:\n\n### Guard.for_pydantic\n\nCreates a Guard instance from a Pydantic BaseModel:\n\n```python\n@classmethod\ndef for_pydantic(\n    cls,\n    output_class: ModelOrListOfModels,\n    *,\n    reask_messages: Optional[List[Dict]] = None,\n    messages: Optional[List[Dict]] = None,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n    output_formatter: Optional[Union[str, BaseFormatter]] = None,\n):\n```\n\n资料来源：[guardrails/guard.py:150-180]()\n\n### Guard.for_rail\n\nCreates a Guard instance from a `.rail` file:\n\n```python\n@classmethod\ndef for_rail(\n    cls,\n    rail_file: str,\n    *,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n):\n```\n\n资料来源：[guardrails/guard.py:200-230]()\n\n### Guard.for_rail_string\n\nCreates a Guard instance from a RAIL XML string:\n\n```python\n@classmethod\ndef for_rail_string(\n    cls,\n    rail_string: str,\n    *,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n):\n```\n\n资料来源：[guardrails/guard.py:240-270]()\n\n## Data Flow Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant SchemaProcessor\n    participant ValidatorMap\n    participant LLM\n    \n    User->>Guard: for_pydantic(PetModel)\n    Guard->>SchemaProcessor: Convert Pydantic to JSON Schema\n    SchemaProcessor->>SchemaProcessor: build_element for each field\n    SchemaProcessor->>ValidatorMap: Map validators\n    Guard->>LLM: Prompt with schema hints\n    LLM->>Guard: Raw output\n    Guard->>SchemaProcessor: validate(output)\n    SchemaProcessor->>ValidatorMap: Run validators\n    ValidatorMap-->>SchemaProcessor: Validation result\n    SchemaProcessor-->>Guard: Structured result\n    Guard-->>User: GuardResponse\n```\n\n## Schema to RAIL Conversion Rules\n\n### Type Conversions\n\n| JSON Schema | RAIL Element | Notes |\n|-------------|--------------|-------|\n| `{type: string}` | `<string>` | Default string type |\n| `{type: integer}` | `<integer>` | Whole numbers only |\n| `{type: number}` | `<float>` | Floating point |\n| `{type: boolean}` | `<bool>` | True/false values |\n| `{type: array}` | `<list>` | Array of items |\n| `{type: object}` | `<object>` | Nested structure |\n\n### Enum Handling\n\n```python\n# JSON Schema\n{\"type\": \"string\", \"enum\": [\"value1\", \"value2\"]}\n\n# Converts to RAIL\n<element name=\"...\" type=\"string\" format=\"enum\" values=\"value1, value2\"/>\n```\n\n资料来源：[guardrails/schema/rail_schema.py:260-280]()\n\n## Configuration Options\n\n### Exec Options\n\nThe schema processing supports various execution options:\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `num_reasks` | int | None | Number of reasking attempts |\n| `full_schema_reask` | bool | None | Reask entire schema vs individual fields |\n| `stream` | bool | None | Enable streaming responses |\n| `metadata` | Dict[str, Any] | None | Custom data for validators |\n\n资料来源：[guardrails/classes/history/call_inputs.py:30-50]()\n\n## Error Handling\n\nThe schema processing system includes robust error handling for:\n\n- Missing required fields\n- Invalid type conversions\n- Reference resolution failures\n- Validator mapping errors\n\n```mermaid\ngraph TD\n    A[Schema Processing] --> B{Error Condition}\n    B -->|Type Mismatch| C[Raise TypeError]\n    B -->|Missing Ref| D[Raise RefResolutionError]\n    B -->|Invalid Validator| E[Raise ValidatorError]\n    B -->|Success| F[Return Valid Element]\n```\n\n## Performance Considerations\n\n1. **Reference Dereferencing**: Uses `jsonref.replace_refs()` for efficient reference resolution\n2. **Lazy Element Construction**: Elements are built on-demand during validation\n3. **Validator Caching**: ValidatorMap instances are reused across calls\n\n## Related Components\n\n| Component | File Path | Purpose |\n|-----------|-----------|---------|\n| Validator Module | `guardrails/schema/validator.py` | Validator implementation and mapping |\n| Pydantic Schema | `guardrails/schema/pydantic_schema.py` | Pydantic model conversion |\n| Primitive Schema | `guardrails/schema/primitive_schema.py` | Primitive type handling |\n| Guard Class | `guardrails/guard.py` | High-level API integration |\n\n## Summary\n\nSchema Processing in Guardrails provides a comprehensive system for:\n\n- Converting between multiple schema formats (JSON Schema, RAIL, Pydantic)\n- Building hierarchical XML element structures from JSON definitions\n- Mapping and applying validators to schema elements\n- Supporting rich type system including dates, times, and enums\n- Enabling structured output generation from LLM responses\n\nThis modular architecture allows flexible schema definition while maintaining strong validation guarantees for LLM-generated content.\n\n---\n\n<a id='execution-pipeline'></a>\n\n## Execution Pipeline\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Async and Streaming Support](#async-streaming)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/run/runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/runner.py)\n- [guardrails/run/stream_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/stream_runner.py)\n- [guardrails/run/async_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/async_runner.py)\n- [guardrails/actions/reask.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/actions/reask.py)\n- [guardrails/utils/parsing_utils.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/utils/parsing_utils.py)\n</details>\n\n# Execution Pipeline\n\nThe Execution Pipeline is the core orchestration mechanism in Guardrails that handles the validation and correction of Large Language Model (LLM) outputs. It manages the lifecycle of a Guard execution from initial prompt submission through iterative validation and potential reasking cycles.\n\n## Overview\n\nThe Execution Pipeline coordinates multiple components to ensure LLM outputs meet specified validation criteria. When a Guard is invoked, the pipeline:\n\n1. Receives the raw LLM output\n2. Parses and extracts structured data\n3. Validates the output against defined validators\n4. Triggers reasking workflows when validation fails\n5. Returns sanitized, validated responses\n\nThe pipeline supports both synchronous and streaming execution modes, with dedicated runner classes handling different invocation patterns.\n\n## Core Components\n\n### Runner Classes\n\nThe execution pipeline is implemented through several runner classes that extend base execution functionality:\n\n| Runner Class | File | Purpose |\n|-------------|------|---------|\n| `Runner` | `runner.py` | Base synchronous execution handler |\n| `StreamRunner` | `stream_runner.py` | Handles streaming LLM responses |\n| `AsyncRunner` | `async_runner.py` | Manages asynchronous LLM invocations |\n\n### Execution Flow Architecture\n\n```mermaid\ngraph TD\n    A[Guard.__call__] --> B[Runner/StreamRunner/AsyncRunner]\n    B --> C[Parse LLM Output]\n    C --> D[Validate Against Validators]\n    D --> E{Validation Passed?}\n    E -->|Yes| F[Return Sanitized Output]\n    E -->|No| G[Check Reask Eligibility]\n    G --> H[Reask Action]\n    H --> I[Regenerate with Corrections]\n    I --> C\n    G -->|No Reasks Left| J[Raise Validation Exception]\n```\n\n## Reask Action System\n\nThe reask mechanism is a critical part of the execution pipeline that handles validation failures intelligently. When output fails validation, the reask action can prompt the LLM to correct its response.\n\n### Reask Configuration\n\nReask behavior is controlled through `CallInputs` parameters:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `num_reasks` | `Optional[int]` | Total number of reask attempts allowed |\n| `full_schema_reask` | `Optional[bool]` | Whether to reask entire schema or individual fields |\n| `metadata` | `Optional[Dict[str, Any]]` | Additional data for validators during execution |\n\n资料来源：[guardrails/classes/history/call_inputs.py:23-30]()\n\n### Reask Workflow\n\n```mermaid\ngraph LR\n    A[Initial Call] --> B[Iteration 1]\n    B --> C{All Validators Pass?}\n    C -->|No| D[Create Reask Prompt]\n    D --> E[LLM Regeneration]\n    E --> F[Iteration 2]\n    F --> G{Valid?}\n    G -->|No| H{num_reasks exhausted?}\n    H -->|No| D\n    H -->|Yes| I[Final Exception]\n    G -->|Yes| J[Success]\n    C -->|Yes| J\n```\n\n## Call History and Iterations\n\nEach Guard execution creates a `Call` object that tracks the full execution history. The call object maintains a stack of `Iteration` objects representing each round of validation.\n\n### Data Model\n\n```\nCall\n├── _id: str (unique identifier)\n├── iterations: Stack[Iteration]\n│   └── Contains validation results per round\n├── inputs: CallInputs\n│   ├── prompt_params\n│   ├── num_reasks\n│   └── metadata\n└── exception: Optional[Exception]\n```\n\n资料来源：[guardrails/classes/history/call.py:12-29]()\n\n## Execution Modes\n\n### Synchronous Execution\n\nThe base `Runner` class handles synchronous LLM invocations:\n\n```python\nraw_response, validated_response = guard(\n    llm_api,\n    prompt_params={...},\n    ...\n)\n```\n\n### Streaming Execution\n\n`StreamRunner` processes LLM outputs as they are generated, enabling real-time validation of streaming responses.\n\n### Asynchronous Execution\n\n`AsyncRunner` manages coroutine-based LLM calls for high-throughput applications:\n\n```python\nasync def validate_async():\n    response = await guard(\n        async_llm_call,\n        prompt_params={...}\n    )\n```\n\n## Parsing Utilities\n\nThe `parsing_utils.py` module provides utilities for extracting structured data from LLM outputs. These parsers handle various output formats and ensure data can be validated against the schema.\n\nKey parsing responsibilities include:\n- Extracting JSON/XML from raw text responses\n- Handling malformed output gracefully\n- Converting parsed data to appropriate types for validation\n\n## Trace Handler Integration\n\nThe execution pipeline integrates with `TraceHandler` for observability:\n\n```python\nwriter = TraceHandler()\nwriter.log(\n    \"guard_name\", start_time, end_time,\n    \"raw_output\", \"sanitized\", \"exception?\"\n)\n```\n\n资料来源：[guardrails/call_tracing/trace_handler.py:1-50]()\n\nLogs are stored in SQLite (`guardrails_calls.db`) by default, with the path configurable via `GUARDRAILS_LOG_FILE_PATH` environment variable.\n\n## Error Handling\n\nThe pipeline implements multi-level error handling:\n\n1. **Validation Exceptions**: Raised when output fails validator criteria\n2. **Reask Exhaustion**: Triggered when all reask attempts are consumed\n3. **LLM Provider Errors**: Propagated from underlying LLM calls\n4. **Parsing Errors**: Handled when LLM output cannot be parsed\n\n## Configuration Parameters\n\n| Parameter | Location | Default | Description |\n|-----------|----------|---------|-------------|\n| `num_reasks` | CallInputs | `None` | Maximum reask iterations |\n| `full_schema_reask` | CallInputs | `None` | Reask scope control |\n| `prompt_params` | CallInputs | `{}` | Template variables |\n| `stream` | CallInputs | `None` | Enable streaming mode |\n| `metadata` | CallInputs | `None` | Custom validator data |\n\n## See Also\n\n- [Guard Class](guardrails/guard.py) - Main API entry point\n- [Validator System](../validators/overview.md) - Validation rules\n- [Call History](../history/call-history.md) - Execution tracking\n- [Hub Validators](../hub/installed-validators.md) - Pre-built validators\n\n---\n\n<a id='async-streaming'></a>\n\n## Async and Streaming Support\n\n### 相关页面\n\n相关主题：[Execution Pipeline](#execution-pipeline), [LLM Provider Integration](#llm-providers)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/run/__init__.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/__init__.py)\n- [guardrails/run/async_stream_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/async_stream_runner.py)\n- [guardrails/run/async_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/async_runner.py)\n- [guardrails/run/stream_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/stream_runner.py)\n- [guardrails/validator_service/async_validator_service.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/async_validator_service.py)\n- [guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n- [guardrails/integrations/databricks/ml_flow_instrumentor.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/databricks/ml_flow_instrumentor.py)\n</details>\n\n# Async and Streaming Support\n\n## Overview\n\nGuardrails provides comprehensive support for asynchronous operations and streaming responses, enabling integration with modern LLM APIs that support async calls or streaming output. This capability is essential for building responsive applications that need to handle real-time validation, provide incremental feedback, and maintain high throughput when processing LLM responses.\n\nThe async and streaming support in Guardrails is built around a modular runner architecture that separates the concerns of asynchronous execution from streaming output. This design allows developers to use either feature independently or combine them for full async streaming capabilities.\n\n资料来源：[guardrails/run/__init__.py:1-15]()\n\n## Architecture\n\n### Runner Class Hierarchy\n\nThe async and streaming functionality is implemented through a class hierarchy that extends a base `Runner` class with async and streaming capabilities.\n\n```mermaid\ngraph TD\n    A[Runner] --> B[AsyncRunner]\n    A --> C[StreamRunner]\n    B --> D[AsyncStreamRunner]\n    C --> D\n    \n    A1[Base synchronous runner] \n    B1[Async execution support]\n    C1[Streaming output support]\n    D1[Combined async + streaming]\n    \n    A --> A1\n    B --> B1\n    C --> C1\n    D --> D1\n```\n\n### Module Structure\n\nThe runners are organized under the `guardrails.run` module with the following structure:\n\n| Module | Purpose |\n|--------|---------|\n| `guardrails.run.runner` | Base synchronous runner |\n| `guardrails.run.async_runner` | Async execution support |\n| `guardrails.run.stream_runner` | Streaming output support |\n| `guardrails.run.async_stream_runner` | Combined async and streaming |\n| `guardrails.run.utils` | Shared utilities including `messages_source` |\n\n资料来源：[guardrails/run/__init__.py:1-15]()\n\n## Async Runner\n\n### AsyncRunner Class\n\nThe `AsyncRunner` extends the base `Runner` with asynchronous execution capabilities. It provides methods for calling LLM providers asynchronously and processing validation outcomes without blocking the calling thread.\n\n```python\nclass AsyncRunner(AsyncRunner, StreamRunner):\n    async def async_run(\n        self, call_log: Call, prompt_params: Optional[Dict] = None\n    ) -> AsyncIterator[ValidationOutcome]:\n```\n\nKey characteristics of `AsyncRunner`:\n\n- Supports fully asynchronous LLM calls using async-compatible prompt callables\n- Provides `async_call` method for making async LLM invocations\n- Integrates with the async validator service for non-blocking validation\n- Returns `ValidationOutcome` objects containing validated results\n\n### Async Prompt Callables\n\nGuardrails supports async prompt callables through the `AsyncPromptCallableBase` interface. Providers like `AsyncManifestCallable` implement this interface to enable async LLM calls.\n\n```python\nclass AsyncManifestCallable(AsyncPromptCallableBase):\n    async def invoke_llm(\n        self,\n        text: str,\n        client: Any,\n        instructions: Optional[str] = None,\n        *args,\n        **kwargs,\n    ):\n```\n\n资料来源：[guardrails/run/async_runner.py]()\n资料来源：[guardrails/llm_providers.py:1-100]()\n\n## Streaming Support\n\n### StreamRunner Class\n\nThe `StreamRunner` provides streaming output capabilities, allowing Guardrails to process LLM responses incrementally as they are generated. This is particularly useful for long-form content generation where users benefit from seeing results progressively.\n\nStreaming support enables:\n\n- Incremental validation of streamed chunks\n- Real-time feedback on validation status\n- Memory-efficient processing of large responses\n\n资料来源：[guardrails/run/stream_runner.py]()\n\n## Async Stream Runner\n\n### AsyncStreamRunner Class\n\nThe `AsyncStreamRunner` combines both async execution and streaming output, providing the most comprehensive integration for modern async LLM APIs with streaming support.\n\n```python\nclass AsyncStreamRunner(AsyncRunner, StreamRunner):\n    async def async_run(\n        self, call_log: Call, prompt_params: Optional[Dict] = None\n    ) -> AsyncIterator[ValidationOutcome]:\n```\n\nThe class uses Python's `contextvars` module for proper context propagation in async environments:\n\n```python\nfrom contextvars import ContextVar, copy_context\n```\n\nThis ensures that context variables are correctly copied when running async code, maintaining proper isolation and state management.\n\n资料来源：[guardrails/run/async_stream_runner.py:1-50]()\n\n### Python Version Compatibility\n\nFor Python versions earlier than 3.10, Guardrails provides a polyfill for the `anext()` builtin function:\n\n```python\nif sys.version_info.minor < 10:\n    from guardrails.utils.polyfills import anext\n```\n\nThis ensures compatibility with Python 3.9+ while maintaining access to async iteration features introduced in Python 3.10.\n\n资料来源：[guardrails/run/async_stream_runner.py:5-8]()\n\n### Streaming Workflow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant AsyncStreamRunner\n    participant AsyncValidatorService\n    participant LLMProvider\n    \n    Client->>AsyncStreamRunner: async_run(call_log, prompt_params)\n    AsyncStreamRunner->>LLMProvider: async_call(messages)\n    LLMProvider-->>AsyncStreamRunner: stream chunks\n    \n    loop For each chunk\n        AsyncStreamRunner->>AsyncValidatorService: validate_chunk(chunk)\n        AsyncValidatorService-->>AsyncStreamRunner: ValidationOutcome\n        AsyncStreamRunner-->>Client: yield ValidationOutcome\n    end\n    \n    Client->>AsyncStreamRunner: Final validation\n    AsyncStreamRunner-->>Client: Final ValidationOutcome\n```\n\n## MLflow Integration\n\nThe async and streaming runners are instrumented for MLflow tracing through the `MLflowInstrumentor` class. This provides observability for async operations and streaming workflows.\n\n### Instrumented Components\n\n| Component | Method | Instrumentation |\n|-----------|--------|------------------|\n| `AsyncRunner` | `async_step` | Async span with step type |\n| `AsyncStreamRunner` | `async_step` | Async + stream span attributes |\n| `Runner.call` | `call` | LLM span for synchronous calls |\n| `AsyncRunner.async_call` | `async_call` | LLM span for async calls |\n\n### Span Attributes\n\nAsync and streaming operations are traced with the following attributes:\n\n```python\n{\n    \"guardrails.version\": GUARDRAILS_VERSION,\n    \"type\": \"guardrails/guard/step\",\n    \"async\": True,\n    \"stream\": True  # Only for streaming runners\n}\n```\n\n资料来源：[guardrails/integrations/databricks/ml_flow_instrumentor.py:1-150]()\n\n### Async Stream Step Instrumentation\n\nThe async stream step wrapper handles async iteration properly:\n\n```python\nasync def trace_async_stream_step_wrapper(\n    *args, **kwargs\n) -> AsyncIterator[ValidationOutcome[OT]]:\n    with mlflow.start_span(...) as step_span:\n        exception = None\n        try:\n            gen = runner_step(*args, **kwargs)\n            next_exists = True\n            while next_exists:\n                try:\n                    res = await anext(gen)\n                    yield res\n                except StopIteration:\n                    next_exists = False\n                except StopAsyncIteration:\n                    next_exists = False\n        except Exception as e:\n            step_span.set_status(status=SpanStatusCode.ERROR)\n            exception = e\n        finally:\n            # Add step attributes\n            if exception:\n                raise exception\n```\n\n资料来源：[guardrails/integrations/databricks/ml_flow_instrumentor.py:80-120]()\n\n## Validation Outcome\n\nBoth async and streaming runners return `ValidationOutcome` objects, which encapsulate the result of validation operations.\n\n### ValidationOutcome Structure\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `call_log` | `Call` | Execution history and metadata |\n| `validation_response` | `ValidationResponse` | Validated and corrected output |\n| `exception` | `Exception` | Any exception that occurred |\n\nThe `Call` object maintains a stack of `Iteration` objects, each representing a step or reask that occurred during execution:\n\n```python\nclass Call:\n    iterations: Stack[Iteration] = Field(\n        description=\"A stack of iterations for each step/reask that occurred.\",\n        default_factory=Stack,\n    )\n    inputs: CallInputs = Field(\n        description=\"The inputs as passed in to Guard.__call__ or Guard.parse\",\n        default_factory=CallInputs,\n    )\n```\n\n资料来源：[guardrails/classes/history/call.py:1-50]()\n\n## API Reference\n\n### Core Imports\n\n```python\nfrom guardrails.run import (\n    Runner,\n    AsyncRunner,\n    StreamRunner,\n    AsyncStreamRunner,\n    messages_source,\n)\n```\n\n### Runner Selection Guide\n\n| Use Case | Recommended Runner |\n|----------|-------------------|\n| Synchronous LLM calls | `Runner` |\n| Async LLM calls (non-streaming) | `AsyncRunner` |\n| Streaming LLM responses | `StreamRunner` |\n| Async LLM calls with streaming | `AsyncStreamRunner` |\n\n## Best Practices\n\n### Async Context Management\n\nWhen using async runners, ensure proper context management:\n\n```python\nimport asyncio\nfrom guardrails.run import AsyncStreamRunner\n\nasync def process_stream():\n    runner = AsyncStreamRunner(...)\n    async for outcome in runner.async_run(call_log):\n        # Process each validation outcome\n        pass\n```\n\n### Error Handling\n\nThe async stream runner handles errors gracefully, setting span status and re-raising exceptions:\n\n```python\ntry:\n    # Stream processing\nexcept Exception as e:\n    step_span.set_status(status=SpanStatusCode.ERROR)\n    raise e\n```\n\n### MLflow Tracing\n\nEnable MLflow tracing to monitor async and streaming performance:\n\n```python\nfrom guardrails.integrations.databricks import MLflowInstrumentor\n\nMLflowInstrumentor().instrument()\n```\n\nThis automatically wraps all runner methods with appropriate span instrumentation.\n\n## Related Components\n\n### Validator Service\n\nThe async validator service provides non-blocking validation:\n\n- Processes validation requests asynchronously\n- Integrates with async runners for parallel validation\n- Maintains thread safety for concurrent operations\n\n### LLM Providers\n\nAsync-compatible LLM providers include:\n\n- `AsyncManifestCallable` for Manifest models\n- `LiteLLMCallable` with async support\n- Custom providers implementing `AsyncPromptCallableBase`\n\n资料来源：[guardrails/llm_providers.py:50-150]()\n\n## Summary\n\nGuardrails' async and streaming support provides a flexible, extensible architecture for handling modern LLM interactions:\n\n1. **Modular Design**: The runner hierarchy allows selective use of async and streaming features\n2. **Async Compatibility**: Full support for async/await patterns with Python 3.9+ compatibility\n3. **Streaming Efficiency**: Memory-efficient processing of large streaming responses\n4. **Observability**: Integrated MLflow tracing for monitoring async and streaming operations\n5. **Type Safety**: Full type hints with generic `ValidationOutcome` returns\n\n---\n\n<a id='llm-providers'></a>\n\n## LLM Provider Integration\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Framework Integrations](#framework-integrations)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n- [guardrails/classes/llm/prompt_callable.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/llm/prompt_callable.py)\n- [guardrails/classes/history/call_inputs.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call_inputs.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n</details>\n\n# LLM Provider Integration\n\n## Overview\n\nThe LLM Provider Integration system in Guardrails provides a unified abstraction layer for connecting various Large Language Model (LLM) providers to the Guardrails validation framework. This system enables Guardrails to work with multiple LLM backends—including OpenAI, LiteLLM, Manifest, and custom providers—while maintaining consistent prompt handling, response parsing, and validation workflows.\n\nThe integration architecture follows a **callable wrapper pattern**, where each LLM provider is wrapped in a standardized `PromptCallableBase` subclass that normalizes the interface between Guardrails and the underlying LLM API.\n\n资料来源：[guardrails/llm_providers.py:1-50]()\n\n## Architecture\n\n### Class Hierarchy\n\nThe LLM provider system is built on an abstract base class that defines the contract for all provider implementations:\n\n```mermaid\ngraph TD\n    A[PromptCallableBase] --> B[LiteLLMCallable]\n    A --> C[ManifestCallable]\n    A --> D[OpenAICallable]\n    \n    B --> E[GPTCallable]\n    B --> F[AnthropicCallable]\n    B --> G[Custom Provider]\n    \n    A --> H[LLM Response Normalization]\n    A --> I[Tracing Integration]\n    A --> J[Error Handling]\n```\n\n资料来源：[guardrails/classes/llm/prompt_callable.py:1-80]()\n\n### Core Components\n\n| Component | Purpose | File Location |\n|-----------|---------|---------------|\n| `PromptCallableBase` | Abstract base class defining the LLM interface contract | `guardrails/classes/llm/prompt_callable.py` |\n| `LiteLLMCallable` | Wrapper for LiteLLM multi-provider support | `guardrails/llm_providers.py` |\n| `ManifestCallable` | Wrapper for Manifest ML client | `guardrails/llm_providers.py` |\n| `LLMResponse` | Normalized response object | `guardrails/llm_providers.py` |\n| `CallInputs` | Captures invocation parameters and metadata | `guardrails/classes/history/call_inputs.py` |\n| `Call` | Records execution history and iterations | `guardrails/classes/history/call.py` |\n\n资料来源：[guardrails/llm_providers.py:50-150]()\n\n## PromptCallableBase\n\nThe `PromptCallableBase` is the foundational abstract class that all LLM providers must implement. It provides:\n\n### Abstract Methods\n\n| Method | Signature | Description |\n|--------|-----------|-------------|\n| `_invoke_llm` | `(text, model, messages, *args, **kwargs) -> LLMResponse` | Core LLM invocation method |\n| `_prepare_prompt` | `(text, instructions) -> str` | Prepares prompt with formatting |\n\n### Common Functionality\n\n- **Tracing Integration**: All providers integrate with Guardrails' tracing system via `trace_operation()` and `trace_llm_call()` functions\n- **Prompt Normalization**: Converts various prompt formats to a standardized structure\n- **Error Handling**: Wraps provider-specific exceptions in `PromptCallableException`\n- **Streaming Support**: Optional streaming via the `stream` parameter\n\n资料来源：[guardrails/classes/llm/prompt_callable.py:30-100]()\n\n## LiteLLM Integration\n\n### Overview\n\n`LiteLLMCallable` provides integration with [LiteLLM](https://github.com/BerriAI/litellm), a unified interface for calling 100+ LLMs including OpenAI, Azure, Anthropic, Cohere, and Hugging Face.\n\n```python\nfrom litellm import completion\n\nraw_llm_response, validated_response = guard(\n    completion,\n    model=\"gpt-3.5-turbo\",\n    prompt_params={...},\n    temperature=0.7,\n)\n```\n\n资料来源：[guardrails/llm_providers.py:80-120]()\n\n### Invocation Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `text` | `Optional[str]` | `None` | Plain text prompt |\n| `model` | `str` | `\"gpt-3.5-turbo\"` | Model identifier |\n| `messages` | `Optional[List[Dict]]` | `None` | Chat messages list |\n| `*args` | `Any` | - | Additional positional arguments |\n| `**kwargs` | `Any` | - | Provider-specific parameters (temperature, max_tokens, etc.) |\n\n### Function Calling Support\n\nLiteLLMCallable supports OpenAI-style function calling through the `tools` parameter:\n\n```python\nfunction_calling_tools = [\n    tool.get(\"function\")\n    for tool in kwargs.get(\"tools\", [])\n    if isinstance(tool, Dict) and tool.get(\"type\") == \"function\"\n]\n```\n\n资料来源：[guardrails/llm_providers.py:130-160]()\n\n## Manifest Integration\n\n### Overview\n\n`ManifestCallable` provides integration with the [Manifest](https://github.com/HazyResearch/manifest) ML client library for models hosted on various backends.\n\n### Usage Pattern\n\n```python\nfrom guardrails import Guard\n\nraw_llm_response, validated_response = guard(\n    client,\n    prompt_params={...},\n    ...\n)\n```\n\n### Prompt Handling\n\nManifest uses a non-chat prompt format:\n\n```python\nprompt = nonchat_prompt(prompt=text, instructions=instructions)\nmanifest_response = client.run(prompt, *args, **kwargs)\n```\n\n资料来源：[guardrails/llm_providers.py:20-60]()\n\n## Response Handling\n\n### LLMResponse Structure\n\nAll providers return a normalized `LLMResponse` object:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `output` | `str` | The raw LLM-generated text |\n| `model` | `Optional[str]` | Model identifier used |\n| `usage` | `Optional[Dict]` | Token usage statistics |\n| `provider` | `str` | Source provider name |\n\n### Tracing Integration\n\nEvery LLM call is traced with full input/output capture:\n\n```python\ntrace_operation(\n    input_mime_type=\"application/json\",\n    input_value={\n        **kwargs,\n        \"model\": model,\n        \"args\": args,\n    },\n)\n\ntrace_llm_call(\n    input_messages=kwargs.get(\"messages\"),\n    invocation_parameters={**kwargs, \"model\": model},\n    function_call=kwargs.get(\"function_call\"),\n)\n```\n\n资料来源：[guardrails/llm_providers.py:140-180]()\n\n## Guard Integration\n\n### Guard Class Methods\n\nThe `Guard` class provides factory methods for creating provider-integrated instances:\n\n| Method | Purpose |\n|--------|---------|\n| `Guard.from_rail()` | Create Guard from RAIL XML specification |\n| `Guard.from_pydantic()` | Create Guard from Pydantic model |\n| `Guard.__call__()` | Invoke LLM with automatic validation |\n\n资料来源：[guardrails/guard.py:100-200]()\n\n### Call History\n\nEach LLM invocation creates a `Call` record containing:\n\n```python\nclass Call:\n    iterations: Stack[Iteration]  # Validation iterations\n    inputs: CallInputs              # Invocation parameters\n    exception: Optional[Exception]  # Any errors during execution\n```\n\nThe `CallInputs` captures:\n- `llm_api`: The callable used\n- `prompt_params`: Parameters for prompt interpolation\n- `num_reasks`: Maximum reask attempts\n- `metadata`: Custom data for validators\n- `full_schema_reask`: Whether to reask entire schema\n- `stream`: Streaming mode flag\n\n资料来源：[guardrails/classes/history/call.py:20-80]()\n\n## Error Handling\n\n### Exception Types\n\n| Exception | Trigger | Handling |\n|-----------|---------|----------|\n| `PromptCallableException` | Missing dependencies or provider errors | Wraps underlying exception with context |\n| `ImportError` | Required package not installed | Clear installation instructions |\n\n### Example Error Handling\n\n```python\ntry:\n    from litellm import completion\nexcept ImportError as e:\n    raise PromptCallableException(\n        \"The `litellm` package is not installed. \"\n        \"Install with `pip install litellm`\"\n    ) from e\n```\n\n资料来源：[guardrails/llm_providers.py:95-105]()\n\n## Workflow Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant PromptCallable\n    participant LLMProvider\n    participant Validator\n    \n    User->>Guard: __call__(llm_api, prompt, params)\n    Guard->>Guard: Create Call record\n    Guard->>PromptCallable: _invoke_llm(text, model, messages)\n    PromptCallable->>PromptCallable: trace_operation()\n    PromptCallable->>LLMProvider: LLM API call\n    LLMProvider-->>PromptCallable: Raw response\n    PromptCallable->>PromptCallable: trace_llm_call()\n    PromptCallable-->>Guard: LLMResponse\n    Guard->>Validator: Validate response\n    Validator-->>Guard: ValidationResult\n    Guard->>Guard: Record Iteration\n    Guard-->>User: (raw_response, validated_response)\n```\n\n## Best Practices\n\n1. **Use LiteLLM for Multi-Provider Support**: LiteLLM provides the most flexibility for switching between providers\n2. **Configure Prompt Parameters**: Always provide `prompt_params` for dynamic prompt interpolation\n3. **Enable Tracing in Development**: Tracing helps debug LLM interactions and validation failures\n4. **Handle Exceptions**: Wrap Guard calls in try-except blocks to handle validation failures gracefully\n5. **Use Pydantic for Structured Output**: The `Guard.from_pydantic()` method provides the cleanest integration for structured data generation\n\n## See Also\n\n- [Guard Usage Guide](../guard/usage.md)\n- [Validator Hub](https://guardrailsai.com/hub/)\n- [RAIL Specification](../rail/overview.md)\n\n---\n\n<a id='framework-integrations'></a>\n\n## Framework Integrations\n\n### 相关页面\n\n相关主题：[LLM Provider Integration](#llm-providers), [Guard Class Reference](#guard-class)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [guardrails/integrations/langchain/guard_runnable.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/langchain/guard_runnable.py)\n- [guardrails/integrations/langchain/base_runnable.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/langchain/base_runnable.py)\n- [guardrails/integrations/llama_index/guardrails_chat_engine.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/llama_index/guardrails_chat_engine.py)\n- [guardrails/integrations/llama_index/guardrails_query_engine.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/llama_index/guardrails_query_engine.py)\n- [guardrails/integrations/databricks/ml_flow_instrumentor.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/databricks/ml_flow_instrumentor.py)\n</details>\n\n# Framework Integrations\n\nGuardrails provides official integrations with popular AI frameworks to enable seamless validation of LLM outputs within existing application stacks. These integrations wrap framework-specific components to transparently apply Guard validation without requiring significant changes to existing code.\n\n## Architecture Overview\n\nFramework integrations in Guardrails follow a consistent design pattern: they wrap framework-native runnable or engine objects, intercepting inputs and outputs to apply validation through the Guard API.\n\n```mermaid\ngraph TD\n    subgraph \"Application Layer\"\n        User[User Application]\n    end\n    \n    subgraph \"Framework Integration Layer\"\n        GR[Guardrails Wrapper]\n        Guard[Guard Instance]\n    end\n    \n    subgraph \"Framework Layer\"\n        LC[LangChain / LlamaIndex]\n        DB[Databricks MLflow]\n    end\n    \n    subgraph \"Guardrails Core\"\n        Validators[Validators]\n        Schema[RAIL / Pydantic Schema]\n    end\n    \n    User --> GR\n    GR --> LC\n    GR --> Guard\n    Guard --> Validators\n    Guard --> Schema\n    \n    style GR fill:#e1f5fe\n    style Guard fill:#fff3e0\n```\n\n## LangChain Integration\n\nThe LangChain integration provides `GuardRunnable` and `BaseRunnable` classes that wrap LangChain components, enabling validation of LLM outputs in chains and agents.\n\n### Core Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `BaseRunnable` | `guardrails/integrations/langchain/base_runnable.py` | Base class providing LangChain-compatible runnable interface |\n| `GuardRunnable` | `guardrails/integrations/langchain/guard_runnable.py` | Concrete implementation wrapping a Guard instance |\n\n### GuardRunnable Class\n\nThe `GuardRunnable` class serves as a LangChain-compatible runnable that applies Guard validation to outputs.\n\n**Key Features:**\n- Implements LangChain's `Runnable` interface for drop-in compatibility\n- Wraps a Guard instance to validate LLM responses\n- Supports streaming responses with validation\n- Integrates with LangChain's tracing and observability\n\n**Usage Pattern:**\n```python\nfrom guardrails.integrations.langchain import GuardRunnable\nfrom guardrails import Guard\n\n# Create a Guard instance\nguard = Guard().use(SomeValidator, ...)\n\n# Wrap it as a LangChain runnable\nguard_runnable = GuardRunnable(guard=guard)\n\n# Use in LangChain chains\nchain = prompt | llm | guard_runnable\n```\n\n资料来源：[guardrails/integrations/langchain/guard_runnable.py]()\n\n### BaseRunnable Abstract Class\n\nThe `BaseRunnable` class defines the abstract interface that all Guardrails runnables must implement, ensuring consistency across different framework integrations.\n\n资料来源：[guardrails/integrations/langchain/base_runnable.py]()\n\n## LlamaIndex Integration\n\nThe LlamaIndex integration provides engines that wrap LlamaIndex query and chat engines with Guard validation.\n\n### Supported Engine Types\n\n| Engine Type | File | Description |\n|-------------|------|-------------|\n| `GuardrailsQueryEngine` | `guardrails/integrations/llama_index/guardrails_query_engine.py` | Validates query engine responses |\n| `GuardrailsChatEngine` | `guardrails/integrations/llama_index/guardrails_chat_engine.py` | Validates chat engine responses |\n\n### GuardrailsQueryEngine\n\nThe query engine integration validates responses from LlamaIndex query operations.\n\n**Key Capabilities:**\n- Wraps base LlamaIndex query engines\n- Validates retrieved context and generated responses\n- Supports custom validators for domain-specific checks\n- Maintains query context through the validation pipeline\n\n**Typical Integration:**\n```python\nfrom guardrails.integrations.llama_index import GuardrailsQueryEngine\nfrom guardrails import Guard\nfrom llama_index import VectorStoreIndex\n\n# Build index\nindex = VectorStoreIndex.from_documents(documents)\n\n# Create Guard\nguard = Guard().use(SomeValidator, ...)\n\n# Wrap query engine\nquery_engine = index.as_query_engine()\nguardrails_engine = GuardrailsQueryEngine(\n    query_engine=query_engine,\n    guard=guard\n)\n```\n\n资料来源：[guardrails/integrations/llama_index/guardrails_query_engine.py]()\n\n### GuardrailsChatEngine\n\nThe chat engine integration validates conversational responses, ensuring consistency and safety across multi-turn interactions.\n\n**Features:**\n- Validates each response in a conversation\n- Supports conversation context preservation\n- Integrates with LlamaIndex memory components\n- Enables custom validation per conversation turn\n\n资料来源：[guardrails/integrations/llama_index/guardrails_chat_engine.py]()\n\n## Databricks MLflow Integration\n\nThe Databricks integration provides automatic instrumentation for LLM calls within the MLflow tracking ecosystem.\n\n### MLflow Instrumentor\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `MLflowInstrumentor` | `guardrails/integrations/databricks/ml_flow_instrumentor.py` | Auto-instruments LLM calls for MLflow tracking |\n\n**Instrumentation Capabilities:**\n- Automatically wraps LLM invocations\n- Logs prompts and responses to MLflow\n- Tracks validation outcomes and errors\n- Associates metrics with MLflow runs\n\n**Setup:**\n```python\nfrom guardrails.integrations.databricks import MLflowInstrumentor\n\n# Initialize instrumentor\ninstrumentor = MLflowInstrumentor()\n\n# Enable instrumentation\ninstrumentor.instrument()\n```\n\n资料来源：[guardrails/integrations/databricks/ml_flow_instrumentor.py]()\n\n## Integration Patterns\n\n### Common Workflow\n\n```mermaid\nsequenceDiagram\n    participant App as Application\n    participant Wrapper as Guardrails Wrapper\n    participant Framework as AI Framework\n    participant Guard as Guard Instance\n    participant Validators as Validators\n    \n    App->>Wrapper: Invoke LLM Call\n    Wrapper->>Framework: Forward Request\n    Framework->>Wrapper: LLM Response\n    Wrapper->>Guard: Validate Response\n    Guard->>Validators: Run Validators\n    Validators-->>Guard: Validation Result\n    alt Validation Passes\n        Guard-->>Wrapper: Validated Output\n        Wrapper-->>App: Return Result\n    else Validation Fails\n        Guard-->>Wrapper: Validation Error\n        Wrapper-->>App: Raise Exception / Return Fix\n    end\n```\n\n### Validation Flow\n\nWhen validation fails, the integration architecture determines how to handle the failure based on the configured `on_fail` action:\n\n| Action | Behavior |\n|--------|----------|\n| `EXCEPTION` | Raises an exception with validation details |\n| `REASK` | Attempts to reask the LLM with corrected context |\n| `FIX` | Attempts to automatically fix the output |\n| `FILTER` | Filters invalid portions from the output |\n| `CUSTOM` | Invokes a custom handler function |\n\n## Configuration Reference\n\n### Guard Configuration\n\nIntegrations accept a Guard instance configured with the desired validators:\n\n```python\nfrom guardrails import Guard, OnFailAction\n\nguard = Guard().use(\n    Validator1(param1=\"value1\", on_fail=OnFailAction.EXCEPTION),\n    Validator2(param2=\"value2\", on_fail=OnFailAction.REASK),\n)\n```\n\n### Integration-Specific Options\n\n| Integration | Option | Description |\n|-------------|--------|-------------|\n| LangChain | `guard` | Guard instance for validation |\n| LlamaIndex | `query_engine` | Base query engine to wrap |\n| LlamaIndex | `chat_engine` | Base chat engine to wrap |\n| Databricks | `instrument()` | Enable/disable auto-instrumentation |\n\n## Best Practices\n\n1. **Centralized Guard Configuration**: Define Guard instances with all required validators in a single location and reuse across integrations\n2. **Fail Action Strategy**: Choose appropriate `on_fail` actions based on use case criticality\n3. **Validator Ordering**: Place faster validators first to fail fast on common issues\n4. **Error Handling**: Implement proper exception handling for validation failures\n5. **Testing**: Test validation logic independently before integration\n\n## Dependencies\n\nFramework integrations have specific dependency requirements:\n\n| Integration | Required Packages |\n|-------------|-------------------|\n| LangChain | `langchain>=0.0.XXX` |\n| LlamaIndex | `llama-index>=0.XXX` |\n| Databricks | `mlflow>=2.XXX`, `databricks-sdk` |\n\n---\n\n<a id='custom-validators'></a>\n\n## Creating Custom Validators\n\n### 相关页面\n\n相关主题：[Validators System](#validators)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/validator_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_base.py)\n- [guardrails/hub/validator_package_service.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/validator_package_service.py)\n- [guardrails/cli/hub/create_validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n- [guardrails/hub/registry.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/registry.py)\n</details>\n\n# Creating Custom Validators\n\nCustom validators in Guardrails enable developers to define domain-specific validation logic that can be integrated seamlessly into the Guard validation pipeline. Validators are reusable components that inspect LLM outputs and either pass or fail based on custom criteria.\n\n## Overview\n\nGuardrails provides a validator framework where validators are classes that inherit from a base `Validator` class and implement a `validate` method. Each validator can receive initialization arguments and define behavior when validation fails through the `on_fail` parameter.\n\n```mermaid\ngraph TD\n    A[LLM Output] --> B[Guard Pipeline]\n    B --> C[Validator 1]\n    C --> D[Validator 2]\n    D --> E[Validator N]\n    E --> F[Validated Output]\n    \n    C -->|Pass| D\n    D -->|Pass| E\n    E -->|Pass| F\n    \n    C -->|Fail| G[On Fail Action]\n    D -->|Fail| G\n    E -->|Fail| G\n```\n\n## Validator Architecture\n\n### Base Class Structure\n\nValidators inherit from `Validator` which provides:\n- Initialization handling for `on_fail` policy\n- Metadata passing through validation pipeline\n- Integration with the Guard validation system\n\nEach validator must implement:\n1. `__init__`: Accept initialization arguments and `on_fail` parameter\n2. `validate`: Perform validation logic and return `PassResult` or `FailResult`\n\n### Validation Result Types\n\n| Result Type | Purpose |\n|-------------|---------|\n| `PassResult` | Value passes validation |\n| `FailResult` | Value fails validation with error message |\n\n## Creating a Custom Validator\n\n### Using the CLI Generator\n\nThe fastest way to create a validator is using the CLI command:\n\n```bash\nguardrails hub create-validator MyValidator\n```\n\nThis generates a template file `./my_validator.py` with the following structure:\n\n```python\nfrom guardrails.validator_base import (\n    Validator,\n    ValidationResult,\n    PassResult,\n    FailResult,\n)\nfrom typing import Any, Dict, Optional, Callable\n\nclass MyValidator(Validator):\n    \"\"\"Description of what your validator does.\n    \n    ## (Optional) Intended Use\n    Describe the intended use of your validator.\n    \"\"\"\n\n    def __init__(\n        self,\n        arg_1: str,  # FIXME: Replace with your custom init args\n        on_fail: Optional[Callable] = None,\n    ):\n        \"\"\"Initializes a new instance of the MyValidator class.\n        \n        Args:\n            arg_1 (str): FIXME: Describe the purpose of this argument.\n            on_fail (str, Callable): The policy when validation fails.\n                If str, must be one of: reask, fix, filter, refrain, noop, \n                exception, or fix_reask.\n        \"\"\"\n        super().__init__(on_fail=on_fail, arg_1=arg_1)\n        self._arg_1 = arg_1\n\n    def validate(self, value: Any, metadata: Dict) -> ValidationResult:\n        \"\"\"Validates the passed value.\n        \n        Args:\n            value (Any): The value to validate.\n            metadata (Dict): Additional metadata for validation.\n        \n        Returns:\n            ValidationResult: PassResult or FailResult\n        \"\"\"\n        # Add custom validator logic here\n        if value == \"pass\":\n            return PassResult()\n        else:\n            return FailResult(\n                error_message=\"Validation failed: value must be 'pass'\"\n            )\n```\n\n资料来源：[guardrails/cli/hub/create_validator.py:1-80]()\n\n### Validator Template Structure\n\n| Section | Description |\n|---------|-------------|\n| Class Definition | Inherits from `Validator` base class |\n| Docstring | Description and usage examples |\n| `__init__` | Initialization with custom args and `on_fail` |\n| `validate` | Core validation logic returning `ValidationResult` |\n\n## Validator Initialization Parameters\n\n### Core Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `on_fail` | `str` or `Callable` | Yes | Policy when validation fails |\n| Custom args | Any | Varies | Validator-specific parameters |\n\n### On Fail Actions\n\n| Action | Behavior |\n|--------|----------|\n| `reask` | Re-ask the LLM for corrected output |\n| `fix` | Attempt to fix the invalid value |\n| `filter` | Remove the invalid value from output |\n| `refrain` | Refrain from providing any value |\n| `noop` | No operation, continue with original value |\n| `exception` | Raise an exception |\n| `fix_reask` | Fix and re-ask if fix fails |\n\n资料来源：[guardrails/validator_service_base.py:1-50]()\n\n## Installation and Registration\n\n### Installing from Local Path\n\nValidators can be installed directly from the repository:\n\n```bash\nguardrails hub install ./path/to/validator.py\n```\n\n### Package Structure for Hub Submission\n\nWhen preparing a validator for Guardrails Hub submission:\n\n```python\n# In your validator package\nfrom guardrails.validator_base import Validator, ValidationResult, PassResult, FailResult\n\nclass MyValidator(Validator):\n    \"\"\"My custom validator description.\"\"\"\n    \n    def __init__(self, threshold: float = 0.5, on_fail: str = None):\n        super().__init__(on_fail=on_fail, threshold=threshold)\n        self._threshold = threshold\n    \n    def validate(self, value: Any, metadata: Dict) -> ValidationResult:\n        # Custom validation logic\n        if self._check_condition(value):\n            return PassResult()\n        return FailResult(error_message=\"Condition not met\")\n```\n\n### Installation Process\n\n```mermaid\nsequenceDiagram\n    participant CLI as Guardrails CLI\n    participant Service as ValidatorPackageService\n    participant Hub as Guardrails Hub\n    participant Local as Local Environment\n    \n    CLI->>Service: install_hub_module(validator_id)\n    Service->>Hub: Fetch manifest\n    Service->>Local: Download dependencies\n    Service->>Local: Install via pip\n    Service-->>CLI: Installation complete\n```\n\nThe installation service handles:\n1. Validating the package URI\n2. Fetching the manifest from Guardrails Hub\n3. Downloading dependencies\n4. Installing the module via pip\n\n资料来源：[guardrails/hub/install.py:1-60]()\n资料来源：[guardrails/hub/validator_package_service.py]()\n\n## Using Custom Validators\n\n### Basic Usage with Guard\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import MyValidator\n\n# Create guard with custom validator\nguard = Guard().use(\n    MyValidator(threshold=0.5, on_fail=OnFailAction.EXCEPTION)\n)\n\n# Validate output\nresult = guard.validate(\"sample_output\")\n```\n\n### Using with Guardrails Hub Validators\n\nValidators from Guardrails Hub are accessed via the `hub` module:\n\n```python\nfrom guardrails.hub import RegexMatch, CompetitorCheck, ToxicLanguage\n\nguard = Guard().use(\n    RegexMatch(regex=r\"\\d{3}-\\d{4}\"),\n    CompetitorCheck([\"Apple\", \"Microsoft\"]),\n    ToxicLanguage(threshold=0.5, validation_method=\"sentence\")\n)\n```\n\n### Multiple Validators\n\nMultiple validators can be chained on the same output:\n\n```mermaid\ngraph LR\n    A[LLM Output] --> B[RegexMatch]\n    B -->|Pass| C[CompetitorCheck]\n    C -->|Pass| D[ToxicLanguage]\n    D -->|Pass| E[Final Output]\n    \n    B -->|Fail| F[On Fail: Exception]\n    C -->|Fail| F\n    D -->|Fail| F\n```\n\n## Validation Metadata\n\nValidators receive metadata during execution that can be used for contextual validation:\n\n```python\ndef validate(self, value: Any, metadata: Dict) -> ValidationResult:\n    \"\"\"Use metadata for contextual validation.\n    \n    Common metadata keys:\n    - prompt_params: Parameters used in the original prompt\n    - llm_response: Raw LLM response\n    - iterations: Number of validation iterations\n    \"\"\"\n    if \"custom_key\" in metadata:\n        # Use metadata for validation decisions\n        pass\n    \n    return PassResult()\n```\n\n资料来源：[guardrails/classes/history/call_inputs.py:1-60]()\n\n## Best Practices\n\n### Validator Design Guidelines\n\n1. **Single Responsibility**: Each validator should check one condition\n2. **Clear Error Messages**: Provide descriptive error messages for failures\n3. **Metadata Utilization**: Leverage metadata for contextual validation\n4. **Default Values**: Set sensible defaults for optional parameters\n5. **Documentation**: Document all parameters and intended use cases\n\n### Testing Custom Validators\n\n```python\nfrom guardrails import Guard\nfrom my_validator import MyValidator\n\nguard = Guard().use(MyValidator(arg=\"expected_value\"))\n\n# Test passing case\nresult = guard.validate(\"expected_value\")\nassert result.validation_passed\n\n# Test failing case\nresult = guard.validate(\"unexpected_value\")\nassert not result.validation_passed\n```\n\n## CLI Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| `guardrails hub create-validator <name>` | Create validator template |\n| `guardrails hub install <uri>` | Install a validator |\n| `guardrails hub install -l <uri>` | Install with local models |\n| `guardrails hub install -q <uri>` | Quiet installation |\n\n资料来源：[guardrails/cli/hub/create_validator.py:1-100]()\n资料来源：[guardrails/cli/hub/install.py:1-60]()\n\n## Integration with Guard Pipeline\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Guard.__call__]\n    B --> C[Call History Created]\n    C --> D[Iteration Loop]\n    D --> E[Run Validators]\n    E --> F{All Validators Pass?}\n    F -->|Yes| G[Return ValidationOutcome]\n    F -->|No| H[Apply On Fail Action]\n    H --> I{Reask Enabled?}\n    I -->|Yes| J[Re-ask LLM]\n    J --> D\n    I -->|No| G\n```\n\nThe Guard class orchestrates the validation pipeline, managing iterations and applying on-fail policies as configured.\n\n资料来源：[guardrails/guard.py:1-100]()\n资料来源：[guardrails/classes/history/call.py:1-50]()\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: guardrails-ai/guardrails\n\nSummary: Found 38 potential pitfall items; 14 are high/blocking. Highest priority: installation - 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?.\n\n## 1. installation · 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_69600563346341a386aa86c6af5d1274 | https://github.com/guardrails-ai/guardrails/issues/1448 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. installation · 来源证据：Feature request: OWASP ASI06 memory poisoning guard validator\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature request: OWASP ASI06 memory poisoning guard validator\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e44b7cdf7b674acf9789c9feddc13dbc | https://github.com/guardrails-ai/guardrails/issues/1488 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. installation · 来源证据：Portable evidence artifacts for validation outcomes\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Portable evidence artifacts for validation outcomes\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ef2970465bbe44c89b513edd115b682c | https://github.com/guardrails-ai/guardrails/issues/1457 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. installation · 来源证据：Proposal: Agent Threat Rules detection integration\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: Agent Threat Rules detection integration\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_64ae6a0aa3324a3a9af980f2f61a5c30 | https://github.com/guardrails-ai/guardrails/issues/1471 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. installation · 来源证据：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d7163e193eb54aab837d87b3ecd73991 | https://github.com/guardrails-ai/guardrails/issues/1453 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. installation · 来源证据：[bug] 429 Rate Limit Error from Opting into Metrics\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[bug] 429 Rate Limit Error from Opting into Metrics\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_3c9ae4fdd14547eea3c3a4be6ac6fb23 | https://github.com/guardrails-ai/guardrails/issues/1385 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. capability · 来源证据：[docs] Fix double logo display in pypi\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：[docs] Fix double logo display in pypi\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_084985c7cb4d4238a44e452b14b2eaf9 | https://github.com/guardrails-ai/guardrails/issues/1362 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 8. security_permissions · 失败模式：security_permissions: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication,...\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- User impact: Developers may expose sensitive permissions or credentials: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation. Context: Observed when using python\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1485\n- Evidence: failure_mode_cluster:github_issue | fmev_819ae3bfce09ed33a4655a81cf59dd44 | https://github.com/guardrails-ai/guardrails/issues/1485 | Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n\n## 9. security_permissions · 失败模式：security_permissions: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- User impact: Developers may expose sensitive permissions or credentials: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard. Context: Observed when using python\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1476\n- Evidence: failure_mode_cluster:github_issue | fmev_2c7b3b6f6709cc847b37fb56bc9973d3 | https://github.com/guardrails-ai/guardrails/issues/1476 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard, failure_mode_cluster:github_issue | fmev_77887b77c9dabcdbce93e8b20c9a7c57 | https://github.com/guardrails-ai/guardrails/issues/1475 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n## 10. security_permissions · 失败模式：security_permissions: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator wit...\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- User impact: Developers may expose sensitive permissions or credentials: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub. Context: Observed when using python, docker, cuda\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1479\n- Evidence: failure_mode_cluster:github_issue | fmev_70a43b34234fca351363180353991f27 | https://github.com/guardrails-ai/guardrails/issues/1479 | [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n\n## 11. security_permissions · 来源证据：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0f957598a5044976a69cdd1925dd9483 | https://github.com/guardrails-ai/guardrails/issues/1476 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. security_permissions · 来源证据：Integration proposal: Cryptographic audit trail validator with asqav\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: Cryptographic audit trail validator with asqav\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8db542ceccff4a71bc11c254ce3abfde | https://github.com/guardrails-ai/guardrails/issues/1446 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 13. security_permissions · 来源证据：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_da275c0a112848ed920af00c76fd3e1b | https://github.com/guardrails-ai/guardrails/issues/1463 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 14. security_permissions · 来源证据：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_3f90fdd47b014d488f2782f04c75b37c | https://github.com/guardrails-ai/guardrails/issues/1479 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 15. installation · 失败模式：installation: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- User impact: Developers may fail before the first successful local run: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: styxx hallucination validator (8-benchmark cross-validated). Context: Observed when using python, cuda\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_2a7dfe1829e559543fd3177ac3a0ace3 | https://github.com/guardrails-ai/guardrails/issues/1463 | Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n## 16. installation · 失败模式：installation: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n- User impact: Developers may fail before the first successful local run: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+). Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_b8ff8a254ff16e4d23faa27660558c49 | https://github.com/guardrails-ai/guardrails/issues/1483 | Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n\n## 17. installation · 失败模式：installation: Proposal: Agent Threat Rules detection integration\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Proposal: Agent Threat Rules detection integration\n- User impact: Developers may fail before the first successful local run: Proposal: Agent Threat Rules detection integration\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Proposal: Agent Threat Rules detection integration. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6bc24f2942ba0fbe13c0d348506bf619 | https://github.com/guardrails-ai/guardrails/issues/1471 | Proposal: Agent Threat Rules detection integration\n\n## 18. installation · 失败模式：installation: [bug] 429 Rate Limit Error from Opting into Metrics\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] 429 Rate Limit Error from Opting into Metrics\n- User impact: Developers may fail before the first successful local run: [bug] 429 Rate Limit Error from Opting into Metrics\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] 429 Rate Limit Error from Opting into Metrics. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_c0442e907dbee8c67e3e11968abd509a | https://github.com/guardrails-ai/guardrails/issues/1385 | [bug] 429 Rate Limit Error from Opting into Metrics\n\n## 19. installation · 失败模式：installation: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'N...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- User impact: Developers may fail before the first successful local run: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'. Context: Observed when using python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4e9aa8a1b02d1ede79b30b62ddb6ceba | https://github.com/guardrails-ai/guardrails/issues/1477 | [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n\n## 20. installation · 失败模式：installation: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n- User impact: Developers may fail before the first successful local run: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2. Context: Observed when using python, macos\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_3d41c127084ca13dab398cfd91d3a12e | https://github.com/guardrails-ai/guardrails/issues/1464 | [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n\n## 21. installation · 失败模式：installation: v0.9.2\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: v0.9.2\n- User impact: Upgrade or migration may change expected behavior: v0.9.2\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: v0.9.2. Context: Observed when using node, python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_release | fmev_c54b42261d198f5d86e2d86b973022b2 | https://github.com/guardrails-ai/guardrails/releases/tag/v0.9.2 | v0.9.2\n\n## 22. installation · 失败模式：installation: v0.9.3\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: v0.9.3\n- User impact: Upgrade or migration may change expected behavior: v0.9.3\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: v0.9.3. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_release | fmev_ccf3f3888877fa148fd2b9e4d1685a07 | https://github.com/guardrails-ai/guardrails/releases/tag/v0.9.3 | v0.9.3\n\n## 23. configuration · 失败模式：configuration: Integration proposal: Cryptographic audit trail validator with asqav\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Integration proposal: Cryptographic audit trail validator with asqav\n- User impact: Developers may misconfigure credentials, environment, or host setup: Integration proposal: Cryptographic audit trail validator with asqav\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: Cryptographic audit trail validator with asqav. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_3e83bc4e63af89b800f024f286804a55 | https://github.com/guardrails-ai/guardrails/issues/1446 | Integration proposal: Cryptographic audit trail validator with asqav\n\n## 24. configuration · 失败模式：configuration: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- User impact: Developers may misconfigure credentials, environment, or host setup: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails. Context: Observed when using node, python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_505b8100ee11945f0044da14ce3d5045 | https://github.com/guardrails-ai/guardrails/issues/1435 | MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n## 25. configuration · 失败模式：configuration: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- User impact: Developers may misconfigure credentials, environment, or host setup: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_7ce2d4758da469cfafebf0b41e8f8f3f | https://github.com/guardrails-ai/guardrails/issues/1453 | Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n## 26. configuration · 来源证据：[feat] Attempt to repair JSON before triggering NonParseableReAsk\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[feat] Attempt to repair JSON before triggering NonParseableReAsk\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0e5b292fafab4cdfb39c7541516cecb7 | https://github.com/guardrails-ai/guardrails/issues/1380 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 27. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | README/documentation is current enough for a first validation pass.\n\n## 28. runtime · 失败模式：runtime: Portable evidence artifacts for validation outcomes\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: Portable evidence artifacts for validation outcomes\n- User impact: Developers may hit a documented source-backed failure mode: Portable evidence artifacts for validation outcomes\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Portable evidence artifacts for validation outcomes. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_2379f90244868de9553a10aa0783be57 | https://github.com/guardrails-ai/guardrails/issues/1457 | Portable evidence artifacts for validation outcomes\n\n## 29. runtime · 失败模式：runtime: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- User impact: Developers may hit a documented source-backed failure mode: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: on_fail=\"refrain\" behavior unclear/inconsistent with documentation. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6963ac9f9e50fbdabe6896ca38295267 | https://github.com/guardrails-ai/guardrails/issues/1395 | on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n## 30. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | last_activity_observed missing\n\n## 31. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | no_demo; severity=medium\n\n## 32. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | no_demo; severity=medium\n\n## 33. security_permissions · 来源证据：Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolat…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_222c3a7398b845d58afc8e03e3cd2d56 | https://github.com/guardrails-ai/guardrails/issues/1485 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 34. security_permissions · 来源证据：MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b6a63df899144908af33089886cfaf51 | https://github.com/guardrails-ai/guardrails/issues/1435 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 35. security_permissions · 来源证据：[bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution fo…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_f801c42622884292b29b3ae18f365af6 | https://github.com/guardrails-ai/guardrails/issues/1477 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 36. security_permissions · 来源证据：on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8881807252f149aeb7bc2c3a46019ce0 | https://github.com/guardrails-ai/guardrails/issues/1395 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 37. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | issue_or_pr_quality=unknown\n\n## 38. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | release_recency=unknown\n\n<!-- canonical_name: guardrails-ai/guardrails; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "guardrails",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:594609262",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/guardrails-ai/guardrails"
        },
        {
          "evidence_id": "art_bb3495c4c9b741779d972b7633462e32",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/guardrails-ai/guardrails#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "guardrails 说明书",
      "toc": [
        "https://github.com/guardrails-ai/guardrails 项目说明书",
        "目录",
        "Getting Started with Guardrails",
        "Overview",
        "Installation",
        "Clone the repository",
        "Install in development mode",
        "Install pre-commit hooks",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "28d74af02215f3d09e6527238f783c561218d539",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "README.md",
      "docs/pydocs/helpers.py",
      "docs/pydocs/pydocs_markdown_impl.py",
      "docs/pydocs/generate_pydocs.py",
      "docs/pydocs/pydocs_to_md.py",
      "docs/how_to_guides/rail.md",
      "docs/how_to_guides/output.md",
      "docs/api_reference/llm_interaction.md",
      "docs/api_reference/history_and_logs.md",
      "docs/api_reference/errors.md",
      "docs/api_reference/guards.md",
      "docs/api_reference/actions.md",
      "docs/api_reference/validator.md",
      "docs/api_reference/types.md",
      "docs/api_reference/formatters.md",
      "docs/api_reference/generics_and_base_classes.md",
      "docs/examples/data/config.py",
      "docs/pydocs/api_reference/llm_interaction.py",
      "docs/pydocs/api_reference/generics_and_base_classes.py",
      "docs/pydocs/api_reference/validation.py",
      "docs/pydocs/api_reference/history.py",
      "docs/pydocs/api_reference/guards.py",
      "docs/pydocs/api_reference/formatters.py",
      "docs/pydocs/api_reference/types.py",
      "docs/pydocs/api_reference/actions.py",
      "docs/pydocs/api_reference/errors.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# guardrails - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 guardrails 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `pip install guardrails-ai` 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：真实输出质量不能在安装前相信。\n- **继续会触碰**：命令执行、本地环境或项目文件、环境变量 / API Key\n\n### 现在可以相信\n\n- **适合人群线索：想在安装前理解开源项目价值和边界的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `guardrails/api_client.py`, `guardrails/cli/hub/create_validator.py`, `guardrails/utils/openai_utils/v1.py` 等\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0004` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：546\n- 重要文件覆盖：40/546\n- 证据索引条目：59\n- 角色 / Skill 条目：17\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 guardrails 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 guardrails 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 guardrails 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 17 个角色 / Skill / 项目文档条目。\n\n- **News and Updates**（project_doc）：! License https://img.shields.io/badge/License-Apache 2.0-blue.svg https://opensource.org/licenses/Apache-2.0 ! PyPI - Python Version https://img.shields.io/pypi/pyversions/guardrails-ai ! Downloads https://static.pepy.tech/badge/guardrails-ai/month https://pepy.tech/project/guardrails-ai ! CI https://github.com/guardrails-ai/guardrails/actions/workflows/ci.yml/badge.svg https://github.com/guardrails-ai/guardrails/a… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Contributing to Guardrails**（project_doc）：Welcome and thank you for your interest in contributing to Guardrails! We appreciate all contributions, big or small, from bug fixes to new features. Before diving in, let's go through some guidelines to make the process smoother for everyone. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Actions**（project_doc）：- incorrect value Any - The value that failed validation. - fail results List FailResult - The results of the failed validations. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/actions.md`\n- **Errors**（project_doc）：This is thrown from the validation engine when a Validator has on fail=OnFailActions.EXCEPTION set and validation fails. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/errors.md`\n- **Formatters**（project_doc）：A Formatter takes an LLM Callable and wraps the method into an abstract callable. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/formatters.md`\n- **Generics And Base Classes**（project_doc）：Empty Pydantic model with a config that allows arbitrary types. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/generics_and_base_classes.md`\n- **Guards**（project_doc）：This class is the main entry point for using Guardrails. It can be initialized by one of the following patterns: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/guards.md`\n- **History and Logs**（project_doc）：A Call represents a single execution of a Guard. One Call is created each time the user invokes the Guard. call , Guard.parse , or Guard.validate method. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/history_and_logs.md`\n- **Helpers for LLM Interactions**（project_doc）：Class for representing a prompt entry. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/llm_interaction.md`\n- **Types**（project_doc）：OnFailAction is an Enum that represents the different actions that can be taken when a validation fails. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/types.md`\n- **Validation**（project_doc）：Do not override this function, instead implement validate . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/api_reference/validator.md`\n- **Output Element**（project_doc）：The ... element of a RAIL spec is used to give precise specification of the expected output of the LLM. It specifies 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/how_to_guides/output.md`\n- **Use Guardrails via RAIL**（project_doc）：.RAIL is a dialect of XML. It stands for \" R eliable AI markup L anguage\", and it can be used to define: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/how_to_guides/rail.md`\n- **Security Advisory: Malicious code in guardrails-ai 0.10.1**（project_doc）：Security Advisory: Malicious code in guardrails-ai 0.10.1 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY_ADVISORY.md`\n- **Bug report**（project_doc）：Describe the bug A clear and concise description of what the bug is. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Documentation issue**（project_doc）：Description Add a clear description of the documentation issue or improvement suggestion 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/documentation.md`\n- **Feature request**（project_doc）：Description Add a description of the feature 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n\n## 证据索引\n\n- 共索引 59 条证据。\n\n- **News and Updates**（documentation）：! License https://img.shields.io/badge/License-Apache 2.0-blue.svg https://opensource.org/licenses/Apache-2.0 ! PyPI - Python Version https://img.shields.io/pypi/pyversions/guardrails-ai ! Downloads https://static.pepy.tech/badge/guardrails-ai/month https://pepy.tech/project/guardrails-ai ! CI https://github.com/guardrails-ai/guardrails/actions/workflows/ci.yml/badge.svg https://github.com/guardrails-ai/guardrails/actions/workflows/ci.yml ! codecov https://codecov.io/gh/guardrails-ai/guardrails/graph/badge.svg?token=CPkjw91Ngo https://codecov.io/gh/guardrails-ai/guardrails ! Checked with pyright https://microsoft.github.io/pyright/img/pyright badge.svg https://microsoft.github.io/pyright/ !… 证据：`README.md`\n- **Contributing to Guardrails**（documentation）：Welcome and thank you for your interest in contributing to Guardrails! We appreciate all contributions, big or small, from bug fixes to new features. Before diving in, let's go through some guidelines to make the process smoother for everyone. 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`\n- **Actions**（documentation）：- incorrect value Any - The value that failed validation. - fail results List FailResult - The results of the failed validations. 证据：`docs/api_reference/actions.md`\n- **Errors**（documentation）：This is thrown from the validation engine when a Validator has on fail=OnFailActions.EXCEPTION set and validation fails. 证据：`docs/api_reference/errors.md`\n- **Formatters**（documentation）：A Formatter takes an LLM Callable and wraps the method into an abstract callable. 证据：`docs/api_reference/formatters.md`\n- **Generics And Base Classes**（documentation）：Empty Pydantic model with a config that allows arbitrary types. 证据：`docs/api_reference/generics_and_base_classes.md`\n- **Guards**（documentation）：This class is the main entry point for using Guardrails. It can be initialized by one of the following patterns: 证据：`docs/api_reference/guards.md`\n- **History and Logs**（documentation）：A Call represents a single execution of a Guard. One Call is created each time the user invokes the Guard. call , Guard.parse , or Guard.validate method. 证据：`docs/api_reference/history_and_logs.md`\n- **Helpers for LLM Interactions**（documentation）：Class for representing a prompt entry. 证据：`docs/api_reference/llm_interaction.md`\n- **Types**（documentation）：OnFailAction is an Enum that represents the different actions that can be taken when a validation fails. 证据：`docs/api_reference/types.md`\n- **Validation**（documentation）：Do not override this function, instead implement validate . 证据：`docs/api_reference/validator.md`\n- **Output Element**（documentation）：The ... element of a RAIL spec is used to give precise specification of the expected output of the LLM. It specifies 证据：`docs/how_to_guides/output.md`\n- **Use Guardrails via RAIL**（documentation）：.RAIL is a dialect of XML. It stands for \" R eliable AI markup L anguage\", and it can be used to define: 证据：`docs/how_to_guides/rail.md`\n- **Security Advisory: Malicious code in guardrails-ai 0.10.1**（documentation）：Security Advisory: Malicious code in guardrails-ai 0.10.1 证据：`SECURITY_ADVISORY.md`\n- **Bug Report**（documentation）：Describe the bug A clear and concise description of what the bug is. 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Documentation**（documentation）：Description Add a clear description of the documentation issue or improvement suggestion 证据：`.github/ISSUE_TEMPLATE/documentation.md`\n- **Feature Request**（documentation）：Description Add a description of the feature 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n- **Pyrightconfig**（structured_config）：{ \"reportDeprecated\": true } 证据：`pyrightconfig.json`\n- **Guard Template**（structured_config）：{ \"name\": \"server-ci\", \"description\": \"basic guard template for oss server ci\", \"template version\": \"0.0.1\", \"namespace\": \"guardrails\", \"guards\": { \"id\": \"test-guard\", \"name\": \"test-guard\", \"validators\": { \"id\": \"guardrails/two words\", \"on\": \"$\", \"onFail\": \"fix\" } } } 证据：`server_ci/guard-template.json`\n- **Config**（structured_config）：{ \" name or path\": \"hf-internal-testing/tiny-random-gpt2\", \"activation function\": \"gelu new\", \"architectures\": \"GPT2LMHeadModel\" , \"attention probs dropout prob\": 0.1, \"attn pdrop\": 0.1, \"bos token id\": 98, \"embd pdrop\": 0.1, \"eos token id\": 98, \"gradient checkpointing\": false, \"hidden act\": \"gelu\", \"hidden dropout prob\": 0.1, \"initializer range\": 0.02, \"intermediate size\": 37, \"layer norm epsilon\": 1e-05, \"model type\": \"gpt2\", \"n ctx\": 512, \"n embd\": 32, \"n head\": 4, \"n inner\": null, \"n layer\": 5, \"n positions\": 512, \"pad token id\": 98, \"reorder and upcast attn\": false, \"resid pdrop\": 0.1, \"scale attn by inverse layer idx\": false, \"scale attn weights\": true, \"summary activation\": null, \"su… 证据：`tests/unit_tests/mocks/tiny-random-gpt2/config.json`\n- **Generation Config**（structured_config）：{ \" from model config\": true, \"bos token id\": 98, \"eos token id\": 98, \"pad token id\": 98, \"transformers version\": \"4.36.2\" } 证据：`tests/unit_tests/mocks/tiny-random-gpt2/generation_config.json`\n- **Special Tokens Map**（structured_config）：{ \"bos token\": { \"content\": \" \", \"lstrip\": false, \"normalized\": false, \"rstrip\": false, \"single word\": false }, \"eos token\": { \"content\": \" \", \"lstrip\": false, \"normalized\": false, \"rstrip\": false, \"single word\": false }, \"unk token\": { \"content\": \" \", \"lstrip\": false, \"normalized\": false, \"rstrip\": false, \"single word\": false } } 证据：`tests/unit_tests/mocks/tiny-random-gpt2/special_tokens_map.json`\n- **Tokenizer**（structured_config）：{ \"version\": \"1.0\", \"truncation\": null, \"padding\": null, \"added tokens\": { \"id\": 0, \"content\": \" \", \"single word\": false, \"lstrip\": false, \"rstrip\": false, \"normalized\": false, \"special\": true } , \"normalizer\": null, \"pre tokenizer\": { \"type\": \"ByteLevel\", \"add prefix space\": false, \"trim offsets\": true, \"use regex\": true }, \"post processor\": { \"type\": \"ByteLevel\", \"add prefix space\": true, \"trim offsets\": false, \"use regex\": true }, \"decoder\": { \"type\": \"ByteLevel\", \"add prefix space\": true, \"trim offsets\": true, \"use regex\": true }, \"model\": { \"type\": \"BPE\", \"dropout\": null, \"unk token\": null, \"continuing subword prefix\": \"\", \"end of word suffix\": \"\", \"fuse unk\": false, \"byte fallback\": f… 证据：`tests/unit_tests/mocks/tiny-random-gpt2/tokenizer.json`\n- **Tokenizer Config**（structured_config）：{ \"add prefix space\": false, \"added tokens decoder\": { \"0\": { \"content\": \" \", \"lstrip\": false, \"normalized\": false, \"rstrip\": false, \"single word\": false, \"special\": true } }, \"bos token\": \" \", \"clean up tokenization spaces\": true, \"eos token\": \" \", \"model max length\": 1024, \"tokenizer class\": \"GPT2Tokenizer\", \"unk token\": \" \" } 证据：`tests/unit_tests/mocks/tiny-random-gpt2/tokenizer_config.json`\n- **Vocab**（structured_config）：{\" \":0,\"!\":1,\"\\\"\":2,\" \":3,\"$\":4,\"%\":5,\"&\":6,\"'\":7,\" \":8,\" \":9,\" \":10,\"+\":11,\",\":12,\"-\":13,\".\":14,\"/\":15,\"0\":16,\"1\":17,\"2\":18,\"3\":19,\"4\":20,\"5\":21,\"6\":22,\"7\":23,\"8\":24,\"9\":25,\":\":26,\";\":27,\" \":30,\"?\":31,\"@\":32,\"A\":33,\"B\":34,\"C\":35,\"D\":36,\"E\":37,\"F\":38,\"G\":39,\"H\":40,\"I\":41,\"J\":42,\"K\":43,\"L\":44,\"M\":45,\"N\":46,\"O\":47,\"P\":48,\"Q\":49,\"R\":50,\"S\":51,\"T\":52,\"U\":53,\"V\":54,\"W\":55,\"X\":56,\"Y\":57,\"Z\":58,\" \":59,\"\\\\\":60,\" \":61,\"^\":62,\" \":63,\" \":64,\"a\":65,\"b\":66,\"c\":67,\"d\":68,\"e\":69,\"f\":70,\"g\":71,\"h\":72,\"i\":73,\"j\":74,\"k\":75,\"l\":76,\"m\":77,\"n\":78,\"o\":79,\"p\":80,\"q\":81,\"r\":82,\"s\":83,\"t\":84,\"u\":85,\"v\":86,\"w\":87,\"x\":88,\"y\":89,\"z\":90,\" \":91,\"}\":92,\"~\":93,\"¡\":94,\"¢\":95,\"£\":96,\"¤\":97,\"¥\":98,\"¦\":99,\"§\":100,\"¨\":101,\"©\":… 证据：`tests/unit_tests/mocks/tiny-random-gpt2/vocab.json`\n- **.dockerignore**（source_file）：pycache .pyc .pyo 证据：`.dockerignore`\n- **.gitignore**（source_file）：openai api key.txt pycache data/ .vscode/ .venv/ .DS Store .ipynb checkpoints/ .pyc .env .log .venv settings.json site/ guardrails.log guardrails ai.egg-info/ /build/ docs/build !docs/dist/ dist/ .rail output .idea/ .cache scratch/ scratch.py .coverage coverage.xml test.db test.index htmlcov node modules .docusaurus .vercel !docs/examples-toc.json .python-version static/docs docusaurus/static/docs /bin/ /etc/ /lib/ /lib64/ /include/ /share/ pyvenv.cfg mlruns mlartifacts /.guardrails .claude .idea .pytest cache .ruff cache .vscode docs/examples/.guardrails/hub registry.json 证据：`.gitignore`\n- **Performs ruff check with safe fixes**（source_file）：repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.13.0 hooks: Performs ruff check with safe fixes - id: ruff name: ruff description: \"Run 'ruff' for linting\" args: \"--fix\" Performs ruff format - id: ruff-format name: ruff-format description: \"Run 'ruff format' for formatting\" 证据：`.pre-commit-config.yaml`\n- **pytest -x -q --no-summary**（source_file）：.PHONY: autoformat type lint test test-basic test-cov view-test-cov view-test-cov-file dev full install docs-gen self-install all precommit refresh update-lock 证据：`Makefile`\n- **Codecov**（source_file）：ignore: - \"guardrails/version.py\" - \"tests\" 证据：`codecov.yml`\n- **Set up init .py so that users can do from guardrails import Response, Schema, etc.**（source_file）：Set up init .py so that users can do from guardrails import Response, Schema, etc. 证据：`guardrails/__init__.py`\n- **Api Client**（source_file）：import json import os from typing import Any, AsyncIterator, Iterator, Optional 证据：`guardrails/api_client.py`\n- **check if validator requirements are fulfilled**（source_file）：from builtins import id as object id import contextvars import inspect from opentelemetry import context as otel context from typing import Any, AsyncIterator, Awaitable, Callable, Dict, Generic, List, Optional, Sequence, Union, cast, 证据：`guardrails/async_guard.py`\n- **Constants**（source_file）：Return a valid JSON object that respects this JSON Schema and extracts only the information requested in this document. Respect the types indicated in the JSON Schema -- the information you extract should be converted into the correct 'type'. Try to be as correct and concise as possible. Find all relevant information in the document. If you are unsure of the answer, enter 'None'. If you answer incorrectly, you will be asked again until you get it right which is expensive. 证据：`guardrails/constants.xml`\n- **Datatypes**（source_file）：from guardrails.types.simple import SimpleTypes from guardrails.types.rail import RailTypes 证据：`guardrails/datatypes.py`\n- **PageCoordinates is a datastructure that points to the location**（source_file）：import hashlib from abc import ABC, abstractmethod from collections import namedtuple from dataclasses import dataclass from typing import Any, Dict, List, Optional 证据：`guardrails/document_store.py`\n- **Detokenize the chunks**（source_file）：from abc import ABC, abstractmethod from functools import cached property from itertools import islice from typing import Callable, List, Optional 证据：`guardrails/embedding.py`\n- **Prevent duplicate declaration in the docs**（source_file）：import contextvars import json import os import uuid from builtins import id as object id from typing import Any, Callable, Dict, Generic, Iterator, List, Optional, Sequence, Union, cast, Iterable, import warnings from langchain core.runnables import Runnable 证据：`guardrails/guard.py`\n- **Llm Providers**（source_file）：import inspect from typing import Any, Awaitable, Callable, Dict, Iterator, List, Optional, Union, cast, 证据：`guardrails/llm_providers.py`\n- **from src.modules.otel logger import handler as otel handler**（source_file）：import logging import logging.config from logging import Handler, LogRecord from typing import Dict, List, Optional 证据：`guardrails/logger.py`\n- **TODO: Support a sink for logs so that they are not solely held in memory**（source_file）：from guardrails.logger import set config, set level 证据：`guardrails/logging_utils.py`\n- **SOURCE: https://github.com/spyder-ide/three-merge/blob/master/three merge/merge.py**（source_file）：SOURCE: https://github.com/spyder-ide/three-merge/blob/master/three merge/merge.py from typing import Optional from diff match patch import diff match patch 证据：`guardrails/merge.py`\n- **Settings**（source_file）：import threading from typing import Optional 证据：`guardrails/settings.py`\n- **TODO:**（source_file）：TODO: - Rename this to just validator.py 0.5.x - Maintain validator base.py for exports but deprecate them - Remove validator base.py in 0.6.x 证据：`guardrails/validator_base.py`\n- **Version**（source_file）：from importlib.metadata import version as importlib version 证据：`guardrails/version.py`\n- **TODO - drop this!**（source_file）：project name = \"guardrails-ai\" version = \"0.10.0\" description = \"Adding guardrails to large language models.\" authors = {name = \"Guardrails AI\", email = \"contact@guardrailsai.com\"} license = \"Apache License 2.0\" license-files = \"LICENSE\" homepage = \"https://www.guardrailsai.com/\" documentation = \"https://www.guardrailsai.com/guardrails/docs\" readme = \"README.md\" requires-python = \" =3.10,<4.0\" 证据：`pyproject.toml`\n- **server_ci/.dockerignore**（source_file）：.coverage .coverage.MacBook-Pro.local.75130.XUoRtLxx .dockerignore .docusaurus .git .github .gitignore .idea .pre-commit-config.yaml .pytest cache .python-version .ruff cache .venv .vscode build codecov.yml CONTRIBUTING.md docs docs-build docs/build docs-graveyard DOCS.md docusaurus htmlcov make.bat mlartifacts mlruns node modules package-lock.json package.json tests .venv 证据：`server_ci/.dockerignore`\n- **New LiteLLM version has a dependency on madoka which requires g++ to build the wheel**（source_file）：New LiteLLM version has a dependency on madoka which requires g++ to build the wheel FROM python:3.13 证据：`server_ci/Dockerfile`\n- **!/bin/bash**（source_file）：bash ./server ci/build.sh; bash ./server ci/run.sh; bash ./server ci/check.sh; bash ./server ci/test.sh; bash ./server ci/clean.sh; 证据：`server_ci/all.sh`\n- **!/bin/bash**（source_file）：docker buildx build \\ --platform linux/amd64 \\ -f \"./server ci/Dockerfile\" \\ -t \"guardrails:server-ci\" \\ --build-arg GUARDRAILS TOKEN=\"$GUARDRAILS TOKEN\" \\ --progress plain \\ --load . \\ exit 1 证据：`server_ci/build.sh`\n- **!/bin/bash**（source_file）：for i in {1..30}; do if docker exec guardrails-container curl -s http://localhost:8000/; then echo \"Server is up!\" break fi echo \"Waiting for server...\" sleep 5 done 证据：`server_ci/check.sh`\n- **!/bin/bash**（source_file）：!/bin/bash docker stop guardrails-container true docker rm guardrails-container true 证据：`server_ci/clean.sh`\n- **instantiate guards**（source_file）：import json import os from guardrails import Guard 证据：`server_ci/config.py`\n- **Fastapi Entry**（source_file）：uvicorn guardrails api.app:create app \\ --workers 3 \\ --host 0.0.0.0 \\ --port 8000 \\ --timeout-keep-alive 20 \\ --timeout-graceful-shutdown 60; 证据：`server_ci/fastapi-entry.sh`\n- **Requirements**（source_file）：pytest pytest-asyncio openai 证据：`server_ci/requirements.txt`\n- **!/bin/bash**（source_file）：docker stop guardrails-container true docker rm guardrails-container true docker run -d --name guardrails-container -p 8000:8000 -e OPENAI API KEY=$OPENAI API KEY guardrails:server-ci exit 1 证据：`server_ci/run.sh`\n- **Test Spec**（source_file）：Answer the question: What is 2+2? 证据：`test_spec.rail`\n- **Conftest**（source_file）：import os import pytest from unittest.mock import patch, MagicMock 证据：`tests/conftest.py`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `CONTRIBUTING.md`, `LICENSE`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `CONTRIBUTING.md`, `LICENSE`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\nThe following material strengthens the Repomix/AI Context Pack body. Human Manual is only a reading skeleton; pitfall logs become hard operating constraints for the host AI.\n\n## Human Manual Skeleton\n\nUsage rule: this is only a reading path and salience signal, not factual authority. Concrete facts must still come from repo evidence / Claim Graph.\n\nHard rules for the host AI:\n- Do not treat page titles, order, summaries, or importance as project facts.\n- When explaining the Human Manual skeleton, state that it is only a reading path / salience signal.\n- Capability, installation, compatibility, runtime status, and risk judgments must cite repo evidence, source paths, or Claim Graph.\n\n- **Getting Started with Guardrails**：importance `high`\n  - source_paths: README.md, guardrails/__init__.py, guardrails/version.py\n- **System Architecture**：importance `high`\n  - source_paths: guardrails/guard.py, guardrails/async_guard.py, guardrails/validator_service/validator_service_base.py, guardrails/classes/schema/processed_schema.py\n- **Guard Class Reference**：importance `high`\n  - source_paths: guardrails/guard.py, guardrails/schema/pydantic_schema.py, guardrails/types/on_fail.py, guardrails/classes/validation_outcome.py\n- **Validators System**：importance `high`\n  - source_paths: guardrails/validator_base.py, guardrails/validator_service/sequential_validator_service.py, guardrails/classes/validation/validation_result.py, guardrails/classes/validation/validation_summary.py\n- **Schema Processing**：importance `high`\n  - source_paths: guardrails/schema/rail_schema.py, guardrails/schema/pydantic_schema.py, guardrails/schema/primitive_schema.py, guardrails/schema/validator.py\n- **Execution Pipeline**：importance `high`\n  - source_paths: guardrails/run/runner.py, guardrails/run/stream_runner.py, guardrails/run/async_runner.py, guardrails/actions/reask.py, guardrails/utils/parsing_utils.py\n- **Async and Streaming Support**：importance `medium`\n  - source_paths: guardrails/run/async_runner.py, guardrails/run/async_stream_runner.py, guardrails/run/stream_runner.py, guardrails/validator_service/async_validator_service.py\n- **LLM Provider Integration**：importance `high`\n  - source_paths: guardrails/llm_providers.py, guardrails/prompt/prompt.py, guardrails/prompt/messages.py, guardrails/classes/llm/prompt_callable.py\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `28d74af02215f3d09e6527238f783c561218d539`\n- inspected_files: `pyproject.toml`, `README.md`, `docs/pydocs/helpers.py`, `docs/pydocs/pydocs_markdown_impl.py`, `docs/pydocs/generate_pydocs.py`, `docs/pydocs/pydocs_to_md.py`, `docs/how_to_guides/rail.md`, `docs/how_to_guides/output.md`, `docs/api_reference/llm_interaction.md`, `docs/api_reference/history_and_logs.md`, `docs/api_reference/errors.md`, `docs/api_reference/guards.md`, `docs/api_reference/actions.md`, `docs/api_reference/validator.md`, `docs/api_reference/types.md`, `docs/api_reference/formatters.md`, `docs/api_reference/generics_and_base_classes.md`, `docs/examples/data/config.py`, `docs/pydocs/api_reference/llm_interaction.py`, `docs/pydocs/api_reference/generics_and_base_classes.py`\n\nHard rules for the host AI:\n- Without repo_clone_verified=true, do not claim the source code has been read.\n- Without repo_inspection_verified=true, do not turn README/docs/package observations into facts.\n- Without quick_start_verified=true, do not claim the Quick Start has been successfully run.\n\n## Doramagic Pitfall Constraints\n\nThese rules come from Doramagic discovery, validation, or compilation pitfalls. The host AI must treat them as operating constraints, not general background notes.\n\n### Constraint 1: 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_69600563346341a386aa86c6af5d1274 | https://github.com/guardrails-ai/guardrails/issues/1448 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 2: 来源证据：Feature request: OWASP ASI06 memory poisoning guard validator\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature request: OWASP ASI06 memory poisoning guard validator\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_e44b7cdf7b674acf9789c9feddc13dbc | https://github.com/guardrails-ai/guardrails/issues/1488 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 3: 来源证据：Portable evidence artifacts for validation outcomes\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Portable evidence artifacts for validation outcomes\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_ef2970465bbe44c89b513edd115b682c | https://github.com/guardrails-ai/guardrails/issues/1457 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 4: 来源证据：Proposal: Agent Threat Rules detection integration\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: Agent Threat Rules detection integration\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_64ae6a0aa3324a3a9af980f2f61a5c30 | https://github.com/guardrails-ai/guardrails/issues/1471 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 5: 来源证据：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_d7163e193eb54aab837d87b3ecd73991 | https://github.com/guardrails-ai/guardrails/issues/1453 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 6: 来源证据：[bug] 429 Rate Limit Error from Opting into Metrics\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[bug] 429 Rate Limit Error from Opting into Metrics\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_3c9ae4fdd14547eea3c3a4be6ac6fb23 | https://github.com/guardrails-ai/guardrails/issues/1385 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 7: 来源证据：[docs] Fix double logo display in pypi\n\n- Trigger: GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：[docs] Fix double logo display in pypi\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_084985c7cb4d4238a44e452b14b2eaf9 | https://github.com/guardrails-ai/guardrails/issues/1362 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 8: 失败模式：security_permissions: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication,...\n\n- Trigger: Developers should check this security_permissions risk before relying on the project: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation. Context: Observed when using python\n- Why it matters: Developers may expose sensitive permissions or credentials: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- Evidence: failure_mode_cluster:github_issue | fmev_819ae3bfce09ed33a4655a81cf59dd44 | https://github.com/guardrails-ai/guardrails/issues/1485 | Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 9: 失败模式：security_permissions: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Trigger: Developers should check this security_permissions risk before relying on the project: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard. Context: Observed when using python\n- Why it matters: Developers may expose sensitive permissions or credentials: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- Evidence: failure_mode_cluster:github_issue | fmev_2c7b3b6f6709cc847b37fb56bc9973d3 | https://github.com/guardrails-ai/guardrails/issues/1476 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard, failure_mode_cluster:github_issue | fmev_77887b77c9dabcdbce93e8b20c9a7c57 | https://github.com/guardrails-ai/guardrails/issues/1475 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 10: 失败模式：security_permissions: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator wit...\n\n- Trigger: Developers should check this security_permissions risk before relying on the project: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub. Context: Observed when using python, docker, cuda\n- Why it matters: Developers may expose sensitive permissions or credentials: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- Evidence: failure_mode_cluster:github_issue | fmev_70a43b34234fca351363180353991f27 | https://github.com/guardrails-ai/guardrails/issues/1479 | [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n",
      "summary": "Context and operating boundaries for host AI agents.",
      "title": "AI Context Pack"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card\n\nProject: guardrails-ai/guardrails\n\n## Doramagic Trial Decision\n\nCurrent decision: it can enter pre-publication recommendation checks. First use should still start with least privilege, a temporary directory, and reversible configuration.\n\n## What The User Can Do Now\n\n- Read the Human Manual first to understand the project purpose and main workflows.\n- Use Prompt Preview for pre-install exploration; it validates interaction shape, not real execution.\n- Run official Quick Start commands only inside an isolated environment, not a primary setup.\n\n## Do Not Do Yet\n\n- Do not treat Prompt Preview as a real project execution result.\n- Do not treat metadata-only validation as sandbox installation validation.\n- Do not describe unverified capabilities as supported, working, or safe to install.\n- Do not provide production data, private files, real secrets, or primary host configuration on first trial.\n\n## Pre-Install Checklist\n\n- Host AI match: chatgpt\n- Official installation entry status: official entry point found\n- Isolated temporary directory, temporary host, or container validation: required\n- Configuration rollback path: required\n- API keys, network access, file access, or host configuration changes: treat as high risk until confirmed\n- Installation command, actual output, and failure logs: must be recorded\n\n## Current Blockers\n\n- No blockers.\n\n## Project-Specific Pitfalls\n\n- 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX? (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Feature request: OWASP ASI06 memory poisoning guard validator (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Portable evidence artifacts for validation outcomes (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Proposal: Agent Threat Rules detection integration (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n\n## Risk And Permission Notes\n\n- no_demo: medium\n\n## Evidence Gaps\n\n- No structured evidence gaps are currently visible.\n",
      "summary": "Installation, permission, validation, and pre-recommendation risks.",
      "title": "Boundary & Risk Card"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/guardrails-ai/guardrails 项目说明书\n\n生成时间：2026-05-15 16:49:27 UTC\n\n## 目录\n\n- [Getting Started with Guardrails](#getting-started)\n- [System Architecture](#system-architecture)\n- [Guard Class Reference](#guard-class)\n- [Validators System](#validators)\n- [Schema Processing](#schema-processing)\n- [Execution Pipeline](#execution-pipeline)\n- [Async and Streaming Support](#async-streaming)\n- [LLM Provider Integration](#llm-providers)\n- [Framework Integrations](#framework-integrations)\n- [Creating Custom Validators](#custom-validators)\n\n<a id='getting-started'></a>\n\n## Getting Started with Guardrails\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Validators System](#validators)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md)\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/cli/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/install.py)\n- [guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n</details>\n\n# Getting Started with Guardrails\n\n## Overview\n\nGuardrails is an open-source Python library that provides validation, correction, and structural guarantees for AI/LLM applications. It enables developers to define constraints on LLM outputs and automatically validates, corrects, or re-asks the model when outputs violate those constraints. 资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\nThe library serves as a critical layer between LLM outputs and application logic, ensuring that AI-generated content meets specified quality, safety, and structural requirements.\n\n## Installation\n\n### Prerequisites\n\n- Python 3.8 or higher\n- pip or pipx\n\n### Standard Installation\n\nInstall Guardrails from PyPI:\n\n```bash\npip install guardrails-ai\n```\n\n### Development Installation\n\nFor contributors or those who want the latest features from the main branch:\n\n```bash\n# Clone the repository\ngit clone https://github.com/guardrails-ai/guardrails.git\ncd guardrails\n\n# Install in development mode\nmake dev\n\n# Install pre-commit hooks\npre-commit install\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md), [CONTRIBUTING.md](https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md)\n\n## Core Concepts\n\n### Guard\n\nThe `Guard` is the central component in Guardrails. It wraps LLM calls and applies validation rules to ensure outputs meet specified constraints.\n\n```python\nfrom guardrails import Guard, OnFailAction\n\nguard = Guard().use(\n    RegexMatch, regex=\"\\(?\\d{3}\\)?-? *\\d{3}-? *-?\\d{4}\", on_fail=OnFailAction.EXCEPTION\n)\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n### Validators\n\nValidators are individual constraint checks that can be applied to LLM outputs. They are installed from the Guardrails Hub or created as custom validators.\n\n```python\nfrom guardrails.hub import RegexMatch, CompetitorCheck, ToxicLanguage\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n### OnFailAction\n\nActions to take when validation fails:\n\n| Action | Description |\n|--------|-------------|\n| `EXCEPTION` | Raise an exception |\n| `REASK` | Re-ask the LLM to produce valid output |\n| `FIX` | Attempt to auto-fix the output |\n| `FILTER` | Filter out invalid parts |\n| `REFRAIN` | Return nothing for invalid fields |\n\n## Quick Start Guide\n\n### Step 1: Configure Guardrails Hub CLI\n\nAfter installation, configure the Guardrails CLI:\n\n```bash\nguardrails configure\n```\n\n### Step 2: Install Required Validators\n\nInstall validators from Guardrails Hub based on your use case:\n\n```bash\n# Example: Install validators for phone number validation and competitor checking\nguardrails hub install hub://guardrails/regex_match\nguardrails hub install hub://guardrails/competitor_check\nguardrails hub install hub://guardrails/toxic_language\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n### Step 3: Create a Guard\n\nCreate a Guard instance with your desired validators:\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import CompetitorCheck, ToxicLanguage\n\nguard = Guard().use(\n    CompetitorCheck([\"Apple\", \"Microsoft\", \"Google\"], on_fail=OnFailAction.EXCEPTION),\n    ToxicLanguage(threshold=0.5, validation_method=\"sentence\", on_fail=OnFailAction.EXCEPTION)\n)\n```\n\n### Step 4: Validate LLM Output\n\nApply the Guard to validate outputs:\n\n```python\n# Valid output - passes all validations\nguard.validate(\n    \"\"\"An apple a day keeps a doctor away.\n    This is good advice for keeping your health.\"\"\"\n)\n\n# Invalid output - fails validations\ntry:\n    guard.validate(\n        \"\"\"Shut the hell up! Apple just released a new iPhone.\"\"\"\n    )\nexcept Exception as e:\n    print(e)\n```\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Application] --> B[Guard Instance]\n    B --> C[Validators Stack]\n    C --> D[LLM Call]\n    D --> E{Validation Pass?}\n    E -->|Yes| F[Return Validated Output]\n    E -->|No| G[OnFailAction Handler]\n    G --> H[EXCEPTION / REASK / FIX / FILTER / REFRAIN]\n    H --> I[Retry if REASK]\n    I --> D\n```\n\n## Creating Guards\n\n### From RAIL String\n\nRAIL (Reliable AI Abstraction Language) is an XML-based specification for defining output constraints:\n\n```python\nfrom guardrails import Guard\n\nrail_string = '''\n<rail version=\"0.1\">\n    <output>\n        <!-- Define output structure and validators -->\n    </output>\n    <prompt>\n        <!-- Define the prompt -->\n    </prompt>\n</rail>\n'''\n\nguard = Guard.from_rail_string(rail_string)\n```\n\n资料来源：[guardrails/guard.py:45-60](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### From Pydantic Model\n\nDefine output structure using Pydantic BaseModel:\n\n```python\nfrom pydantic import BaseModel, Field\nfrom guardrails import Guard\n\nclass Pet(BaseModel):\n    pet_type: str = Field(description=\"Species of pet\")\n    name: str = Field(description=\"a unique pet name\")\n\nguard = Guard.for_pydantic(Pet)\n```\n\nThe Guard uses two methods to generate structured data:\n1. **Function calling**: For LLMs that support function calling\n2. **Prompt optimization**: For LLMs that don't support function calling (schema added to prompt)\n\n资料来源：[README.md](https://github.com/guardrails-ai/guardrails/blob/main/README.md), [guardrails/guard.py:85-115](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n## Guardrails Hub Validators\n\nThe Guardrails Hub provides pre-built validators for common use cases:\n\n| Validator | Purpose | Example Usage |\n|-----------|---------|---------------|\n| `RegexMatch` | Validate string against regex pattern | Phone number format |\n| `CompetitorCheck` | Detect mentions of competitors | Brand safety |\n| `ToxicLanguage` | Detect toxic/offensive content | Content moderation |\n| `LowerCase` | Ensure text is lowercase | Normalization |\n| `UpperCase` | Ensure text is uppercase | Normalization |\n\n### Installing Validators\n\n```bash\n# From Guardrails Hub\nguardrails hub install hub://guardrails/<validator_name>\n\n# With specific version\nguardrails hub install hub://guardrails/regex_match~=1.4\n```\n\n资料来源：[guardrails/hub/install.py:45-60](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n\n## Validation Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant Validators\n    participant LLM\n    \n    User->>Guard: validate(input)\n    Guard->>Validators: Check constraints\n    alt Validation Failed\n        Validators-->>Guard: ValidationError\n        Guard->>Guard: Handle OnFailAction\n        alt OnFailAction.REASK\n            Guard->>LLM: Request correction\n            LLM-->>Guard: New response\n            Guard->>Validators: Re-validate\n        end\n    end\n    Guard-->>User: Validated output / Exception\n```\n\n## Creating Custom Validators\n\nUse the CLI to scaffold a new validator:\n\n```bash\nguardrails hub create-validator MyValidator\n```\n\nThis creates a template file with the required structure:\n\n```python\nfrom guardrails import Validator\nfrom guardrails.validators import ValidationResult, PassResult\n\nclass MyValidator(Validator):\n    \"\"\"Description of what your validator does.\"\"\"\n    \n    def __init__(self, arg_1: str, **kwargs):\n        # Initialize with custom arguments\n        super().__init__(**kwargs)\n    \n    def validate(self, value: Any, **kwargs) -> ValidationResult:\n        # Implement validation logic\n        if valid:\n            return PassResult()\n        else:\n            return FailResult()\n```\n\n资料来源：[guardrails/cli/hub/create_validator.py:35-70](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n\n## Development Workflow\n\nFor contributing to Guardrails:\n\n1. **Clone and setup**:\n   ```bash\n   git clone https://github.com/guardrails-ai/guardrails.git\n   cd guardrails\n   make dev\n   ```\n\n2. **Run tests**:\n   ```bash\n   make test\n   ```\n\n3. **Format code**:\n   ```bash\n   make autoformat\n   ```\n\n4. **Type checking**:\n   ```bash\n   make type\n   ```\n\n5. **Update documentation**:\n   ```bash\n   make docs-gen\n   ```\n\n资料来源：[CONTRIBUTING.md](https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md)\n\n## Call History and Debugging\n\nThe Guard maintains a history of all calls, useful for debugging and monitoring:\n\n```python\ncall = guard.validate(\"123-456-7890\")\nprint(call.iterations)  # View all iterations\nprint(call.id)          # Unique call identifier\n```\n\nEach `Call` object contains:\n- `iterations`: Stack of validation iterations\n- `inputs`: Original inputs to the Guard\n- `exception`: Any exception that occurred\n\n资料来源：[guardrails/classes/history/call.py:15-35](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n\n## CLI Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| `guardrails configure` | Configure Guardrails Hub CLI |\n| `guardrails hub install <package>` | Install a validator from Hub |\n| `guardrails hub create-validator <name>` | Create a new validator template |\n| `guardrails start` | Start the Guardrails API server |\n\n资料来源：[guardrails/cli/start.py:25-50](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/start.py), [guardrails/cli/hub/install.py:20-45](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/install.py)\n\n## Common Patterns\n\n### Input and Output Guards\n\nApply different validators to input and output:\n\n```python\nguard = Guard()\n\n# Input validation\nguard.use(InputValidator(CompetitorCheck, competitors=[...]))\n\n# Output validation  \nguard.use(OutputValidator(ToxicLanguage))\n```\n\n### Multiple Validators\n\nChain multiple validators on a single Guard:\n\n```python\nguard = Guard().use(\n    Validator1(param1=value1),\n    Validator2(param2=value2),\n    Validator3()\n)\n```\n\n### Streaming Support\n\nGuardrails supports streaming responses:\n\n```python\nguard.validate(\n    llm_output,\n    metadata={\"stream\": True}\n)\n```\n\n## Next Steps\n\n- Explore the [Guardrails Hub](https://guardrailsai.com/hub/) for available validators\n- Read the API documentation for detailed parameter descriptions\n- Join the [Discord community](https://discord.gg/Jsey3mX98B) for support\n- Check existing issues and contribute to the project\n\n---\n\n<a id='system-architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Getting Started with Guardrails](#getting-started), [Execution Pipeline](#execution-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/async_guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/async_guard.py)\n- [guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n- [guardrails/classes/schema/processed_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/schema/processed_schema.py)\n</details>\n\n# System Architecture\n\n## Overview\n\nGuardrails is a Python library for validating and constraining outputs from Large Language Models (LLMs). The system provides a flexible framework for defining validation rules (validators), composing them into Guards, and applying them to LLM outputs to ensure they meet specified quality and safety criteria.\n\n资料来源：[README.md:1-20]()\n\n## High-Level Architecture\n\nThe Guardrails system consists of several key layers that work together to provide LLM output validation:\n\n```mermaid\ngraph TB\n    subgraph \"Presentation Layer\"\n        Guard[\"Guard Class\"]\n        AsyncGuard[\"AsyncGuard Class\"]\n    end\n    \n    subgraph \"Schema Layer\"\n        ProcessedSchema[\"ProcessedSchema\"]\n        RailSchema[\"RailSchema\"]\n    end\n    \n    subgraph \"Validation Layer\"\n        ValidatorService[\"ValidatorService\"]\n        Validators[\"Validators\"]\n    end\n    \n    subgraph \"Integration Layer\"\n        LLMProviders[\"LLM Providers\"]\n        APIClient[\"APIClient\"]\n    end\n    \n    Guard --> ProcessedSchema\n    AsyncGuard --> ProcessedSchema\n    ProcessedSchema --> ValidatorService\n    ValidatorService --> Validators\n    Guard --> LLMProviders\n    Guard --> APIClient\n```\n\n资料来源：[guardrails/guard.py:1-50]()\n\n## Core Components\n\n### Guard Class\n\nThe `Guard` class is the primary entry point for using Guardrails. It serves as a container for validators and provides methods for validating LLM outputs.\n\n#### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Validator Composition** | Chain multiple validators using `.use()` method |\n| **Schema Support** | Support for RAIL, Pydantic, and JSON Schema |\n| **LLM Integration** | Built-in support for various LLM providers |\n| **History Tracking** | Records all validation iterations and outcomes |\n| **Async Support** | Separate `AsyncGuard` class for async operations |\n\n#### Factory Methods\n\n```python\n@classmethod\ndef from_rail(cls, rail_string: str, ...) -> Guard\n@classmethod\ndef for_pydantic(cls, output_class: ModelOrListOfModels, ...) -> Guard\n```\n\nThe `Guard` class provides multiple ways to create instances:\n\n1. **`from_rail()`** - Creates a Guard from a RAIL (Rich Application Information Language) string\n2. **`for_pydantic()`** - Creates a Guard using Pydantic models to define output structure\n\n资料来源：[guardrails/guard.py:200-280]()\n\n### AsyncGuard Class\n\nThe `AsyncGuard` class provides asynchronous validation capabilities, enabling non-blocking LLM output validation for high-throughput applications.\n\n#### Key Differences from Guard\n\n| Aspect | Guard | AsyncGuard |\n|--------|-------|------------|\n| Execution | Synchronous | Asynchronous (async/await) |\n| Use Case | Standard applications | High-performance async apps |\n| API | `guard.validate()` | `await guard.avalidate()` |\n\n### Validator Service\n\nThe `ValidatorService` is the core validation engine that executes validators against input data.\n\n#### Responsibilities\n\n- Load and initialize validators\n- Execute validation pipeline\n- Handle validation failures and reasks\n- Collect and aggregate validation results\n\n```mermaid\ngraph LR\n    Input[\"Input Data\"] --> ValidatorService\n    ValidatorService --> V1[\"Validator 1\"]\n    ValidatorService --> V2[\"Validator 2\"]\n    ValidatorService --> VN[\"Validator N\"]\n    V1 --> Result1[\"Result 1\"]\n    V2 --> Result2[\"Result 2\"]\n    VN --> ResultN[\"Result N\"]\n    Result1 --> Aggregated[\"Aggregated Result\"]\n    Result2 --> Aggregated\n    ResultN --> Aggregated\n```\n\n资料来源：[guardrails/validator_service/validator_service_base.py:1-50]()\n\n### ProcessedSchema\n\nThe `ProcessedSchema` class handles the parsing and processing of validation schemas into an internal format that can be executed by the validator service.\n\n#### Schema Processing Flow\n\n```mermaid\ngraph TD\n    RawSchema[\"Raw Schema Input\"] --> Parser[\"Schema Parser\"]\n    Parser --> Processed[\"ProcessedSchema\"]\n    Processed --> Serialization[\"Serialization\"]\n    Serialization --> Storage[\"Storage/Caching\"]\n    Processed --> Execution[\"Validation Execution\"]\n```\n\n资料来源：[guardrails/classes/schema/processed_schema.py:1-40]()\n\n## Validation Flow\n\n### Standard Validation Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant ProcessedSchema\n    participant ValidatorService\n    participant Validator\n    participant LLM\n\n    User->>Guard: validate(output)\n    Guard->>ProcessedSchema: parse_and_validate()\n    ProcessedSchema->>ValidatorService: run_validators()\n    ValidatorService->>Validator: validate()\n    Validator-->>ValidatorService: ValidationResult\n    ValidatorService-->>ProcessedSchema: AggregatedResult\n    ProcessedSchema-->>Guard: FinalResult\n    Guard-->>User: Result/Exception\n```\n\n### ReAsk Flow\n\nWhen initial validation fails, the system can trigger a reask mechanism:\n\n1. Validation fails for field\n2. System generates reask prompt\n3. LLM receives reask prompt\n4. New output is validated\n5. Process repeats until valid or max iterations reached\n\n资料来源：[guardrails/guard.py:300-400]()\n\n## Schema System\n\n### Supported Schema Formats\n\n| Format | Method | Description |\n|--------|--------|-------------|\n| RAIL | `Guard.from_rail()` | XML-based schema with validators |\n| Pydantic | `Guard.for_pydantic()` | Python class-based schema |\n| JSON Schema | `json_schema_to_rail_output()` | JSON schema conversion |\n\n### RAIL Schema Processing\n\nThe `rail_schema.py` module handles conversion between different schema formats:\n\n```python\ndef json_schema_to_rail_output(\n    json_schema: Dict[str, Any], \n    validator_map: ValidatorMap\n) -> str:\n    \"\"\"Takes a JSON Schema and converts it to the RAIL output specification.\"\"\"\n```\n\n资料来源：[guardrails/schema/rail_schema.py:60-80]()\n\n## History and Call Tracking\n\nThe `Call` class tracks each execution of a Guard, maintaining a history of all iterations:\n\n```python\nclass Call:\n    iterations: Stack[Iteration]  # Stack of iterations for reasks\n    inputs: CallInputs             # Original inputs to Guard\n    exception: Optional[Exception] # Any exceptions during execution\n```\n\n#### Call Structure\n\n| Attribute | Type | Description |\n|-----------|------|-------------|\n| `iterations` | `Stack[Iteration]` | Each validation round and reask |\n| `inputs` | `CallInputs` | Original prompt, parameters, etc. |\n| `exception` | `Exception` | Exception if Guard execution failed |\n\n资料来源：[guardrails/classes/history/call.py:10-50]()\n\n## Integration Architecture\n\n### LLM Provider Integration\n\nGuardrails integrates with multiple LLM providers through a unified interface:\n\n```mermaid\ngraph TB\n    Guard[\"Guard Class\"]\n    ManifestCallable[\"ManifestCallable\"]\n    LiteLLMCallable[\"LiteLLMCallable\"]\n    CustomCallable[\"Custom Provider\"]\n    \n    Guard --> ManifestCallable\n    Guard --> LiteLLMCallable\n    Guard --> CustomCallable\n```\n\nSupported providers include:\n- OpenAI\n- Anthropic\n- LiteLLM (unified interface)\n- Manifest (local models)\n\n资料来源：[guardrails/llm_providers.py:1-100]()\n\n### API Client Integration\n\nThe `APIClient` enables remote Guard management:\n\n| Method | Purpose |\n|--------|---------|\n| `upsert_guard()` | Create or update a Guard on the server |\n| `fetch_guard()` | Retrieve a Guard by name |\n| `aupsert_guard()` | Async version of upsert |\n\n```python\nasync def aupsert_guard(self, guard: Guard) -> Guard:\n    existing_guard = await self.afetch_guard(guard.name)\n    if existing_guard:\n        response = await self.ahttp_client.put(...)\n    else:\n        response = await self.ahttp_client.post(...)\n```\n\n资料来源：[guardrails/api_client.py:1-80]()\n\n## Hub Integration\n\n### Validator Installation\n\nThe Hub system allows dynamic installation of validators:\n\n```python\ndef install(package_uri: str, ...) -> ModuleType:\n    # 1. Validate package URI\n    # 2. Fetch manifest\n    # 3. Download dependencies\n    # 4. Install via pip\n```\n\n#### Installation Flow\n\n```mermaid\ngraph LR\n    A[\"hub://guardrails/regex_match\"] --> B[\"ValidatorPackageService\"]\n    B --> C[\"Fetch Manifest\"]\n    C --> D[\"Install Dependencies\"]\n    D --> E[\"Load Module\"]\n```\n\n资料来源：[guardrails/hub/install.py:20-60]()\n\n## CLI Architecture\n\n### Command Structure\n\n| Command | File | Purpose |\n|---------|------|---------|\n| `guardrails configure` | CLI setup | Configure Guardrails settings |\n| `guardrails hub install` | `cli/hub/install.py` | Install validators from Hub |\n| `guardrails hub create-validator` | `cli/hub/create_validator.py` | Scaffold new validators |\n| `guardrails start` | `cli/start.py` | Start Guardrails API server |\n\n资料来源：[guardrails/cli/start.py:1-50]()\n\n## Error Handling and Logging\n\n### Log Levels\n\n| Level | Value | Usage |\n|-------|-------|-------|\n| `SPAM` | 5 | Verbose debug information |\n| `VERBOSE` | 15 | Detailed execution info |\n| `NOTICE` | 25 | Important events |\n| `SUCCESS` | 35 | Successful operations |\n\n资料来源：[guardrails/cli/logger.py:1-30]()\n\n## Summary\n\nThe Guardrails architecture follows a layered approach:\n\n1. **Presentation Layer** - `Guard` and `AsyncGuard` classes provide the user-facing API\n2. **Schema Layer** - `ProcessedSchema` and `RailSchema` handle input parsing and validation rules\n3. **Validation Layer** - `ValidatorService` executes validators and aggregates results\n4. **Integration Layer** - LLM providers and API client enable seamless integration with external services\n\nThis separation of concerns allows for:\n- Flexible validator composition\n- Multiple schema format support\n- Both sync and async operation modes\n- Extensible provider integrations\n\n---\n\n<a id='guard-class'></a>\n\n## Guard Class Reference\n\n### 相关页面\n\n相关主题：[Validators System](#validators), [Schema Processing](#schema-processing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/pydantic_schema.py)\n- [guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/rail_schema.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n- [guardrails/classes/history/call_inputs.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call_inputs.py)\n- [guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n- [guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n</details>\n\n# Guard Class Reference\n\nThe `Guard` class is the central orchestrator in the Guardrails library, serving as the primary interface for validating, parsing, and constraining LLM outputs. It acts as a container that manages validators, output schemas, and validation outcomes while maintaining execution history.\n\n## Overview\n\nThe Guard class provides a unified API for:\n\n- Defining validation rules through RAIL XML strings or Pydantic models\n- Validating LLM outputs against specified schemas and constraints\n- Parsing raw LLM responses into structured data\n- Tracking validation history across multiple iterations and reasks\n- Configuring behavior on validation failure through `OnFailAction` strategies\n\n```mermaid\ngraph TD\n    A[LLM Output] --> B[Guard Instance]\n    B --> C{Validation}\n    C -->|Pass| D[Validated Output]\n    C -->|Fail| E{OnFailAction}\n    E -->|EXCEPTION| F[Raise Exception]\n    E -->|REASK| G[Reask LLM]\n    E -->|FIX| H[Return Fixed Value]\n    E -->|[None]| I[Return None]\n    G --> A\n```\n\n## Creating Guard Instances\n\n### Factory Methods\n\nThe Guard class provides two primary factory methods for instantiation:\n\n| Method | Input Type | Use Case |\n|--------|------------|----------|\n| `Guard.from_rail()` | RAIL XML string | Complex schemas with validators |\n| `Guard.for_pydantic()` | Pydantic BaseModel | Structured data generation |\n\n### Creating from RAIL Strings\n\n```python\n@classmethod\ndef from_rail(cls, rail_string: str, *, name: str = None, description: str = None) -> \"Guard\"\n```\n\nA RAIL (Rich AI Language) string is an XML-based specification that defines:\n\n- Output schema structure\n- Field-level validators\n- Error handling behaviors\n\n```python\nfrom guardrails import Guard\n\nrail_string = \"\"\"\n<rail version=\"0.1\">\n    <output>\n        <string name=\"response\" />\n    </output>\n</rail>\n\"\"\"\n\nguard = Guard.from_rail(rail_string, name=\"my-guard\")\n```\n\n资料来源：[guardrails/guard.py:from_rail-method](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### Creating from Pydantic Models\n\n```python\n@classmethod\ndef for_pydantic(\n    cls,\n    output_class: ModelOrListOfModels,\n    *,\n    reask_messages: Optional[List[Dict]] = None,\n    messages: Optional[List[Dict]] = None,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n    output_formatter: Optional[Union[str, BaseFormatter]] = None,\n) -> \"Guard\"\n```\n\nThis method accepts Pydantic `BaseModel` classes and internally converts them to RAIL format for validation.\n\n```python\nfrom guardrails import Guard\nfrom pydantic import BaseModel, Field\n\nclass Pet(BaseModel):\n    pet_type: str = Field(description=\"Species of pet\")\n    name: str = Field(description=\"a unique pet name\")\n\nguard = Guard.for_pydantic(Pet)\n```\n\n资料来源：[guardrails/guard.py:for_pydantic-method](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### Internal Schema Processing\n\nBoth factory methods ultimately convert their input to an internal RAIL schema representation:\n\n```mermaid\ngraph LR\n    A[Pydantic Model] -->|for_pydantic| B[JSON Schema]\n    C[RAIL String] -->|from_rail| D[Schema Parser]\n    B --> D\n    D --> E[RAIL Schema]\n    E --> F[Guard Instance]\n```\n\n资料来源：[guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/rail_schema.py)\n\n## Guard Configuration\n\n### Using Validators with `Guard.use()`\n\nValidators are added to a Guard instance using the `.use()` method, which chains multiple validators onto the same instance.\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import RegexMatch, CompetitorCheck\n\nguard = Guard().use(\n    RegexMatch(regex=r\"\\d{4}\", on_fail=OnFailAction.EXCEPTION),\n    CompetitorCheck([\"Apple\", \"Google\"], on_fail=OnFailAction.REASK)\n)\n```\n\n资料来源：[README.md:example-code](https://github.com/guardrails-ai/guardrails/blob/main/README.md)\n\n## Validation Process\n\n### Core Validation Methods\n\n| Method | Purpose | Returns |\n|--------|---------|---------|\n| `validate()` | Validates LLM output against schema | `ValidationOutcome` |\n| `parse()` | Parses raw output without full validation | Parsed result |\n| `__call__()` | Combined call and validation | LLM response + validated output |\n\n### ValidationOutcome Class\n\nThe `ValidationOutcome` class encapsulates the results of validation:\n\n```python\n@dataclass\nclass ValidationOutcome:\n    validation_passed: bool\n    corrected_output: Any\n    error_message: Optional[str]\n    reasks: List[ReAsk]\n```\n\n资料来源：[guardrails/classes/validation_outcome.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/validation_outcome.py)\n\n### OnFailAction Enum\n\nWhen validation fails, the configured `OnFailAction` determines the behavior:\n\n| Action | Behavior |\n|--------|----------|\n| `EXCEPTION` | Raises an exception with error details |\n| `REASK` | Attempts to regenerate the LLM output with feedback |\n| `FIX` | Returns a corrected/fallback value |\n| `REFRAIN` | Returns `None` instead of output |\n| `NOOP` | Returns the original output unchanged |\n| `CUSTOM` | Uses a custom handler function |\n\n资料来源：[guardrails/types/on_fail.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/types/on_fail.py)\n\n## Call History and Iteration Tracking\n\n### Call Class Structure\n\nThe `Call` class maintains a complete history of Guard executions:\n\n```python\nclass Call:\n    _id: str | None = None\n    iterations: Stack[Iteration] = Field(default_factory=Stack)\n    inputs: CallInputs = Field(default_factory=CallInputs)\n    exception: Optional[Exception] = None\n    \n    @computed_field\n    @property\n    def id(self) -> str:\n        \"\"\"Unique identifier for this Call execution.\"\"\"\n        if not self._id:\n            self._id = str(object_id(self))\n        return self._id\n```\n\n资料来源：[guardrails/classes/history/call.py:Call-class](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n\n### Iteration Stack\n\nEach `Call` contains a stack of `Iteration` objects representing:\n\n1. The initial validation round\n2. Each subsequent reask iteration\n\n```mermaid\ngraph TD\n    A[Call] --> B[Iteration 1: Initial Call]\n    A --> C[Iteration 2: Reask 1]\n    A --> D[Iteration N: Reask N-1]\n    B --> E[Step 1: LLM Call]\n    B --> F[Step 2: Validation]\n    C --> G[Step: LLM Reask]\n    C --> H[Step: Validation]\n```\n\n### CallInputs Data Model\n\nThe `CallInputs` class captures all inputs passed to a Guard execution:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `prompt_params` | Dict | Parameters formatted into messages |\n| `num_reasks` | int | Maximum reask attempts |\n| `metadata` | Dict | Additional runtime data |\n| `full_schema_reask` | bool | Reask entire schema vs individual fields |\n| `stream` | bool | Streaming mode flag |\n| `args` | List[Any] | Additional positional arguments |\n| `kwargs` | Dict[str, Any] | Additional keyword arguments |\n\n资料来源：[guardrails/classes/history/call_inputs.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call_inputs.py)\n\n## LLM Provider Integration\n\n### PromptCallableBase Interface\n\nThe Guard class integrates with multiple LLM providers through the `PromptCallableBase` interface:\n\n```python\nclass PromptCallableBase:\n    def _invoke_llm(\n        self,\n        text: Optional[str] = None,\n        model: str = \"gpt-3.5-turbo\",\n        messages: Optional[List[Dict]] = None,\n        *args,\n        **kwargs\n    ) -> LLMResponse:\n        \"\"\"Abstract method to invoke LLM.\"\"\"\n```\n\nSupported providers include:\n\n- **LiteLLM** - Unified interface to multiple LLMs\n- **Manifest** - ML model inference client\n- **OpenAI** - Direct OpenAI API integration\n\n资料来源：[guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n\n### LLM Response Structure\n\n```python\n@dataclass\nclass LLMResponse:\n    output: Any  # The raw LLM response\n    token_usage: Optional[Dict] = None  # Token consumption metrics\n    model_name: Optional[str] = None  # Model identifier\n```\n\n## Validator Installation via Hub\n\n### Installing Validators\n\nValidators from Guardrails Hub can be installed programmatically:\n\n```python\nfrom guardrails.hub.install import install\n\nRegexMatch = install(\"hub://guardrails/regex_match\").RegexMatch\n```\n\nThe installation process:\n\n1. Validates the package URI format\n2. Fetches the module manifest\n3. Downloads dependencies via pip\n4. Installs to site-packages\n\n资料来源：[guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n\n## Complete Usage Example\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import RegexMatch, CompetitorCheck\n\n# Create a Guard with multiple validators\nguard = Guard().use(\n    RegexMatch(\n        regex=r\"\\d{3}-\\d{3}-\\d{4}\",\n        on_fail=OnFailAction.EXCEPTION\n    ),\n    CompetitorCheck(\n        competitors=[\"Apple\", \"Microsoft\"],\n        on_fail=OnFailAction.REASK\n    )\n)\n\n# Validate output\ntry:\n    result = guard.validate(\"123-456-7890\")\n    print(f\"Validation passed: {result.validation_passed}\")\nexcept Exception as e:\n    print(f\"Validation failed: {e}\")\n\n# Access call history\ncall_history = guard.history  # List of Call objects\n```\n\n## Summary\n\nThe `Guard` class serves as the central orchestrator for LLM output validation in the Guardrails library. Key responsibilities include:\n\n- **Schema Management**: Creating Guards from RAIL strings or Pydantic models\n- **Validation Orchestration**: Running validators and applying OnFailAction strategies\n- **History Tracking**: Maintaining complete execution history with iterations and steps\n- **LLM Integration**: Supporting multiple LLM providers through a unified interface\n- **Extensibility**: Allowing composition of multiple validators through the `.use()` method\n\n资料来源：[guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py), [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py), [guardrails/types/on_fail.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/types/on_fail.py)\n\n---\n\n<a id='validators'></a>\n\n## Validators System\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Creating Custom Validators](#custom-validators)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n- [guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n- [guardrails/cli/hub/create_validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n- [guardrails/telemetry/validator_tracing.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/telemetry/validator_tracing.py)\n- [guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n</details>\n\n# Validators System\n\n## Overview\n\nThe Validators System is a core component of the Guardrails framework that provides validation capabilities for LLM (Large Language Model) outputs. Validators are modular, composable validation units that can be attached to a `Guard` instance to enforce constraints on data before, during, or after LLM inference.\n\nValidators enable developers to:\n\n- Validate string, structured (JSON), and typed outputs from LLMs\n- Define custom failure handling policies via the `on_fail` mechanism\n- Chain multiple validators to create complex validation pipelines\n- Track validation history and results through the Call/Iteration data model\n\n## Architecture\n\n### High-Level Component Flow\n\n```mermaid\ngraph TD\n    A[LLM Output] --> B[Guard.validate]\n    B --> C[ValidatorService]\n    C --> D[Validator 1]\n    C --> E[Validator 2]\n    C --> F[Validator N]\n    D --> G[ValidationResult]\n    E --> H[ValidationResult]\n    F --> I[ValidationResult]\n    G --> J[ValidationOutcome]\n    H --> J\n    I --> J\n    J --> K[Pass or Fail with Corrections]\n```\n\n### Validator Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Initialized\n    Initialized --> Running: before_run_validator\n    Running --> Success: validate returns PassResult\n    Running --> Failed: validate returns FailResult\n    Success --> Completed: after_run_validator\n    Failed --> Completed: on_fail handler applied\n    Completed --> [*]\n```\n\n## Core Components\n\n### Validator Base Class\n\nValidators inherit from the base `Validator` class which provides:\n\n- Standard initialization with `on_fail` policy configuration\n- `validate(value, metadata)` method implementation contract\n- Integration with the validator service infrastructure\n- Telemetry and tracing capabilities\n\n### Validation Result Classes\n\nThe system uses two primary result types:\n\n| Class | Purpose |\n|-------|---------|\n| `PassResult` | Indicates validation succeeded |\n| `FailResult` | Indicates validation failed with error details |\n\n```mermaid\nclassDiagram\n    class ValidationResult {\n        <<abstract>>\n    }\n    class PassResult {\n        +str error_message = None\n        +ValidationResult fix_value = None\n    }\n    class FailResult {\n        +str error_message\n        +Any fix_value\n    }\n    ValidationResult <|-- PassResult\n    ValidationResult <|-- FailResult\n```\n\n### OnFailAction Policies\n\nWhen validation fails, the `on_fail` parameter determines the behavior:\n\n| Policy | Behavior |\n|--------|----------|\n| `REASK` | Trigger a reask to the LLM |\n| `FIX` | Attempt to fix the value automatically |\n| `FILTER` | Remove invalid elements |\n| `REFRAIN` | Return empty/null value |\n| `NOOP` | Return the original value unchanged |\n| `EXCEPTION` | Raise an exception |\n\n资料来源：[guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n\n## Validator Service\n\n### Sequential Validator Service\n\nThe `SequentialValidatorService` executes validators in order, one after another, stopping on the first failure unless configured otherwise.\n\nKey methods:\n\n| Method | Description |\n|--------|-------------|\n| `before_run_validator` | Prepares logging and tracking before validation |\n| `after_run_validator` | Records results and timing after validation |\n| `run_validator` | Executes a single validator's validation logic |\n\n资料来源：[guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n\n### Validation Logging\n\nThe `ValidatorLogs` class tracks each validator execution:\n\n```python\nvalidator_logs = ValidatorLogs(\n    validatorName=validator_class_name,\n    valueBeforeValidation=value,\n    registeredName=validator.rail_alias,\n    propertyPath=absolute_property_path,\n    instanceId=id(validator),\n)\n```\n\n| Field | Description |\n|-------|-------------|\n| `validatorName` | Class name of the validator |\n| `valueBeforeValidation` | Original value before validation |\n| `registeredName` | RAIL alias for the validator |\n| `propertyPath` | JSON path to the validated property |\n| `instanceId` | Memory address of validator instance |\n| `start_time` | Timestamp when validation began |\n| `end_time` | Timestamp when validation completed |\n| `validation_result` | Result of the validation |\n\n资料来源：[guardrails/validator_service/validator_service_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/validator_service_base.py)\n\n## Guard Integration\n\n### Attaching Validators to Guard\n\nValidators are attached to a `Guard` instance using the `.use()` method:\n\n```python\nguard = Guard().use(\n    RegexMatch, regex=\"\\\\(?\\\\d{3}\\\\)?-? *\\\\d{3}-? *-?\\\\d{4}\"\n)\n```\n\nThe `use()` method signature:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `*validators` | Validator | Positional args for validators |\n| `on` | str | Property path (\"output\", \"messages\", \"$.property\") |\n\n```python\ndef use(\n    self,\n    *validators: Validator,\n    on: str = \"output\",\n    **kwargs,\n) -> \"Guard\":\n```\n\n资料来源：[guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n### Validation Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant ValidatorService\n    participant Validator\n    participant LLM\n\n    User->>Guard: validate(llm_output)\n    Guard->>Guard: parse(llm_output)\n    Guard->>ValidatorService: run_validators()\n    ValidatorService->>Validator: before_run_validator()\n    Validator->>Validator: validate(value, metadata)\n    Validator-->>ValidatorService: ValidationResult\n    ValidatorService->>Validator: after_run_validator()\n    ValidatorService-->>Guard: ValidationOutcome\n    Guard-->>User: Pass/Fail with corrections\n```\n\n### Getting Attached Validators\n\nRetrieve validators attached to a specific property:\n\n```python\nvalidators = guard.get_validators(on=\"output\")\n```\n\n| Parameter | Valid Options | Description |\n|-----------|---------------|-------------|\n| `on` | `\"output\"`, `\"messages\"`, `\"$.path\"` | Property to query |\n\n资料来源：[guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n\n## Validation History Tracking\n\n### Call and Iteration Model\n\nValidation history is tracked through a hierarchical model:\n\n```mermaid\nclassDiagram\n    class Call {\n        +str id\n        +Stack~Iteration~ iterations\n        +CallInputs inputs\n        +Exception exception\n    }\n    class Iteration {\n        +Step[] steps\n        +IterationOutputs outputs\n    }\n    class Step {\n        +ValidatorLogs[] validator_logs\n    }\n    Call \"1\" --> \"*\" Iteration\n    Iteration \"1\" --> \"*\" Step\n```\n\n| Class | Purpose |\n|-------|---------|\n| `Call` | Represents a single Guard execution (validate/parse/call) |\n| `Iteration` | A single validation round, including reasks |\n| `Step` | Contains validator execution logs |\n\n资料来源：[guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n\n### Call Inputs\n\nThe `CallInputs` class captures the original inputs to each Guard invocation:\n\n- `llm_output`: Raw LLM response\n- ` Prompt parameters and messages\n- Configuration options passed during validation\n\n## Telemetry and Tracing\n\n### Validator Tracing\n\nThe validator tracing system provides observability into validation execution:\n\n```mermaid\ngraph TD\n    A[Validate Request] --> B[trace_validator_decorator]\n    B --> C[Create Span]\n    C --> D[Execute Validator]\n    D --> E{Success?}\n    E -->|Yes| F[Record PassResult]\n    E -->|No| G[Record FailResult]\n    F --> H[Add Attributes]\n    G --> H\n    H --> I[Close Span]\n    I --> J[Return Result]\n```\n\nKey tracing attributes:\n\n| Attribute | Description |\n|-----------|-------------|\n| `validator_name` | Name of the validator class |\n| `validator_span` | OpenTelemetry span reference |\n| `obj_id` | Object identifier |\n| `on_fail_descriptor` | Policy applied on failure |\n| `init_kwargs` | Validator initialization arguments |\n| `validation_session_id` | Session identifier |\n\n资料来源：[guardrails/telemetry/validator_tracing.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/telemetry/validator_tracing.py)\n\n## Creating Custom Validators\n\n### Validator Template\n\nThe CLI command `guardrails create-validator` generates a template:\n\n```bash\nguardrails create-validator MyValidator\n```\n\nGenerated template structure:\n\n```python\nfrom guardrails import Validator\nfrom guardrails.properties import register_validator\nfrom guardrails.classes import ValidationResult\n\n@register_validator(name=\"my_validator\", fmt=\"native\")\nclass MyValidator(Validator):\n    \"\"\"Validator description.\n    \n    Args:\n        arg_1: Description of the argument.\n        on_fail: Policy when validation fails.\n    \"\"\"\n    \n    def __init__(\n        self,\n        arg_1: str,\n        on_fail: Optional[Callable] = None,\n    ):\n        super().__init__(on_fail=on_fail, arg_1=arg_1)\n        self._arg_1 = arg_1\n\n    def validate(self, value: Any, metadata: Dict) -> ValidationResult:\n        \"\"\"Validates the input value.\n        \n        Args:\n            value: The value to validate.\n            metadata: Additional context for validation.\n        \"\"\"\n        if value != \"pass\":\n            return FailResult(\n                error_message=\"Value must be 'pass'\",\n                fix_value=\"fails\"\n            )\n        return PassResult()\n```\n\n资料来源：[guardrails/cli/hub/create_validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n\n### Validator Registration\n\nValidators are registered using the `@register_validator` decorator:\n\n| Parameter | Description |\n|-----------|-------------|\n| `name` | Unique identifier for the validator |\n| `fmt` | Format (\"native\" or \"raw\") |\n| `rail_alias` | RAIL XML alias |\n\n## Hub Installation\n\n### Installing Validators from Hub\n\nValidators can be installed from Guardrails Hub:\n\n```bash\nguardrails hub install hub://guardrails/regex_match\n```\n\nThe `install()` function:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `package_uri` | str | Hub package URI (e.g., `hub://guardrails/regex_match`) |\n| `quiet` | bool | Suppress output |\n| `upgrade` | bool | Force upgrade to latest |\n\n```python\n>>> RegexMatch = install(\"hub://guardrails/regex_match\").RegexMatch\n>>> RegexMatch = install(\"hub://guard://guardrails/regex_match~=1.4\").RegexMatch\n```\n\n资料来源：[guardrails/hub/install.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/install.py)\n\n### Installation Process\n\n```mermaid\ngraph LR\n    A[Install Request] --> B[Get Validator ID]\n    B --> C[Fetch Manifest]\n    C --> D[Download Dependencies]\n    D --> E[Install via Pip]\n    E --> F[Register Validator]\n```\n\n## Usage Examples\n\n### Basic String Validation\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import RegexMatch\n\nguard = Guard().use(\n    RegexMatch, \n    regex=\"\\\\(?\\\\d{3}\\\\)?-? *\\\\d{3}-? *-?\\\\d{4}\",\n    on_fail=OnFailAction.EXCEPTION\n)\n\nguard.validate(\"123-456-7890\")  # Passes\n```\n\n### Multiple Validators\n\n```python\nfrom guardrails import Guard\nfrom guardrails.hub import CompetitorCheck, ToxicLanguage\n\nguard = Guard().use(\n    CompetitorCheck([\"Apple\", \"Microsoft\"]),\n    on_fail=OnFailAction.EXCEPTION\n).use(\n    ToxicLanguage(threshold=0.5),\n    on_fail=OnFailAction.FILTER\n)\n```\n\n### Custom Validator\n\n```python\nfrom guardrails import Validator\nfrom guardrails.classes import ValidationResult, PassResult, FailResult\n\nclass UppercaseValidator(Validator):\n    def validate(self, value, metadata):\n        if value.isupper():\n            return PassResult()\n        return FailResult(\n            error_message=\"Value must be uppercase\",\n            fix_value=value.upper()\n        )\n\nguard = Guard().use(UppercaseValidator)\n```\n\n## Best Practices\n\n1. **Error Messages**: Provide clear, actionable error messages in `FailResult`\n2. **Fix Values**: Always provide sensible `fix_value` when possible\n3. **Metadata**: Use metadata for context-aware validation (e.g., schema info)\n4. **Ordering**: Place more restrictive validators first for early failure\n5. **Testing**: Test both passing and failing cases for each validator\n\n## Related Components\n\n| Component | File | Role |\n|-----------|------|------|\n| Guard | `guardrails/guard.py` | Main entry point for validation |\n| ValidatorService | `validator_service_base.py` | Orchestrates validation execution |\n| Call History | `classes/history/call.py` | Tracks validation execution history |\n| Hub Install | `hub/install.py` | Handles validator distribution |\n| Telemetry | `telemetry/validator_tracing.py` | Observability into validation |\n\n---\n\n<a id='schema-processing'></a>\n\n## Schema Processing\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Execution Pipeline](#execution-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/schema/rail_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/rail_schema.py)\n- [guardrails/schema/pydantic_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/pydantic_schema.py)\n- [guardrails/schema/primitive_schema.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/primitive_schema.py)\n- [guardrails/schema/validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/schema/validator.py)\n</details>\n\n# Schema Processing\n\nSchema Processing is the core system within Guardrails that handles conversion, validation, and transformation of data structures between different schema formats. It provides the foundational infrastructure for validating LLM outputs against defined schemas, supporting multiple schema specification formats including RAIL (Rich AI Language), Pydantic models, and JSON Schema.\n\n## Overview\n\nThe Schema Processing module enables Guardrails to:\n\n- Convert JSON Schema to RAIL output specifications\n- Build element hierarchies from JSON Schema definitions\n- Support multiple data types including primitives, dates, times, and enums\n- Map validators to schema elements\n- Generate structured output from LLM responses\n\n资料来源：[guardrails/schema/rail_schema.py:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[JSON Schema / Pydantic / RAIL] --> B[Schema Processing Module]\n    B --> C[rail_schema.py]\n    B --> D[pydantic_schema.py]\n    B --> E[primitive_schema.py]\n    B --> F[validator.py]\n    C --> G[build_element]\n    C --> H[json_schema_to_rail_output]\n    D --> I[Schema Generation]\n    E --> J[Type Handling]\n    F --> K[Validator Mapping]\n    G --> L[XML Element Tree]\n    H --> M[RAIL Output String]\n```\n\n## Core Components\n\n### Schema Type System\n\nThe schema processing system uses a dual type classification system:\n\n| Type Category | Values | Description |\n|---------------|--------|-------------|\n| **SimpleTypes** | STRING, INTEGER, NUMBER, BOOLEAN, ARRAY, OBJECT, NULL | JSON Schema primitive types |\n| **RailTypes** | STRING, INTEGER, FLOAT, BOOL, DATE, TIME, DATETIME, PERCENTAGE, ENUM | RAIL-specific type representations |\n\n资料来源：[guardrails/schema/rail_schema.py:30-45]()\n\n### Type Mapping Matrix\n\n```mermaid\ngraph LR\n    A[JSON Schema Type] -->|Mapping| B[Internal Schema Type]\n    A1[STRING] --> B1[SimpleTypes.STRING]\n    A2[integer] --> A2a[integer] --> B2[SimpleTypes.INTEGER]\n    A3[number] --> A3a[number] --> B3[SimpleTypes.NUMBER]\n    A4[boolean] --> B4[SimpleTypes.BOOLEAN]\n    A5[array] --> B5[SimpleTypes.ARRAY]\n    A6[object] --> B6[SimpleTypes.OBJECT]\n```\n\n### build_element Function\n\nThe `build_element` function is the central dispatcher for converting JSON Schema definitions into XML element structures:\n\n```python\ndef build_element(\n    json_schema: Dict[str, Any],\n    validator_map: ValidatorMap,\n    *,\n    json_path: str = \"$\",\n    elem: Callable[..., _Element] = SubElement,\n    tag_override: Optional[str] = None,\n    parent: Optional[_Element] = None,\n    required: Optional[str] = \"true\",\n    attributes: Optional[Dict[str, Any]] = None,\n) -> _Element:\n```\n\n**Parameters:**\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `json_schema` | Dict[str, Any] | required | The JSON Schema definition to process |\n| `validator_map` | ValidatorMap | required | Mapping of validator names to implementations |\n| `json_path` | str | \"$\" | Current path in the JSON structure for tracking |\n| `elem` | Callable | SubElement | Element construction function |\n| `tag_override` | Optional[str] | None | Override the XML tag name |\n| `parent` | Optional[_Element] | None | Parent element for nesting |\n| `required` | Optional[str] | \"true\" | Whether field is required |\n| `attributes` | Optional[Dict[str, Any]] | None | Additional XML attributes |\n\n资料来源：[guardrails/schema/rail_schema.py:100-130]()\n\n### json_schema_to_rail_output Function\n\nConverts a JSON Schema back to RAIL XML format for interoperability:\n\n```python\ndef json_schema_to_rail_output(\n    json_schema: Dict[str, Any], validator_map: ValidatorMap\n) -> str:\n```\n\n**Process Flow:**\n\n```mermaid\ngraph TD\n    A[JSON Schema Input] --> B[jsonref.replace_refs]\n    B --> C[dereferenced_json_schema]\n    C --> D[build_element with tag_override='output']\n    D --> E[ET.tostring with pretty_print]\n    E --> F[canonicalize output]\n    F --> G[Replace &#xA; entities]\n    G --> H[RAIL XML String]\n```\n\n资料来源：[guardrails/schema/rail_schema.py:60-75]()\n\n## Type-Specific Processing\n\n### String Element Builder\n\nThe `build_string_element` function handles all string-based types with special formatting:\n\n```mermaid\ngraph TD\n    A[String Type Detected] --> B{format.internal_type}\n    B -->|DATE| C[Set date-format attribute]\n    B -->|TIME| D[Set time-format attribute]\n    B -->|DATETIME| E[Set datetime-format attribute]\n    B -->|PERCENTAGE| F[Set percentage handling]\n    B -->|STRING| G[Standard string processing]\n    C --> H[Return Element with attributes]\n    D --> H\n    E --> H\n    F --> H\n    G --> H\n```\n\n**Date/Time Format Handling:**\n\n| Internal Type | XML Attribute | Purpose |\n|---------------|---------------|---------|\n| `RailTypes.DATE` | `date-format` | Custom date patterns |\n| `RailTypes.TIME` | `time-format` | Custom time patterns |\n| `RailTypes.DATETIME` | `datetime-format` | Custom datetime patterns |\n\n资料来源：[guardrails/schema/rail_schema.py:140-180]()\n\n### Format Extraction\n\nThe format extraction system maps JSON Schema formats to internal RAIL types:\n\n```python\ndef extract_format(\n    element,\n    internal_type: RailTypes,\n    internal_format_attr: str,\n) -> Optional[Format]:\n```\n\n**Supported Format Mappings:**\n\n| JSON Schema Format | RailTypes Value | Internal Format Attr |\n|--------------------|-----------------|---------------------|\n| date | DATE | date-format |\n| date-time | DATETIME | datetime-format |\n| time | TIME | time-format |\n| percentage | PERCENTAGE | (empty string) |\n| email | STRING | - |\n| uri | STRING | - |\n| uuid | STRING | - |\n\n资料来源：[guardrails/schema/rail_schema.py:200-250]()\n\n## Integration with Guard Class\n\nThe Schema Processing module integrates with the Guard class through multiple factory methods:\n\n### Guard.for_pydantic\n\nCreates a Guard instance from a Pydantic BaseModel:\n\n```python\n@classmethod\ndef for_pydantic(\n    cls,\n    output_class: ModelOrListOfModels,\n    *,\n    reask_messages: Optional[List[Dict]] = None,\n    messages: Optional[List[Dict]] = None,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n    output_formatter: Optional[Union[str, BaseFormatter]] = None,\n):\n```\n\n资料来源：[guardrails/guard.py:150-180]()\n\n### Guard.for_rail\n\nCreates a Guard instance from a `.rail` file:\n\n```python\n@classmethod\ndef for_rail(\n    cls,\n    rail_file: str,\n    *,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n):\n```\n\n资料来源：[guardrails/guard.py:200-230]()\n\n### Guard.for_rail_string\n\nCreates a Guard instance from a RAIL XML string:\n\n```python\n@classmethod\ndef for_rail_string(\n    cls,\n    rail_string: str,\n    *,\n    name: Optional[str] = None,\n    description: Optional[str] = None,\n):\n```\n\n资料来源：[guardrails/guard.py:240-270]()\n\n## Data Flow Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant SchemaProcessor\n    participant ValidatorMap\n    participant LLM\n    \n    User->>Guard: for_pydantic(PetModel)\n    Guard->>SchemaProcessor: Convert Pydantic to JSON Schema\n    SchemaProcessor->>SchemaProcessor: build_element for each field\n    SchemaProcessor->>ValidatorMap: Map validators\n    Guard->>LLM: Prompt with schema hints\n    LLM->>Guard: Raw output\n    Guard->>SchemaProcessor: validate(output)\n    SchemaProcessor->>ValidatorMap: Run validators\n    ValidatorMap-->>SchemaProcessor: Validation result\n    SchemaProcessor-->>Guard: Structured result\n    Guard-->>User: GuardResponse\n```\n\n## Schema to RAIL Conversion Rules\n\n### Type Conversions\n\n| JSON Schema | RAIL Element | Notes |\n|-------------|--------------|-------|\n| `{type: string}` | `<string>` | Default string type |\n| `{type: integer}` | `<integer>` | Whole numbers only |\n| `{type: number}` | `<float>` | Floating point |\n| `{type: boolean}` | `<bool>` | True/false values |\n| `{type: array}` | `<list>` | Array of items |\n| `{type: object}` | `<object>` | Nested structure |\n\n### Enum Handling\n\n```python\n# JSON Schema\n{\"type\": \"string\", \"enum\": [\"value1\", \"value2\"]}\n\n# Converts to RAIL\n<element name=\"...\" type=\"string\" format=\"enum\" values=\"value1, value2\"/>\n```\n\n资料来源：[guardrails/schema/rail_schema.py:260-280]()\n\n## Configuration Options\n\n### Exec Options\n\nThe schema processing supports various execution options:\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `num_reasks` | int | None | Number of reasking attempts |\n| `full_schema_reask` | bool | None | Reask entire schema vs individual fields |\n| `stream` | bool | None | Enable streaming responses |\n| `metadata` | Dict[str, Any] | None | Custom data for validators |\n\n资料来源：[guardrails/classes/history/call_inputs.py:30-50]()\n\n## Error Handling\n\nThe schema processing system includes robust error handling for:\n\n- Missing required fields\n- Invalid type conversions\n- Reference resolution failures\n- Validator mapping errors\n\n```mermaid\ngraph TD\n    A[Schema Processing] --> B{Error Condition}\n    B -->|Type Mismatch| C[Raise TypeError]\n    B -->|Missing Ref| D[Raise RefResolutionError]\n    B -->|Invalid Validator| E[Raise ValidatorError]\n    B -->|Success| F[Return Valid Element]\n```\n\n## Performance Considerations\n\n1. **Reference Dereferencing**: Uses `jsonref.replace_refs()` for efficient reference resolution\n2. **Lazy Element Construction**: Elements are built on-demand during validation\n3. **Validator Caching**: ValidatorMap instances are reused across calls\n\n## Related Components\n\n| Component | File Path | Purpose |\n|-----------|-----------|---------|\n| Validator Module | `guardrails/schema/validator.py` | Validator implementation and mapping |\n| Pydantic Schema | `guardrails/schema/pydantic_schema.py` | Pydantic model conversion |\n| Primitive Schema | `guardrails/schema/primitive_schema.py` | Primitive type handling |\n| Guard Class | `guardrails/guard.py` | High-level API integration |\n\n## Summary\n\nSchema Processing in Guardrails provides a comprehensive system for:\n\n- Converting between multiple schema formats (JSON Schema, RAIL, Pydantic)\n- Building hierarchical XML element structures from JSON definitions\n- Mapping and applying validators to schema elements\n- Supporting rich type system including dates, times, and enums\n- Enabling structured output generation from LLM responses\n\nThis modular architecture allows flexible schema definition while maintaining strong validation guarantees for LLM-generated content.\n\n---\n\n<a id='execution-pipeline'></a>\n\n## Execution Pipeline\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Async and Streaming Support](#async-streaming)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/run/runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/runner.py)\n- [guardrails/run/stream_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/stream_runner.py)\n- [guardrails/run/async_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/async_runner.py)\n- [guardrails/actions/reask.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/actions/reask.py)\n- [guardrails/utils/parsing_utils.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/utils/parsing_utils.py)\n</details>\n\n# Execution Pipeline\n\nThe Execution Pipeline is the core orchestration mechanism in Guardrails that handles the validation and correction of Large Language Model (LLM) outputs. It manages the lifecycle of a Guard execution from initial prompt submission through iterative validation and potential reasking cycles.\n\n## Overview\n\nThe Execution Pipeline coordinates multiple components to ensure LLM outputs meet specified validation criteria. When a Guard is invoked, the pipeline:\n\n1. Receives the raw LLM output\n2. Parses and extracts structured data\n3. Validates the output against defined validators\n4. Triggers reasking workflows when validation fails\n5. Returns sanitized, validated responses\n\nThe pipeline supports both synchronous and streaming execution modes, with dedicated runner classes handling different invocation patterns.\n\n## Core Components\n\n### Runner Classes\n\nThe execution pipeline is implemented through several runner classes that extend base execution functionality:\n\n| Runner Class | File | Purpose |\n|-------------|------|---------|\n| `Runner` | `runner.py` | Base synchronous execution handler |\n| `StreamRunner` | `stream_runner.py` | Handles streaming LLM responses |\n| `AsyncRunner` | `async_runner.py` | Manages asynchronous LLM invocations |\n\n### Execution Flow Architecture\n\n```mermaid\ngraph TD\n    A[Guard.__call__] --> B[Runner/StreamRunner/AsyncRunner]\n    B --> C[Parse LLM Output]\n    C --> D[Validate Against Validators]\n    D --> E{Validation Passed?}\n    E -->|Yes| F[Return Sanitized Output]\n    E -->|No| G[Check Reask Eligibility]\n    G --> H[Reask Action]\n    H --> I[Regenerate with Corrections]\n    I --> C\n    G -->|No Reasks Left| J[Raise Validation Exception]\n```\n\n## Reask Action System\n\nThe reask mechanism is a critical part of the execution pipeline that handles validation failures intelligently. When output fails validation, the reask action can prompt the LLM to correct its response.\n\n### Reask Configuration\n\nReask behavior is controlled through `CallInputs` parameters:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `num_reasks` | `Optional[int]` | Total number of reask attempts allowed |\n| `full_schema_reask` | `Optional[bool]` | Whether to reask entire schema or individual fields |\n| `metadata` | `Optional[Dict[str, Any]]` | Additional data for validators during execution |\n\n资料来源：[guardrails/classes/history/call_inputs.py:23-30]()\n\n### Reask Workflow\n\n```mermaid\ngraph LR\n    A[Initial Call] --> B[Iteration 1]\n    B --> C{All Validators Pass?}\n    C -->|No| D[Create Reask Prompt]\n    D --> E[LLM Regeneration]\n    E --> F[Iteration 2]\n    F --> G{Valid?}\n    G -->|No| H{num_reasks exhausted?}\n    H -->|No| D\n    H -->|Yes| I[Final Exception]\n    G -->|Yes| J[Success]\n    C -->|Yes| J\n```\n\n## Call History and Iterations\n\nEach Guard execution creates a `Call` object that tracks the full execution history. The call object maintains a stack of `Iteration` objects representing each round of validation.\n\n### Data Model\n\n```\nCall\n├── _id: str (unique identifier)\n├── iterations: Stack[Iteration]\n│   └── Contains validation results per round\n├── inputs: CallInputs\n│   ├── prompt_params\n│   ├── num_reasks\n│   └── metadata\n└── exception: Optional[Exception]\n```\n\n资料来源：[guardrails/classes/history/call.py:12-29]()\n\n## Execution Modes\n\n### Synchronous Execution\n\nThe base `Runner` class handles synchronous LLM invocations:\n\n```python\nraw_response, validated_response = guard(\n    llm_api,\n    prompt_params={...},\n    ...\n)\n```\n\n### Streaming Execution\n\n`StreamRunner` processes LLM outputs as they are generated, enabling real-time validation of streaming responses.\n\n### Asynchronous Execution\n\n`AsyncRunner` manages coroutine-based LLM calls for high-throughput applications:\n\n```python\nasync def validate_async():\n    response = await guard(\n        async_llm_call,\n        prompt_params={...}\n    )\n```\n\n## Parsing Utilities\n\nThe `parsing_utils.py` module provides utilities for extracting structured data from LLM outputs. These parsers handle various output formats and ensure data can be validated against the schema.\n\nKey parsing responsibilities include:\n- Extracting JSON/XML from raw text responses\n- Handling malformed output gracefully\n- Converting parsed data to appropriate types for validation\n\n## Trace Handler Integration\n\nThe execution pipeline integrates with `TraceHandler` for observability:\n\n```python\nwriter = TraceHandler()\nwriter.log(\n    \"guard_name\", start_time, end_time,\n    \"raw_output\", \"sanitized\", \"exception?\"\n)\n```\n\n资料来源：[guardrails/call_tracing/trace_handler.py:1-50]()\n\nLogs are stored in SQLite (`guardrails_calls.db`) by default, with the path configurable via `GUARDRAILS_LOG_FILE_PATH` environment variable.\n\n## Error Handling\n\nThe pipeline implements multi-level error handling:\n\n1. **Validation Exceptions**: Raised when output fails validator criteria\n2. **Reask Exhaustion**: Triggered when all reask attempts are consumed\n3. **LLM Provider Errors**: Propagated from underlying LLM calls\n4. **Parsing Errors**: Handled when LLM output cannot be parsed\n\n## Configuration Parameters\n\n| Parameter | Location | Default | Description |\n|-----------|----------|---------|-------------|\n| `num_reasks` | CallInputs | `None` | Maximum reask iterations |\n| `full_schema_reask` | CallInputs | `None` | Reask scope control |\n| `prompt_params` | CallInputs | `{}` | Template variables |\n| `stream` | CallInputs | `None` | Enable streaming mode |\n| `metadata` | CallInputs | `None` | Custom validator data |\n\n## See Also\n\n- [Guard Class](guardrails/guard.py) - Main API entry point\n- [Validator System](../validators/overview.md) - Validation rules\n- [Call History](../history/call-history.md) - Execution tracking\n- [Hub Validators](../hub/installed-validators.md) - Pre-built validators\n\n---\n\n<a id='async-streaming'></a>\n\n## Async and Streaming Support\n\n### 相关页面\n\n相关主题：[Execution Pipeline](#execution-pipeline), [LLM Provider Integration](#llm-providers)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/run/__init__.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/__init__.py)\n- [guardrails/run/async_stream_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/async_stream_runner.py)\n- [guardrails/run/async_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/async_runner.py)\n- [guardrails/run/stream_runner.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/run/stream_runner.py)\n- [guardrails/validator_service/async_validator_service.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_service/async_validator_service.py)\n- [guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n- [guardrails/integrations/databricks/ml_flow_instrumentor.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/databricks/ml_flow_instrumentor.py)\n</details>\n\n# Async and Streaming Support\n\n## Overview\n\nGuardrails provides comprehensive support for asynchronous operations and streaming responses, enabling integration with modern LLM APIs that support async calls or streaming output. This capability is essential for building responsive applications that need to handle real-time validation, provide incremental feedback, and maintain high throughput when processing LLM responses.\n\nThe async and streaming support in Guardrails is built around a modular runner architecture that separates the concerns of asynchronous execution from streaming output. This design allows developers to use either feature independently or combine them for full async streaming capabilities.\n\n资料来源：[guardrails/run/__init__.py:1-15]()\n\n## Architecture\n\n### Runner Class Hierarchy\n\nThe async and streaming functionality is implemented through a class hierarchy that extends a base `Runner` class with async and streaming capabilities.\n\n```mermaid\ngraph TD\n    A[Runner] --> B[AsyncRunner]\n    A --> C[StreamRunner]\n    B --> D[AsyncStreamRunner]\n    C --> D\n    \n    A1[Base synchronous runner] \n    B1[Async execution support]\n    C1[Streaming output support]\n    D1[Combined async + streaming]\n    \n    A --> A1\n    B --> B1\n    C --> C1\n    D --> D1\n```\n\n### Module Structure\n\nThe runners are organized under the `guardrails.run` module with the following structure:\n\n| Module | Purpose |\n|--------|---------|\n| `guardrails.run.runner` | Base synchronous runner |\n| `guardrails.run.async_runner` | Async execution support |\n| `guardrails.run.stream_runner` | Streaming output support |\n| `guardrails.run.async_stream_runner` | Combined async and streaming |\n| `guardrails.run.utils` | Shared utilities including `messages_source` |\n\n资料来源：[guardrails/run/__init__.py:1-15]()\n\n## Async Runner\n\n### AsyncRunner Class\n\nThe `AsyncRunner` extends the base `Runner` with asynchronous execution capabilities. It provides methods for calling LLM providers asynchronously and processing validation outcomes without blocking the calling thread.\n\n```python\nclass AsyncRunner(AsyncRunner, StreamRunner):\n    async def async_run(\n        self, call_log: Call, prompt_params: Optional[Dict] = None\n    ) -> AsyncIterator[ValidationOutcome]:\n```\n\nKey characteristics of `AsyncRunner`:\n\n- Supports fully asynchronous LLM calls using async-compatible prompt callables\n- Provides `async_call` method for making async LLM invocations\n- Integrates with the async validator service for non-blocking validation\n- Returns `ValidationOutcome` objects containing validated results\n\n### Async Prompt Callables\n\nGuardrails supports async prompt callables through the `AsyncPromptCallableBase` interface. Providers like `AsyncManifestCallable` implement this interface to enable async LLM calls.\n\n```python\nclass AsyncManifestCallable(AsyncPromptCallableBase):\n    async def invoke_llm(\n        self,\n        text: str,\n        client: Any,\n        instructions: Optional[str] = None,\n        *args,\n        **kwargs,\n    ):\n```\n\n资料来源：[guardrails/run/async_runner.py]()\n资料来源：[guardrails/llm_providers.py:1-100]()\n\n## Streaming Support\n\n### StreamRunner Class\n\nThe `StreamRunner` provides streaming output capabilities, allowing Guardrails to process LLM responses incrementally as they are generated. This is particularly useful for long-form content generation where users benefit from seeing results progressively.\n\nStreaming support enables:\n\n- Incremental validation of streamed chunks\n- Real-time feedback on validation status\n- Memory-efficient processing of large responses\n\n资料来源：[guardrails/run/stream_runner.py]()\n\n## Async Stream Runner\n\n### AsyncStreamRunner Class\n\nThe `AsyncStreamRunner` combines both async execution and streaming output, providing the most comprehensive integration for modern async LLM APIs with streaming support.\n\n```python\nclass AsyncStreamRunner(AsyncRunner, StreamRunner):\n    async def async_run(\n        self, call_log: Call, prompt_params: Optional[Dict] = None\n    ) -> AsyncIterator[ValidationOutcome]:\n```\n\nThe class uses Python's `contextvars` module for proper context propagation in async environments:\n\n```python\nfrom contextvars import ContextVar, copy_context\n```\n\nThis ensures that context variables are correctly copied when running async code, maintaining proper isolation and state management.\n\n资料来源：[guardrails/run/async_stream_runner.py:1-50]()\n\n### Python Version Compatibility\n\nFor Python versions earlier than 3.10, Guardrails provides a polyfill for the `anext()` builtin function:\n\n```python\nif sys.version_info.minor < 10:\n    from guardrails.utils.polyfills import anext\n```\n\nThis ensures compatibility with Python 3.9+ while maintaining access to async iteration features introduced in Python 3.10.\n\n资料来源：[guardrails/run/async_stream_runner.py:5-8]()\n\n### Streaming Workflow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant AsyncStreamRunner\n    participant AsyncValidatorService\n    participant LLMProvider\n    \n    Client->>AsyncStreamRunner: async_run(call_log, prompt_params)\n    AsyncStreamRunner->>LLMProvider: async_call(messages)\n    LLMProvider-->>AsyncStreamRunner: stream chunks\n    \n    loop For each chunk\n        AsyncStreamRunner->>AsyncValidatorService: validate_chunk(chunk)\n        AsyncValidatorService-->>AsyncStreamRunner: ValidationOutcome\n        AsyncStreamRunner-->>Client: yield ValidationOutcome\n    end\n    \n    Client->>AsyncStreamRunner: Final validation\n    AsyncStreamRunner-->>Client: Final ValidationOutcome\n```\n\n## MLflow Integration\n\nThe async and streaming runners are instrumented for MLflow tracing through the `MLflowInstrumentor` class. This provides observability for async operations and streaming workflows.\n\n### Instrumented Components\n\n| Component | Method | Instrumentation |\n|-----------|--------|------------------|\n| `AsyncRunner` | `async_step` | Async span with step type |\n| `AsyncStreamRunner` | `async_step` | Async + stream span attributes |\n| `Runner.call` | `call` | LLM span for synchronous calls |\n| `AsyncRunner.async_call` | `async_call` | LLM span for async calls |\n\n### Span Attributes\n\nAsync and streaming operations are traced with the following attributes:\n\n```python\n{\n    \"guardrails.version\": GUARDRAILS_VERSION,\n    \"type\": \"guardrails/guard/step\",\n    \"async\": True,\n    \"stream\": True  # Only for streaming runners\n}\n```\n\n资料来源：[guardrails/integrations/databricks/ml_flow_instrumentor.py:1-150]()\n\n### Async Stream Step Instrumentation\n\nThe async stream step wrapper handles async iteration properly:\n\n```python\nasync def trace_async_stream_step_wrapper(\n    *args, **kwargs\n) -> AsyncIterator[ValidationOutcome[OT]]:\n    with mlflow.start_span(...) as step_span:\n        exception = None\n        try:\n            gen = runner_step(*args, **kwargs)\n            next_exists = True\n            while next_exists:\n                try:\n                    res = await anext(gen)\n                    yield res\n                except StopIteration:\n                    next_exists = False\n                except StopAsyncIteration:\n                    next_exists = False\n        except Exception as e:\n            step_span.set_status(status=SpanStatusCode.ERROR)\n            exception = e\n        finally:\n            # Add step attributes\n            if exception:\n                raise exception\n```\n\n资料来源：[guardrails/integrations/databricks/ml_flow_instrumentor.py:80-120]()\n\n## Validation Outcome\n\nBoth async and streaming runners return `ValidationOutcome` objects, which encapsulate the result of validation operations.\n\n### ValidationOutcome Structure\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `call_log` | `Call` | Execution history and metadata |\n| `validation_response` | `ValidationResponse` | Validated and corrected output |\n| `exception` | `Exception` | Any exception that occurred |\n\nThe `Call` object maintains a stack of `Iteration` objects, each representing a step or reask that occurred during execution:\n\n```python\nclass Call:\n    iterations: Stack[Iteration] = Field(\n        description=\"A stack of iterations for each step/reask that occurred.\",\n        default_factory=Stack,\n    )\n    inputs: CallInputs = Field(\n        description=\"The inputs as passed in to Guard.__call__ or Guard.parse\",\n        default_factory=CallInputs,\n    )\n```\n\n资料来源：[guardrails/classes/history/call.py:1-50]()\n\n## API Reference\n\n### Core Imports\n\n```python\nfrom guardrails.run import (\n    Runner,\n    AsyncRunner,\n    StreamRunner,\n    AsyncStreamRunner,\n    messages_source,\n)\n```\n\n### Runner Selection Guide\n\n| Use Case | Recommended Runner |\n|----------|-------------------|\n| Synchronous LLM calls | `Runner` |\n| Async LLM calls (non-streaming) | `AsyncRunner` |\n| Streaming LLM responses | `StreamRunner` |\n| Async LLM calls with streaming | `AsyncStreamRunner` |\n\n## Best Practices\n\n### Async Context Management\n\nWhen using async runners, ensure proper context management:\n\n```python\nimport asyncio\nfrom guardrails.run import AsyncStreamRunner\n\nasync def process_stream():\n    runner = AsyncStreamRunner(...)\n    async for outcome in runner.async_run(call_log):\n        # Process each validation outcome\n        pass\n```\n\n### Error Handling\n\nThe async stream runner handles errors gracefully, setting span status and re-raising exceptions:\n\n```python\ntry:\n    # Stream processing\nexcept Exception as e:\n    step_span.set_status(status=SpanStatusCode.ERROR)\n    raise e\n```\n\n### MLflow Tracing\n\nEnable MLflow tracing to monitor async and streaming performance:\n\n```python\nfrom guardrails.integrations.databricks import MLflowInstrumentor\n\nMLflowInstrumentor().instrument()\n```\n\nThis automatically wraps all runner methods with appropriate span instrumentation.\n\n## Related Components\n\n### Validator Service\n\nThe async validator service provides non-blocking validation:\n\n- Processes validation requests asynchronously\n- Integrates with async runners for parallel validation\n- Maintains thread safety for concurrent operations\n\n### LLM Providers\n\nAsync-compatible LLM providers include:\n\n- `AsyncManifestCallable` for Manifest models\n- `LiteLLMCallable` with async support\n- Custom providers implementing `AsyncPromptCallableBase`\n\n资料来源：[guardrails/llm_providers.py:50-150]()\n\n## Summary\n\nGuardrails' async and streaming support provides a flexible, extensible architecture for handling modern LLM interactions:\n\n1. **Modular Design**: The runner hierarchy allows selective use of async and streaming features\n2. **Async Compatibility**: Full support for async/await patterns with Python 3.9+ compatibility\n3. **Streaming Efficiency**: Memory-efficient processing of large streaming responses\n4. **Observability**: Integrated MLflow tracing for monitoring async and streaming operations\n5. **Type Safety**: Full type hints with generic `ValidationOutcome` returns\n\n---\n\n<a id='llm-providers'></a>\n\n## LLM Provider Integration\n\n### 相关页面\n\n相关主题：[Guard Class Reference](#guard-class), [Framework Integrations](#framework-integrations)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/llm_providers.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/llm_providers.py)\n- [guardrails/classes/llm/prompt_callable.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/llm/prompt_callable.py)\n- [guardrails/classes/history/call_inputs.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call_inputs.py)\n- [guardrails/classes/history/call.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/classes/history/call.py)\n- [guardrails/guard.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/guard.py)\n</details>\n\n# LLM Provider Integration\n\n## Overview\n\nThe LLM Provider Integration system in Guardrails provides a unified abstraction layer for connecting various Large Language Model (LLM) providers to the Guardrails validation framework. This system enables Guardrails to work with multiple LLM backends—including OpenAI, LiteLLM, Manifest, and custom providers—while maintaining consistent prompt handling, response parsing, and validation workflows.\n\nThe integration architecture follows a **callable wrapper pattern**, where each LLM provider is wrapped in a standardized `PromptCallableBase` subclass that normalizes the interface between Guardrails and the underlying LLM API.\n\n资料来源：[guardrails/llm_providers.py:1-50]()\n\n## Architecture\n\n### Class Hierarchy\n\nThe LLM provider system is built on an abstract base class that defines the contract for all provider implementations:\n\n```mermaid\ngraph TD\n    A[PromptCallableBase] --> B[LiteLLMCallable]\n    A --> C[ManifestCallable]\n    A --> D[OpenAICallable]\n    \n    B --> E[GPTCallable]\n    B --> F[AnthropicCallable]\n    B --> G[Custom Provider]\n    \n    A --> H[LLM Response Normalization]\n    A --> I[Tracing Integration]\n    A --> J[Error Handling]\n```\n\n资料来源：[guardrails/classes/llm/prompt_callable.py:1-80]()\n\n### Core Components\n\n| Component | Purpose | File Location |\n|-----------|---------|---------------|\n| `PromptCallableBase` | Abstract base class defining the LLM interface contract | `guardrails/classes/llm/prompt_callable.py` |\n| `LiteLLMCallable` | Wrapper for LiteLLM multi-provider support | `guardrails/llm_providers.py` |\n| `ManifestCallable` | Wrapper for Manifest ML client | `guardrails/llm_providers.py` |\n| `LLMResponse` | Normalized response object | `guardrails/llm_providers.py` |\n| `CallInputs` | Captures invocation parameters and metadata | `guardrails/classes/history/call_inputs.py` |\n| `Call` | Records execution history and iterations | `guardrails/classes/history/call.py` |\n\n资料来源：[guardrails/llm_providers.py:50-150]()\n\n## PromptCallableBase\n\nThe `PromptCallableBase` is the foundational abstract class that all LLM providers must implement. It provides:\n\n### Abstract Methods\n\n| Method | Signature | Description |\n|--------|-----------|-------------|\n| `_invoke_llm` | `(text, model, messages, *args, **kwargs) -> LLMResponse` | Core LLM invocation method |\n| `_prepare_prompt` | `(text, instructions) -> str` | Prepares prompt with formatting |\n\n### Common Functionality\n\n- **Tracing Integration**: All providers integrate with Guardrails' tracing system via `trace_operation()` and `trace_llm_call()` functions\n- **Prompt Normalization**: Converts various prompt formats to a standardized structure\n- **Error Handling**: Wraps provider-specific exceptions in `PromptCallableException`\n- **Streaming Support**: Optional streaming via the `stream` parameter\n\n资料来源：[guardrails/classes/llm/prompt_callable.py:30-100]()\n\n## LiteLLM Integration\n\n### Overview\n\n`LiteLLMCallable` provides integration with [LiteLLM](https://github.com/BerriAI/litellm), a unified interface for calling 100+ LLMs including OpenAI, Azure, Anthropic, Cohere, and Hugging Face.\n\n```python\nfrom litellm import completion\n\nraw_llm_response, validated_response = guard(\n    completion,\n    model=\"gpt-3.5-turbo\",\n    prompt_params={...},\n    temperature=0.7,\n)\n```\n\n资料来源：[guardrails/llm_providers.py:80-120]()\n\n### Invocation Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `text` | `Optional[str]` | `None` | Plain text prompt |\n| `model` | `str` | `\"gpt-3.5-turbo\"` | Model identifier |\n| `messages` | `Optional[List[Dict]]` | `None` | Chat messages list |\n| `*args` | `Any` | - | Additional positional arguments |\n| `**kwargs` | `Any` | - | Provider-specific parameters (temperature, max_tokens, etc.) |\n\n### Function Calling Support\n\nLiteLLMCallable supports OpenAI-style function calling through the `tools` parameter:\n\n```python\nfunction_calling_tools = [\n    tool.get(\"function\")\n    for tool in kwargs.get(\"tools\", [])\n    if isinstance(tool, Dict) and tool.get(\"type\") == \"function\"\n]\n```\n\n资料来源：[guardrails/llm_providers.py:130-160]()\n\n## Manifest Integration\n\n### Overview\n\n`ManifestCallable` provides integration with the [Manifest](https://github.com/HazyResearch/manifest) ML client library for models hosted on various backends.\n\n### Usage Pattern\n\n```python\nfrom guardrails import Guard\n\nraw_llm_response, validated_response = guard(\n    client,\n    prompt_params={...},\n    ...\n)\n```\n\n### Prompt Handling\n\nManifest uses a non-chat prompt format:\n\n```python\nprompt = nonchat_prompt(prompt=text, instructions=instructions)\nmanifest_response = client.run(prompt, *args, **kwargs)\n```\n\n资料来源：[guardrails/llm_providers.py:20-60]()\n\n## Response Handling\n\n### LLMResponse Structure\n\nAll providers return a normalized `LLMResponse` object:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `output` | `str` | The raw LLM-generated text |\n| `model` | `Optional[str]` | Model identifier used |\n| `usage` | `Optional[Dict]` | Token usage statistics |\n| `provider` | `str` | Source provider name |\n\n### Tracing Integration\n\nEvery LLM call is traced with full input/output capture:\n\n```python\ntrace_operation(\n    input_mime_type=\"application/json\",\n    input_value={\n        **kwargs,\n        \"model\": model,\n        \"args\": args,\n    },\n)\n\ntrace_llm_call(\n    input_messages=kwargs.get(\"messages\"),\n    invocation_parameters={**kwargs, \"model\": model},\n    function_call=kwargs.get(\"function_call\"),\n)\n```\n\n资料来源：[guardrails/llm_providers.py:140-180]()\n\n## Guard Integration\n\n### Guard Class Methods\n\nThe `Guard` class provides factory methods for creating provider-integrated instances:\n\n| Method | Purpose |\n|--------|---------|\n| `Guard.from_rail()` | Create Guard from RAIL XML specification |\n| `Guard.from_pydantic()` | Create Guard from Pydantic model |\n| `Guard.__call__()` | Invoke LLM with automatic validation |\n\n资料来源：[guardrails/guard.py:100-200]()\n\n### Call History\n\nEach LLM invocation creates a `Call` record containing:\n\n```python\nclass Call:\n    iterations: Stack[Iteration]  # Validation iterations\n    inputs: CallInputs              # Invocation parameters\n    exception: Optional[Exception]  # Any errors during execution\n```\n\nThe `CallInputs` captures:\n- `llm_api`: The callable used\n- `prompt_params`: Parameters for prompt interpolation\n- `num_reasks`: Maximum reask attempts\n- `metadata`: Custom data for validators\n- `full_schema_reask`: Whether to reask entire schema\n- `stream`: Streaming mode flag\n\n资料来源：[guardrails/classes/history/call.py:20-80]()\n\n## Error Handling\n\n### Exception Types\n\n| Exception | Trigger | Handling |\n|-----------|---------|----------|\n| `PromptCallableException` | Missing dependencies or provider errors | Wraps underlying exception with context |\n| `ImportError` | Required package not installed | Clear installation instructions |\n\n### Example Error Handling\n\n```python\ntry:\n    from litellm import completion\nexcept ImportError as e:\n    raise PromptCallableException(\n        \"The `litellm` package is not installed. \"\n        \"Install with `pip install litellm`\"\n    ) from e\n```\n\n资料来源：[guardrails/llm_providers.py:95-105]()\n\n## Workflow Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Guard\n    participant PromptCallable\n    participant LLMProvider\n    participant Validator\n    \n    User->>Guard: __call__(llm_api, prompt, params)\n    Guard->>Guard: Create Call record\n    Guard->>PromptCallable: _invoke_llm(text, model, messages)\n    PromptCallable->>PromptCallable: trace_operation()\n    PromptCallable->>LLMProvider: LLM API call\n    LLMProvider-->>PromptCallable: Raw response\n    PromptCallable->>PromptCallable: trace_llm_call()\n    PromptCallable-->>Guard: LLMResponse\n    Guard->>Validator: Validate response\n    Validator-->>Guard: ValidationResult\n    Guard->>Guard: Record Iteration\n    Guard-->>User: (raw_response, validated_response)\n```\n\n## Best Practices\n\n1. **Use LiteLLM for Multi-Provider Support**: LiteLLM provides the most flexibility for switching between providers\n2. **Configure Prompt Parameters**: Always provide `prompt_params` for dynamic prompt interpolation\n3. **Enable Tracing in Development**: Tracing helps debug LLM interactions and validation failures\n4. **Handle Exceptions**: Wrap Guard calls in try-except blocks to handle validation failures gracefully\n5. **Use Pydantic for Structured Output**: The `Guard.from_pydantic()` method provides the cleanest integration for structured data generation\n\n## See Also\n\n- [Guard Usage Guide](../guard/usage.md)\n- [Validator Hub](https://guardrailsai.com/hub/)\n- [RAIL Specification](../rail/overview.md)\n\n---\n\n<a id='framework-integrations'></a>\n\n## Framework Integrations\n\n### 相关页面\n\n相关主题：[LLM Provider Integration](#llm-providers), [Guard Class Reference](#guard-class)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [guardrails/integrations/langchain/guard_runnable.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/langchain/guard_runnable.py)\n- [guardrails/integrations/langchain/base_runnable.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/langchain/base_runnable.py)\n- [guardrails/integrations/llama_index/guardrails_chat_engine.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/llama_index/guardrails_chat_engine.py)\n- [guardrails/integrations/llama_index/guardrails_query_engine.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/llama_index/guardrails_query_engine.py)\n- [guardrails/integrations/databricks/ml_flow_instrumentor.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/integrations/databricks/ml_flow_instrumentor.py)\n</details>\n\n# Framework Integrations\n\nGuardrails provides official integrations with popular AI frameworks to enable seamless validation of LLM outputs within existing application stacks. These integrations wrap framework-specific components to transparently apply Guard validation without requiring significant changes to existing code.\n\n## Architecture Overview\n\nFramework integrations in Guardrails follow a consistent design pattern: they wrap framework-native runnable or engine objects, intercepting inputs and outputs to apply validation through the Guard API.\n\n```mermaid\ngraph TD\n    subgraph \"Application Layer\"\n        User[User Application]\n    end\n    \n    subgraph \"Framework Integration Layer\"\n        GR[Guardrails Wrapper]\n        Guard[Guard Instance]\n    end\n    \n    subgraph \"Framework Layer\"\n        LC[LangChain / LlamaIndex]\n        DB[Databricks MLflow]\n    end\n    \n    subgraph \"Guardrails Core\"\n        Validators[Validators]\n        Schema[RAIL / Pydantic Schema]\n    end\n    \n    User --> GR\n    GR --> LC\n    GR --> Guard\n    Guard --> Validators\n    Guard --> Schema\n    \n    style GR fill:#e1f5fe\n    style Guard fill:#fff3e0\n```\n\n## LangChain Integration\n\nThe LangChain integration provides `GuardRunnable` and `BaseRunnable` classes that wrap LangChain components, enabling validation of LLM outputs in chains and agents.\n\n### Core Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `BaseRunnable` | `guardrails/integrations/langchain/base_runnable.py` | Base class providing LangChain-compatible runnable interface |\n| `GuardRunnable` | `guardrails/integrations/langchain/guard_runnable.py` | Concrete implementation wrapping a Guard instance |\n\n### GuardRunnable Class\n\nThe `GuardRunnable` class serves as a LangChain-compatible runnable that applies Guard validation to outputs.\n\n**Key Features:**\n- Implements LangChain's `Runnable` interface for drop-in compatibility\n- Wraps a Guard instance to validate LLM responses\n- Supports streaming responses with validation\n- Integrates with LangChain's tracing and observability\n\n**Usage Pattern:**\n```python\nfrom guardrails.integrations.langchain import GuardRunnable\nfrom guardrails import Guard\n\n# Create a Guard instance\nguard = Guard().use(SomeValidator, ...)\n\n# Wrap it as a LangChain runnable\nguard_runnable = GuardRunnable(guard=guard)\n\n# Use in LangChain chains\nchain = prompt | llm | guard_runnable\n```\n\n资料来源：[guardrails/integrations/langchain/guard_runnable.py]()\n\n### BaseRunnable Abstract Class\n\nThe `BaseRunnable` class defines the abstract interface that all Guardrails runnables must implement, ensuring consistency across different framework integrations.\n\n资料来源：[guardrails/integrations/langchain/base_runnable.py]()\n\n## LlamaIndex Integration\n\nThe LlamaIndex integration provides engines that wrap LlamaIndex query and chat engines with Guard validation.\n\n### Supported Engine Types\n\n| Engine Type | File | Description |\n|-------------|------|-------------|\n| `GuardrailsQueryEngine` | `guardrails/integrations/llama_index/guardrails_query_engine.py` | Validates query engine responses |\n| `GuardrailsChatEngine` | `guardrails/integrations/llama_index/guardrails_chat_engine.py` | Validates chat engine responses |\n\n### GuardrailsQueryEngine\n\nThe query engine integration validates responses from LlamaIndex query operations.\n\n**Key Capabilities:**\n- Wraps base LlamaIndex query engines\n- Validates retrieved context and generated responses\n- Supports custom validators for domain-specific checks\n- Maintains query context through the validation pipeline\n\n**Typical Integration:**\n```python\nfrom guardrails.integrations.llama_index import GuardrailsQueryEngine\nfrom guardrails import Guard\nfrom llama_index import VectorStoreIndex\n\n# Build index\nindex = VectorStoreIndex.from_documents(documents)\n\n# Create Guard\nguard = Guard().use(SomeValidator, ...)\n\n# Wrap query engine\nquery_engine = index.as_query_engine()\nguardrails_engine = GuardrailsQueryEngine(\n    query_engine=query_engine,\n    guard=guard\n)\n```\n\n资料来源：[guardrails/integrations/llama_index/guardrails_query_engine.py]()\n\n### GuardrailsChatEngine\n\nThe chat engine integration validates conversational responses, ensuring consistency and safety across multi-turn interactions.\n\n**Features:**\n- Validates each response in a conversation\n- Supports conversation context preservation\n- Integrates with LlamaIndex memory components\n- Enables custom validation per conversation turn\n\n资料来源：[guardrails/integrations/llama_index/guardrails_chat_engine.py]()\n\n## Databricks MLflow Integration\n\nThe Databricks integration provides automatic instrumentation for LLM calls within the MLflow tracking ecosystem.\n\n### MLflow Instrumentor\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `MLflowInstrumentor` | `guardrails/integrations/databricks/ml_flow_instrumentor.py` | Auto-instruments LLM calls for MLflow tracking |\n\n**Instrumentation Capabilities:**\n- Automatically wraps LLM invocations\n- Logs prompts and responses to MLflow\n- Tracks validation outcomes and errors\n- Associates metrics with MLflow runs\n\n**Setup:**\n```python\nfrom guardrails.integrations.databricks import MLflowInstrumentor\n\n# Initialize instrumentor\ninstrumentor = MLflowInstrumentor()\n\n# Enable instrumentation\ninstrumentor.instrument()\n```\n\n资料来源：[guardrails/integrations/databricks/ml_flow_instrumentor.py]()\n\n## Integration Patterns\n\n### Common Workflow\n\n```mermaid\nsequenceDiagram\n    participant App as Application\n    participant Wrapper as Guardrails Wrapper\n    participant Framework as AI Framework\n    participant Guard as Guard Instance\n    participant Validators as Validators\n    \n    App->>Wrapper: Invoke LLM Call\n    Wrapper->>Framework: Forward Request\n    Framework->>Wrapper: LLM Response\n    Wrapper->>Guard: Validate Response\n    Guard->>Validators: Run Validators\n    Validators-->>Guard: Validation Result\n    alt Validation Passes\n        Guard-->>Wrapper: Validated Output\n        Wrapper-->>App: Return Result\n    else Validation Fails\n        Guard-->>Wrapper: Validation Error\n        Wrapper-->>App: Raise Exception / Return Fix\n    end\n```\n\n### Validation Flow\n\nWhen validation fails, the integration architecture determines how to handle the failure based on the configured `on_fail` action:\n\n| Action | Behavior |\n|--------|----------|\n| `EXCEPTION` | Raises an exception with validation details |\n| `REASK` | Attempts to reask the LLM with corrected context |\n| `FIX` | Attempts to automatically fix the output |\n| `FILTER` | Filters invalid portions from the output |\n| `CUSTOM` | Invokes a custom handler function |\n\n## Configuration Reference\n\n### Guard Configuration\n\nIntegrations accept a Guard instance configured with the desired validators:\n\n```python\nfrom guardrails import Guard, OnFailAction\n\nguard = Guard().use(\n    Validator1(param1=\"value1\", on_fail=OnFailAction.EXCEPTION),\n    Validator2(param2=\"value2\", on_fail=OnFailAction.REASK),\n)\n```\n\n### Integration-Specific Options\n\n| Integration | Option | Description |\n|-------------|--------|-------------|\n| LangChain | `guard` | Guard instance for validation |\n| LlamaIndex | `query_engine` | Base query engine to wrap |\n| LlamaIndex | `chat_engine` | Base chat engine to wrap |\n| Databricks | `instrument()` | Enable/disable auto-instrumentation |\n\n## Best Practices\n\n1. **Centralized Guard Configuration**: Define Guard instances with all required validators in a single location and reuse across integrations\n2. **Fail Action Strategy**: Choose appropriate `on_fail` actions based on use case criticality\n3. **Validator Ordering**: Place faster validators first to fail fast on common issues\n4. **Error Handling**: Implement proper exception handling for validation failures\n5. **Testing**: Test validation logic independently before integration\n\n## Dependencies\n\nFramework integrations have specific dependency requirements:\n\n| Integration | Required Packages |\n|-------------|-------------------|\n| LangChain | `langchain>=0.0.XXX` |\n| LlamaIndex | `llama-index>=0.XXX` |\n| Databricks | `mlflow>=2.XXX`, `databricks-sdk` |\n\n---\n\n<a id='custom-validators'></a>\n\n## Creating Custom Validators\n\n### 相关页面\n\n相关主题：[Validators System](#validators)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [guardrails/validator_base.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/validator_base.py)\n- [guardrails/hub/validator_package_service.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/validator_package_service.py)\n- [guardrails/cli/hub/create_validator.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/cli/hub/create_validator.py)\n- [guardrails/hub/registry.py](https://github.com/guardrails-ai/guardrails/blob/main/guardrails/hub/registry.py)\n</details>\n\n# Creating Custom Validators\n\nCustom validators in Guardrails enable developers to define domain-specific validation logic that can be integrated seamlessly into the Guard validation pipeline. Validators are reusable components that inspect LLM outputs and either pass or fail based on custom criteria.\n\n## Overview\n\nGuardrails provides a validator framework where validators are classes that inherit from a base `Validator` class and implement a `validate` method. Each validator can receive initialization arguments and define behavior when validation fails through the `on_fail` parameter.\n\n```mermaid\ngraph TD\n    A[LLM Output] --> B[Guard Pipeline]\n    B --> C[Validator 1]\n    C --> D[Validator 2]\n    D --> E[Validator N]\n    E --> F[Validated Output]\n    \n    C -->|Pass| D\n    D -->|Pass| E\n    E -->|Pass| F\n    \n    C -->|Fail| G[On Fail Action]\n    D -->|Fail| G\n    E -->|Fail| G\n```\n\n## Validator Architecture\n\n### Base Class Structure\n\nValidators inherit from `Validator` which provides:\n- Initialization handling for `on_fail` policy\n- Metadata passing through validation pipeline\n- Integration with the Guard validation system\n\nEach validator must implement:\n1. `__init__`: Accept initialization arguments and `on_fail` parameter\n2. `validate`: Perform validation logic and return `PassResult` or `FailResult`\n\n### Validation Result Types\n\n| Result Type | Purpose |\n|-------------|---------|\n| `PassResult` | Value passes validation |\n| `FailResult` | Value fails validation with error message |\n\n## Creating a Custom Validator\n\n### Using the CLI Generator\n\nThe fastest way to create a validator is using the CLI command:\n\n```bash\nguardrails hub create-validator MyValidator\n```\n\nThis generates a template file `./my_validator.py` with the following structure:\n\n```python\nfrom guardrails.validator_base import (\n    Validator,\n    ValidationResult,\n    PassResult,\n    FailResult,\n)\nfrom typing import Any, Dict, Optional, Callable\n\nclass MyValidator(Validator):\n    \"\"\"Description of what your validator does.\n    \n    ## (Optional) Intended Use\n    Describe the intended use of your validator.\n    \"\"\"\n\n    def __init__(\n        self,\n        arg_1: str,  # FIXME: Replace with your custom init args\n        on_fail: Optional[Callable] = None,\n    ):\n        \"\"\"Initializes a new instance of the MyValidator class.\n        \n        Args:\n            arg_1 (str): FIXME: Describe the purpose of this argument.\n            on_fail (str, Callable): The policy when validation fails.\n                If str, must be one of: reask, fix, filter, refrain, noop, \n                exception, or fix_reask.\n        \"\"\"\n        super().__init__(on_fail=on_fail, arg_1=arg_1)\n        self._arg_1 = arg_1\n\n    def validate(self, value: Any, metadata: Dict) -> ValidationResult:\n        \"\"\"Validates the passed value.\n        \n        Args:\n            value (Any): The value to validate.\n            metadata (Dict): Additional metadata for validation.\n        \n        Returns:\n            ValidationResult: PassResult or FailResult\n        \"\"\"\n        # Add custom validator logic here\n        if value == \"pass\":\n            return PassResult()\n        else:\n            return FailResult(\n                error_message=\"Validation failed: value must be 'pass'\"\n            )\n```\n\n资料来源：[guardrails/cli/hub/create_validator.py:1-80]()\n\n### Validator Template Structure\n\n| Section | Description |\n|---------|-------------|\n| Class Definition | Inherits from `Validator` base class |\n| Docstring | Description and usage examples |\n| `__init__` | Initialization with custom args and `on_fail` |\n| `validate` | Core validation logic returning `ValidationResult` |\n\n## Validator Initialization Parameters\n\n### Core Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `on_fail` | `str` or `Callable` | Yes | Policy when validation fails |\n| Custom args | Any | Varies | Validator-specific parameters |\n\n### On Fail Actions\n\n| Action | Behavior |\n|--------|----------|\n| `reask` | Re-ask the LLM for corrected output |\n| `fix` | Attempt to fix the invalid value |\n| `filter` | Remove the invalid value from output |\n| `refrain` | Refrain from providing any value |\n| `noop` | No operation, continue with original value |\n| `exception` | Raise an exception |\n| `fix_reask` | Fix and re-ask if fix fails |\n\n资料来源：[guardrails/validator_service_base.py:1-50]()\n\n## Installation and Registration\n\n### Installing from Local Path\n\nValidators can be installed directly from the repository:\n\n```bash\nguardrails hub install ./path/to/validator.py\n```\n\n### Package Structure for Hub Submission\n\nWhen preparing a validator for Guardrails Hub submission:\n\n```python\n# In your validator package\nfrom guardrails.validator_base import Validator, ValidationResult, PassResult, FailResult\n\nclass MyValidator(Validator):\n    \"\"\"My custom validator description.\"\"\"\n    \n    def __init__(self, threshold: float = 0.5, on_fail: str = None):\n        super().__init__(on_fail=on_fail, threshold=threshold)\n        self._threshold = threshold\n    \n    def validate(self, value: Any, metadata: Dict) -> ValidationResult:\n        # Custom validation logic\n        if self._check_condition(value):\n            return PassResult()\n        return FailResult(error_message=\"Condition not met\")\n```\n\n### Installation Process\n\n```mermaid\nsequenceDiagram\n    participant CLI as Guardrails CLI\n    participant Service as ValidatorPackageService\n    participant Hub as Guardrails Hub\n    participant Local as Local Environment\n    \n    CLI->>Service: install_hub_module(validator_id)\n    Service->>Hub: Fetch manifest\n    Service->>Local: Download dependencies\n    Service->>Local: Install via pip\n    Service-->>CLI: Installation complete\n```\n\nThe installation service handles:\n1. Validating the package URI\n2. Fetching the manifest from Guardrails Hub\n3. Downloading dependencies\n4. Installing the module via pip\n\n资料来源：[guardrails/hub/install.py:1-60]()\n资料来源：[guardrails/hub/validator_package_service.py]()\n\n## Using Custom Validators\n\n### Basic Usage with Guard\n\n```python\nfrom guardrails import Guard, OnFailAction\nfrom guardrails.hub import MyValidator\n\n# Create guard with custom validator\nguard = Guard().use(\n    MyValidator(threshold=0.5, on_fail=OnFailAction.EXCEPTION)\n)\n\n# Validate output\nresult = guard.validate(\"sample_output\")\n```\n\n### Using with Guardrails Hub Validators\n\nValidators from Guardrails Hub are accessed via the `hub` module:\n\n```python\nfrom guardrails.hub import RegexMatch, CompetitorCheck, ToxicLanguage\n\nguard = Guard().use(\n    RegexMatch(regex=r\"\\d{3}-\\d{4}\"),\n    CompetitorCheck([\"Apple\", \"Microsoft\"]),\n    ToxicLanguage(threshold=0.5, validation_method=\"sentence\")\n)\n```\n\n### Multiple Validators\n\nMultiple validators can be chained on the same output:\n\n```mermaid\ngraph LR\n    A[LLM Output] --> B[RegexMatch]\n    B -->|Pass| C[CompetitorCheck]\n    C -->|Pass| D[ToxicLanguage]\n    D -->|Pass| E[Final Output]\n    \n    B -->|Fail| F[On Fail: Exception]\n    C -->|Fail| F\n    D -->|Fail| F\n```\n\n## Validation Metadata\n\nValidators receive metadata during execution that can be used for contextual validation:\n\n```python\ndef validate(self, value: Any, metadata: Dict) -> ValidationResult:\n    \"\"\"Use metadata for contextual validation.\n    \n    Common metadata keys:\n    - prompt_params: Parameters used in the original prompt\n    - llm_response: Raw LLM response\n    - iterations: Number of validation iterations\n    \"\"\"\n    if \"custom_key\" in metadata:\n        # Use metadata for validation decisions\n        pass\n    \n    return PassResult()\n```\n\n资料来源：[guardrails/classes/history/call_inputs.py:1-60]()\n\n## Best Practices\n\n### Validator Design Guidelines\n\n1. **Single Responsibility**: Each validator should check one condition\n2. **Clear Error Messages**: Provide descriptive error messages for failures\n3. **Metadata Utilization**: Leverage metadata for contextual validation\n4. **Default Values**: Set sensible defaults for optional parameters\n5. **Documentation**: Document all parameters and intended use cases\n\n### Testing Custom Validators\n\n```python\nfrom guardrails import Guard\nfrom my_validator import MyValidator\n\nguard = Guard().use(MyValidator(arg=\"expected_value\"))\n\n# Test passing case\nresult = guard.validate(\"expected_value\")\nassert result.validation_passed\n\n# Test failing case\nresult = guard.validate(\"unexpected_value\")\nassert not result.validation_passed\n```\n\n## CLI Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| `guardrails hub create-validator <name>` | Create validator template |\n| `guardrails hub install <uri>` | Install a validator |\n| `guardrails hub install -l <uri>` | Install with local models |\n| `guardrails hub install -q <uri>` | Quiet installation |\n\n资料来源：[guardrails/cli/hub/create_validator.py:1-100]()\n资料来源：[guardrails/cli/hub/install.py:1-60]()\n\n## Integration with Guard Pipeline\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Guard.__call__]\n    B --> C[Call History Created]\n    C --> D[Iteration Loop]\n    D --> E[Run Validators]\n    E --> F{All Validators Pass?}\n    F -->|Yes| G[Return ValidationOutcome]\n    F -->|No| H[Apply On Fail Action]\n    H --> I{Reask Enabled?}\n    I -->|Yes| J[Re-ask LLM]\n    J --> D\n    I -->|No| G\n```\n\nThe Guard class orchestrates the validation pipeline, managing iterations and applying on-fail policies as configured.\n\n资料来源：[guardrails/guard.py:1-100]()\n资料来源：[guardrails/classes/history/call.py:1-50]()\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: guardrails-ai/guardrails\n\nSummary: Found 38 potential pitfall items; 14 are high/blocking. Highest priority: installation - 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?.\n\n## 1. installation · 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_69600563346341a386aa86c6af5d1274 | https://github.com/guardrails-ai/guardrails/issues/1448 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. installation · 来源证据：Feature request: OWASP ASI06 memory poisoning guard validator\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature request: OWASP ASI06 memory poisoning guard validator\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e44b7cdf7b674acf9789c9feddc13dbc | https://github.com/guardrails-ai/guardrails/issues/1488 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. installation · 来源证据：Portable evidence artifacts for validation outcomes\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Portable evidence artifacts for validation outcomes\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ef2970465bbe44c89b513edd115b682c | https://github.com/guardrails-ai/guardrails/issues/1457 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. installation · 来源证据：Proposal: Agent Threat Rules detection integration\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: Agent Threat Rules detection integration\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_64ae6a0aa3324a3a9af980f2f61a5c30 | https://github.com/guardrails-ai/guardrails/issues/1471 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. installation · 来源证据：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d7163e193eb54aab837d87b3ecd73991 | https://github.com/guardrails-ai/guardrails/issues/1453 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. installation · 来源证据：[bug] 429 Rate Limit Error from Opting into Metrics\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[bug] 429 Rate Limit Error from Opting into Metrics\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_3c9ae4fdd14547eea3c3a4be6ac6fb23 | https://github.com/guardrails-ai/guardrails/issues/1385 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. capability · 来源证据：[docs] Fix double logo display in pypi\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：[docs] Fix double logo display in pypi\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_084985c7cb4d4238a44e452b14b2eaf9 | https://github.com/guardrails-ai/guardrails/issues/1362 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 8. security_permissions · 失败模式：security_permissions: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication,...\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- User impact: Developers may expose sensitive permissions or credentials: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation. Context: Observed when using python\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1485\n- Evidence: failure_mode_cluster:github_issue | fmev_819ae3bfce09ed33a4655a81cf59dd44 | https://github.com/guardrails-ai/guardrails/issues/1485 | Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n\n## 9. security_permissions · 失败模式：security_permissions: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- User impact: Developers may expose sensitive permissions or credentials: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard. Context: Observed when using python\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1476\n- Evidence: failure_mode_cluster:github_issue | fmev_2c7b3b6f6709cc847b37fb56bc9973d3 | https://github.com/guardrails-ai/guardrails/issues/1476 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard, failure_mode_cluster:github_issue | fmev_77887b77c9dabcdbce93e8b20c9a7c57 | https://github.com/guardrails-ai/guardrails/issues/1475 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n## 10. security_permissions · 失败模式：security_permissions: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator wit...\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- User impact: Developers may expose sensitive permissions or credentials: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub. Context: Observed when using python, docker, cuda\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1479\n- Evidence: failure_mode_cluster:github_issue | fmev_70a43b34234fca351363180353991f27 | https://github.com/guardrails-ai/guardrails/issues/1479 | [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n\n## 11. security_permissions · 来源证据：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0f957598a5044976a69cdd1925dd9483 | https://github.com/guardrails-ai/guardrails/issues/1476 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. security_permissions · 来源证据：Integration proposal: Cryptographic audit trail validator with asqav\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: Cryptographic audit trail validator with asqav\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8db542ceccff4a71bc11c254ce3abfde | https://github.com/guardrails-ai/guardrails/issues/1446 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 13. security_permissions · 来源证据：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_da275c0a112848ed920af00c76fd3e1b | https://github.com/guardrails-ai/guardrails/issues/1463 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 14. security_permissions · 来源证据：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_3f90fdd47b014d488f2782f04c75b37c | https://github.com/guardrails-ai/guardrails/issues/1479 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 15. installation · 失败模式：installation: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- User impact: Developers may fail before the first successful local run: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: styxx hallucination validator (8-benchmark cross-validated). Context: Observed when using python, cuda\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_2a7dfe1829e559543fd3177ac3a0ace3 | https://github.com/guardrails-ai/guardrails/issues/1463 | Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n## 16. installation · 失败模式：installation: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n- User impact: Developers may fail before the first successful local run: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+). Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_b8ff8a254ff16e4d23faa27660558c49 | https://github.com/guardrails-ai/guardrails/issues/1483 | Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n\n## 17. installation · 失败模式：installation: Proposal: Agent Threat Rules detection integration\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Proposal: Agent Threat Rules detection integration\n- User impact: Developers may fail before the first successful local run: Proposal: Agent Threat Rules detection integration\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Proposal: Agent Threat Rules detection integration. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6bc24f2942ba0fbe13c0d348506bf619 | https://github.com/guardrails-ai/guardrails/issues/1471 | Proposal: Agent Threat Rules detection integration\n\n## 18. installation · 失败模式：installation: [bug] 429 Rate Limit Error from Opting into Metrics\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] 429 Rate Limit Error from Opting into Metrics\n- User impact: Developers may fail before the first successful local run: [bug] 429 Rate Limit Error from Opting into Metrics\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] 429 Rate Limit Error from Opting into Metrics. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_c0442e907dbee8c67e3e11968abd509a | https://github.com/guardrails-ai/guardrails/issues/1385 | [bug] 429 Rate Limit Error from Opting into Metrics\n\n## 19. installation · 失败模式：installation: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'N...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- User impact: Developers may fail before the first successful local run: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'. Context: Observed when using python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4e9aa8a1b02d1ede79b30b62ddb6ceba | https://github.com/guardrails-ai/guardrails/issues/1477 | [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n\n## 20. installation · 失败模式：installation: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n- User impact: Developers may fail before the first successful local run: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2. Context: Observed when using python, macos\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_3d41c127084ca13dab398cfd91d3a12e | https://github.com/guardrails-ai/guardrails/issues/1464 | [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n\n## 21. installation · 失败模式：installation: v0.9.2\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: v0.9.2\n- User impact: Upgrade or migration may change expected behavior: v0.9.2\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: v0.9.2. Context: Observed when using node, python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_release | fmev_c54b42261d198f5d86e2d86b973022b2 | https://github.com/guardrails-ai/guardrails/releases/tag/v0.9.2 | v0.9.2\n\n## 22. installation · 失败模式：installation: v0.9.3\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: v0.9.3\n- User impact: Upgrade or migration may change expected behavior: v0.9.3\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: v0.9.3. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_release | fmev_ccf3f3888877fa148fd2b9e4d1685a07 | https://github.com/guardrails-ai/guardrails/releases/tag/v0.9.3 | v0.9.3\n\n## 23. configuration · 失败模式：configuration: Integration proposal: Cryptographic audit trail validator with asqav\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Integration proposal: Cryptographic audit trail validator with asqav\n- User impact: Developers may misconfigure credentials, environment, or host setup: Integration proposal: Cryptographic audit trail validator with asqav\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: Cryptographic audit trail validator with asqav. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_3e83bc4e63af89b800f024f286804a55 | https://github.com/guardrails-ai/guardrails/issues/1446 | Integration proposal: Cryptographic audit trail validator with asqav\n\n## 24. configuration · 失败模式：configuration: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- User impact: Developers may misconfigure credentials, environment, or host setup: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails. Context: Observed when using node, python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_505b8100ee11945f0044da14ce3d5045 | https://github.com/guardrails-ai/guardrails/issues/1435 | MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n## 25. configuration · 失败模式：configuration: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- User impact: Developers may misconfigure credentials, environment, or host setup: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_7ce2d4758da469cfafebf0b41e8f8f3f | https://github.com/guardrails-ai/guardrails/issues/1453 | Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n## 26. configuration · 来源证据：[feat] Attempt to repair JSON before triggering NonParseableReAsk\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[feat] Attempt to repair JSON before triggering NonParseableReAsk\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0e5b292fafab4cdfb39c7541516cecb7 | https://github.com/guardrails-ai/guardrails/issues/1380 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 27. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | README/documentation is current enough for a first validation pass.\n\n## 28. runtime · 失败模式：runtime: Portable evidence artifacts for validation outcomes\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: Portable evidence artifacts for validation outcomes\n- User impact: Developers may hit a documented source-backed failure mode: Portable evidence artifacts for validation outcomes\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Portable evidence artifacts for validation outcomes. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_2379f90244868de9553a10aa0783be57 | https://github.com/guardrails-ai/guardrails/issues/1457 | Portable evidence artifacts for validation outcomes\n\n## 29. runtime · 失败模式：runtime: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- User impact: Developers may hit a documented source-backed failure mode: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: on_fail=\"refrain\" behavior unclear/inconsistent with documentation. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6963ac9f9e50fbdabe6896ca38295267 | https://github.com/guardrails-ai/guardrails/issues/1395 | on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n## 30. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | last_activity_observed missing\n\n## 31. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | no_demo; severity=medium\n\n## 32. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | no_demo; severity=medium\n\n## 33. security_permissions · 来源证据：Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolat…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_222c3a7398b845d58afc8e03e3cd2d56 | https://github.com/guardrails-ai/guardrails/issues/1485 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 34. security_permissions · 来源证据：MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b6a63df899144908af33089886cfaf51 | https://github.com/guardrails-ai/guardrails/issues/1435 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 35. security_permissions · 来源证据：[bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution fo…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_f801c42622884292b29b3ae18f365af6 | https://github.com/guardrails-ai/guardrails/issues/1477 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 36. security_permissions · 来源证据：on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8881807252f149aeb7bc2c3a46019ce0 | https://github.com/guardrails-ai/guardrails/issues/1395 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 37. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | issue_or_pr_quality=unknown\n\n## 38. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | release_recency=unknown\n\n<!-- canonical_name: guardrails-ai/guardrails; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "Human Manual"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log\n\nProject: guardrails-ai/guardrails\n\nSummary: Found 38 potential pitfall items; 14 are high/blocking. Highest priority: installation - 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?.\n\n## 1. installation · 来源证据：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：FIX action silently mutates output - should there be a 'quarantine' tier between LOG and FIX?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_69600563346341a386aa86c6af5d1274 | https://github.com/guardrails-ai/guardrails/issues/1448 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. installation · 来源证据：Feature request: OWASP ASI06 memory poisoning guard validator\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature request: OWASP ASI06 memory poisoning guard validator\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e44b7cdf7b674acf9789c9feddc13dbc | https://github.com/guardrails-ai/guardrails/issues/1488 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. installation · 来源证据：Portable evidence artifacts for validation outcomes\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Portable evidence artifacts for validation outcomes\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ef2970465bbe44c89b513edd115b682c | https://github.com/guardrails-ai/guardrails/issues/1457 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. installation · 来源证据：Proposal: Agent Threat Rules detection integration\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: Agent Threat Rules detection integration\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_64ae6a0aa3324a3a9af980f2f61a5c30 | https://github.com/guardrails-ai/guardrails/issues/1471 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. installation · 来源证据：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d7163e193eb54aab837d87b3ecd73991 | https://github.com/guardrails-ai/guardrails/issues/1453 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. installation · 来源证据：[bug] 429 Rate Limit Error from Opting into Metrics\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[bug] 429 Rate Limit Error from Opting into Metrics\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_3c9ae4fdd14547eea3c3a4be6ac6fb23 | https://github.com/guardrails-ai/guardrails/issues/1385 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. capability · 来源证据：[docs] Fix double logo display in pypi\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：[docs] Fix double logo display in pypi\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_084985c7cb4d4238a44e452b14b2eaf9 | https://github.com/guardrails-ai/guardrails/issues/1362 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 8. security_permissions · 失败模式：security_permissions: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication,...\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- User impact: Developers may expose sensitive permissions or credentials: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation. Context: Observed when using python\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1485\n- Evidence: failure_mode_cluster:github_issue | fmev_819ae3bfce09ed33a4655a81cf59dd44 | https://github.com/guardrails-ai/guardrails/issues/1485 | Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n\n## 9. security_permissions · 失败模式：security_permissions: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- User impact: Developers may expose sensitive permissions or credentials: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard. Context: Observed when using python\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1476\n- Evidence: failure_mode_cluster:github_issue | fmev_2c7b3b6f6709cc847b37fb56bc9973d3 | https://github.com/guardrails-ai/guardrails/issues/1476 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard, failure_mode_cluster:github_issue | fmev_77887b77c9dabcdbce93e8b20c9a7c57 | https://github.com/guardrails-ai/guardrails/issues/1475 | Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n## 10. security_permissions · 失败模式：security_permissions: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator wit...\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: Developers should check this security_permissions risk before relying on the project: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- User impact: Developers may expose sensitive permissions or credentials: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub. Context: Observed when using python, docker, cuda\n- Guardrail action: Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/guardrails-ai/guardrails/issues/1479\n- Evidence: failure_mode_cluster:github_issue | fmev_70a43b34234fca351363180353991f27 | https://github.com/guardrails-ai/guardrails/issues/1479 | [bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n\n## 11. security_permissions · 来源证据：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: OWASP ASI06 memory write validation via Agent Memory Guard\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0f957598a5044976a69cdd1925dd9483 | https://github.com/guardrails-ai/guardrails/issues/1476 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. security_permissions · 来源证据：Integration proposal: Cryptographic audit trail validator with asqav\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: Cryptographic audit trail validator with asqav\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8db542ceccff4a71bc11c254ce3abfde | https://github.com/guardrails-ai/guardrails/issues/1446 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 13. security_permissions · 来源证据：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_da275c0a112848ed920af00c76fd3e1b | https://github.com/guardrails-ai/guardrails/issues/1463 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 14. security_permissions · 来源证据：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Failures and Delayed Responses from guard.validate Method Using Different Validator with Guardrails Hub\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_3f90fdd47b014d488f2782f04c75b37c | https://github.com/guardrails-ai/guardrails/issues/1479 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 15. installation · 失败模式：installation: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- User impact: Developers may fail before the first successful local run: Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: styxx hallucination validator (8-benchmark cross-validated). Context: Observed when using python, cuda\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_2a7dfe1829e559543fd3177ac3a0ace3 | https://github.com/guardrails-ai/guardrails/issues/1463 | Integration proposal: styxx hallucination validator (8-benchmark cross-validated)\n\n## 16. installation · 失败模式：installation: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n- User impact: Developers may fail before the first successful local run: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+). Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_b8ff8a254ff16e4d23faa27660558c49 | https://github.com/guardrails-ai/guardrails/issues/1483 | Lift litellm <1.82.6 pin to allow post-incident safe releases (1.83+)\n\n## 17. installation · 失败模式：installation: Proposal: Agent Threat Rules detection integration\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Proposal: Agent Threat Rules detection integration\n- User impact: Developers may fail before the first successful local run: Proposal: Agent Threat Rules detection integration\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Proposal: Agent Threat Rules detection integration. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6bc24f2942ba0fbe13c0d348506bf619 | https://github.com/guardrails-ai/guardrails/issues/1471 | Proposal: Agent Threat Rules detection integration\n\n## 18. installation · 失败模式：installation: [bug] 429 Rate Limit Error from Opting into Metrics\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] 429 Rate Limit Error from Opting into Metrics\n- User impact: Developers may fail before the first successful local run: [bug] 429 Rate Limit Error from Opting into Metrics\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] 429 Rate Limit Error from Opting into Metrics. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_c0442e907dbee8c67e3e11968abd509a | https://github.com/guardrails-ai/guardrails/issues/1385 | [bug] 429 Rate Limit Error from Opting into Metrics\n\n## 19. installation · 失败模式：installation: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'N...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- User impact: Developers may fail before the first successful local run: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'. Context: Observed when using python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4e9aa8a1b02d1ede79b30b62ddb6ceba | https://github.com/guardrails-ai/guardrails/issues/1477 | [bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n\n## 20. installation · 失败模式：installation: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n- User impact: Developers may fail before the first successful local run: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: [bug] Guardrails CLI start command broken with guardrails-api 0.4.2. Context: Observed when using python, macos\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_3d41c127084ca13dab398cfd91d3a12e | https://github.com/guardrails-ai/guardrails/issues/1464 | [bug] Guardrails CLI start command broken with guardrails-api 0.4.2\n\n## 21. installation · 失败模式：installation: v0.9.2\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: v0.9.2\n- User impact: Upgrade or migration may change expected behavior: v0.9.2\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: v0.9.2. Context: Observed when using node, python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_release | fmev_c54b42261d198f5d86e2d86b973022b2 | https://github.com/guardrails-ai/guardrails/releases/tag/v0.9.2 | v0.9.2\n\n## 22. installation · 失败模式：installation: v0.9.3\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: v0.9.3\n- User impact: Upgrade or migration may change expected behavior: v0.9.3\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: v0.9.3. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_release | fmev_ccf3f3888877fa148fd2b9e4d1685a07 | https://github.com/guardrails-ai/guardrails/releases/tag/v0.9.3 | v0.9.3\n\n## 23. configuration · 失败模式：configuration: Integration proposal: Cryptographic audit trail validator with asqav\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Integration proposal: Cryptographic audit trail validator with asqav\n- User impact: Developers may misconfigure credentials, environment, or host setup: Integration proposal: Cryptographic audit trail validator with asqav\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Integration proposal: Cryptographic audit trail validator with asqav. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_3e83bc4e63af89b800f024f286804a55 | https://github.com/guardrails-ai/guardrails/issues/1446 | Integration proposal: Cryptographic audit trail validator with asqav\n\n## 24. configuration · 失败模式：configuration: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- User impact: Developers may misconfigure credentials, environment, or host setup: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails. Context: Observed when using node, python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_505b8100ee11945f0044da14ce3d5045 | https://github.com/guardrails-ai/guardrails/issues/1435 | MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n## 25. configuration · 失败模式：configuration: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- User impact: Developers may misconfigure credentials, environment, or host setup: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_7ce2d4758da469cfafebf0b41e8f8f3f | https://github.com/guardrails-ai/guardrails/issues/1453 | Proposal: PromptDefenseAudit Hub validator — static system prompt hardening check\n\n## 26. configuration · 来源证据：[feat] Attempt to repair JSON before triggering NonParseableReAsk\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[feat] Attempt to repair JSON before triggering NonParseableReAsk\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0e5b292fafab4cdfb39c7541516cecb7 | https://github.com/guardrails-ai/guardrails/issues/1380 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 27. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | README/documentation is current enough for a first validation pass.\n\n## 28. runtime · 失败模式：runtime: Portable evidence artifacts for validation outcomes\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: Portable evidence artifacts for validation outcomes\n- User impact: Developers may hit a documented source-backed failure mode: Portable evidence artifacts for validation outcomes\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Portable evidence artifacts for validation outcomes. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_2379f90244868de9553a10aa0783be57 | https://github.com/guardrails-ai/guardrails/issues/1457 | Portable evidence artifacts for validation outcomes\n\n## 29. runtime · 失败模式：runtime: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- User impact: Developers may hit a documented source-backed failure mode: on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: on_fail=\"refrain\" behavior unclear/inconsistent with documentation. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6963ac9f9e50fbdabe6896ca38295267 | https://github.com/guardrails-ai/guardrails/issues/1395 | on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n## 30. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | last_activity_observed missing\n\n## 31. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | no_demo; severity=medium\n\n## 32. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | no_demo; severity=medium\n\n## 33. security_permissions · 来源证据：Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolat…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Best-practice: litellm pin excludes patched CVE versions, unverified-jwt-decode duplication, workflow inputs interpolation\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_222c3a7398b845d58afc8e03e3cd2d56 | https://github.com/guardrails-ai/guardrails/issues/1485 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 34. security_permissions · 来源证据：MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：MCP Server Compliance Scanning: OWASP MCP Top 10 guardrails\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b6a63df899144908af33089886cfaf51 | https://github.com/guardrails-ai/guardrails/issues/1435 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 35. security_permissions · 来源证据：[bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution fo…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[bug] Command 'guardrails hub install hub://arize-ai/llm_rag_evaluator' fails with 500 and 'No matching distribution found'\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_f801c42622884292b29b3ae18f365af6 | https://github.com/guardrails-ai/guardrails/issues/1477 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 36. security_permissions · 来源证据：on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：on_fail=\"refrain\" behavior unclear/inconsistent with documentation\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8881807252f149aeb7bc2c3a46019ce0 | https://github.com/guardrails-ai/guardrails/issues/1395 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 37. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | issue_or_pr_quality=unknown\n\n## 38. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:594609262 | https://github.com/guardrails-ai/guardrails | release_recency=unknown\n",
      "summary": "Identity, installation, configuration, runtime, and safety pitfalls before user trial.",
      "title": "Pitfall Log"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# guardrails - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for guardrails-ai/guardrails.\n\nProject:\n- Name: guardrails\n- Repository: https://github.com/guardrails-ai/guardrails\n- Summary: Adding guardrails to large language models.\n- Host target: chatgpt\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Adding guardrails to large language models.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Adding guardrails to large language models.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. getting-started: Getting Started with Guardrails. Produce one small intermediate artifact and wait for confirmation.\n2. system-architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. guard-class: Guard Class Reference. Produce one small intermediate artifact and wait for confirmation.\n4. validators: Validators System. Produce one small intermediate artifact and wait for confirmation.\n5. schema-processing: Schema Processing. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/guardrails-ai/guardrails\n- https://github.com/guardrails-ai/guardrails#readme\n- README.md\n- guardrails/__init__.py\n- guardrails/version.py\n- guardrails/guard.py\n- guardrails/async_guard.py\n- guardrails/validator_service/validator_service_base.py\n- guardrails/classes/schema/processed_schema.py\n- guardrails/schema/pydantic_schema.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start\n\nProject: guardrails-ai/guardrails\n\n## Official Entry Points\n\n### Python / pip · 官方安装入口\n\n```bash\npip install guardrails-ai\n```\n\nSource：https://github.com/guardrails-ai/guardrails#readme\n\n## Sources\n\n- repo: https://github.com/guardrails-ai/guardrails\n- docs: https://github.com/guardrails-ai/guardrails#readme\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_4e8dcba9fe0c48c2ac835e2e5a64cd86"
}
