Agent 开发框架

guardrails|为大语言模型应用添加输入输出校验与结构化输出的 Python 框架

guardrails

一个 Python 框架,用于为大语言模型应用的输入输出执行风险校验,并从模型生成结构化数据。

获取与使用

需要部署

按官方资料自行安装或部署

使用难度待核验
国内可用性待核验

2026-11-09 更新 · 本站尚未实测

项目介绍

Agent 开发框架 · 2026-11-09 更新 · 本站尚未实测

Guardrails 是一个 Python 框架,README 将其定位为帮助构建可靠 AI 应用的开发框架,主要承担两项功能:一是在应用中运行输入/输出 Guard(守卫),检测、量化并缓解特定类型风险;二是帮助从大语言模型生成结构化数据。

它本身不是一个可直接对话使用的 Agent,也不是 MCP 服务或 Skill 包,而是需要开发者写代码集成的框架。校验规则以“validator(校验器)”形式提供,多个校验器可组合成 Input Guard 与 Output Guard,拦截模型的输入与输出。官方另有 Guardrails Hub 作为校验器集合,README 给出的 Hub 入口为 guardrailsai.com/hub/。

核心能力

点击能力名称查看输入、输出和原文依据。

  • 输入输出校验:通过 Guard 对进入和离开模型的文本做规则检查,并按失败动作(如抛出异常)处理。README 示例使用正则匹配校验电话号码、竞品名称检查与有毒语言检测。
  • 结构化数据生成:用 Pydantic 模型描述期望输出结构,框架据模型是否支持函数调用,选择函数调用语法或把输出 schema 加入提示词两种方式生成结构化结果。
  • 校验器组合:一个 Guard 内可串联多个 validator,任一环节失败即反馈对应错误信息。
  • 自定义校验器:README 称可以自行创建 validator 并贡献到 Guardrails Hub。
  • 独立服务模式:可通过 guardrails start 以 Flask 形式提供 REST API,支持以 Guardrails 客户端或 OpenAI SDK 兼容方式调用;生产部署建议使用 Docker 配合 Gunicorn。
  • 语言支持:README 明确支持 Python 与 JavaScript,并称正在扩展其他语言。

实际应用场景

适用场景

适合需要在上线前为模型输出增加可控性检查的工程团队,例如:对用户输入或模型回复做格式与内容规则校验;要求模型按固定字段结构返回数据(如示例中的宠物信息结构);把校验逻辑封装成 REST 服务,供多个应用统一调用。

若只是希望找一个开箱即用的聊天 Agent 或可视化工作流工具,本项目并不对应这类形态,需要自行编码集成。

安装与接入

README 给出的安装方式为:

pip install guardrails-ai

基础使用流程(依据 README 示例整理,示例代码请以官方文档为准):

  1. 安装框架并运行 guardrails configure 完成配置;
  2. 从 Guardrails Hub 安装所需校验器,例如 pip install guardrails-ai-regex-match;
  3. 在 Python 中从 guardrails 导入 Guard、OnFailAction,并从对应校验器包导入校验器类,构造 Guard 后调用 guard.validate(...)。

结构化输出场景中,README 示例以 Guard.for_pydantic(output_class=..., prompt=...) 构造 Guard,并传入 LLM 调用函数与模型名。服务模式示例步骤为:pip install "guardrails-ai"、guardrails configure、guardrails create --validators=hub://guardrails/two_words --guard-name=two-word-guard、guardrails start --config=./config.py,随后通过本地 8000 端口的 REST 接口访问。

README 未提供 MCP 配置,采集资料中 MCP 与 server 配置文件均返回 404,因此不应视为 MCP 服务。

使用条件与限制

是否需要部署
需自行准备运行环境,具体要求见正文
是否需要注册
账号和认证要求见正文;未明确说明的项目仍待核验
是否需要 API Key
待核验
费用与额度
费用边界见正文,项目许可不代表模型或托管服务免费
所需权限
待核验
许可证与服务条款
待核验

权限费用与限制

  • 框架本身通过 pip 安装使用,仓库代码采用 Apache 2.0 许可证。
  • README 公告:自 2026 年 7 月 6 日起,Guardrails 校验器迁移为标准 PyPI 包,可直接用 pip 安装,同时 Guardrails 公告计划于 2026 年 8 月 25 日停止托管远程推理服务,该日期已过,当前服务状态仍应以官方确认结果为准,迁移说明见仓库 issue 1560。依赖托管推理的功能需要按此公告评估。
  • 使用 OpenAI 等模型时需自备对应 API Key,示例中出现 OPENAI_API_KEY 环境变量;模型调用产生的费用由模型提供方收取,README 未给出价格信息,具体费用待向相关服务商核验。
  • guardrails configure 是否需要账号或令牌、Hub 校验器的授权与使用条件,README 未完整说明,待核验。
  • 托管服务(如 Hub、Index 等站点)的可用性、数据处理方式与地域,README 未说明,待核验。

