Observed since 21 Oct, 09:51 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
A formal framework for governing autonomous AI agents through explicit resource constraints and temporal boundaries
A formal framework for governing autonomous AI agents through explicit resource constraints and temporal boundaries.
Agent Contracts transforms autonomous AI agents from unbounded explorers into bounded optimizers by introducing formal contracts that specify:
Current agentic AI systems face critical challenges:
Agent Contracts provide a mathematical framework that enables:
from agent_contracts import Contract, ContractedLLM, ResourceConstraints, ContractMode
# Define a contract with resource budgets
contract = Contract(
id="research-task",
name="Research Assistant",
mode=ContractMode.BALANCED, # Optimize for quality-cost-time balance
resources=ResourceConstraints(
tokens=10000,
api_calls=50,
cost_usd=1.0
)
)
# Execute LLM calls within contract constraints
with ContractedLLM(contract) as llm:
response = llm.completion(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Summarize recent AI papers"}]
)
# Contract automatically enforces:
# ✅ Token budget limits
# ✅ API call tracking
# ✅ Cost monitoring
# ✅ Violations trigger warnings or stops
Fine-grained control over individual tool usage:
from agent_contracts import Contract, ResourceConstraints
contract = Contract(
id="research-agent",
name="Research Agent",
resources=ResourceConstraints(
tokens=10000,
tool_invocations=20, # Total limit across all tools
per_tool_limits={
"web_search": 5, # Max 5 web searches
"code_exec": 3, # Max 3 code executions
# Other tools limited only by aggregate
}
)
)
When one agent is funded by several others — an aggregator merging two workers,
a shared reviewer — a strict hierarchy cannot express it without double-counting.
DelegationGraph models delegation as a DAG where budget flows along edges:
from agent_contracts import Contract, ResourceConstraints
from agent_contracts.core import DelegationGraph
root = Contract(
id="research",
name="Research",
resources=ResourceConstraints(tokens=100_000, per_tool_limits={"web_search": 20}),
)
graph = DelegationGraph(root)
for name in ("scout_a", "scout_b", "aggregator"):
graph.add_node(name)
graph.allocate("root", "scout_a", tokens=40_000, per_tool={"web_search": 10})
graph.allocate("root", "scout_b", tokens=40_000, per_tool={"web_search": 10})
graph.allocate("scout_a", "aggregator", tokens=15_000, per_tool={"web_search": 0})
graph.allocate("scout_b", "aggregator", tokens=15_000, per_tool={"web_search": 0})
graph.seal() # validates the whole graph, then freezes its topology
graph.contract_for("aggregator").resources.tokens # 30_000 — the sum of its in-edges
graph.verify() # every node satisfies the invariant
The invariant at every node is in-flow ≥ own consumption + out-flow. Because
that is a purely local check, and internal allocations cancel when summed across
the graph, satisfying it everywhere guarantees total consumption never exceeds
the root budget — with no global lock and no central accountant. See
whitepaper §4.6 for the proof and its scope.
Add custom governance logic that runs before every constraint check:
from agent_contracts import (
Contract, ContractedLLM, CheckContext, HookResult,
EnforcementAction, ResourceConstraints,
)
# Define a hook that blocks off-topic requests
def topic_guard(ctx: CheckContext) -> HookResult:
messages = ctx.metadata.get("messages", [])
if any("off-topic" in str(m) for m in messages):
return HookResult(
allow=False,
reason="Request outside allowed domain",
action=EnforcementAction.HARD_STOP,
)
return HookResult() # allow by default
contract = Contract(
id="guarded-agent",
resources=ResourceConstraints(tokens=10000, cost_usd=1.0)
)
with ContractedLLM(contract) as llm:
llm.enforcer.add_pre_check_hook(topic_guard)
# Hooks fire automatically on every LLM call
# Works with all integrations: LiteLLM, LangGraph, Google ADK, Claude SDK
For complex workflows with cycles and multi-agent coordination:
from langgraph.graph import StateGraph, END
from agent_contracts import Contract, ResourceConstraints
from agent_contracts.integrations.langgraph import ContractedGraph
# Build complex graph with validation cycle
workflow = StateGraph(AgentState)
workflow.add_node("research", research_agent)
workflow.add_node("validate", validate_agent)
workflow.add_conditional_edges(
"validate",
should_retry,
{True: "research", False: END} # Can loop!
)
app = workflow.compile()
# Wrap with contract to prevent runaway loops
contract = Contract(
id="research-workflow",
resources=ResourceConstraints(
tokens=50000,
api_calls=25, # Limit iterations!
cost_usd=2.0
)
)
contracted_workflow = ContractedGraph(contract=contract, graph=app)
result = contracted_workflow.invoke({"query": "Research topic"})
# Budget enforced across ALL nodes and cycles:
# ✅ Prevents infinite loops
# ✅ Multi-agent budget sharing
# ✅ Real-time violation detection
# ✅ Cumulative tracking across entire graph
For Google ADK-based agents and multi-agent hierarchies:
from google.adk.agents import LlmAgent
from agent_contracts import Contract, ResourceConstraints
from agent_contracts.integrations.google_adk import ContractedAdkAgent
# Create multi-agent hierarchy
researcher = LlmAgent(
name="researcher",
model="gemini-2.0-flash",
instruction="You research topics thoroughly."
)
summarizer = LlmAgent(
name="summarizer",
model="gemini-2.0-flash",
instruction="You create concise summaries."
)
coordinator = LlmAgent(
name="coordinator",
model="gemini-2.0-flash",
instruction="You coordinate research and summarization.",
sub_agents=[researcher, summarizer]
)
# Single budget for ENTIRE multi-agent system
contract = Contract(
id="research-system",
resources=ResourceConstraints(
tokens=50000, # For ALL agents combined
api_calls=25,
cost_usd=2.0
)
)
contracted_system = ContractedAdkAgent(contract=contract, agent=coordinator)
result = contracted_system.run(
user_id="user1",
session_id="session1",
message="Research and summarize quantum computing"
)
# Budget enforced across ALL agents in hierarchy:
# ✅ Detailed token tracking (prompt/response/thinking/cached)
# ✅ Multi-turn conversation protection
# ✅ Multi-agent coordination governance
# ✅ Tool execution monitoring
Choose the mode that fits your requirements:
# URGENT mode: Minimize time, accept higher costs
contract = Contract(
mode=ContractMode.URGENT,
resources=ResourceConstraints(tokens=10000)
)
# → 50% faster execution, 20% more tokens
# BALANCED mode: Optimize quality-cost-time tradeoff
contract = Contract(
mode=ContractMode.BALANCED,
resources=ResourceConstraints(tokens=10000)
)
# → Standard execution with quality focus
# ECONOMICAL mode: Minimize costs, accept longer runtime
contract = Contract(
mode=ContractMode.ECONOMICAL,
resources=ResourceConstraints(tokens=10000)
)
# → 60% fewer tokens, 50% longer execution
An Agent Contract C = (I, O, S, R, T, Φ, Ψ) includes:
Agents can optimize along multiple dimensions:
| Mode | Time | Resources | Quality |
|---|---|---|---|
| Urgent | Low ⚡ | High 💰 | 85% |
| Balanced | Medium ⏱️ | Medium 💵 | 95% |
| Economical | High 🐢 | Low 💸 | 90% |
DRAFTED → ACTIVE → {FULFILLED, VIOLATED, EXPIRED, TERMINATED}
Agent Contracts supports the agentskills.io open standard for defining reusable agent behaviors:
from agent_contracts import SkillSpec, Capabilities, Contract
# Define a rich skill with full instructions
code_review = SkillSpec(
name="code-reviewer",
description="Review code for best practices, security issues, and test coverage.",
instructions="""
## Instructions
1. Read the target files
2. Check for common issues:
- Error handling
- Security vulnerabilities
- Test coverage
3. Provide detailed feedback
""",
allowed_tools=["Read", "Grep", "Glob"],
version="1.0.0",
)
# Use in capabilities (mix strings and SkillSpec)
contract = Contract(
id="review-task",
name="Code Review",
capabilities=Capabilities(
skills=[code_review, "simple-skill"], # Both types work
tools=["web_search"],
),
)
# Access skills programmatically
skill = contract.capabilities.get_skill("code-reviewer")
print(skill.instructions)
Features:
to_skill_md(), from_skill_md())🎉 Ready for Release (November 2025)
Current Version: 0.1.0 Status: Production-ready, validated, documented
Phase 1: Core Framework ✅ Complete
Phase 2A: Strategic Optimization ✅ Complete
Phase 2B: Governance & Benchmarks ✅ Complete
LangGraph Integration ✅ Complete (Premium Feature)
Google ADK Integration ✅ Complete
Claude Agent SDK Integration ✅ Complete
aexecute() and sync execute()Pre-Execution Hooks ✅ Complete
CheckContext, HookResult, CheckHook types for custom policy governanceEvaluation Pipelines ✅ Complete
Total: 646+ tests, 81%+ coverage
Agent Contracts are designed for:
LangChain (simple chains):
LangGraph (complex workflows) ⭐:
Claude Agent SDK (agentic coding & file/web/terminal):
Google ADK (multi-turn & multi-agent):
agent-contracts/
├── src/agent_contracts/ # Core package
│ ├── core/
│ │ ├── contract.py # Contract data structures
│ │ ├── monitor.py # Resource monitoring
│ │ ├── enforcement.py # Constraint enforcement
│ │ ├── tokens.py # Token counting
│ │ ├── planning.py # Strategic planning
│ │ └── prompts.py # Budget-aware prompts
│ └── integrations/
│ ├── litellm_wrapper.py # LiteLLM integration
│ ├── langchain.py # LangChain integration
│ ├── langgraph.py # LangGraph integration ⭐
│ ├── google_adk.py # Google ADK integration
│ └── claude_agent_sdk.py # Claude Agent SDK integration
├── tests/ # 247+ tests, 94%+ coverage
│ ├── core/ # Core module tests (209 tests)
│ └── integrations/ # Integration tests (38 tests)
├── benchmarks/ # Live demonstrations & benchmarks
│ ├── demo_phase1.py # Phase 1 interactive demo
│ ├── strategic/ # Strategic optimization benchmarks
│ ├── research_agent/ # Multi-step research benchmark
│ ├── governance/ # Policy & governance tests
│ ├── langchain/ # LangChain demos
│ ├── langgraph/ # LangGraph demos (multi-agent)
│ └── google_adk/ # Google ADK demos (multi-turn, multi-agent)
├── evaluation/ # Experimental evaluations
│ ├── research_pipeline/ # Multi-agent research experiment
│ └── code_review_pipeline/ # Coder↔Reviewer experiment
├── docs/
│ ├── whitepaper.md # Complete theoretical framework
│ └── testing-strategy.md # Testing & validation plan
├── pyproject.toml # Package configuration
└── README.md # This file
# Install from PyPI
pip install ai-agent-contracts
# Or with uv
uv add ai-agent-contracts
The package is importable as agent_contracts:
from agent_contracts import Contract, ResourceConstraints
For development (from source):
git clone https://github.com/flyersworder/agent-contracts.git
cd agent-contracts
uv sync --dev
Requirements: Python ≥ 3.12
Optional dependencies:
litellm - For LLM integration (automatically installed)langchain - For LangChain integration (uv sync --extra langchain)langgraph - For LangGraph integration ⭐ (uv sync --extra langgraph)google-adk - For Google ADK integration (uv sync --extra google-adk)claude-agent-sdk - For Claude Agent SDK integration (uv sync --extra claude-agent-sdk)matplotlib - For visualization benchmarks (pip install matplotlib)This project uses uv for dependency management. To set up the development environment:
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone https://github.com/flyersworder/agent-contracts.git
cd agent-contracts
# Install dependencies (including dev dependencies)
uv sync --dev
# Install pre-commit hooks
uv run pre-commit install
This project uses several tools to maintain code quality:
Pre-commit hooks will automatically run on every commit. To manually run all checks:
# Run all pre-commit hooks
uv run pre-commit run --all-files
# Run specific tools
uv run ruff check . # Linting
uv run ruff format . # Formatting
uv run mypy . # Type checking
# Run tests (when available)
uv run pytest
# Run with coverage
uv run pytest --cov=agent_contracts --cov-report=html
docs/ - Documentation (whitepaper, testing strategy)src/ - Source code (planned)tests/ - Test suite (planned)pyproject.toml - Project configuration and dependenciesuv.lock - Locked dependencies for reproducibilityThis is an evolving framework. We welcome contributions in:
This project is licensed under CC BY 4.0.
Qing Ye (with assistance from Claude, Anthropic)
If you use this framework in your research, please cite:
@techreport{ye2025agentcontracts,
title={Agent Contracts: A Resource-Bounded Optimization Framework for Autonomous AI Systems},
author={Ye, Qing},
year={2025},
month={October}
}
Version: 0.5.0 | Last Updated: August 22, 2026 | Status: Production Ready ⭐
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 0.5.0 | 22 Aug 2026 | 14 |
This describes our collected data; it is not a security assessment.
Shared repository data · GitHub
Observed since 21 Oct, 09:51 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:fe6ee1afb05c7d0452c8e1e5862a209e8c6353c380a60b9ed69107ce9f563d04