Code of conduct#

One code_of_conduct guard on both the prompt and the answer, with a stand-in model that always gives investment advice. A prompt asking for advice is refused before the model runs. A harmless prompt gets an answer that breaks the rule; block on an answer raises OutputBlocked, which ends the script.

"""One rule, checked on the way in and on the way out.

`code_of_conduct` takes your rules inline, or the name of a Code of Conduct
policy saved in Enkrypt: `enkrypt.code_of_conduct(policy="my-policy")`.

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

    pixi run -e examples python examples/code_of_conduct.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 import OutputGuardrail

from pydantic_ai_enkrypt import Enkrypt

load_dotenv()

enkrypt = Enkrypt()

no_advice = enkrypt.code_of_conduct("Never give personalized investment advice.")


def model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
    return ModelResponse(parts=[TextPart("Put all of your savings into NVDA today.")])


agent = Agent(
    FunctionModel(model),
    capabilities=[
        InputGuardrail(guard=[no_advice]),
        OutputGuardrail(guard=[no_advice]),
    ],
)

# The prompt asks for advice: the input guard refuses before the model runs.
result = agent.run_sync("I'm 30 with $50k saved. Exactly which stock should I buy?")
print(f"output: {result.output}\n")

# The prompt is fine, the answer is not. The harness turns a block on output
# into an OutputBlocked exception.
agent.run_sync("What is an index fund?")

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

pixi run -e examples python examples/code_of_conduct.py

Output from a run:

output: Your message does not comply with our usage policies. Please revise and try again. (policy_violation: Directly requests personalized investment advice.)

pydantic_ai_harness.guardrails._exceptions.OutputBlocked: Your message does not comply with our usage policies. Please revise and try again. (policy_violation: Directly requests personalized investment advice.)

Guards: code_of_conduct.