Typed declarative contracts for AI agent systems.
pip install contract4agents==0.22.2 Copy PIP instructions
Contract4Agents is a free, open-source toolkit for defining structured agents in external specifications and turning those specifications into usable agent components. It includes a typed contract language, a compiler, code generators, and adapters for OpenAI Agents SDK, Strands Agents, Google ADK, and Amazon Bedrock AgentCore Harness.
Define each agent in its own .agent.contract file. Keep its inputs, output, grants, context, goal, and guidance in that file. Put shared types and capabilities in .types.contract and .capabilities.contract files. Contract4Agents compiles all source files in the project together and derives schemas, documentation, and normal framework objects. Your application supplies the tool implementations and runs the agents.
This gives you one place to read and change the agent design. You can review its guardrails and expectations without finding them across prompts, SDK configuration, and application code. Target bindings select implementations and models without repeating the contract. Validation and evaluation tools help you check that the implementation matches the design.
This example defines one support agent, connects a Python tool, and runs the agent through the OpenAI Agents SDK.
In a Python 3.11+ project managed by PDM, install the OpenAI adapter:
pdm add "contract4agents[openai]" Create these files, including an empty your_app/__init__.py:
your_app/ __init__.py tools.py run_agent.py agent_contracts/ support.agent.contract support.types.contract support.capabilities.contract contract4agents.targets.toml 1. Define the Agent and Its Tool Put the shared types in your_app/agent_contracts/support.types.contract:
type KnowledgeResult: answer: string source_ids: list[string] type SupportReply: answer: string source_ids: list[string] needs_follow_up: boolean Put the tool interface in your_app/agent_contracts/support.capabilities.contract:
tool knowledge.search(query: string) -> KnowledgeResult: description = "Search the approved support knowledge base." side_effect = false Put the agent definition in your_app/agent_contracts/support.agent.contract:
agent SupportResponder(question: string) -> SupportReply: use knowledge.search: availability = enabled authorization = preapproved execution = host goal = "Answer the support question from approved evidence." description = "Handles first-line support questions." guidance = [ "Use the knowledge tool before answering.", "Include the source IDs behind the answer.", "Set needs_follow_up when the evidence is insufficient.", ] The tool declaration defines the interface. The use block gives this agent access to it. The agent's return type defines the structure of its answer. Names are global across the project. The agent can reference the shared tool and types directly. File boundaries organize the source; they do not create scope boundaries. Each named file suffix limits which declarations that file can contain. See File Organization for the complete rules.
def search_knowledge(query: str) -> dict[str, object]: return { "answer": "Orders normally leave the warehouse within two business days.", "source_ids": ["shipping-policy-2026"], } This example returns fixed data. In your application, replace the function body with a lookup in your knowledge base.
Connect that function and select a model in your_app/agent_contracts/contract4agents.targets.toml:
schema_version = "1" [targets.openai] adapter = "openai" [targets.openai.tools."knowledge.search"] python = "your_app.tools:search_knowledge" [targets.openai.profiles.development] default_model = "gpt-6-luna" The target binding contains implementation choices. It does not repeat the agent's instructions, tool access, or output schema. Choose a model available to your provider account.
pdm run contract4agents check your_app/agent_contracts pdm run contract4agents compile your_app/agent_contracts --out .contract/build pdm run contract4agents plan your_app/agent_contracts --target openai --profile development check validates the source and target bindings. compile writes schemas, instructions, and documentation. plan shows how the selected target will represent the agent and reports missing bindings or unsupported requirements.
These commands do not call a model. Binding checks import Python modules to inspect callable signatures, so module-level code runs during those imports.
import asyncio from agents import Runner from contract4agents import materialize async def main() -> None: system = materialize( "your_app/agent_contracts", target="openai", profile="development", ) agent = system.agents["SupportResponder"] run_input = system.serialize_input_for_agent( agent, {"question": "When will my order ship?"}, ) result = await Runner.run(agent, input=run_input) print(result.final_output) if __name__ == "__main__": asyncio.run(main()) Set OPENAI_API_KEY in your environment, then run:
pdm run python -m your_app.run_agent This step makes a provider request. materialize() constructs an ordinary SDK agent with its tool and generated output type. The SDK runs it and returns a structured SupportReply. You write the tool and invocation code; the contract supplies the agent configuration.
Your application continues to own credentials, business rules, approval decisions, sessions, retries, persistence, and deployment.
File generation and runtime construction serve different needs:
materialize() compiles the contract internally; it does not require a prior compile command. It checks the objects it constructs against the target plan. When generated files are committed, compile --check and generate --check can detect stale files in CI.
See Compiler Outputs for file layouts and generation commands.
Install the corresponding extra: contract4agents[openai], contract4agents[strands], contract4agents[google-adk], or contract4agents[agentcore-harness].
The Harness Research example runs with synthetic transport offline. Its live route requires explicit deployment and verification. The application owns approvals, tool execution, and continuation.
Targets have different capabilities. Planning reports those differences and rejects required mappings that would lose declared behavior. For example, Strands and Google ADK do not currently support contract handoffs. The target references describe the supported combinations of tools, approvals, context, and composition. TypeScript generation produces data types and validators; the current native agent adapters run in Python.
You can add .eval scenarios, capture traces, compare contract changes, and assemble review reports as your application needs them.
These tools support implementation and review. Missing evidence stays unverified. See Capture and Assure a Run for a worked example and Evals, Controls, and Assurance for the assessment rules.
The VS Code extension provides syntax highlighting, completions, diagnostics, hover help, navigation, rename, and optional inlay hints for .contract and .eval files. It uses the package's Python language server, so editor feedback follows the same language rules as the CLI.
Install the native Perfect Doc executable and make it available on PATH. On macOS, use:
brew install btfranklin/tap/perfect-doc pdm install npm --prefix tests/typescript ci npm --prefix editors/vscode ci pdm run docs-check pdm run validate pdm build pdm run docs-check runs Perfect Doc offline with perfect-doc.toml, then checks repository documentation consistency. pdm run validate includes both documentation checks.
See Validation and Quality Gates for checks by change type and opt-in live tests. Coding agents should start with AGENTS.md.
All 2 files in this release have provenance metadata.
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.
All 2 files in this release have been uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




