Package: guardrails-ai
🛤️ Guardrails AIGuardrails is an open-source Python package for specifying structure and type, validating and correcting the outputs of large language models (LLMs).Docs🧩 What is Guardrails?Guardrails is a Python package that lets a user add structure, type and quality guarantees to the outputs of large language models (LLMs). Guardrails:does pydantic-style validation of LLM outputs (including semantic validation such as checking for bias in generated text, checking for bugs in generated code, etc.)takes corrective actions (e.g. reasking LLM) when validation fails,enforces structure and type guarantees (e.g. JSON).🚒 Under the hoodGuardrails provides a file format (.rail) for enforcing a specification on an LLM output, and a lightweight wrapper around LLM API calls to implement this spec.rail(ReliableAImarkupLanguage) files for specifying structure and type information, validators and corrective actions over LLM outputs.gd.Guardwraps around LLM API calls to structure, validate and correct the outputs.graph LR
    A[Create `RAIL` spec] --> B["Initialize `guard` from spec"];
    B --> C["Wrap LLM API call with `guard`"];Check out theGetting Startedguide to learn how to use Guardrails.📜RAILspecAt the heart of Guardrails is therailspec.railis intended to be a language-agnostic, human-readable format for specifying structure and type information, validators and corrective actions over LLM outputs.railis a flavor of XML that lets users specify:the expected structure and types of the LLM output (e.g. JSON)the quality criteria for the output to be considered valid (e.g. generated text should be bias-free, generated code should be bug-free)and corrective actions to be taken if the output is invalid (e.g. reask the LLM, filter out the invalid output, etc.)To learn more about theRAILspec and the design decisions behind it, check out thedocs. To learn how to write your ownRAILspec, check outthis link.📦 Installationpipinstallguardrails-ai📍 RoadmapJavascript SDKWider variety of language support (TypeScript, Go, etc)Informative loggingVSCode extension for.railfilesNext version of.railformatValidator playgroundInput ValidationPydantic 2.0Improving reasking logicIntegration with LangChainAdd more LLM providers🚀 Getting StartedLet's go through an example where we ask an LLM to generate fake pet names. To do this, we'll use Pydantic, a popular data validation library for Python.📝 Creating Structured OutputsIn order to create a LLM that generates fake pet names, we can create a classPetthat inherits from the Pydantic classLink BaseModel:frompydanticimportBaseModel,FieldclassPet(BaseModel):pet_type:str=Field(description="Species of pet")name:str=Field(description="a unique pet name")We can now pass in this newPetclass as theoutput_classparameter in our Guard. When we run the code, the LLM's output is formatted to the pydnatic structure. We also add${gr.complete_json_suffix_v2}to the prompt which tells our LLM to only respond with JSON:fromguardrailsimportGuardimportopenaiprompt="""What kind of pet should I get and what should I name it?${gr.complete_json_suffix_v2}"""guard=Guard.from_pydantic(output_class=Pet,prompt=prompt)validated_output,*rest=guard(llm_api=openai.completions.create,engine="gpt-3.5-turbo-instruct")print(f"{validated_output}")This prints:{
    "pet_type": "dog",
    "name": "Buddy
}Structured Outputs with ValidationWe can add validation to our Guard instead of just structuring the ouput in a specific format. In the below code, we add a Validator that checks if the pet name generated is of valid length. If it does not pass the validation, the reask is triggered and the query is reasked to the LLM. Check out theLink Validators API Specfor a list of supported validators.fromguardrails.validatorsimportValidLength,TwoWordsfromrichimportprintclassPet(BaseModel):pet_type:str=Field(description="Species of pet")name:str=Field(description="a unique pet name",validators=[ValidLength(min=1,max=32,on_fail='reask')])guard=Guard.from_pydantic(output_class=Pet,prompt=prompt)raw_llm_output,validated_output,*rest=guard(llm_api=openai.chat.completions.create,model="gpt-3.5-turbo",max_tokens=1024,temperature=0.5)print(guard.history.last.tree)🛠️ ContributingGet started by checking out Github issues and of course using Guardrails to familiarize yourself with the project. Guardrails is still actively under development and any support is gladly welcomed. Feel free to open an issue, or reach out if you would like to add to the project!