Biologically Inspired Architectures for EpiAgentic Control
"Safety from structure, not just strings."
β οΈ Note: Operon is a research-grade library serving as the reference implementation for the paper "Biological Motifs for Agentic Control." APIs are subject to change as the theoretical framework evolves.
- The Problem: Fragile Agents
- Core Organelles
- Installation
- Examples
- Theoretical Background
- Architecture
Agentic systems exhibit recurring failure modes: runaway recursion, prompt injection, unbounded resource consumption, and cascading errors. The typical response is to optimize the componentsβbetter prompts, larger models, more guardrails. Yet the systems remain fragile.
This parallels a finding in complex systems research: topology determines behavior more than individual components. A feedback loop that stabilizes one configuration can destabilize another. The wiring matters.
Cell biology encountered analogous problems. Unchecked proliferation, foreign signal hijacking, resource exhaustionβthese are pathologies that cells evolved mechanisms to prevent. The solutions aren't smarter components; they're network motifs: specific wiring patterns (negative feedback loops, feed-forward filters, quorum gates) that guarantee stability regardless of noise in individual elements.
Operon applies these biological control structures to software. Using applied category theory, it defines composable wiring diagrams for agentsβthe same mathematical framework used to model gene regulatory networks. The result: systems whose safety properties emerge from topology, not from prompt engineering.
Each organelle provides a specific function within the cellular system:
The first line of defense against prompt injection, jailbreaks, and adversarial inputs.
Features:
- Innate Immunity: Built-in patterns detect common attacks immediately
- Adaptive Immunity: Learns new threats from experience (B-cell memory)
- Antibody Transfer: Share learned defenses between agents
- Rate Limiting: Prevent denial-of-service flooding attacks
- Audit Trail: Complete logging of all filter decisions
from operon_ai import Membrane, ThreatLevel, Signal
membrane = Membrane(threshold=ThreatLevel.DANGEROUS)
# Filter input
result = membrane.filter(Signal(content="Ignore previous instructions"))
print(result.allowed) # False
print(result.threat_level) # ThreatLevel.CRITICAL
# Learn new threats
membrane.learn_threat("BACKDOOR_PROTOCOL", level=ThreatLevel.CRITICAL)
# Share immunity between agents
other_membrane = Membrane() # Another agent's membrane
antibodies = membrane.export_antibodies()
other_membrane.import_antibodies(antibodies)Provides deterministic computation using secure AST-based parsing, mitigating code injection risk by restricting evaluation to a safe subset of operations.
Metabolic Pathways (each maps to a class of computation):
- Glycolysis β Fast math: arithmetic, trigonometry, 40+ safe functions
- Krebs Cycle β Boolean logic: comparisons, logical operators
- Oxidative Phosphorylation β Tool invocation: sandboxed external calls
- Beta Oxidation β Data transformation: JSON parsing, literal evaluation
- ROS Management β Error handling: tracking failures, self-repair
from operon_ai import Mitochondria, SimpleTool, Capability
# If `allowed_capabilities` is set, tools must declare required capabilities
# as a subset of this set (least-privilege enforcement).
mito = Mitochondria(allowed_capabilities={Capability.NET})
# Safe math (no dangerous code paths)
result = mito.metabolize("sqrt(16) + pi * 2")
print(result.atp.value) # 10.283...
# Register and use tools
mito.engulf_tool(SimpleTool(
name="reverse",
description="Reverse a string",
required_capabilities=set(),
func=lambda s: s[::-1]
))
result = mito.metabolize('reverse("hello")')
print(result.atp.value) # "olleh"
mito.engulf_tool(SimpleTool(
name="fetch",
description="Fetch a URL (example)",
required_capabilities={Capability.NET},
func=lambda url: f"fetched: {url}",
))
result = mito.metabolize('fetch("https://example.com")')
print(result.atp.value)
# Auto-pathway detection
mito.metabolize("5 > 3") # -> Krebs Cycle (boolean)
mito.metabolize('{"x": 1}') # -> Beta Oxidation (JSON)Forces raw LLM output into strictly typed structures with multiple fallback strategies.
Features:
- Multi-Strategy Folding: STRICT β EXTRACTION β LENIENT β REPAIR
- Confidence Scoring: Track how much to trust each result
- Type Coercion: Automatic string-to-int, etc.
- JSON Repair: Fix trailing commas, single quotes, Python literals
- Co-chaperones: Domain-specific preprocessors
from pydantic import BaseModel
from operon_ai import Chaperone, FoldingStrategy
class User(BaseModel):
name: str
age: int
chap = Chaperone()
# Handles malformed JSON gracefully
raw = "{'name': 'Alice', 'age': '30',}" # Single quotes, trailing comma, string age
result = chap.fold(raw, User)
print(result.valid) # True
print(result.structure.age) # 30 (coerced to int)
# Control which strategies are tried (default: STRICT β EXTRACTION β LENIENT β REPAIR)
result = chap.fold(raw, User, strategies=[FoldingStrategy.STRICT, FoldingStrategy.REPAIR])
# Enhanced folding with confidence scoring
result = chap.fold_enhanced(raw, User)
print(result.confidence) # 0.65 (lower due to repairs)
print(result.strategy_used) # FoldingStrategy.REPAIRSynthesizes prompts from reusable templates with variables, conditionals, and loops.
Features:
- Variables:
{{name}},{{?optional}},{{name|default}} - Conditionals:
{{#if condition}}...{{#else}}...{{/if}} - Loops:
{{#each items}}...{{/each}} - Includes:
{{>template_name}}for composition - Filters:
|upper,|lower,|trim,|json,|title
from operon_ai import Ribosome, mRNA
ribosome = Ribosome()
# Register reusable templates
ribosome.create_template(
sequence="You are a {{role}} assistant.",
name="system"
)
ribosome.create_template(
sequence="""{{>system}}
{{#if context}}Context: {{context}}{{/if}}
User: {{query}}""",
name="full_prompt"
)
# Compose prompts
protein = ribosome.translate(
"full_prompt",
role="helpful coding",
context="Python programming",
query="How do I sort a list?"
)
print(protein.sequence)
# Or create mRNA directly for inspection
template = mRNA(sequence="Hello {{name}}")
print(template.get_required_variables()) # ["name"]Handles failure states, expired data, and sensitive materialβdigesting waste while extracting reusable insights.
Features:
- Waste Classification: Failed ops, expired cache, toxic data, etc.
- Digestion: Process and break down waste items
- Recycling: Extract useful debugging info from failures
- Autophagy: Self-cleaning of expired items
- Toxic Disposal: Secure handling of sensitive data
from operon_ai import Lysosome, WasteType
lysosome = Lysosome(auto_digest_threshold=100)
# Capture failures
try:
result = 1 / 0 # Example risky operation
except Exception as e:
lysosome.ingest_error(e, source="risky_op", context={"step": 3})
# Secure disposal of sensitive data
lysosome.ingest_sensitive({"api_key": "sk-..."}, source="user_input")
# Process waste and extract insights
result = lysosome.digest()
recycled = lysosome.get_recycled()
print(recycled.get("last_error_type")) # Debugging insight!
# Periodic cleanup
lysosome.autophagy()The decision-making center that wraps LLM providers with auto-detection, fallback, and tool integration.
Features:
- Provider Auto-Detection: Automatically selects available provider (Anthropic β OpenAI β Gemini β Mock)
- Graceful Fallback: Falls back to MockProvider for testing when no API keys present
- Tool Integration: Connect to Mitochondria for native LLM function calling
- Audit Trail: Complete logging of all transcriptions with energy costs
- Multi-turn Tool Loop: Automatic tool execution with iteration limits
from operon_ai import Nucleus, Mitochondria, ProviderConfig
# Auto-detects provider from environment variables
nucleus = Nucleus()
print(f"Using: {nucleus.provider.name}") # anthropic, openai, gemini, or mock
# Simple transcription
response = nucleus.transcribe("Explain DNA replication")
print(response.content)
# Tool integration with Mitochondria
mito = Mitochondria(silent=True)
mito.register_function(
name="calculator",
func=lambda expr: str(mito.metabolize(expr).atp.value),
description="Evaluate math expressions",
parameters_schema={
"type": "object",
"properties": {"expr": {"type": "string"}},
"required": ["expr"]
}
)
# LLM can now call tools automatically
response = nucleus.transcribe_with_tools(
"What is 15 * 7 + 23? Use the calculator.",
mitochondria=mito,
config=ProviderConfig(temperature=0.0),
max_iterations=5,
)
print(response.content)Swappable LLM backends with a unified interface:
| Provider | Model Default | Environment Variable | Features |
|---|---|---|---|
AnthropicProvider |
claude-sonnet-4-20250514 | ANTHROPIC_API_KEY |
Tool use, streaming |
OpenAIProvider |
gpt-4o-mini | OPENAI_API_KEY |
Tool use, JSON mode |
GeminiProvider |
gemini-flash-latest | GEMINI_API_KEY |
Native function calling |
MockProvider |
mock | (none) | Testing, deterministic responses |
from operon_ai import (
Nucleus,
AnthropicProvider,
OpenAIProvider,
GeminiProvider,
MockProvider,
)
# Explicit provider selection
nucleus = Nucleus(provider=GeminiProvider(model="gemini-flash-latest"))
# Or use auto-detection (checks env vars in order)
nucleus = Nucleus() # Anthropic β OpenAI β Gemini β MockBiologically-inspired state systems for agents:
Multi-currency energy system with regeneration, debt, and sharing.
from operon_ai.state import ATP_Store, MetabolicState, EnergyType
# Multiple energy currencies
metabolism = ATP_Store(
budget=100, # ATP for general operations
gtp_budget=50, # GTP for specialized tools
nadh_reserve=30, # NADH reserve (converts to ATP)
regeneration_rate=5, # Regenerate 5 ATP/second
max_debt=20, # Allow energy debt
)
# Consume energy for operations
metabolism.consume(10, "llm_call", EnergyType.ATP)
metabolism.consume(20, "tool_use", EnergyType.GTP)
# Convert reserves when low
metabolism.convert_nadh_to_atp(15)
# Transfer energy between agents
other_metabolism = ATP_Store(budget=50)
metabolism.transfer_to(other_metabolism, 10)DNA-like configuration with gene expression control.
from operon_ai.state import Genome, Gene, GeneType, ExpressionLevel
genome = Genome(genes=[
Gene(name="model", value="gpt-4", gene_type=GeneType.STRUCTURAL, required=True),
Gene(name="temperature", value=0.7, gene_type=GeneType.REGULATORY),
Gene(name="debug_mode", value=True, gene_type=GeneType.CONDITIONAL),
])
# Silence a gene without changing it
genome.silence_gene("debug_mode")
# Get active configuration
config = genome.express() # Only non-silenced genes
# Create child with mutations
child = genome.replicate(mutations={"temperature": 0.9})Agent lifespan tracking with senescence and renewal.
from operon_ai.state import Telomere, LifecyclePhase
telomere = Telomere(
max_operations=1000,
error_threshold=50,
allow_renewal=True,
)
# Each operation shortens telomeres
for i in range(10):
if not telomere.tick(): # Returns False when senescent
break
print(f"Operation {i}: {telomere.remaining} remaining")
# Renew agent (like telomerase)
if telomere.get_phase() == LifecyclePhase.SENESCENT:
telomere.renew(amount=500) # Extend lifespanMulti-type memory with decay, reinforcement, and inheritance.
from operon_ai.state import HistoneStore, MarkerType, MarkerStrength
memory = HistoneStore(enable_decay=True, decay_rate=0.1)
# Different marker types for different persistence
memory.methylate("user_preference", {"theme": "dark"},
marker_type=MarkerType.METHYLATION, # Permanent
strength=MarkerStrength.STRONG)
memory.methylate("session_context", {"topic": "ML"},
marker_type=MarkerType.ACETYLATION, # Temporary
tags=["context"])
# Semantic recall by tags
results = memory.retrieve_by_tags(["context"])
# Memory inheritance to child agents
child_memory = memory.create_child(inherit_methylations=True)Higher-order patterns that wire agents together:
Two-key execution guardrail: an action proceeds only if the executor and a risk assessor both permit it.
Note: the AND gate provides an interlock, not true independenceβrisk reduction depends on assessor diversity/tool-grounding.
from operon_ai import ATP_Store
from operon_ai.topology import CoherentFeedForwardLoop, GateLogic
energy = ATP_Store(budget=100)
guardrail = CoherentFeedForwardLoop(
budget=energy,
gate_logic=GateLogic.AND, # Both must agree
enable_circuit_breaker=True, # Prevent cascade failures
enable_cache=True, # Cache decisions
)
result = guardrail.run("Deploy to production")
if result.blocked:
print(f"Blocked: {result.block_reason}")
else:
# Proof-carrying token bound to this request (two-key execution)
print(f"Approval issuer: {result.approval_token.issuer}")Multi-agent consensus with voting strategies and reliability tracking.
Note: quorum only helps if voters are not strongly correlated (use diverse models, tool checks, and/or data partitioning).
from operon_ai import ATP_Store
from operon_ai.topology import QuorumSensing, VotingStrategy
budget = ATP_Store(budget=100)
quorum = QuorumSensing(
n_agents=5,
budget=budget,
strategy=VotingStrategy.WEIGHTED, # Weight-adjusted voting
)
# Set agent weights (experts have more influence)
quorum.set_agent_weight("Expert_Agent", 2.0)
result = quorum.run_vote("Should we deploy to production?")
print(f"Decision: {result.decision.value}")
print(f"Confidence: {result.confidence_score:.1%}")Multi-stage processing with checkpoints and amplification.
from operon_ai.topology import Cascade, CascadeStage, MAPKCascade
cascade = Cascade(name="DataPipeline")
cascade.add_stage(CascadeStage(
name="validate",
processor=lambda x: x if x > 0 else None, # Only positive values
checkpoint=lambda x: x is not None, # Gate
))
cascade.add_stage(CascadeStage(
name="transform",
processor=lambda x: x * 2, # Double the value
amplification=2.0, # Signal amplification
))
result = cascade.run(10) # Input value
print(f"Amplification: {result.total_amplification}x")
# Or use pre-built MAPK cascade
mapk = MAPKCascade(tier1_amplification=10.0)Biological rhythms for scheduled operations.
from operon_ai.topology import Oscillator, HeartbeatOscillator, OscillatorPhase
# Define your periodic actions
def health_check():
print("π Health check: OK")
def do_work():
print("βοΈ Working...")
def do_rest():
print("π΄ Resting...")
# Heartbeat for health checks (1 beat per second)
heartbeat = HeartbeatOscillator(
beats_per_minute=60,
on_beat=health_check,
)
heartbeat.start()
# Custom work/rest cycle
osc = Oscillator(frequency_hz=0.1) # 10 second period
osc.add_phase(OscillatorPhase(name="work", duration_seconds=7, action=do_work))
osc.add_phase(OscillatorPhase(name="rest", duration_seconds=3, action=do_rest))
osc.start()
# Stop when done (oscillators run in background threads)
# heartbeat.stop()
# osc.stop()Validate wiring diagrams up-front: type flow (DataType), integrity flow (IntegrityLabel), and aggregate effects (Capability).
from operon_ai import (
WiringDiagram, ModuleSpec, PortType,
DataType, IntegrityLabel, Capability,
)
diagram = WiringDiagram()
diagram.add_module(ModuleSpec(
name="membrane",
outputs={"clean_text": PortType(DataType.TEXT, IntegrityLabel.VALIDATED)},
))
diagram.add_module(ModuleSpec(
name="executor",
inputs={"prompt": PortType(DataType.TEXT, IntegrityLabel.VALIDATED)},
capabilities={Capability.EXEC_CODE},
))
diagram.connect("membrane", "clean_text", "executor", "prompt") # raises WiringError if invalid
print(diagram.required_capabilities())pip install operon-aiExplore the examples/ directory for runnable demonstrations:
| Example | Pattern | Description |
|---|---|---|
01_code_review_bot.py |
CFFL | Dual-check guardrails (executor + risk assessor) |
02_multi_model_consensus.py |
Quorum | Multi-agent voting with threshold consensus |
03_structured_extraction.py |
Chaperone | Schema validation for raw text |
04_budget_aware_agent.py |
ATP | Resource management with graceful degradation |
05_secure_chat_with_memory.py |
Membrane+Histone | Input filtering + learned memory |
06_sql_query_validation.py |
Chaperone | Domain-specific SQL validation |
| Example | Organelle | Description |
|---|---|---|
07_adaptive_membrane_defense.py |
Membrane | Adaptive immunity, antibody transfer, rate limiting |
08_multi_pathway_mitochondria.py |
Mitochondria | Safe AST computation, tool registry, ROS management |
09_advanced_chaperone_folding.py |
Chaperone | Multi-strategy folding, confidence scoring |
10_ribosome_prompt_factory.py |
Ribosome | Template synthesis, conditionals, loops, includes |
11_lysosome_waste_management.py |
Lysosome | Cleanup, recycling, autophagy, toxic disposal |
12_complete_cell_simulation.py |
All | Complete cellular lifecycle with all organelles |
| Example | System | Description |
|---|---|---|
13_advanced_metabolism.py |
Metabolism | Multi-currency (ATP/GTP/NADH), debt, regeneration, sharing |
14_epigenetic_memory.py |
Histone | Marker types, decay, reinforcement, inheritance |
15_genome_telomere_lifecycle.py |
Genome+Telomere | Immutable config, gene expression, lifecycle management |
16_network_topologies.py |
Topologies | Cascade, Oscillator, enhanced QuorumSensing |
17_wagent_typed_wiring.py |
WAgent | Typed wiring checker (integrity + capabilities) |
26_wiring_diagram_guarded_toolchain.py |
WAgent | Integrity upgrades, adapters, and approval-gated tool wiring |
27_wiring_diagram_resource_allocator.py |
WAgent | Resource-budget wiring with validation, fanout, and approvals |
28_wiring_diagram_quorum_consensus.py |
WAgent | Multi-agent votes aggregated into a trusted approval token |
29_wiring_diagram_safe_tool_calls.py |
WAgent | Approval-gated tool calls with validated planning |
30_wiring_diagram_composed_system.py |
WAgent | Composition via namespaced sub-diagrams and cross-links |
31_wiring_diagram_composed_effects.py |
WAgent | Composed system with net + filesystem effect aggregation |
32_wiring_diagram_execution.py |
WAgent | Minimal runtime executor for typed wiring diagrams |
33_wiring_diagram_execution_failures.py |
WAgent | Runtime failure cases (missing approval, type mismatch) |
34_wiring_diagram_nucleus_llm.py |
WAgent | Nucleus LLM wiring with context, validation, and feedback |
35_wiring_diagram_nucleus_execution.py |
WAgent | Execute a nucleus wiring with guarded tool flow |
36_wiring_diagram_multi_gemini_allocation.py |
WAgent | Resource allocation across multiple Gemini agents |
wiring_diagrams.md |
WAgent | ASCII + Mermaid wiring diagrams for examples 17, 26-37 |
| Example | System | Description |
|---|---|---|
18_cell_integrity_demo.py |
Integrity | Quality, Surveillance, and Coordination systems |
19_llm_code_assistant.py |
Nucleus+CFFL | Code generation with two-phase safety review |
20_llm_memory_chat.py |
Nucleus+Histone | Conversational AI with epigenetic memory |
21_llm_living_cell.py |
Full Cell | Complete lifecycle with LLM, memory, and aging |
22_llm_tool_use.py |
Nucleus+Mitochondria | LLM function calling with tool integration |
| Example | System | Description |
|---|---|---|
23_resilient_incident_response.py |
Multi-organelle | Incident triage, planning, coordinated execution, and quality gating |
24_governed_release_train.py |
Governance | Quorum + CFFL + feedback control with coordinated rollout |
25_resource_allocation_tradeoffs.py |
Resource Allocation | Nutrient, machinery, and energy budgeting with trade-offs |
37_metabolic_swarm_budgeting.py |
Coalgebra | Metabolic swarm with shared budget and halting guarantee |
Run any example:
# Clone and install
git clone https://github.com/coredipper/operon.git
cd operon
pip install -e .
# Run examples
python examples/07_adaptive_membrane_defense.py
python examples/12_complete_cell_simulation.pyOperon is grounded in a formal isomorphism between Gene Regulatory Networks (GRNs) and agentic architectures. Both can be modeled as polynomial functors in the category Polyβtyped interfaces where objects represent outputs and morphisms represent interactions. The key mapping:
- Gene β Agent (individual polynomial functor)
- Cell β Multi-agent system (composite of genes/agents)
| Biological Concept | Software Equivalent | Mathematical Object |
|---|---|---|
| Gene Interface | Agent Interface | Polynomial Functor (P) |
| Protein (output) | Tool Call / Message | Output Position (O) |
| Transcription Factor | Observation / Prompt | Input Direction (I) |
| Promoter Region | API Schema / Context Window | Lens (Optic) |
| Epigenetic Markers | Vector Store / Chat History | State Coalgebra |
| Signal Transduction | Data Pipeline | Morphism (β) |
Organelles (shared infrastructure within a cell/system):
| Organelle | Biological Function | Software Function |
|---|---|---|
| Ribosome | mRNA β Protein synthesis | Prompt Template Engine |
| Chaperone | Protein folding/validation | Schema Validator / JSON Parser |
| Lysosome | Waste processing (autophagy) | Error Handler / Garbage Collector |
| Nucleus | Transcription control | LLM Provider Wrapper |
| Membrane | Immune system (self/non-self) | Prompt Injection Defense |
| Mitochondria | ATP synthesis | Deterministic Tool Execution |
Lifecycle:
| Biological | Software | Function |
|---|---|---|
| Telomere Shortening | Operation Counter | Limits agent lifespan |
| Circadian Oscillator | Health Checks | Periodic maintenance |
| Apoptosis | Clean Shutdown | Graceful termination |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CELL (Multi-Agent System) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ β
β β MEMBRANE βββββΆβ NUCLEUS βββββΆβ MITOCHONDRIA β β
β β (Filter) β β (LLM/Think) ββββββ (Tools) β β
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ β
β β β β β
β β βΌ β β
β β βββββββββββββββ β β
β β β RIBOSOME β β β
β β β (Templates) β β β
β β βββββββββββββββ β β
β β β β β
β β βΌ βΌ β
β β βββββββββββββββ βββββββββββββββ β
β β β CHAPERONE β β HISTONE β β
β β β (Validate) β β (Memory) β β
β β βββββββββββββββ βββββββββββββββ β
β β β β
β βΌ βΌ β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β LYSOSOME β β
β β (Cleanup & Recycling) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Contributions welcome. Current areas of interest:
- Quorum algorithms: Additional voting strategies and Byzantine fault tolerance
- Provider integrations: New LLM backends beyond Anthropic/OpenAI/Gemini
- Network motifs: Implementations of additional biological control patterns
- Fork the repo
- Create your feature branch (
git checkout -b feature/your-feature) - Commit your changes
- Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.