Skip to main content

Context Engineering Multi-Agent Framework - A pluggable, modular framework for building AI agent systems

Project description

CEMAF

Context Engineering Multi-Agent Framework

Open Source Project Status: Alpha Discord Python License Tests Coverage CI Ruff MyPy Stars Issues Open Startup

Open source context engineering infrastructure that solves the hard problems in AI agent systems. CEMAF can be used standalone or plugged into existing frameworks like LangGraph, AutoGen, and CrewAI.


Table of Contents


Overview

CEMAF is a protocol-first framework designed for context engineering in multi-agent AI systems. It provides:

  • Token budgeting and automatic context optimization
  • Deterministic run recording and replay capabilities
  • Full provenance tracking for every context change
  • Memory management with strict scoping and TTL
  • Zero-config defaults with environment-based customization

Philosophy: Own the hard infrastructure problems while remaining framework-agnostic.

Design: Protocol-based architecture where modules work standalone. Use our defaults or replace them with your own implementations. See Protocol Guide for details.


The Hard Problems We Solve

Problem What Happens CEMAF Solution
Context Growth Token limits blow up Token budgeting + automatic summarization
Reliability Non-deterministic behavior Patch-based provenance tracking
Cost Wasteful token usage Smart context compilation
Reproducibility Can't replay/debug runs Run recording + deterministic replay
Memory Leaks State bleeds between scopes Strict memory boundaries with TTL
Content Safety Harmful outputs slip through Pre/post-flight moderation gates + PII detection
Quality Drift Output quality degrades silently Online eval pipeline with rolling monitors and halt gates
Prompt Engineering Inconsistent LLM outputs Semantic blueprints for structured content generation

Installation

# Core installation (minimal dependencies)
pip install cemaf

# With optional integrations
pip install "cemaf[openai]"        # OpenAI + tiktoken
pip install "cemaf[anthropic]"     # Anthropic
pip install "cemaf[tiktoken]"      # Accurate token counting only
pip install "cemaf[prometheus]"    # Prometheus metrics export
pip install "cemaf[all]"           # All optional dependencies

# Development installation
git clone https://github.com/drchinca/cemaf.git
cd cemaf
pip install -e ".[dev]"

Requirements: Python 3.14+


Quick Start

from cemaf.context import Context, ContextPatch
from cemaf.observability import InMemoryRunLogger
from cemaf.replay import Replayer
from cemaf.blueprint import Blueprint, SceneGoal, StyleGuide
from cemaf.moderation import ModerationPipeline, PreFlightGate, KeywordRule, PIIRule

# Create context with provenance tracking
ctx = Context()
patch = ContextPatch.from_tool("search", "results", {"items": [...]})
ctx = ctx.apply(patch)

# Record runs for replay
logger = InMemoryRunLogger()
logger.start_run("run-123", initial_context=ctx)
logger.record_patch(patch)
record = logger.end_run(final_context=ctx)

# Replay deterministically
replayer = Replayer(record)
result = await replayer.replay()
assert result.final_context == record.final_context  # Deterministic!

# Use semantic blueprints for structured content generation
blueprint = Blueprint(
    id="social-post",
    name="Social Media Post",
    scene_goal=SceneGoal(objective="Create engaging social media content"),
    style_guide=StyleGuide(tone="casual", length_hint="concise")
)
prompt = blueprint.to_prompt()  # Convert to LLM-ready prompt

# Add content safety with moderation guardrails
moderation = ModerationPipeline(
    pre_flight=PreFlightGate([KeywordRule(["spam", "scam"]), PIIRule()])
)
result = await moderation.check_input(user_message)
if not result.allowed:
    raise ValueError(f"Content blocked: {result.violations}")

See the Quick Start Guide for more detailed examples.


Integration Modes

Mode A: CEMAF Orchestrates

CEMAF owns execution, external frameworks are "engines":

from cemaf.orchestration import DAGExecutor
from cemaf.observability import InMemoryRunLogger

executor = DAGExecutor(
    node_executor=LangGraphNodeExecutor(langgraph_app),
    run_logger=InMemoryRunLogger(),
)
result = await executor.run(dag, context)

# Replay later for debugging
replayer = Replayer(run_logger.get_record("run-123"))
await replayer.replay()