国内使用情况

网友核验 用户经验分享

与站长实测独立,不代表官方认证或本站已实测。

我要核验
0 位参与者0 份有效分项记录

最近核验:暂无有效核验。参与人数按当前项目有效身份去重;不同核验项分别统计,不合并成用户总结果。仅统计审核通过且未过期的记录。

分项统计、有效期与样本量
核验项目有效人数成功 / 部分 / 失败 / 无法判断成功率最近核验 / 有效期
官方网站访问00 / 0 / 0 / 0样本不足暂无 / 7 天
GitHub 仓库访问00 / 0 / 0 / 0样本不足暂无 / 7 天
安装与运行00 / 0 / 0 / 0样本不足暂无 / 30 天
官方服务国内连接 / MCP 连接00 / 0 / 0 / 0样本不足暂无 / 30 天
国内网络情况00 / 0 / 0 / 0样本不足暂无 / 7 天
国内模型兼容性00 / 0 / 0 / 0样本不足暂无 / 30 天
自定义 API00 / 0 / 0 / 0样本不足暂无 / 30 天
海外服务依赖
00 / 0 / 0 / 0样本不足暂无 / 30 天
海外账号要求
00 / 0 / 0 / 0样本不足暂无 / 30 天
中文界面
00 / 0 / 0 / 0样本不足暂无 / 30 天
客户端兼容性00 / 0 / 0 / 0样本不足暂无 / 30 天
账号及费用信息
00 / 0 / 0 / 0样本不足暂无 / 30 天

成功率 = 成功 ÷(成功 + 部分成功 + 失败);无法判断不计入分母。至少 5 份可判断结果才显示成功率。账号、费用、海外依赖与语言等事实项,成功表示核查结论与资料吻合,具体观察另行统计;不表示免费或没有海外依赖。不同网络、客户端和版本的结果不能直接等同。

最近有效核验

暂无审核通过且未过期的网友核验。欢迎提交真实使用记录。

查看全部有效核验 →

国内实测状态:国内可用性待核验。协议兼容和官方资料说明不等于国内网络可用。

官方网站访问
尚未实测 待核验
GitHub 仓库访问
尚未实测 待核验
官方服务国内连接
尚未实测 待核验
国内网络情况
尚未实测 待核验
国内模型兼容性
尚未实测 待核验
自定义 API
尚未实测 待核验
海外服务依赖
尚未实测 待核验
海外账号要求
尚未实测 待核验
中文界面
尚未实测 待核验
国内最后核验时间
尚未实测

许可与国内使用

仓库 LICENSE 文件为 Apache License 2.0,可据此判断仓库代码的许可条件;此许可不自动覆盖第三方校验器包、Hub 托管服务、商业模块或任何第三方模型,这些组件的许可与条款需分别核验。

公开仓库不代表全部能力免费,模型 API 与托管服务可能另有费用与条款。README 未提及国内网络访问、国内模型适配或国内部署情况,相关内容待核验,本文不作可用性承诺。README 明确可搭配专有与开源 LLM 使用,但未逐一列出受支持模型清单,具体模型支持范围请查阅官方文档。

项目资料与来源

官方网站 ↗

GitHub 仓库 ↗

官方文档 ↗

字段依据与待核验事项

access:来源确认 · pip install guardrails-ai

project_type:来源确认 · Guardrails is a Python framework that helps build reliable AI applications by performing two key functions

原始 README(折叠技术参考)
<div align="center">

<img src="https://raw.githubusercontent.com/guardrails-ai/guardrails/main/docs/assets/Guardrails-ai-logo-for-dark-bg.svg#gh-dark-mode-only" alt="Guardrails AI Logo" width="600px">
<img src="https://raw.githubusercontent.com/guardrails-ai/guardrails/main/docs/assets/Guardrails-ai-logo-for-white-bg.svg#gh-light-mode-only" alt="Guardrails AI Logo" width="600px">

<hr>

