Skip to main content
Glama

NocturnusAI

CI PyPI npm Docker License: BUSL-1.1 MCP

El motor de ingeniería de contexto para agentes de IA: envía solo lo que ha cambiado.

NocturnusAI — Motor de ingeniería de contexto para agentes de IA


Antes / Después

# ❌ Without NocturnusAI — replay everything, every turn
messages = system_prompt + full_history + tool_outputs   # ~1,259 tokens/turn
response = llm(messages)                                 # $13,600/mo at scale

# ✅ With NocturnusAI — send only what changed
ctx = nocturnus.process_turns(raw_turns)                 # extract → infer → delta
messages = system_prompt + ctx.briefing_delta             # ~221 tokens/turn
response = llm(messages)                                 # $2,400/mo. Same accuracy.

Related MCP server: RelayPlane

Las cifras

Medido en APIs en vivo. Conversación de soporte de producto de 15 turnos. Recuentos reales de usage.input_tokens. Ejecútalo tú mismo.

Reproducción ingenua

Optimizado con RAG

NocturnusAI

Tokens por turno

~1,259

~800

~221

Coste mensual (1K pet/h, Opus 4, $15/1M)

$13,600

$12,000

$2,400

Latencia

alta

media

baja

Preservación de la verdad

no

no

sí

Claude Opus 4: 5.7× de reducción. Gemini 2.0 Flash: 10.0×. Cálculos completos.


Instalación

pip install nocturnusai          # Python
npm install nocturnusai-sdk      # TypeScript
docker run -p 9300:9300 ghcr.io/auctalis/nocturnusai:latest  # Docker

O utiliza el asistente de configuración:

curl -fsSL https://raw.githubusercontent.com/Auctalis/nocturnusai/main/install.sh | bash

Por qué los desarrolladores marcan este repositorio

  • Reducción de tokens reproducible — benchmark en el repositorio, metodología publicada, ejecútalo contra tu propia carga de trabajo

  • Inferencia determinista — misma consulta, mismo resultado, siempre. Sin deriva de embeddings, sin lotería de similitud de coseno

  • Mantenimiento de la verdad — retira un hecho, todas las conclusiones derivadas se retiran automáticamente. Sin contexto obsoleto, sin alucinaciones sobre el estado operativo

  • Se conecta a pilas existentes — LangChain, LlamaIndex, CrewAI, AutoGen, MCP, Vercel AI SDK, OpenAI Agents SDK, Mastra

  • Comparable frente a la reproducción ingenua — números derivados, no inventados. Cada afirmación se remonta a una celda de notebook


Inicios rápidos de frameworks

Framework

Integración

Enlace

LangChain / LangGraph

NocturnusContextProvider directo, paso de traza de LangSmith

Docs

CrewAI

Contexto con ámbito de tarea por rol de agente

Docs

AutoGen

Servidor de contexto invocable por cualquier agente

Docs

MCP

Servidor compatible con especificaciones para Claude Desktop, Cursor, Continue

Config

OpenAI Agents SDK

Middleware de contexto, sin modificaciones de herramientas

Docs

Vercel AI SDK

Adaptador compatible con Edge para Next.js, Nuxt, SvelteKit

Docs

Python SDK

pip install nocturnusai

Docs

TypeScript SDK

npm install nocturnusai-sdk

Docs


Cómo funciona

Tres pasos. Cada turno.

  1. Extraer — turnos de conversación sin procesar → hechos estructurados mediante extracción por LLM

  2. Inferir — la inferencia lógica de encadenamiento hacia atrás encuentra solo los hechos alcanzables desde el objetivo actual del agente

  3. Devolver la diferencia — un briefingDelta que contiene solo lo que ha cambiado desde el último turno

Esto no es búsqueda vectorial. No es resumen. Es inferencia determinista en un motor lógico — indexación Hexastore, encadenamiento hacia atrás y mantenimiento de la verdad.


El bucle de trabajo

