Getting Started
WIRE is a production governance layer for autonomous AI agents. It wraps any agent framework — LangGraph, CrewAI, AutoGen, OpenAI Agents, Microsoft Foundry — and enforces safety, cost, compliance, and human-in-the-loop controls without modifying your agent code.
One wire.deploy() call gives every agent iteration-limits, token budgets, cryptographic audit trails,
HITLGates, idempotency, SLA tracking, and compliance presets. One wire.hire() call spins up
an entire AI workforce from a plain-English description.
Installation
pip install wire-ai[redis], wire-ai[postgres], wire-ai[all].
Quick Start
Govern your first LangGraph agent in five lines:
import wire
# 1. Build your graph as normal
graph = build_my_langgraph()
# 2. Wrap it — one call adds all governance
governed = wire.deploy(graph, backend="langgraph", max_iterations=50, max_cost_usd=1.0)
# 3. Run exactly as before
result = await governed.ainvoke({"messages": [{"role": "user", "content": "Analyse Q3 spend"}]})
# 4. Verify the cryptographic audit trail
wire.AuditChain.verify("wire-audit.jsonl")
Core Primitives
WIRE's safety layer is built from composable primitives. Each primitive can be used standalone
or automatically composed when you call wire.deploy().
LoopGuard
Terminates runaway agents by counting iterations and raising LoopGuardError when the limit is exceeded.
from wire.primitives import LoopGuard
guard = LoopGuard(max_iterations=100, window_seconds=60)
@guard
async def agent_step(state):
# Automatically tracked — raises LoopGuardError if limit hit
return await my_llm_call(state)
# Or use context manager style:
async with LoopGuard(max_iterations=50) as guard:
result = await governed.ainvoke(state)
AuditChain
SHA-256 linked-list audit log. Every agent event is cryptographically chained — any tampering is detectable.
from wire.primitives import AuditChain
# Records are auto-written by wire.deploy(); you can also write manually:
chain = AuditChain(path="wire-audit.jsonl")
chain.record(event="tool_call", agent="planner", payload={"tool": "web_search", "query": "..."})
# Verify integrity at any time — returns True or raises AuditIntegrityError
AuditChain.verify("wire-audit.jsonl")
# Export to Parquet for SIEM ingestion
chain.export("wire-audit.parquet", format="parquet")
Budget
Hard limits on token consumption and USD cost. Raises BudgetExceededError before the limit is breached.
from wire.primitives import Budget
budget = Budget(
max_tokens=100_000,
max_cost_usd=2.50,
warn_at_pct=80, # emit warning event at 80 %
on_breach="raise", # or "pause" | "checkpoint"
)
# Attach to a governed graph
governed = wire.deploy(graph, backend="langgraph", budget=budget)
# Inspect at runtime
print(budget.status())
# {'tokens_used': 12400, 'cost_usd': 0.31, 'pct': 12.4, 'status': 'ok'}
HITLGate
Pause agent execution at any step and require human approval before continuing. Supports async webhooks and CLI approval.
from wire.primitives import HITLGate
gate = HITLGate(
trigger="before_tool_call", # or "after_tool_call" | "on_cost_threshold"
cost_threshold_usd=0.50,
notify_url="https://hooks.example.com/wire-hitl",
timeout_seconds=3600, # auto-reject after 1 h
)
governed = wire.deploy(graph, backend="langgraph", hitl=gate)
# Approve / reject from CLI:
# wire hitl approve
# wire hitl reject --reason "Out of scope"
IdempotencyGuard
Prevents duplicate agent runs and tool calls by tracking execution fingerprints. Supports four backends:
from wire.primitives import IdempotencyGuard
# In-memory (dev / single process)
guard = IdempotencyGuard(backend="memory", ttl_seconds=3600)
# Redis (multi-process / multi-host)
guard = IdempotencyGuard(backend="redis", url="redis://localhost:6379", ttl_seconds=86400)
# PostgreSQL (persistent, auditable)
guard = IdempotencyGuard(backend="postgres", dsn="postgresql://user:pass@localhost/wire")
# DynamoDB (AWS-native, serverless)
guard = IdempotencyGuard(backend="dynamodb", table="wire-idempotency", region="us-east-1")
governed = wire.deploy(graph, backend="langgraph", idempotency=guard)
# Duplicate invocations with the same key return the cached result immediately
SLATracker
Measures agent execution time against SLA targets and emits events when thresholds are breached.
from wire.primitives import SLATracker
sla = SLATracker(
warn_seconds=30,
breach_seconds=120,
on_breach="emit_event", # or "raise" | "checkpoint_and_raise"
)
governed = wire.deploy(graph, backend="langgraph", sla=sla)
# Query SLA status
print(sla.report())
# {'elapsed_s': 18.4, 'status': 'ok', 'warn_pct': 61, 'breaches_today': 0}
PolicyEnforcer
Declarative allow/deny rules that inspect agent actions before execution. Rules are evaluated in order; first match wins.
from wire.primitives import PolicyEnforcer, Policy
policy = PolicyEnforcer(rules=[
Policy(action="deny", match={"tool": "shell_exec", "args.cmd": {"$contains": "rm -rf"}}),
Policy(action="allow", match={"tool": "web_search"}),
Policy(action="allow", match={"tool": "read_file", "args.path": {"$startswith": "/data/"}}),
Policy(action="deny", match={"tool": "*"}), # default deny
])
governed = wire.deploy(graph, backend="langgraph", policy=policy)
Framework Adapters
wire.deploy() is the single entry point for all framework integrations. It auto-detects
the graph type or accepts an explicit backend parameter.
wire.deploy() API
governed = wire.deploy(
graph, # Your agent graph / crew / team / assistant
backend="langgraph", # "langgraph" | "crewai" | "autogen" | "openai" | "foundry" | "auto"
max_iterations=100, # LoopGuard limit
max_cost_usd=5.0, # Budget (USD)
max_tokens=200_000, # Budget (tokens)
hitl=None, # HITLGate instance or config dict
idempotency=None, # IdempotencyGuard instance
sla=None, # SLATracker instance
policy=None, # PolicyEnforcer instance
compliance=None, # CompliancePreset enum
audit_path="wire-audit.jsonl", # AuditChain output file
metrics=True, # Enable Prometheus metrics
)
LangGraph
from langgraph.graph import StateGraph
import wire
builder = StateGraph(MyState)
builder.add_node("planner", planner_node)
builder.add_node("executor", executor_node)
builder.add_edge("planner", "executor")
graph = builder.compile()
governed = wire.deploy(graph, backend="langgraph", max_iterations=50, max_cost_usd=1.0)
result = await governed.ainvoke({"messages": [{"role": "user", "content": "Run the report"}]})
CrewAI
from crewai import Crew, Agent, Task
import wire
researcher = Agent(role="Researcher", goal="Find the latest AI papers", backstory="...")
writer = Agent(role="Writer", goal="Summarise findings", backstory="...")
crew = Crew(agents=[researcher, writer], tasks=[Task(description="Weekly AI digest", agent=writer)])
governed = wire.deploy(crew, backend="crewai", max_iterations=20, max_cost_usd=0.50)
result = governed.kickoff() # wire wraps kickoff transparently
AutoGen
from autogen import AssistantAgent, UserProxyAgent
import wire
assistant = AssistantAgent("assistant", llm_config={"model": "gpt-4o"})
user_proxy = UserProxyAgent("user_proxy", human_input_mode="NEVER")
governed = wire.deploy(
(user_proxy, assistant),
backend="autogen",
max_iterations=30,
policy=wire.PolicyEnforcer.from_yaml("policy.yaml"),
)
governed.initiate_chat(assistant, message="Summarise last quarter's revenue data")
OpenAI Agents SDK
from agents import Agent, Runner
import wire
agent = Agent(
name="Analyst",
instructions="You are a financial analyst. Be precise and cite sources.",
model="gpt-4o",
)
governed = wire.deploy(agent, backend="openai", max_iterations=25, max_cost_usd=0.75)
result = await governed.run("What are the top 3 risks in our Q4 pipeline?")
Microsoft Foundry / Azure AI
from azure.ai.projects import AIProjectClient
import wire
project = AIProjectClient.from_connection_string(os.environ["AZURE_AI_PROJECT_CONN"])
agent = project.agents.create_agent(model="gpt-4o", name="FoundryAgent", instructions="...")
governed = wire.deploy(
agent,
backend="foundry",
max_iterations=40,
compliance=wire.CompliancePreset.HIPAA,
audit_path="wire-audit.jsonl",
)
thread = governed.create_thread()
governed.create_message(thread_id=thread.id, role="user", content="Analyse patient data trends")
HIRE Engine
wire.hire() converts a plain-English workforce description into a fully governed multi-agent system.
It selects roles, wires communication, applies governance primitives, and returns a ready-to-run
Workforce object — no configuration files, no boilerplate.
wire.hire()
import wire
workforce = wire.hire("Monitor AWS costs. Open Jira P1 on breach. Escalate to ops.")
print(workforce.describe())
roles : AWS Cost Monitor, Jira P1 Responder, Incident Commander
primitives : LoopGuard(50) · Budget($2.00) · HITLGate(cost>$500) · AuditChain
communication: internal-bus · escalation→ops-webhook
status : ready
Run with: await workforce.run()
Async Workforce
# Spin up asynchronously with full governance options
workforce = await wire.hire_async(
"Scan S3 buckets for PII. Alert security team. Generate compliance report.",
compliance=wire.CompliancePreset.HIPAA,
max_cost_usd=10.0,
notify_slack="https://hooks.slack.com/services/T.../B.../xxx",
)
await workforce.run()
# Stream events as they happen
async for event in workforce.stream():
print(f"[{event.agent}] {event.type}: {event.summary}")
Built-in Role Templates
HIRE ships with 20 production-tested role templates. Specify by name or let HIRE auto-select from your description.
| Role Template | Default Integrations | Key Primitives |
|---|---|---|
| AWS Cost Monitor | AWS Cost Explorer, CloudWatch | Budget, HITLGate |
| Jira P1 Responder | Jira, PagerDuty | SLATracker, AuditChain |
| Security Scanner | Snyk, SIEM, AWS GuardDuty | PolicyEnforcer, AuditChain |
| Data Pipeline Monitor | Airflow, dbt, Great Expectations | SLATracker, LoopGuard |
| Customer Support Triage | Zendesk, Salesforce | HITLGate, Budget |
| Code Review Assistant | GitHub, GitLab | PolicyEnforcer, AuditChain |
| Deployment Guardian | ArgoCD, Spinnaker, GitHub Actions | HITLGate, PolicyEnforcer |
| Incident Commander | PagerDuty, Slack, Opsgenie | SLATracker, HITLGate |
| Compliance Auditor | AWS Config, Azure Policy | CompliancePreset, AuditChain |
| Log Analyst | Elasticsearch, Splunk, Datadog | Budget, LoopGuard |
| Performance Optimizer | Datadog, New Relic, Grafana | SLATracker, Budget |
| API Gateway Monitor | Kong, AWS API GW, Apigee | SLATracker, LoopGuard |
| Database Health Check | PostgreSQL, MySQL, MongoDB | SLATracker, PolicyEnforcer |
| ML Model Monitor | MLflow, SageMaker, Vertex AI | DriftDetector, AuditChain |
| Certificate Expiry Tracker | AWS ACM, Vault, Let's Encrypt | SLATracker, HITLGate |
| Backup Validator | AWS Backup, Restic, Velero | IdempotencyGuard, AuditChain |
| Cost Anomaly Detector | AWS Cost Anomaly, Azure Cost Mgmt | Budget, HITLGate |
| SLA Guardian | PagerDuty, Datadog, Slack | SLATracker, PolicyEnforcer |
| Capacity Planner | AWS Compute Optimizer, Kubernetes | Budget, SLATracker |
| Release Manager | GitHub, Jira, Confluence | HITLGate, PolicyEnforcer |
Visibility
WIRE provides real-time observability into every agent, workforce, and event — from a local terminal dashboard to a full web UI with auth.
WorkforceDashboard
In-process rich terminal dashboard built on Textual. Zero extra services required.
from wire.visibility import WorkforceDashboard
dash = WorkforceDashboard(workforce=workforce)
await dash.start() # Launches full-screen TUI in current terminal
Web Dashboard
Browser-based dashboard with API-key authentication, WebSocket live updates, and role-based views.
from wire.visibility.web_dashboard import WebDashboard
web = WebDashboard(dashboard=dash, port=8080, api_key="your-secret-key")
await web.start()
# Open http://localhost:8080 — authenticate with the API key
# Supports: agent timeline, cost waterfall, event log, HITL queue
CLI Dashboard
Launch from the terminal for any running or recorded workforce:
# Live dashboard for a running workforce
wire dashboard --workforce cost-monitor-v1
# Replay from an audit log
wire dashboard --replay wire-audit.jsonl
DriftDetector
Compares agent behaviour across runs and flags statistical deviation — useful for catching prompt injection, model drift, or unexpected tool-use changes.
from wire.visibility import DriftDetector
detector = DriftDetector(
baseline="wire-audit-baseline.jsonl",
sensitivity=0.15, # flag if metric deviates > 15 %
metrics=["tool_call_rate", "avg_cost_per_step", "token_distribution"],
)
report = detector.scan("wire-audit-current.jsonl")
print(report.summary())
# Drift detected in: avg_cost_per_step (+34%) — investigate before promoting
TimeTravel
Replay any agent execution from a checkpoint in the audit log. Step forward/backward, inspect state at every decision point, and branch off to test alternative paths.
from wire.visibility import TimeTravel
tt = TimeTravel.from_audit("wire-audit.jsonl")
# Replay from a specific step
for frame in tt.replay(from_step=12, to_step=25):
print(f"Step {frame.step}: {frame.agent} → {frame.action}")
print(f" State: {frame.state_summary}")
# Branch: modify state at step 15 and re-run
branched = await tt.branch(at_step=15, state_patch={"budget_usd": 2.0})
result = await branched.run()
Enterprise
WIRE ships first-class support for regulated environments: compliance presets, RBAC, multi-tenancy, and durable audit backends.
CompliancePreset
One-line compliance. Presets configure the correct combination of primitives, audit settings, and policy rules for each standard.
import wire
# Apply SOC-2 compliance to any deployment
governed = wire.deploy(graph, backend="langgraph", compliance=wire.CompliancePreset.SOC2)
# Other presets
wire.deploy(graph, backend="langgraph", compliance=wire.CompliancePreset.HIPAA)
wire.deploy(graph, backend="langgraph", compliance=wire.CompliancePreset.GDPR)
wire.deploy(graph, backend="langgraph", compliance=wire.CompliancePreset.NIST)
| Preset | Audit Retention | Primitives Enforced | Extra Controls |
|---|---|---|---|
| SOC-2 | 1 year | AuditChain, PolicyEnforcer, HITLGate | Immutable log storage, access control review |
| HIPAA | 6 years | AuditChain, PolicyEnforcer, IdempotencyGuard | PHI data masking, BA agreement tagging |
| GDPR | Configurable | AuditChain, PolicyEnforcer, HITLGate | PII detection, right-to-erasure hooks |
| NIST | 3 years | AuditChain, PolicyEnforcer, DriftDetector | NIST AI RMF controls, incident playbooks |
RBACPolicy
Role-based access control for agent actions. Define roles, assign permissions, and bind users or service accounts.
from wire.enterprise import RBACPolicy, Role, Permission
policy = RBACPolicy(
roles=[
Role("ops-engineer", permissions=[Permission("tool.*"), Permission("hitl.approve")]),
Role("data-analyst", permissions=[Permission("tool.read_*"), Permission("tool.query_*")]),
Role("auditor", permissions=[Permission("audit.*")]),
],
default_role="data-analyst",
)
governed = wire.deploy(graph, backend="langgraph", rbac=policy)
# Check permissions programmatically
policy.can("ops-engineer", "hitl.approve") # True
policy.can("data-analyst", "tool.shell_exec") # False
TenantRegistry
Namespace agent runs by tenant. Each tenant gets isolated budgets, audit trails, and RBAC policies.
from wire.enterprise import TenantRegistry
registry = TenantRegistry(backend="postgres", dsn=os.environ["DATABASE_URL"])
# Register a tenant
registry.register("acme-corp", config={
"max_cost_usd": 50.0,
"compliance": "SOC2",
"audit_backend": "s3",
"s3_bucket": "acme-wire-audit",
})
# Deploy with tenant isolation
governed = wire.deploy(graph, backend="langgraph", tenant=registry.get("acme-corp"))
Audit Backends
For production, store audit logs in durable external storage rather than local JSONL files.
from wire.audit import S3AuditBackend, PostgresAuditBackend
# Amazon S3 — immutable object storage, lifecycle policies
audit_backend = S3AuditBackend(
bucket="my-wire-audit",
prefix="wire-logs/",
kms_key_id="arn:aws:kms:...", # optional server-side encryption
object_lock=True, # WORM compliance
)
# PostgreSQL — queryable, existing SIEM-friendly
audit_backend = PostgresAuditBackend(
dsn="postgresql://user:pass@db.example.com/wire",
table="wire_audit_events",
retention_days=365,
)
governed = wire.deploy(graph, backend="langgraph", audit_backend=audit_backend)
Integrations
WIRE provides lightweight wrappers for common agent patterns — LangChain chains, LlamaIndex query engines, individual tools, and automatic discovery.
wire.wrap_chain()
Wrap any LangChain Runnable or chain with full WIRE governance in one call.
import wire
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
chain = LLMChain(llm=ChatOpenAI(model="gpt-4o"), prompt=my_prompt)
governed_chain = wire.wrap_chain(chain, max_cost_usd=0.25, max_iterations=10)
result = await governed_chain.ainvoke({"topic": "climate change impacts"})
wire.wrap_query_engine()
Govern a LlamaIndex query engine — apply budgets and audit trails to RAG pipelines.
import wire
from llama_index.core import VectorStoreIndex
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
governed_qe = wire.wrap_query_engine(
query_engine,
max_cost_usd=0.10,
audit_path="rag-audit.jsonl",
)
response = await governed_qe.aquery("What are the key findings?")
@wire.tool
Decorate any Python function to make it a governed tool — adds audit logging, policy checks, and budget tracking automatically.
import wire
@wire.tool(
audit=True,
policy=wire.PolicyEnforcer.from_yaml("tools-policy.yaml"),
max_cost_usd=0.05,
)
async def search_web(query: str) -> str:
"""Search the web for current information."""
results = await my_search_client.search(query)
return results.top_result
# The decorated tool is now auto-discovered by any wire.deploy() call
governed = wire.deploy(graph, backend="langgraph")
wire.patch()
Apply a hot-patch to a running governed agent — update budget limits, swap policy rules, or rotate audit backends without restarting.
import wire
# Increase budget limit on a live deployment
wire.patch(governed, budget=wire.Budget(max_cost_usd=10.0))
# Swap policy rules in production
wire.patch(governed, policy=wire.PolicyEnforcer.from_yaml("new-policy.yaml"))
# From CLI:
# wire patch apply --target cost-monitor-v1 --budget '{"max_cost_usd": 10.0}'
wire.auto
Zero-configuration mode — WIRE inspects your environment and applies sensible defaults. Useful for rapid prototyping and CI/CD pipelines.
import wire
# Auto-detect framework, apply default governance
governed = wire.auto(graph)
# Or set a risk profile: "low" | "medium" | "high" | "paranoid"
governed = wire.auto(graph, risk_profile="high")
# high: max_iterations=25, max_cost_usd=1.0, hitl=True, compliance=SOC2
Observability
WIRE exposes structured events, queryable audit logs, and Prometheus-compatible metrics for integration with any monitoring stack.
EventStore
Every governed event is stored in a queryable EventStore. Filter by agent, type, time range, or custom predicates — then replay subsets for debugging.
from wire.observability import EventStore
store = EventStore.open("wire-audit.jsonl")
# Query: all tool calls in the last hour that cost more than $0.10
events = store.query(
type="tool_call",
after=datetime.utcnow() - timedelta(hours=1),
where=lambda e: e.cost_usd > 0.10,
)
for event in events:
print(f"{event.ts} | {event.agent} | {event.tool} | ${event.cost_usd:.4f}")
# Replay a filtered subset — useful for reproducing bugs
replayer = store.replay(events, speed=2.0) # 2x real-time
async for frame in replayer:
print(frame)
MetricsCollector & Prometheus Export
WIRE exposes a Prometheus /metrics endpoint out of the box. Scrape with Prometheus, visualise in Grafana.
from wire.observability import MetricsCollector
collector = MetricsCollector(
port=9090,
labels={"env": "production", "service": "agent-platform"},
)
governed = wire.deploy(graph, backend="langgraph", metrics=collector)
await collector.start() # http://localhost:9090/metrics
# Exposed metrics:
# wire_iterations_total{agent, backend} counter
# wire_cost_usd_total{agent, backend} counter
# wire_tokens_total{agent, backend, model} counter
# wire_hitl_pending{workforce} gauge
# wire_sla_breach_total{agent} counter
# wire_budget_utilisation_pct{agent} gauge
# wire_audit_events_total{type} counter
wire/observability/grafana-dashboard.json — import it directly into your Grafana instance.
CLI Reference
The wire CLI provides operational access to governed agents, workforces, audit logs, and runtime configuration.
pip install wire-ai # installs the 'wire' CLI
wire --help # list all commands
wire --version # print version
| Command | Description |
|---|---|
wire deploy | Deploy a governed agent graph from a Python module |
wire hire | Spin up an AI workforce from a natural-language description |
wire dashboard | Launch real-time monitoring dashboard (TUI or web) |
wire audit verify | Verify the SHA-256 integrity of an audit chain file |
wire audit export | Export audit log to JSON, CSV, or Parquet format |
wire budget status | Show current token and USD cost consumption |
wire budget set | Update budget limits on a running deployment |
wire hitl pending | List all pending human-in-the-loop gates |
wire hitl approve <id> | Approve a pending HITL gate by ID |
wire hitl reject <id> | Reject a pending HITL gate with optional reason |
wire drift check | Run a drift detection scan against a baseline audit log |
wire timetravel replay | Replay agent execution from a checkpoint in the audit log |
wire compliance check | Validate a deployment configuration against a compliance preset |
wire tenant list | List all registered tenants and their configurations |
wire rbac check | Check whether a role has a given permission |
wire metrics export | Export current Prometheus metrics to stdout or a file |
wire events query | Query the event store with filter expressions |
wire patch apply | Apply a hot-patch to a live governed agent at runtime |
Changelog
All notable changes to WIRE are documented here.
- TimeTravel: branch-at-step, async replay, state-patch API
- DriftDetector: configurable sensitivity, 8 new metric types, JSON report output
- CompliancePreset.NIST: full NIST AI RMF controls + incident playbooks
- CLI:
wire timetravel replay --branch,wire drift check --baseline - Bug fix: HITLGate webhook retry on transient 5xx responses
- HIRE engine:
wire.hire()andwire.hire_async() - 20 built-in role templates (see HIRE Engine section)
- WorkforceDashboard TUI with live event timeline
- Workforce-level SLA tracking and escalation
- WebDashboard: browser-based monitoring with API-key auth
- MetricsCollector: Prometheus
/metricsendpoint, 7 built-in gauges - EventStore: queryable audit log with replay API
- Grafana dashboard JSON bundled in package
- Enterprise: TenantRegistry with PostgreSQL backend
- RBACPolicy: roles, permissions, service-account binding
- S3AuditBackend with WORM / object-lock support
- PostgresAuditBackend with configurable retention
- CompliancePreset: SOC-2, HIPAA, GDPR presets
- IdempotencyGuard: Redis, PostgreSQL, and DynamoDB backends
- SLATracker: breach events, warn thresholds, daily report
- Budget:
on_breach="checkpoint"mode for safe suspension
- HITLGate: webhook notification, timeout auto-reject, CLI approval
- PolicyEnforcer: YAML rule files,
$contains/$startswithmatchers - CLI:
wire hitl pending/approve/reject
wire.deploy(): unified API replacing per-framework wrappers- CrewAI adapter:
governed.kickoff()transparent wrap - AutoGen adapter: multi-agent conversation governance
wire.wrap_chain()for LangChain Runnables
- AuditChain: SHA-256 linked-list log, Parquet export,
wire audit verify - Budget: token + cost limits, warn-at-pct,
wire budget status/set - IdempotencyGuard: in-memory backend
- Initial public release
- LoopGuard: iteration limiter with configurable window
- LangGraph adapter: first supported framework
wire deployCLI command- JSONL audit log (pre-chain)