Secrets#

Local redact_secrets first, then enkrypt.secrets(). A token with a known shape is rewritten locally and the run goes on; a secret with no known shape is caught by Enkrypt, and the run raises. The script ends with that exception, so its traceback is part of the output.

"""Stop the run when a secret gets past the local regexes.

The harness's `redact_secrets` runs first, locally, and rewrites credentials
with a known shape. `enkrypt.secrets()` then asks Enkrypt about anything it missed and
raises, so your code, not the agent, decides what happens next.

The model here is a stand-in, so only an Enkrypt key is needed: set
ENKRYPTAI_API_KEY in the environment or in .env.

    pixi run -e examples python examples/secrets_raise.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 InputGuardrail
from pydantic_ai_harness.guardrails.detectors import redact_secrets

from pydantic_ai_enkrypt import Enkrypt

load_dotenv()

enkrypt = Enkrypt()


def model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
    return ModelResponse(parts=[TextPart("(the model answered the prompt)")])


agent = Agent(
    FunctionModel(model),
    capabilities=[InputGuardrail(guard=[redact_secrets, enkrypt.secrets()])],
)

# A GitHub token has a known shape: redact_secrets rewrites it locally.
result = agent.run_sync(
    "Why does my token ghp_abcdefghijklmnopqrstuvwxyz0123456789 fail?"
)
print(f"model saw: {result.all_messages()[0].parts[-1].content}")
print(f"output: {result.output}\n")

# This one has no known shape: only Enkrypt catches it, and the run raises
# EnkryptInputBlocked (a subclass of the harness's InputBlocked).
agent.run_sync("My config has VERY_SECRET_TOO = 'f6CGV4aMM9zedoh3OUNbSakBymo7yplB'")

Run it with an Enkrypt key in the environment or in .env:

pixi run -e examples python examples/secrets_raise.py

Output from a run:

model saw: Why does my token [redacted:github_token] fail?
output: (the model answered the prompt)

pydantic_ai_enkrypt.core.EnkryptInputBlocked: Enkrypt AI blocked the prompt (secrets).

Guards: secrets.