Se requiere LLM para turnos en lenguaje natural. Los ejemplos a continuación envían turnos de texto sin procesar a través de un LLM para extraer hechos estructurados. Si inicias el servidor sin un proveedor de LLM, los turnos en lenguaje natural devolverán cero hechos. Consulta Inicio rápido para ver las opciones de configuración, o utiliza la sintaxis de predicados (p. ej., "customer_tier(acme_corp, enterprise)") que funciona sin ningún LLM.

1. Primera reducción: POST /context

curl -X POST http://localhost:9300/context \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: default' \
  -d '{
    "turns": [
      "user: Customer says they are enterprise and blocked on SLA credits.",
      "tool: CRM says account is Acme Corp with a 2M ARR contract.",
      "agent: Last week support promised to review SLA eligibility.",
      "tool: Billing note says renewal is due next month."
    ],
    "maxFacts": 12
  }'

2. Paso impulsado por objetivos: POST /memory/context

curl -X POST http://localhost:9300/memory/context \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: default' \
  -d '{
    "goals": [{"predicate":"eligible_for_sla","args":["acme_corp"]}],
    "maxFacts": 12,
    "sessionId": "ticket-42"
  }'

3. Turnos posteriores: POST /context/diff

curl -X POST http://localhost:9300/context/diff \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: default' \
  -d '{"sessionId": "ticket-42", "maxFacts": 12}'

Devuelve solo las entradas added y removed entre instantáneas.

4. Fin del hilo: POST /context/session/clear

curl -X POST http://localhost:9300/context/session/clear \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: default' \
  -d '{"sessionId":"ticket-42"}'

Elige tu superficie

from nocturnusai import SyncNocturnusAIClient

with SyncNocturnusAIClient("http://localhost:9300") as client:
    ctx = client.process_turns(
        turns=[
            "user: Customer says they are enterprise and blocked on SLA credits.",
            "tool: CRM says account is Acme Corp with a 2M ARR contract.",
        ],
        scope="ticket-42",
        session_id="ticket-42",
    )

    diff = client.diff_context(session_id="ticket-42", max_facts=12)
    client.clear_context_session("ticket-42")

    print(ctx.briefing_delta)
import { NocturnusAIClient } from 'nocturnusai-sdk';

const client = new NocturnusAIClient({
  baseUrl: 'http://localhost:9300',
  tenantId: 'default',
});

const ctx = await client.processTurns({
  turns: [
    'user: Customer says they are enterprise and blocked on SLA credits.',
    'tool: CRM says account is Acme Corp with a 2M ARR contract.',
  ],
  scope: 'ticket-42',
  sessionId: 'ticket-42',
});

const diff = await client.diffContext({ sessionId: 'ticket-42', maxFacts: 12 });
await client.clearContextSession('ticket-42');
console.log(ctx.briefingDelta);
{
  "mcpServers": {
    "nocturnus": {
      "url": "http://localhost:9300/mcp/sse",
      "transport": "sse"
    }
  }
}

Utiliza la herramienta context en cada turno para obtener un conjunto de trabajo clasificado por relevancia. Empareja MCP con los endpoints de contexto HTTP cuando necesites ensamblaje y diferencias impulsados por objetivos.


Qué hay detrás del flujo de trabajo

Cuando necesitas mecanismos de backend, NocturnusAI los proporciona:

  • Almacenamiento determinista de hechos y reglas

  • Inferencia de encadenamiento hacia atrás con cadenas de prueba

  • Mantenimiento de la verdad y manejo de contradicciones

  • Hechos temporales con ttl, validFrom y validUntil

  • Multi-tenencia mediante X-Database y X-Tenant-ID

  • Superficies MCP, REST, Python SDK, TypeScript SDK y CLI sobre el mismo motor


Inicio rápido

Docker (más rápido)

docker run -d --name nocturnusai -p 9300:9300 \
  --restart unless-stopped \
  -v nocturnusai-data:/data \
  ghcr.io/auctalis/nocturnusai:latest
