Skip to main content

Typed declarative contracts for AI agent systems.

Project description

Contract4Agents

Contract4Agents banner

Contract4Agents is a free, open-source, typed contract language for building agent systems that are reviewable before they run and accountable afterward. The contract is the source of truth for agents, shared capabilities, authorization, composition, controls, quality criteria, and expected evidence. Target bindings supply only the framework-specific implementation details.

The product loop is:

Declare -> Compile -> Plan -> Materialize -> Run -> Trace -> Assure

That separation is the point. You can change a model, provider profile, or tool implementation without rewriting the portable agent design. Before execution, the plan shows exactly how the selected target will implement each requested semantic and blocks required guarantees it cannot honestly enforce. After execution, contract-bound traces and assurance results distinguish passed, violated, and unverified instead of treating missing evidence as success.

Quickstart

Install the core package and the OpenAI target:

pdm add "contract4agents[openai]"

To explore this repository's complete Incident Command example:

pdm install
pdm run python examples/incident-command/data/seed.py
pdm run contract4agents check examples/incident-command
pdm run contract4agents compile examples/incident-command --out .contract/build/incident-command
pdm run contract4agents plan examples/incident-command --target openai --profile test

The first two commands need no provider credentials and do not import or call application implementations. plan loads target bindings only far enough to validate coverage and safely inspect callable signatures; it does not construct agents or execute business code.

Rich Editor Support

The repo-owned VS Code extension combines the complete TextMate grammar with the same Python parser and semantic model used by the CLI. In .contract and .eval files it provides hover help, contextual completion, diagnostics and quick fixes, definition and reference navigation, rename, symbols, semantic highlighting, and optional inlay hints. Type and callable hovers show their declared shape, while contract vocabulary such as grant settings explains the meaning of each accepted value.

A Small Contract-First Team

Define portable types and a shared capability:

type SupportRequest:
    ticket_id: string
    question: string

type SupportReply:
    answer: string
    needs_follow_up: boolean

tool knowledge.search(query: string) -> SupportReply:
    description = "Search the approved support knowledge base."
    side_effect = false

Grant the capability to an agent. Availability, authorization, and execution are independent and explicit:

agent SupportResponder(request: SupportRequest) -> SupportReply:
    use knowledge.search:
        availability = enabled
        authorization = preapproved
        execution = host

    goal = "Answer the support request accurately."
    description = "Handles first-line support questions."
    guidance = [
        "Use only evidence returned by approved capabilities.",
        "Say when the available evidence is insufficient.",
    ]

Bind the portable name to one target implementation in contract4agents.targets.toml:

schema_version = "1"

[targets.openai]
adapter = "openai"

[targets.openai.tools."knowledge.search"]
python = "your_app.tools:search_knowledge"

[targets.openai.profiles.test]
default_model = "test-model"

[targets.openai.profiles.production]
default_model = "gpt-5.2"

Every target declares at least one named profile. Each profile is complete: a default_model or explicit per-agent model selects a model for every canonical agent, and stale agent overrides are rejected. The binding does not repeat prompts, permissions, schemas, agent factories, or controls. Those remain contract-owned.

Inspect Before Construction

Compile provider-neutral artifacts and review the resolved target plan:

contract4agents check agent_contracts
contract4agents compile agent_contracts --out .contract/build
contract4agents plan agent_contracts --target openai --profile production \
  --out .contract/build/production-plan.json

check remains provider-neutral when no target-binding file exists. When the file is present, it also validates every declared target and named profile. Compilation produces deterministic canonical IR, its digest, JSON Schemas, audience-safe instructions, and reviewer documentation. compile --check makes stale review artifacts a CI failure. Run generate separately with an explicit python or typescript target only when application code imports generated source; use the same target selection with generate --check.

The plan resolves models, bindings, grants, approvals, composition, controls, isolation mechanisms, host obligations, and expected event types. Each mapping is reported as exact, host_enforced, emulated, degraded, or unsupported. Required degraded or unsupported guarantees fail closed.

Materialize Normal Framework Objects

Contract4Agents constructs the complete native agent graph at runtime:

from agents import Runner
from contract4agents import materialize

