Round trip#

The user’s own data, hidden from the model and given back to the tool and the user. p redacts the prompt and the tool result; enkrypt.restore restores the tool’s arguments and the answer.

"""Hide personal data from the model, and give it back to the tool and the user.

Use this for the user's own data that the model does not need to see: the
prompt sent to the provider, the run's message history and your traces only
ever hold placeholders, while the tools and the user work with real values.

`p` replaces each name Enkrypt finds with a placeholder like <<PERSON:1>>, the
same one every time that name comes up in the conversation. `enkrypt.restore`
swaps the real names back in, wherever it is placed.

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_roundtrip.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.messages import ToolCallPart
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_harness import ToolGuardrail

from pydantic_ai_enkrypt import Enkrypt

load_dotenv()

enkrypt = Enkrypt()
p = enkrypt.pii(entities=["pii", "person"])


def model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
    latest = messages[-1].parts[-1]
    print(f"model saw:     {latest.content}")
    if isinstance(latest, UserPromptPart):
        print('model calls:   lookup_account(name="<<PERSON:1>>")')
        return ModelResponse(
            parts=[ToolCallPart("lookup_account", {"name": "<<PERSON:1>>"})]
        )
    answer = "<<PERSON:1>>, your account was locked by <<PERSON:2>>."
    print(f"model answers: {answer}")
    return ModelResponse(parts=[TextPart(answer)])


agent = Agent(
    FunctionModel(model),
    capabilities=[
        InputGuardrail(guard=[p]),  # redact the prompt
        ToolGuardrail(
            guard=enkrypt.restore, result_guard=p
        ),  # real names in, redacted out
        OutputGuardrail(guard=[enkrypt.restore]),  # the user sees real names
    ],
)


@agent.tool_plain
def lookup_account(name: str) -> str:
    print(f"tool got:      {name}")
    result = f"Account of {name}: locked by the admin, Jane Doe."
    print(f"tool returns:  {result}")
    return result


prompt = "Hi, I'm John Smith. Why is my account locked?"
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_roundtrip.py

Output from a run:

user types:    Hi, I'm John Smith. Why is my account locked?
model saw:     Hi, I'm <<PERSON:1>>. Why is my account locked?
model calls:   lookup_account(name="<<PERSON:1>>")
tool got:      John Smith
tool returns:  Account of John Smith: locked by the admin, Jane Doe.
model saw:     Account of <<PERSON:1>>: locked by the admin, <<PERSON:2>>.
model answers: <<PERSON:1>>, your account was locked by <<PERSON:2>>.
user sees:     John Smith, your account was locked by Jane Doe.

Personal data: Redaction and restoring, purposes.