Skip to main content

Ejentum Python SDK

PyPI Version License: MIT Latency

The official Python SDK for Ejentum: Deterministic Reasoning-Augmented Retrieval (RAR) Cognitive Infrastructure.

Ejentum indexes 300+ deterministic mental models and cognitive scaffolds. In less than 80ms, it retrieves and injects the optimal reasoning scaffold into your LLM prompt, eliminating hallucinated leaps, sycophantic shortcuts, and premature convergence in production AI agents.


Official Resources


Installation

pip install ejentum

Zero dependencies required. Uses Python standard library only. Optional framework integrations for OpenAI, Anthropic, LangChain, LangGraph, and CrewAI.


Authentication

Export your API key in your environment (or pass api_key="..." directly to the client):

export EJENTUM_API_KEY="ej_live_your_key_here"

Need an API key? Get instant access at ejentum.com/pricing.


Quickstart

1. Basic Scaffold Retrieval

from ejentum import Ejentum

client = Ejentum()

# Retrieve the deterministic cognitive scaffold for any query (<80ms)
scaffold = client.scaffold("diagnose PostgreSQL high CPU and lock contention")
print(scaffold)

2. Auto-Augment a Prompt

# Automatically prepends the scaffold instruction block to your task prompt
prompt = "Design a failover strategy for our payment processing service."
augmented_prompt = client.augment(prompt, mode="reasoning")

print(augmented_prompt)
# Output:
# Apply the cognitive scaffold below, then answer the user's task.
# [COGNITIVE SCAFFOLD]
# ... [Deterministic Causal / Resiliency Scaffold] ...
# [END SCAFFOLD]
# Design a failover strategy for our payment processing service.

3. Recursive Multi-Hop Cognitive DAG (depth=2)

For complex agent workflows, generate a recursive Directed Acyclic Graph (DAG) across the 933-edge synergy graph with an automated 4-stage execution plan:

# Retrieve 2-hop topological execution plan and compound scaffold
graph_plan = client.graph("Migrate 50M rows across sharded PostgreSQL database", depth=2)

print("Root Operator:", graph_plan["dag"]["root"])
print("Execution Stages:", len(graph_plan["dag"]["execution_plan"]))
for stage in graph_plan["dag"]["execution_plan"]:
    print(f"  Stage {stage['stage']} ({stage['phase']}): {stage['abilities']}")

# Injects 4-stage cognitive scaffold (prerequisites -> root -> compounding multipliers -> fallbacks)
scaffold = graph_plan["graph_scaffold"]

Perform lightning-fast full-text keyword searches with BM25 ranking across the 311 ability catalog:

# Sub-1ms SQLite FTS5 query
results = client.fts_search("deadlock circular dependency sequence", limit=3)

for match in results["results"]:
    print(f"[{match['ability_id']}] {match['ability_name']} ({match['domain']}) - Rank: {match['rank']}")

Drop-in Wrappers

OpenAI Drop-in

Wrap your existing OpenAI() client. All chat.completions.create calls will automatically fetch and inject the optimal Ejentum scaffold before invoking OpenAI:

from openai import OpenAI
from ejentum import wrap_openai

# Wrap your existing client in 1 line:
client = wrap_openai(OpenAI())

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "Diagnose silent failure in checkout webhooks"}
    ],
    ejentum_mode="reasoning"  # Optional: defaults to "reasoning"
)

print(response.choices[0].message.content)

Anthropic Drop-in

from anthropic import Anthropic
from ejentum import wrap_anthropic

client = wrap_anthropic(Anthropic())

response = client.messages.create(
    model="claude-3-7-sonnet-20250219",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Refactor auth token refresh to prevent race condition"}
    ]
)

print(response.content[0].text)

LangChain and Agent Loop Integration

from ejentum import Ejentum
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

ejentum = Ejentum()

def scaffold_runnable(inputs):
    scaffold = ejentum.scaffold(inputs["task"])
    return {
        "system_scaffold": f"Apply this scaffold:\n{scaffold}",
        "task": inputs["task"]
    }

prompt = ChatPromptTemplate.from_messages([
    ("system", "{system_scaffold}"),
    ("user", "{task}")
])

chain = scaffold_runnable | prompt | ChatOpenAI(model="gpt-4o")
result = chain.invoke({"task": "Plan a zero-downtime database migration for 50M rows."})

Advanced Architecture (v1.9.0)

Drop-In @guard_tool & Temporal Safety Recipes

Enforce deterministic pre-condition and ordering invariants on agent tools with one-line decorators and curated safety recipes:

from ejentum import TemporalGuard, get_temporal_recipe

guard = TemporalGuard(rules=get_temporal_recipe("database_migration"))

@guard.protect(action="run_dry_run_migration")
def run_dry_run():
    return "dry_run_ok"

@guard.protect(action="write_db", requires_prior="run_dry_run_migration")
def apply_migration():
    return "migration_applied"

run_dry_run()
print("Migration Result:", apply_migration())

Negative-Constraint Dead-End Memory

Record failed actions per session so subsequent scaffold retrievals automatically inject prohibited paths and prevent repeated retry loops:

from ejentum import Ejentum