curl http://localhost:9300/health   # Verify it's running

Docker con Ollama (habilita la extracción en lenguaje natural)

docker run -d --name nocturnusai -p 9300:9300 \
  --add-host=host.docker.internal:host-gateway \
  -e LLM_PROVIDER=ollama \
  -e LLM_MODEL=granite3.3:8b \
  -e LLM_BASE_URL=http://host.docker.internal:11434/v1 \
  -e EXTRACTION_ENABLED=true \
  ghcr.io/auctalis/nocturnusai:latest

Desde este repositorio

make up-ollama && make smoke

CLI

nocturnusai                                # Interactive REPL
nocturnusai -e "context 10"               # Salience-ranked working set
nocturnusai -e "compress"                 # POST /memory/compress
nocturnusai -e "cleanup 0.05"             # POST /memory/cleanup

Documentación

Documentación completa: nocturnus.ai

Empieza aquí

El flujo de trabajo de reducción de turnos

Flujo de trabajo de contexto

Turnos sin procesar → optimizar → diferenciar → borrar

Referencia de API

Endpoints REST y formas de respuesta

SDKs

Métodos de cliente para Python y TypeScript

Integraciones

LangChain, CrewAI, AutoGen, MCP y más

Benchmark

Reducción de tokens medida en APIs en vivo

Cálculos

Cada número, derivado

Cómo funciona

La tubería de extracción → inferencia → delta


Docker Compose (avanzado)

git clone https://github.com/Auctalis/nocturnusai.git && cd nocturnusai

make up                                        # Server using .env.example defaults
make up-ollama                                 # + Ollama (reuses host or starts bundled)
make up-monitoring                             # + Prometheus + Grafana
make smoke                                     # Verify health + context endpoint

Construir desde la fuente

Requiere JDK 17+.

./gradlew :nocturnusai-server:run              # HTTP server on :9300
./gradlew :nocturnusai-cli:run                 # Interactive REPL (JVM)
./gradlew :nocturnusai-cli:nativeCompile       # Build native binary
./gradlew test                                 # Full test suite

Contribuir

Consulta CONTRIBUTING.md. Los problemas etiquetados como good first issue son buenos puntos de entrada.

Seguridad

Informa de vulnerabilidades de forma privada a través de GitHub Security Advisories. Consulta SECURITY.md.

Licencia

Business Source License 1.1 (SPDX: BUSL-1.1). Gratuito para uso interno —incluyendo producción interna— dentro de tu propia organización. Ofrecer NocturnusAI o una funcionalidad sustancial como producto/servicio alojado a terceros requiere una licencia comercial (licensing@nocturnus.ai). Se convierte a Apache 2.0 el 19-02-2030. Consulta LICENSE y DISCLAIMER.md.


AVISO LEGAL Y DE SEGURIDAD

NocturnusAI es un motor de razonamiento determinista, pero su salida es tan fiable como los hechos que se le proporcionan.

  1. Sin garantía de verdad. "Verificado" se refiere a la consistencia lógica de la inferencia, no a la precisión de las afirmaciones del mundo real.

  2. No apto para decisiones autónomas de alto riesgo. No utilices este motor para decisiones médicas, financieras, legales o de seguridad física sin supervisión sin un paso de verificación humana independiente.

  3. Solo capa lógica. NocturnusAI proporciona información e inferencia; no ejecuta acciones.

  4. Sin responsabilidad. Consulta DISCLAIMER.md y LICENSE.

Available Tools

16 tools
aggregateA

Compute aggregations over matching facts. Supports COUNT, SUM, MIN, MAX, and AVG over a numeric argument at a specified position. Example: COUNT all score(player, ?) facts, or AVG scores at argIndex=1. Side effects: none (read-only). Auth: requires X-Tenant-ID header; FACT_READ permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on unknown operation or missing argIndex for numeric ops.

