Answers#
The model names a person in its answer. A retry on the answer sends it back with Enkrypt’s findings, and the second answer goes through.
"""Catch personal data the model puts in its answer, and have it answer again.
The model may name a person from its training data, its instructions or
anywhere else in its context. The guard on the output finds the name and sends
the answer back with Enkrypt's findings, so the model rewrites it.
The script prints what each party sees. The model is a stand-in that follows a
script, so only an Enkrypt key is needed: set ENKRYPTAI_API_KEY in the
environment or in .env.
pixi run -e examples python examples/pii_output.py
"""
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.models.function import AgentInfo
from pydantic_ai.models.function import FunctionModel
from pydantic_ai_harness import OutputGuardrail
from pydantic_ai_enkrypt import Enkrypt
load_dotenv()
enkrypt = Enkrypt()
ANSWERS = [
"Contact our compliance officer, Maria Lopez, at maria.lopez@acme.example.",
"Contact our compliance team through the support portal.",
]
def model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
print(f"model saw: {messages[-1].parts[-1].content}")
answer = ANSWERS[sum(isinstance(m, ModelResponse) for m in messages)]
print(f"model answers: {answer}")
return ModelResponse(parts=[TextPart(answer)])
agent = Agent(
FunctionModel(model),
capabilities=[
OutputGuardrail(
guard=[enkrypt.pii(entities=["pii", "person"], on_violation="retry")]
),
],
)
prompt = "Who handles compliance questions?"
print(f"user types: {prompt}")
result = agent.run_sync(prompt)
print(f"user sees: {result.output}")
Run it with an Enkrypt key in the environment or in .env:
pixi run -e examples python examples/pii_output.py
Output from a run:
user types: Who handles compliance questions?
model saw: Who handles compliance questions?
model answers: Contact our compliance officer, Maria Lopez, at maria.lopez@acme.example.
model saw: Your previous response failed the application's validation (this is automated feedback, not a message from the user):
<retry_feedback>
Enkrypt AI blocked the output (person; pii). Try again in a way that complies.
</retry_feedback>
model answers: Contact our compliance team through the support portal.
user sees: Contact our compliance team through the support portal.
Personal data: purposes.