client = Ejentum()
client.record_dead_end(
    session_id="incident_42",
    failed_action="restart_pgbouncer",
    error_summary="Connection pool exhausted immediately due to zombie locks"
)
scaffold = client.scaffold("Resolve database connection saturation", session_id="incident_42")
print("Dead-End Guard Active:", "PROHIBITED DEAD-END PATHS" in scaffold)

Turnkey ISO 42001 / SOC2 Audit Evidence Export

Generate a signed, deterministic compliance evidence bundle capturing guardrail applications, traces, and dead-end ledgers:

evidence = client.export_audit_evidence(framework="ISO-42001-SOC2")
print("Compliance Events Logged:", evidence["summary"]["total_audit_events"])
print("Bundle Signature Verified:", evidence["bundle_attestation"]["verified"])

1-Click MCP Server Configuration

Copy and paste the configuration below into Cursor, Claude Desktop, or Antigravity to connect the Ejentum MCP server:

{
  "mcpServers": {
    "ejentum": {
      "command": "python",
      "args": ["-m", "ejentum.mcp"],
      "env": {
        "EJENTUM_API_KEY": "ej_live_your_key_here"
      }
    }
  }
}

Multi-Agent Handshake Engine

Prevent agent communication collapse, circular delegation, and assumption compounding with deterministic runtime contracts:

from ejentum import HandshakeEngine, AgentRole, get_preset_topology

engine = HandshakeEngine(topology=get_preset_topology("hierarchical_triage"))
contract = engine.propose(
    sender_role=AgentRole.COORDINATOR,
    recipient_role=AgentRole.SPECIALIST,
    task_scope="Verify database schema migrations against lock contention limits"
)
print("Contract Status:", contract.status)

Temporal Policy Guard

Enforce strict ordering constraints, required prerequisites, and forbidden actions across multi-step execution traces:

from ejentum import TemporalGuard, RequirePriorRule, ForbidFollowingRule

guard = TemporalGuard(rules=[
    RequirePriorRule(action="execute_transaction", required_prior="acquire_idempotency_lock"),
    ForbidFollowingRule(action="delete_record", forbidden_following="read_record")
])

# 1. Block action when prerequisites are missing:
verdict = guard.verify_action("execute_transaction")
print("Allowed:", verdict.is_valid)  # False

# 2. Allow action once prerequisites are recorded:
guard.record_action("acquire_idempotency_lock")
verdict = guard.verify_action("execute_transaction")
print("Allowed:", verdict.is_valid)  # True

Enterprise Checkpoint Storage

State management with swappable backends:

from ejentum import create_checkpoint_store

# Supported: memory, file, redis, s3, gcs
store = create_checkpoint_store("memory")
store.save_checkpoint("session_123", {"step": 4, "state": "verified"})

API Reference

Ejentum(api_key=None, base_url="https://api.ejentum.com/logicv1/", timeout=10.0)

  • scaffold(query: str, mode="reasoning") -> str: Returns the raw cognitive scaffold string for system prompt injection.
  • graph(query: str, depth: int = 1) -> dict: Returns the Cognitive DAG across the 933-edge synergy graph. Supports depth=1 and depth=2 (4-stage recursive execution plan).
  • fts_search(query: str, limit: int = 4) -> dict: Executes sub-millisecond SQLite FTS5 full-text keyword search and BM25 ranking.
  • augment(prompt: str, mode="reasoning") -> str: Prepends the cognitive scaffold instruction block directly to your prompt string.
  • augment_messages(messages: list[dict], mode="reasoning") -> list[dict]: Augments an OpenAI/Anthropic messages list in-place or prepends to the system message.
  • feedback(ability_id: str, outcome="success", score=1.0, query="", comment="") -> dict: Submits execution telemetry to calibrate adaptive retrieval weights.
  • get_ability(query: str, mode="reasoning") -> dict: Returns the full metadata payload including ability_id and matched domain.

License

MIT (c) Ejentum.com

Metadata

Release files for ejentum 1.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ejentum 1.9.0
File Size Uploaded Provenance Actions
ejentum-1.9.0.tar.gz 75.1 kB Without provenance Details for ejentum-1.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ejentum 1.9.0
File Interpreter ABI Platform Actions
ejentum-1.9.0-py3-none-any.whl Python 3 none any Details for ejentum-1.9.0-py3-none-any.whl

Total release size: 138.3 kB

Release files / ejentum-1.9.0.tar.gz

Download URL ejentum-1.9.0.tar.gz
Size 75.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2105f706d88ee05572e5f586509d56d35358be86e8621beb23c8f49cba40e983
BLAKE2b-256 checksum
How to use checksums
ac4e537ff87fc440a36c462748dea4bfd0681ddfd1ec49373510a9cf772cf7c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / ejentum-1.9.0-py3-none-any.whl

Download URL ejentum-1.9.0-py3-none-any.whl
Size 63.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fe70b08f074a8ab1c72969c719409f26da3f4775209d59b7ef7f0c4be86825ea
BLAKE2b-256 checksum
How to use checksums
a79f2d8dc2b5ba1f61253edad23049c4c8395d0e5b6268414a72cabc27872678
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for ejentum 1.9.0

Provenance

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page