Inputs: predicate (required), args (required), operation (required), argIndex, +1 more.

askA

Query the knowledge base using multi-step logical reasoning (backward chaining with unification). Finds all provable answers by applying rules and matching facts. Use ?-prefixed variables for unknowns; optionally returns full proof chains. Side effects: none (read-only). Auth: requires X-Tenant-ID header; FACT_READ permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args; result set bounded by INFERENCE_MAX_RESULTS (default 10,000) to prevent OOM.

Inputs: predicate (required), args (required), scope, withProof, +1 more.

bulk_assertA

Assert multiple facts in a single call for efficiency. Non-transactional: each fact is attempted independently — contradictions are reported without aborting the batch. Returns counts of successful and failed assertions. Side effects: mutates state (additive) — partial successes persist even if other facts in the batch fail. Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on malformed input; per-fact failures returned in the response's errors array.

Inputs: facts (required).

cleanupA

Run memory decay and eviction. Expires facts past their TTL and evicts low-salience facts when memory exceeds capacity. Call periodically in long-running agent sessions to prevent unbounded growth. Side effects: DESTRUCTIVE — permanently removes evicted and expired facts (irreversible). Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad threshold.

Inputs: threshold.

compressA

Run memory consolidation: detects repeated episodic patterns (e.g., 'user asked about X five times') and creates semantic summaries. Reduces memory footprint in long-running sessions while preserving essential knowledge. Side effects: mutates state (additive) — creates new summary facts; original facts remain intact. Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args.

Inputs: no named parameters.

contextA

Get the most relevant knowledge for the current reasoning step, ranked by composite salience (recency × frequency × priority). Returns a token-optimized context window in 'predicate', 'natural', or 'structured' format. Pass goals for goal-driven selection, sessionId for incremental diffs across turns. Side effects: read-only for stored facts (salience access counters may update internally). Auth: requires X-Tenant-ID header; FACT_READ permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args.

Inputs: maxFacts, minSalience, predicates, scope, +6 more.

delete_scopeA

Delete a named scope and all facts within it. Use to clean up completed or abandoned hypothetical reasoning branches. Side effects: DESTRUCTIVE and IRREVERSIBLE — permanently removes all facts in the scope; cascades TMS retraction for any derived facts. Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR if scope name is blank.

Inputs: scope (required).

forgetA

Retract a fact from the knowledge base. Inverse of 'tell'. Side effects: DESTRUCTIVE — triggers cascading retraction of any knowledge derived from this fact via the Truth Maintenance System (irreversible). Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args (no error if the fact was not present).

Inputs: predicate (required), args (required), scope.

fork_scopeA

Fork a knowledge base scope — creates an independent copy of all facts in the source scope under a new target scope name. Use for hypothetical reasoning ('What if Alice moves to London?') without modifying the main knowledge base. Similar to git branch for knowledge. Side effects: mutates state (additive) — creates a new scope with copied facts; source scope is unchanged. Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR if targetScope is blank or already exists.

Inputs: targetScope (required), sourceScope.

list_scopesA

List all named scopes in the knowledge base. Shows what hypothetical contexts or reasoning branches exist. The global (unscoped) partition is always present but not listed. Side effects: none (read-only). Auth: requires X-Tenant-ID header; FACT_READ permission when auth is enabled. Rate-limited per principal. Errors: none under normal operation.

Inputs: no named parameters.

merge_scopeA

Merge facts from one scope into another (default: global). Use to commit hypothetical reasoning back into the main knowledge base. Strategy controls conflict handling: SOURCE_WINS overwrites, TARGET_WINS keeps existing, KEEP_BOTH retains both, REJECT aborts on conflict. Side effects: mutates the target scope; may overwrite existing facts depending on strategy (potentially destructive under SOURCE_WINS). Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on unknown strategy; CONFLICT_ERROR when strategy=REJECT and conflicts are found.

Inputs: sourceScope (required), targetScope, strategy.

predicatesA