result = materialize(
    "agent_contracts",
    target="openai",
    profile="production",
)

support_agent = result.agents["SupportResponder"]
reviewed_plan = result.plan
run_result = await Runner.run(support_agent, input="Where is my order?")

result.agents contains ordinary OpenAI Agents SDK Agent objects. Generated output types, host tools, approval hooks, delegations, and handoffs are wired from the contract graph and target bindings; host code does not maintain a parallel agent registry.

The host still owns credentials, approval decisions and UI, persistence, external services, and deterministic application workflow. Contract4Agents is not a general workflow language and does not hide provider differences.

Evidence, Evals, and Assurance

The normalized trace schema binds every event to a contract digest, plan digest, stable semantic IDs, provider-native correlation, provenance, and audience-safe redaction metadata. Identity-bound closure evidence records which attempts, provider responses, and instrumentation channels were completely observed at an exact ordered trace frontier. OpenAI sessions expose consistent non-closing snapshots, validated cross-session retry continuation, and disposable router bindings. The same control assessor is used for controlled evals and imported production traces.

Run specs have a separate post-run assessor for host-supplied stage outputs, derived values, cardinality, assertions, and explicit workflow-completeness evidence. Controls and run specs remain distinct assurance results. Retried invocations can carry portable attempt identity and an explicit selected terminal attempt without moving retry or recovery decisions out of host code.

.eval files name scenarios and expectations. The target/profile eval workflow derives its agent, capability, grant, control, and event-type inventory from the contract and plan; users do not restate the runtime in a fixture manifest. Repeated campaigns report pass, violation, and unverified rates with uncertainty, latency and cost summaries, thresholds, and optional baseline comparisons.

Assurance bundles join the canonical contract, materialization plan, normalized traces, trace closure, control results, eval summaries, and semantic diffs into one portable review package. Missing or incomplete evidence remains explicitly unverified. This is useful evidence for compliance and release review; it is not a legal certification by itself.

Public Examples

  • Incident Command is the recommended first read. It demonstrates shared capabilities, different authorization grants, explicit context origins, generated delegations, controls, target bindings, and deterministic eval data.
  • Multi-Lens Research demonstrates a larger delegation graph, typed workflow boundaries, and an explicit isolation profile.
  • Market Research Brief demonstrates host tools alongside a provider-native web-search binding.

See the examples guide for the common project structure.

Documentation

The semantic model is the detailed architecture specification. Coding agents should begin with AGENTS.md.

Development

pdm install
pdm run docs-check
pdm run validate
pdm build

Normal local checks do not require an API key. Opt-in OpenAI live checks are documented in Validation and Quality Gates.

License

MIT. See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

contract4agents-0.12.2.tar.gz (184.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

contract4agents-0.12.2-py3-none-any.whl (233.2 kB view details)

Uploaded Python 3

File details

Details for the file contract4agents-0.12.2.tar.gz.

File metadata

  • Download URL: contract4agents-0.12.2.tar.gz
  • Upload date:
  • Size: 184.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for contract4agents-0.12.2.tar.gz
Algorithm Hash digest
SHA256 5e5d31b29b0b0de13dbcea581810e64f2f8002a4db442217772ccc04c3a7d305
MD5 833f286cc909499bc64f9df23f96dfb1
BLAKE2b-256 29359527dec3a87344a7e937b5c3e2b146c28ea8fecb4cf3239270ed4709a3fe

See more details on using hashes here.

Provenance

The following attestation bundles were made for contract4agents-0.12.2.tar.gz:

Publisher: python-publish.yml on btfranklin/contract4agents

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file contract4agents-0.12.2-py3-none-any.whl.

File metadata

File hashes

Hashes for contract4agents-0.12.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e63ce4c0794eff1a72ddf227c93b2248ca4cc1448ec32805a97d01d40c97fe78
MD5 43c1ad22105b9836bd9cfbc7168885a8
BLAKE2b-256 4cb7e18c362162e37f48064a8d3740ee5c743d53508057a43f29628bf247ac98

See more details on using hashes here.

Provenance

The following attestation bundles were made for contract4agents-0.12.2-py3-none-any.whl:

Publisher: python-publish.yml on btfranklin/contract4agents

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page