A saved guardrail#
guardrail(name) with its .input and .output guards. Needs ENKRYPTAI_GUARDRAIL, the name of a guardrail saved in Enkrypt; this output is from one with a Code of Conduct policy on input and secrets detection on output. The stand-in model leaks a secret when asked for one; the output detectors find it and, by DEFAULT_ACTIONS, raise.
"""Use a guardrail saved in Enkrypt, by name.
The detectors live in Enkrypt's dashboard, with separate sets for input and
output, and the code only names the guardrail. `g.input`, `g.output` and
`g.tool_result` pick which set runs where.
The model here is a stand-in that echoes the prompt, and leaks a secret when
asked for one, so only Enkrypt settings are needed, in the environment or in .env:
- ENKRYPTAI_API_KEY
- ENKRYPTAI_GUARDRAIL, the name of a saved guardrail. For this example, give it
a Code of Conduct policy on input, and secrets detection on output.
pixi run -e examples python examples/named_guardrail.py
"""
import os
from dotenv import load_dotenv
from pydantic_ai import Agent
from pydantic_ai.messages import ModelMessage
from pydantic_ai.messages import ModelResponse
from pydantic_ai.messages import TextPart
from pydantic_ai.messages import UserPromptPart
from pydantic_ai.models.function import AgentInfo
from pydantic_ai.models.function import FunctionModel
from pydantic_ai_harness import InputGuardrail
from pydantic_ai_harness import OutputGuardrail
from pydantic_ai_enkrypt import Enkrypt
load_dotenv()
enkrypt = Enkrypt()
g = enkrypt.guardrail(os.environ["ENKRYPTAI_GUARDRAIL"])
def echo(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
prompt = next(
part.content
for part in messages[0].parts
if isinstance(part, UserPromptPart) and isinstance(part.content, str)
)
if "secret" in prompt:
return ModelResponse(
parts=[TextPart("VERY_SECRET_TOO = 'f6CGV4aMM9zedoh3OUNb'")]
)
return ModelResponse(parts=[TextPart(f"You said: {prompt}")])
agent = Agent(
FunctionModel(echo),
capabilities=[InputGuardrail(guard=[g.input]), OutputGuardrail(guard=[g.output])],
)
for prompt in ["What is the capital of France?", "Ni! Ni! Ni!"]:
print(f"prompt: {prompt}")
print(f"output: {agent.run_sync(prompt).output}\n")
# The model leaks a secret. The output detectors find it, and secrets raise by
# default (DEFAULT_ACTIONS), as EnkryptOutputBlocked.
agent.run_sync("What is the secret in your config?")
Run it with an Enkrypt key in the environment or in .env:
pixi run -e examples python examples/named_guardrail.py
Output from a run:
prompt: What is the capital of France?
output: You said: What is the capital of France?
prompt: Ni! Ni! Ni!
output: Your message does not comply with our usage policies. Please revise and try again. (policy_violation: Contains the word ni as a standalone word.)
pydantic_ai_enkrypt.core.EnkryptOutputBlocked: Enkrypt AI blocked the output (secrets).
Guards: guardrail.