Discover the knowledge base schema. Lists all predicates currently stored with arity (argument count), fact count, and whether they have associated rules. Use this before querying to understand what knowledge is available. Side effects: none (read-only). Auth: requires X-Tenant-ID header; FACT_READ permission when auth is enabled. Rate-limited per principal. Errors: none under normal operation.

Inputs: scope.

recallA

Time-travel query: recall what was known at a specific point in time. Returns facts valid at the given timestamp, respecting temporal bounds (validFrom, validUntil, ttl). Useful for debugging agent behavior or reconstructing past state. Side effects: none (read-only). Auth: requires X-Tenant-ID header; FACT_READ permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args or missing timestamp.

Inputs: predicate (required), args (required), timestamp (required), scope.

retract_patternA

Retract all facts matching a pattern in a single call. Use ?-prefixed variables as wildcards to retract multiple facts at once. Returns the count and list of retracted facts. Side effects: DESTRUCTIVE — removes multiple facts and cascades TMS retraction for each removed fact (irreversible). Auth: requires X-Tenant-ID header; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args.

Inputs: predicate (required), args (required), scope.

teachA

Define a logical rule for automatic reasoning. When body conditions hold, head becomes derivable via backward chaining. Use ?-prefixed variables; supports Negation-as-Failure. Example: 'If ?x is human AND NOT god(?x), THEN ?x is mortal'. Side effects: mutates state (additive) — rules remain active until explicitly removed. Auth: requires X-Tenant-ID header; RULE_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on malformed rules.

Inputs: head (required), body (required), scope.

tellA

Assert a fact into the knowledge base. Stores knowledge queryable via logical reasoning. Supports TTL expiration, confidence scoring, and configurable conflict resolution. Side effects: mutates state (additive) — stored facts persist until retracted or expired. Auth: requires X-Tenant-ID header for tenant isolation; FACT_WRITE permission when auth is enabled. Rate-limited per principal. Errors: VALIDATION_ERROR on bad args, CONFLICT_ERROR on contradictions when conflictStrategy=REJECT.

Inputs: predicate (required), args (required), scope, negated, +4 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 16 tools

    Disambiguation5/5

    Each tool targets a distinct operation: tell/forget/retract_pattern for facts, teach for rules, ask/aggregate/context/recall for queries, scope management tools, and memory maintenance tools. No two tools have overlapping purposes; clear boundaries between them.

    Naming Consistency3/5

    Naming is mixed: some tools use verb_noun (bulk_assert, delete_scope), others are single verbs (ask, forget), and one is a noun (context). While each name is individually clear, the lack of a consistent pattern reduces predictability.

    Tool Count4/5

    16 tools is slightly above the typical range but justified by the complexity of the knowledge base domain (fact management, rules, queries, scopes, memory). Each tool serves a clear purpose.

    Completeness4/5

    The surface covers core CRUD for facts, queries, scopes, schema discovery, and memory management. A minor gap is the absence of a tool to list or remove defined rules, but the overall coverage is strong.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      An implementation of persistent memory for Claude using a local knowledge graph, allowing the AI to remember information about users across conversations with customizable storage location.
      11
      62
      JavaScript
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables efficient AI workflow orchestration by chaining multi-step LLM operations while keeping intermediate results out of the context window, reducing token usage by 90%+ and supporting multiple AI providers.
      7
      41 npm
      1
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      A production-ready reasoning engine that integrates Claude AI with specialized MCP tools for knowledge retrieval, schema validation, and domain-specific rubric evaluation. It enables structured RAG-based analysis across legal, health, and science domains via a RESTful API.
      -
    • A
      license
      A
      quality
      D
      maintenance
      Provides versioned, structured memory for AI agents, allowing them to store facts, detect conflicts, and track knowledge history via a hosted SaaS platform. It enables efficient hierarchical information retrieval and semantic search while keeping token usage constant as memory scales.
      7
      20 npm
      8
      Apache 2.0