Mode B: CEMAF as Library

External frameworks orchestrate, CEMAF provides infrastructure:

from cemaf.context import Context, ContextPatch
from cemaf.observability import InMemoryRunLogger

@langgraph_node
def my_node(state):
    ctx = Context.from_dict(state)

    # Track provenance of every change
    patch = ContextPatch.from_tool("search", "results", search_results)
    ctx = ctx.apply(patch)
    run_logger.record_patch(patch)

    # Compile within budget
    compiled = compiler.compile(ctx, budget)
    return compiled.to_dict()

See the Integration Guide for detailed patterns.


Key Features

Context Engineering

  • Context Patches: Track every context change with full provenance
  • Token Budgeting: Stay within limits with smart compilation (greedy, knapsack, optimal algorithms)
  • Deterministic Replay: Record and replay runs for debugging
  • Glass Box Audit: Full provenance chain linking every LLM call to its context sources, citations, and costs
  • Context Type Classification: RESOURCE/MEMORY/SKILL behavioral semantics with per-type compaction rules
  • Semantic Blueprints: Structured content generation with Denis Rothman's blueprint pattern
  • Recursive LLM: Parallel divide-and-conquer querying for 1M+ token contexts

Memory System

  • Strict Scoping: Memory boundaries with TTL prevent state leaks
  • Three-Tier Progressive Loading: L0 abstract / L1 overview / L2 full content for token-efficient retrieval
  • Semantic Deduplication: Exact key + embedding similarity detection with merge/skip resolution
  • Post-Session Extraction: Automatic promotion of session learnings to long-term memory (patterns, corrections, facts)
  • Hierarchical Scope Propagation: Parent-to-child score propagation for scope-aware retrieval
  • SQLite Persistence: Production-ready persistent memory store via aiosqlite

Online Evaluation

  • Hierarchical Judge: Three-tier evaluation -- fast deterministic checks, semantic similarity, LLM judge (escalates only when needed)
  • Online Eval Pipeline: Subscribe to execution events and run evaluators on node outputs in real-time
  • Quality Police: Rolling window quality monitor with anomaly detection and automatic halt gates
  • Eval Tools & Agents: RunEvalTool, CheckQualityTool, RecordScoreTool, QualityGuardAgent -- dogfooding the eval system as CEMAF tools

Production Backends

  • Resilient LLM Client: Retry with exponential backoff + circuit breaker + rate limiter composing around any LLMClient
  • OpenAI Embeddings: Production embedding provider using text-embedding-3-small with batch support
  • Structured Logging: JSON-lines logger with context fields for production observability
  • Prometheus Metrics: Counter/gauge/histogram/timing export with lazy metric registration

Orchestration

  • DAG Executor: Topological sort, parallel execution, conditional routing, loop nodes, cooperative cancellation
  • Node Type Handlers: Extracted router, conditional, loop, parallel handlers for clean separation
  • RuntimeServices: Frozen dataclass bundling 15+ optional dependencies for composition root
  • Bootstrap: Single create_executor() entry point wiring registry, services, and subscriptions
  • Context Agents: Built-in Librarian, Researcher, Summarizer, Writer agents with dynamic registry
  • Budget Guard: Configurable cost and token limits with warning/critical/halt thresholds

Infrastructure

  • Protocol-Based: Plug into any framework -- modules work standalone, extend with your own implementations
  • Extensible Registries: ProviderRegistry pattern for pluggable LLM, compiler, and retrieval backends
  • Instrumented LLM: Transparent LLM call recording for automatic glass box audit
  • Moderation & Guardrails: Pre/post-flight content safety with PII detection and compliance rules
  • Configuration-Driven: Zero-config defaults with .env customization
  • Resilience: Retry, circuit breaker, rate limiting as composable decorators

Self-Hosting Engine (v0.2.0)

