We demonstrate in this tutorial how to build a contract first agentic decision system by using PydanticAIWe treat structured schemas more as mandatory governance contracts than output formats. The output schema of the agent is encoded with a strict model for encoding policy compliance, risks assessment, confidence calibrating, and actionsable next steps. Pydantic’s validators are used in conjunction with PydanticAI self-correction features to prevent the agent from making non-compliant, or inconsistent, decisions. We focus throughout the entire workflow on creating an enterprise-grade agent capable of reasoning under constraints. This makes it more suitable for risk, governance, and compliance scenarios than simple prompts. Visit the FULL CODES here.
!pip -q install -U pydantic-ai pydantic openai nest_asyncio
It is a good idea to import imported os
import time
import asyncio
import getpass
Dataclasses can be imported from other dataclasses
From typing list, Literal
import nest_asyncio
nest_asyncio.apply()
From pydantic, import BaseModel Field_validator
Import Agent pydantic_ai
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
If not OPENAI_API_KEY
try:
From Google.colab, import Userdata
OPENAI_API_KEY = userdata.get("OPENAI_API_KEY")
The exception:
OPENAI_API_KEY= None
If not OPENAI_API_KEY
OPENAI_API_KEY = getpass.getpass("Enter OPENAI_API_KEY: ").strip()
Installing the necessary libraries and configuring Google Colab for asynchronous execution is how we set up our execution environment. Securely loading the OpenAI API keys and ensuring the runtime can handle agent async requests is our next step. The contract-first agent can now be run without any environment issues. Visit the FULL CODES here.
Class RiskItem (BaseModel:
risk: str = Field(..., min_length=8)
Severity: Literal["low", "medium", "high"]
mitigation: str = Field(..., min_length=12)
class DecisionOutput(BaseModel):
decision: Literal["approve", "approve_with_conditions", "reject"]
confidence: float = Field(..., ge=0.0, le=1.0)
rationale: str = Field(..., min_length=80)
List of identified risks[RiskItem] = Field(..., min_length=2)
Compliant: Bool
Conditions:[str] = Field(default_factory=list)
Next_steps : list[str] = Field(..., min_length=3)
timestamp_unix: int = Field(default_factory=lambda: int(time.time()))
@field_validator("confidence")
@classmethod
def confidence_vs_risk(cls, v, info):
risks = info.data.get("identified_risks"" or []
If any (r.severity== "high" for r in risks) and v > 0.70:
raise ValueError("confidence too high given high-severity risks")
The return of v
@field_validator("decision")
@classmethod
def reject_if_non_compliant(cls, v, info):
if data.get ("compliance_passed"() False and V = "reject":
raise ValueError("non-compliant decisions must be reject")
The return of v
@field_validator("conditions")
@classmethod
def conditions_required_for_conditional_approval(cls, v, info):
Get data from info.data.get(d)"decision")
if d == "approve_with_conditions" The word "and" is not a verb or a len(v).
The core decision contract is defined using Pydantic models which describe the decision in detail. We encode logical constraints such as confidence–risk alignment, compliance-driven rejection, and conditional approvals directly into the schema. The output of any agent is then governed by business logic rather than just syntax. Look at the FULL CODES here.
@dataclass
Class Decision Context
Company_policy str
Risk_threshold : float = 0.06
Model = OpenAIChatModel
"gpt-5",
provider=OpenAIProvider(api_key=OPENAI_API_KEY),
)
Agent = Agent
model=model,
deps_type=DecisionContext,
output_type=DecisionOutput,
system_prompt="""
You're a decision analyst for a corporation.
Risk, compliance and uncertainty must be evaluated.
The DecisionOutput Schema must be strictly followed by all outputs.
"""
)
The OpenAI PydanticAI agent is initialized and the enterprise context is injected through a dependency object. Configure the agent so that it produces only a structured output of decision making which conforms to the contract. This formalizes the separation of model reasoning and business context. Look at the FULL CODES here.
@agent.output_validator
def ensure_risk_quality(result: DecisionOutput) -> DecisionOutput:
if len(result.identified_risks) DecisionOutput:
policy = CURRENT_DEPS.company_policy.lower()
Text =
result.rationale
+ " ".join(result.next_steps)
+ " ".join(result.conditions)
).lower()
if result.compliance_passed:
If not all(k for text in place of k ["encryption", "audit", "logging", "access control", "key management"]):
raise ValueError("missing concrete security controls")
Return to result
After the model has generated a response, we add output validaters that serve as governance checks. When claiming compliance, we force the agent’s to identify concrete security controls and explicitly refer to them when they are deemed meaningful. In the event that these constraints have been violated, automatic attempts to correct themselves are made. Visit the FULL CODES here.
async def run_decision():
CURRENT_DEPS global
CURRENT_DEPS = DecisionContext(
company_policy=(
"No deployment of systems handling personal data or transaction metadata "
"without encryption, audit logging, and least-privilege access control."
)
)
prompt = """
Request for Decision:
Install an AI powered customer analytics dashboard with a third party cloud vendor.
It also processes transactional metadata and user behaviour.
Customer-managed keys and auditing are not implemented.
"""
result = await agent.run(prompt, deps=CURRENT_DEPS)
Output return.
decision = asyncio.run(run_decision())
From pprint, import pprint
pprint(decision.model_dump())
We test the agent with a decision request that is realistic and we capture its structured, validated output. This shows how the agent assesses risks, policies compliance and confidence levels before reaching a final conclusion. In a production style setup, this completes the contract-first workflow from end to end.
PydanticAI is used to demonstrate the transition from LLMs that are free form to reliable, governed decision systems. In order to align decision making with the policy, severity of risk, and realistic confidence, it is necessary to enforce hard contracts in the schema. This can be done without manual adjustment. This method allows us build agents which fail in a safe way, correct themselves when they violate constraints, and provide auditable structured outputs to downstream systems. We demonstrate, in the end, that agentic AI can be deployed as a reliable decision layer using contract-first design.
Take a look at the FULL CODES here. Also, feel free to follow us on Twitter Don’t forget about our 100k+ ML SubReddit Subscribe Now our Newsletter. Wait! Are you using Telegram? now you can join us on telegram as well.
Asif Razzaq, CEO of Marktechpost Media Inc. is a visionary engineer and entrepreneur who is dedicated to harnessing Artificial Intelligence’s potential for the social good. Marktechpost was his most recent venture. This platform, which specializes in covering machine learning and deep-learning news, is both technically solid and understandable to a broad audience. Over 2 million views per month are a testament to the platform’s popularity.