[![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/)
[![X (formerly Twitter) Follow](https://img.shields.io/twitter/follow/guardrails_ai)](https://x.com/guardrails_ai)
[![Discord](https://img.shields.io/discord/1085077079697150023?logo=discord&label=support&link=https%3A%2F%2Fdiscord.gg%2Fgw4cR9QvYE)](https://discord.gg/U9RKkZSBgx)
[![Static Badge](https://img.shields.io/badge/Docs-blue?link=https%3A%2F%2Fwww.guardrailsai.com%2Fdocs)](https://guardrailsai.com/guardrails/docs)
[![Static Badge](https://img.shields.io/badge/Blog-blue?link=https%3A%2F%2Fwww.guardrailsai.com%2Fblog)](https://www.guardrailsai.com/blog)
[![Gurubase](https://img.shields.io/badge/Gurubase-Ask%20Guardrails%20Guru-006BFF)](https://gurubase.io/g/guardrails)

</div>

## News and Updates
- **[July 6, 2026]** Guardrails validators are moving to standard PyPI packages you install directly with `pip`, and Guardrails is discontinuing its hosted remote inferencing. See [How to Migrate](https://github.com/guardrails-ai/guardrails/issues/1560) for what to do. **Planned cutoff: August 25, 2026.**
- **[Feb 12, 2025]** We just launched Guardrails Index -- the first of its kind benchmark comparing the performance and latency of 24 guardrails across 6 most common categories! Check out the index at index.guardrailsai.com

## What is Guardrails?

Guardrails is a Python framework that helps build reliable AI applications by performing two key functions:
1. Guardrails runs Input/Output Guards in your application that detect, quantify and mitigate the presence of specific types of risks. To look at the full suite of risks, check out [Guardrails Hub](https://guardrailsai.com/hub/).
2. Guardrails help you generate structured data from LLMs.


<div align="center">
<img src="https://raw.githubusercontent.com/guardrails-ai/guardrails/main/docs/assets/with_and_without_guardrails.svg" alt="Guardrails in your application" width="1500px">
</div>


### Guardrails Hub

Guardrails Hub is a collection of pre-built measures of specific types of risks (called 'validators'). Multiple validators can be combined together into Input and Output Guards that intercept the inputs and outputs of LLMs. Visit [Guardrails Hub](https://guardrailsai.com/hub/) to see the full list of validators and their documentation.

<div align="center">
<img src="https://raw.githubusercontent.com/guardrails-ai/guardrails/main/docs/assets/guardrails_hub.gif" alt="Guardrails Hub gif" width="600px">
</div>


## Installation

```python
pip install guardrails-ai
```


## Getting Started


### Create Input and Output Guards for LLM Validation

1. Download and configure the Guardrails Hub CLI.

    ```bash
    pip install guardrails-ai
    guardrails configure
    ```
2. Install a guardrail from Guardrails Hub.

    ```bash
    pip install guardrails-ai-regex-match
    ```
3. Create a Guard from the installed guardrail.

    ```python
    from guardrails import Guard, OnFailAction
    from guardrails_ai.regex_match import RegexMatch

    guard = Guard().use(
        RegexMatch, regex="\(?\d{3}\)?-? *\d{3}-? *-?\d{4}", on_fail=OnFailAction.EXCEPTION
    )

    guard.validate("123-456-7890")  # Guardrail passes

    try:
        guard.validate("1234-789-0000")  # Guardrail fails
    except Exception as e:
        print(e)
    ```
    Output:
    ```console
    Validation failed for field with errors: Result must match \(?\d{3}\)?-? *\d{3}-? *-?\d{4}
    ```
4. Run multiple guardrails within a Guard.
    First, install the necessary guardrails from Guardrails Hub.

    ```bash
    pip install guardrails-ai-competitor-check guardrails-ai-toxic-language
    ```

    Then, create a Guard from the installed guardrails.

    ```python
    from guardrails import Guard, OnFailAction
    from guardrails_ai.competitor_check import CompetitorCheck
    from guardrails_ai.toxic_language import ToxicLanguage

    guard = Guard().use(
        CompetitorCheck(["Apple", "Microsoft", "Google"], on_fail=OnFailAction.EXCEPTION),
        ToxicLanguage(threshold=0.5, validation_method="sentence", on_fail=OnFailAction.EXCEPTION)
    )

    guard.validate(
        """An apple a day keeps a doctor away.
        This is good advice for keeping your health."""
    )  # Both the guardrails pass

    try:
        guard.validate(
            """Shut the hell up! Apple just released a new iPhone."""
        )  # Both the guardrails fail
    except Exception as e:
        print(e)
    ```
    Output:
    ```console
    Validation failed for field with errors: Found the following competitors: [['Apple']]. Please avoid naming those competitors next time, The following sentences in your response were found to be toxic:

    - Shut the hell up!
    ```

### Use Guardrails to generate structured data from LLMs


Let's go through an example where we ask an LLM to generate fake pet names. To do this, we'll create a Pydantic [BaseModel](https://docs.pydantic.dev/latest/api/base_model/) that represents the structure of the output we want.

```py
from pydantic import BaseModel, Field

class Pet(BaseModel):
    pet_type: str = Field(description="Species of pet")
    name: str = Field(description="a unique pet name")
```

Now, create a Guard from the `Pet` class. The Guard can be used to call the LLM in a manner so that the output is formatted to the `Pet` class. Under the hood, this is done by either of two methods:
1. Function calling: For LLMs that support function calling, we generate structured data using the function call syntax.
2. Prompt optimization: For LLMs that don't support function calling, we add the schema of the expected output to the prompt so that the LLM can generate structured data.

```py
from guardrails import Guard
import openai

prompt = """
    What kind of pet should I get and what should I name it?

    ${gr.complete_json_suffix_v2}
"""
guard = Guard.for_pydantic(output_class=Pet, prompt=prompt)

raw_output, validated_output, *rest = guard(
    llm_api=openai.completions.create,
    engine="gpt-3.5-turbo-instruct"
)

print(validated_output)
```

This prints:
```
{
    "pet_type": "dog",
    "name": "Buddy
}
```

### Guardrails Server

Guardrails can be set up as a standalone service served by Flask with `guardrails start`, allowing you to interact with it via a REST API. This approach simplifies development and deployment of Guardrails-powered applications.

1. Install: `pip install "guardrails-ai"`
2. Configure: `guardrails configure`
3. Create a config: `guardrails create --validators=hub://guardrails/two_words --guard-name=two-word-guard`
4. Start the dev server: `guardrails start --config=./config.py`
5. Interact with the dev server via the snippets below
```
# with the guardrails client
import guardrails as gr

gr.settings.use_server = True
guard = gr.Guard(name='two-word-guard')
guard.validate('this is more than two words')

# or with the openai sdk
import openai
openai.base_url = "http://localhost:8000/guards/two-word-guard/openai/v1/"
os.environ["OPENAI_API_KEY"] = "youropenaikey"

messages = [
        {
            "role": "user",
            "content": "tell me about an apple with 3 words exactly",
        },
    ]

completion = openai.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
)
```

For production deployments, we recommend using Docker with Gunicorn as the WSGI server for improved performance and scalability.

## FAQ

#### I'm running into issues with Guardrails. Where can I get help?

You can reach out to us on [Discord](https://discord.gg/gw4cR9QvYE) or [Twitter](https://twitter.com/guardrails_ai).

#### Can I use Guardrails with any LLM?

Yes, Guardrails can be used with proprietary and open-source LLMs. Check out this guide on [how to use Guardrails with any LLM](https://guardrailsai.com/guardrails/docs/how-to-guides/using_llms).

#### Can I create my own validators?

Yes, you can create your own validators and contribute them to Guardrails Hub. Check out this guide on [how to create your own validators](https://guardrailsai.com/guardrails/docs/how-to-guides/custom_validators).

#### Does Guardrails support other languages?

Guardrails can be used with Python and JavaScript. Check out the docs on how to use Guardrails from JavaScript. We are working on adding support for other languages. If you would like to contribute to Guardrails, please reach out to us on [Discord](https://discord.gg/gw4cR9QvYE) or [Twitter](https://twitter.com/guardrails_ai).


## Contributing

We welcome contributions to Guardrails!

Get started by checking out Github issues and check out the [Contributing Guide](CONTRIBUTING.md). Feel free to open an issue, or reach out if you would like to add to the project!
历史前置条件说明(补充参考)

Python 环境(README 标注 PyPI Python 版本徽章,具体版本范围待核验);使用模型需自备 LLM 提供方 API Key(示例使用 OPENAI_API_KEY);guardrails configure 是否需要账号或凭据待核验;校验器需从 Guardrails Hub 或 PyPI 单独安装;托管远程推理服务将于公告的 2026-08-25 截止,迁移方式待核验;费用以模型提供方与官方为准,价格待核验;国内网络与国内模型适配情况待核验。

项目来源与清单版权许可

https://github.com/guardrails-ai/guardrails

https://twitter.com/guardrails_ai

整理来源:https://github.com/slavakurilyak/awesome-ai-agents

清单版权与许可:

MIT License

Copyright (c) 2024 Slava Kurilyak

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.