CEMAF is its own first client — three opt-in modules where the framework uses its own primitives to introspect, audit, and extend itself. Fully decoupled from the base framework.

  • Audit Trail: EventBusAuditLog subscribes to EventBus, converts events into queryable AuditEntry records with quality trend analysis and z-score anomaly detection
  • Knowledge Graph: MemoryBackedKnowledgeGraph — entities and relations backed by MemoryManager with semantic search and neighbor traversal
  • Meta-Agents: MetaArchitect (DAG design), MetaSynthesizer (code gen), MetaAuditor (trace analysis), MetaKnowledgeGraph (KG operations)
  • Pre-built DAGs: create_self_audit_dag(), create_feature_synthesis_dag(), create_knowledge_refresh_dag()
  • Entry point: create_meta_executor() wraps create_executor(), auto-wires audit + KG from RuntimeServices

Documentation

Full Documentation →

Getting Started

Core Guides

Module References


Configuration

CEMAF is designed for zero-config startup with production-ready defaults. Customize via environment variables:

# Copy example configuration
cp .env.example .env

# Configure your setup
CEMAF_LLM_PROVIDER=openai
CEMAF_LLM_API_KEY=your-key
CEMAF_CACHE_BACKEND=redis
CEMAF_CACHE_MAX_SIZE=10000

Use factory functions for automatic configuration loading:

from cemaf.llm import create_llm_client_from_config
from cemaf.cache import create_cache_from_config

# Automatically loads from .env or environment
client = create_llm_client_from_config()
cache = create_cache_from_config()

See the Configuration Guide for all available settings.


Testing

# Run all tests
pytest tests/

# Unit tests only
pytest tests/unit/

# Skip slow tests
pytest tests/ -m "not slow"

# With coverage
pytest tests/ --cov=cemaf

# Pre-commit checks
pre-commit run --all-files

Project Stats: 2301+ tests | 100% passing | TDD from day one


Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development setup:

# Fork and clone the repo
git clone https://github.com/YOUR_USERNAME/cemaf.git
cd cemaf

# Install dependencies with uv
uv venv
uv sync

# Install pre-commit hooks
uv run pre-commit install

See HOW_TO_USE.md for detailed usage examples.


Getting Help

We're here to help! Here are the best ways to get support:

Documentation

Community

Contributing

Want to contribute? Check out our Contributing Guide to get started!

We're in Alpha and actively seeking feedback!


Philosophy & Open Startup

CEMAF operates as an open startup - we believe in radical transparency, community collaboration, and building in public.

Our Principles

  • Community First: We serve developers building AI agents
  • Transparent: All decisions, metrics, and roadmap are public
  • Bias Toward Action: Show > tell. Open PRs, not long debates
  • Anyone Can Help: Contribution > credentials
  • Learn in Public: We share wins AND mistakes

Resources

We're building CEMAF together. Your voice matters.


License

This project is licensed under the MIT License - see the LICENSE file for details.


Authors

Hikuri Bado Chinca (@drchinca) Email: chincadr@gmail.com

Copyright (c) 2026 | Published on 1.1.2026 🎉


Links

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

cemaf-0.2.1.tar.gz (791.0 kB view details)

Uploaded Source

Built Distribution

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

cemaf-0.2.1-py3-none-any.whl (414.5 kB view details)

Uploaded Python 3

File details

Details for the file cemaf-0.2.1.tar.gz.

File metadata

  • Download URL: cemaf-0.2.1.tar.gz
  • Upload date:
  • Size: 791.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cemaf-0.2.1.tar.gz
Algorithm Hash digest
SHA256 be8e0edecafd0c0e7e84a239a06b060c96ed838787f00695fca618e7f368761a
MD5 176d54683f3ade4e7188d7a048230f12
BLAKE2b-256 362f01e8d95d512a1b82646ec6dae3da586de8697dc0b1e1f3b0cc6e334ee0f5

See more details on using hashes here.

Provenance

The following attestation bundles were made for cemaf-0.2.1.tar.gz:

Publisher: publish-to-pypi.yml on drchinca/cemaf

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

File details

Details for the file cemaf-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: cemaf-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 414.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cemaf-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 55b5620fe0f5322b4086bc6d35817da912b83be084c5c798f435239cfae4acac
MD5 eccae533c928af3db81c5d3bb09c081f
BLAKE2b-256 cf4f8a4b99c145b407e66772d3311512fafc8ce0a4dcf9acb36fb57c5f701c45

See more details on using hashes here.

Provenance

The following attestation bundles were made for cemaf-0.2.1-py3-none-any.whl:

Publisher: publish-to-pypi.yml on drchinca/cemaf

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