Snippet
Deterministic capabilities with a strict request contract
A complete Python module that validates model output as data, then runs approved normal code for calculator, email syntax, and mock support-ticket requests.
AI-generated, human-reviewed: the first draft was generated by an AI agent; I fact-checked, tested, and edited it. AI use policy
What it does#
Defines the boring part that should stay boring: a strict request contract and deterministic Python functions. The model can propose an intent, but this module rejects missing fields, extra fields, invented tool names, Boolean numbers, and unsupported operations before any capability runs.
You need#
- Python 3.10 or later
- No third-party packages
- Optional configuration placeholders:
<ticket-prefix>if you want ticket IDs with a different prefix<allowed-priorities>if your mock priorities differ
Where it goes#
Save it as deterministic_capabilities.py. Other snippets import from it.
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Sarang Datye
"""Deterministic capabilities and a strict request contract."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
import math
from numbers import Real
import re
from typing import Any
ALLOWED_INTENTS = frozenset(
{
"calculator",
"email_validator",
"create_support_ticket",
"general_explanation",
"unsupported",
}
)
SUPPORTED_OPERATIONS = frozenset({"add", "subtract", "multiply", "divide"})
TOP_LEVEL_FIELDS = frozenset({"intent", "confidence", "parameters"})
LOCAL_PART_PATTERN = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+$")
DOMAIN_LABEL_PATTERN = re.compile(r"^[A-Za-z0-9-]+$")
ALLOWED_PRIORITIES = frozenset({"low", "medium", "high", "critical"})
TICKETS: list[dict[str, str]] = []
NEXT_TICKET_NUMBER = 1
class RequestValidationError(ValueError):
"""Raised when a structured request does not match the expected contract."""
@dataclass(frozen=True)
class NormalizedRequest:
intent: str
confidence: float
parameters: dict[str, Any]
def require_string(parameters: dict[str, Any], name: str, intent: str) -> str:
if name not in parameters:
raise RequestValidationError(
f"Missing required parameter '{name}' for intent '{intent}'."
)
value = parameters[name]
if not isinstance(value, str) or not value.strip():
raise RequestValidationError(
f"Parameter '{name}' for intent '{intent}' must be a nonempty string."
)
return value.strip()
def is_finite_number(value: object) -> bool:
"""Accept real numbers except Booleans, NaN, and infinity."""
if isinstance(value, bool) or not isinstance(value, Real):
return False
return isinstance(value, int) or math.isfinite(value)
def require_number(parameters: dict[str, Any], name: str, intent: str) -> int | float:
if name not in parameters:
raise RequestValidationError(
f"Missing required parameter '{name}' for intent '{intent}'."
)
value = parameters[name]
if not is_finite_number(value):
raise RequestValidationError(
f"Parameter '{name}' for intent '{intent}' must be a finite number, "
"not Boolean, NaN, or infinity."
)
return value
def require_exact_fields(parameters: dict[str, Any], required: set[str], intent: str) -> None:
actual = set(parameters)
if actual == required:
return
missing = sorted(required - actual)
extra = sorted(actual - required)
details = []
if missing:
details.append(f"missing {missing}")
if extra:
details.append(f"unexpected {extra}")
raise RequestValidationError(
f"Parameters for intent '{intent}' have invalid fields: {', '.join(details)}."
)
def validate_request(request: object) -> NormalizedRequest:
"""Validate and normalize a model-proposed request without inventing values."""
if not isinstance(request, dict):
raise RequestValidationError("Structured request must be a dictionary.")
for field in TOP_LEVEL_FIELDS:
if field not in request:
raise RequestValidationError(f"Structured request is missing '{field}'.")
extra_fields = sorted(set(request) - TOP_LEVEL_FIELDS)
if extra_fields:
raise RequestValidationError(
f"Structured request has unexpected top-level fields: {extra_fields}."
)
intent = request["intent"]
if not isinstance(intent, str) or intent not in ALLOWED_INTENTS:
raise RequestValidationError(f"Unknown intent: {intent!r}.")
confidence = request["confidence"]
if isinstance(confidence, bool) or not isinstance(confidence, Real):
raise RequestValidationError("Confidence must be a number, not Boolean.")
if not 0 <= confidence <= 1:
raise RequestValidationError("Confidence must be between 0 and 1.")
parameters = request["parameters"]
if not isinstance(parameters, dict):
raise RequestValidationError("Parameters must be a dictionary.")
if intent == "calculator":
require_exact_fields(parameters, {"operation", "left", "right"}, intent)
operation = require_string(parameters, "operation", intent)
if operation not in SUPPORTED_OPERATIONS:
raise RequestValidationError(
"Calculator operation must be add, subtract, multiply, or divide."
)
normalized_parameters = {
"operation": operation,
"left": require_number(parameters, "left", intent),
"right": require_number(parameters, "right", intent),
}
elif intent == "email_validator":
require_exact_fields(parameters, {"email"}, intent)
normalized_parameters = {"email": require_string(parameters, "email", intent)}
elif intent == "create_support_ticket":
require_exact_fields(parameters, {"application", "description", "priority"}, intent)
normalized_parameters = {
"application": require_string(parameters, "application", intent),
"description": require_string(parameters, "description", intent),
"priority": require_string(parameters, "priority", intent),
}
elif intent == "general_explanation":
require_exact_fields(parameters, {"prompt"}, intent)
normalized_parameters = {"prompt": require_string(parameters, "prompt", intent)}
else:
require_exact_fields(parameters, set(), intent)
normalized_parameters = {}
return NormalizedRequest(intent, float(confidence), normalized_parameters)
def calculate(operation: str, left: object, right: object) -> dict[str, Any]:
"""Perform one supported arithmetic operation without dynamic evaluation."""
if not isinstance(operation, str) or operation not in SUPPORTED_OPERATIONS:
raise ValueError("Unsupported operation.")
if not is_finite_number(left):
raise TypeError("left must be a finite number.")
if not is_finite_number(right):
raise TypeError("right must be a finite number.")
if operation == "add":
result = left + right
elif operation == "subtract":
result = left - right
elif operation == "multiply":
result = left * right
else:
if right == 0:
raise ZeroDivisionError("Cannot divide by zero.")
result = left / right
if not is_finite_number(result):
raise OverflowError("Result is not a finite number.")
return {"tool": "calculator", "operation": operation, "result": result}
def validate_email(email: str) -> dict[str, Any]:
"""Apply practical syntax checks without claiming the mailbox exists."""
if not isinstance(email, str):
raise TypeError("email must be a string.")
if any(character.isspace() for character in email) or email.count("@") != 1:
return {"tool": "email_validator", "is_valid": False, "mailbox_verified": False}
local, domain = email.split("@")
domain_labels = domain.split(".")
is_valid = (
bool(local)
and bool(domain)
and "." in domain
and ".." not in email
and LOCAL_PART_PATTERN.fullmatch(local) is not None
and all(DOMAIN_LABEL_PATTERN.fullmatch(label) for label in domain_labels)
and all(not label.startswith("-") and not label.endswith("-") for label in domain_labels)
)
return {"tool": "email_validator", "is_valid": is_valid, "mailbox_verified": False}
def create_support_ticket(application: str, description: str, priority: str) -> dict[str, Any]:
"""Create and retain a mock support ticket without contacting another system."""
global NEXT_TICKET_NUMBER
clean_application = application.strip()
clean_description = description.strip()
clean_priority = priority.strip().lower()
if not clean_application or not clean_description:
raise ValueError("application and description are required.")
if clean_priority not in ALLOWED_PRIORITIES:
raise ValueError("priority must be one of: low, medium, high, critical.")
ticket = {
"id": f"TICKET-{NEXT_TICKET_NUMBER:04d}",
"application": clean_application,
"description": clean_description,
"priority": clean_priority,
"created_at": datetime.now(timezone.utc).isoformat(),
}
NEXT_TICKET_NUMBER += 1
TICKETS.append(ticket)
return {"tool": "create_support_ticket", "ticket": dict(ticket)}
if __name__ == "__main__":
request = validate_request(
{
"intent": "calculator",
"confidence": 0.95,
"parameters": {"operation": "multiply", "left": 125, "right": 48},
}
)
answer = calculate(**request.parameters)
print(answer["result"])
Check that it works#
Run:
python3 -m py_compile deterministic_capabilities.py
python3 deterministic_capabilities.py
The script prints 6000. Try adding a tool field under parameters; validation fails
before any capability runs.