Skip to main content
Glama

NocturnusAI

CI PyPI npm Docker License: BUSL-1.1 MCP

AI 에이전트를 위한 컨텍스트 엔지니어링 엔진: 변경된 내용만 전송하세요.

NocturnusAI — AI 에이전트를 위한 컨텍스트 엔지니어링 엔진


이전 / 이후

# ❌ 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

수치

실제 API에서 측정되었습니다. 15턴의 제품 지원 대화. 실제 usage.input_tokens 카운트. 직접 실행해 보세요.

단순 재생

RAG 최적화

NocturnusAI

턴당 토큰

~1,259

~800

~221

월 비용 (1K 요청/시간, Opus 4, $15/1M)

$13,600

$12,000

$2,400

지연 시간

높음

중간

낮음

진실 보존

아니요

아니요

예

Claude Opus 4: 5.7배 감소. Gemini 2.0 Flash: 10.0배. 전체 계산 내역.


설치

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

또는 설정 마법사를 사용하세요:

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

개발자들이 이 저장소에 별을 주는 이유

  • 재현 가능한 토큰 감소 — 저장소 내 벤치마크, 방법론 공개, 자신의 워크로드에 직접 실행 가능

  • 결정론적 추론 — 동일한 쿼리, 동일한 결과, 매번 동일함. 임베딩 드리프트나 코사인 유사도 복권 없음

  • 진실 유지 — 사실을 철회하면 파생된 모든 결론이 자동으로 철회됨. 오래된 컨텍스트나 운영 상태에 대한 환각 없음

  • 기존 스택에 연결 — LangChain, LlamaIndex, CrewAI, AutoGen, MCP, Vercel AI SDK, OpenAI Agents SDK, Mastra 지원

  • 단순 재생 대비 벤치마크 가능 — 수치는 발명된 것이 아니라 도출된 것임. 모든 주장은 노트북 셀로 추적 가능


프레임워크 퀵스타트

프레임워크

통합

링크

LangChain / LangGraph

드롭인 NocturnusContextProvider, LangSmith 트레이스 패스스루

문서

CrewAI

에이전트 역할별 작업 범위 컨텍스트

문서

AutoGen

모든 에이전트가 호출 가능한 컨텍스트 서버

문서

MCP

Claude Desktop, Cursor, Continue용 사양 준수 서버

설정

OpenAI Agents SDK

컨텍스트 미들웨어, 도구 수정 불필요

문서

Vercel AI SDK

Next.js, Nuxt, SvelteKit용 엣지 호환 어댑터

문서

Python SDK

pip install nocturnusai

문서

TypeScript SDK

npm install nocturnusai-sdk

문서


작동 원리

세 단계. 매 턴마다.

  1. 추출 — 원시 대화 턴 → LLM 추출을 통한 구조화된 사실

  2. 추론 — 역방향 체인 논리 추론을 통해 에이전트의 현재 목표에서 도달 가능한 사실만 찾음

  3. 델타 반환 — 마지막 턴 이후 변경된 내용만 포함하는 briefingDelta 반환

이것은 벡터 검색이 아닙니다. 요약도 아닙니다. 논리 엔진에서의 결정론적 추론입니다 — Hexastore 인덱싱, 역방향 체인, 진실 유지를 사용합니다.


작업 루프

자연어 턴에는 LLM이 필요합니다. 아래 예제는 원시 텍스트 턴을 LLM에 보내 구조화된 사실을 추출합니다. LLM 제공자 없이 서버를 시작하면 자연어 턴은 0개의 사실을 반환합니다. 설정 옵션은 퀵스타트를 참조하거나, LLM 없이 작동하는 술어 구문(예: "customer_tier(acme_corp, enterprise)")을 사용하세요.

1. 첫 번째 감소: 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. 목표 중심 패스: 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. 이후 턴: 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}'

스냅샷 간의 added 및 removed 항목만 반환합니다.

4. 스레드 종료: 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"}'

인터페이스 선택

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"
    }
  }
}

매 턴마다 context 도구를 사용하여 중요도 순으로 정렬된 작업 세트를 얻으세요. 목표 중심 어셈블리 및 차이점이 필요할 때 MCP와 HTTP 컨텍스트 엔드포인트를 함께 사용하세요.


워크플로우의 기반

백엔드 메커니즘이 필요할 때 NocturnusAI는 다음을 제공합니다:

  • 결정론적 사실 및 규칙 저장소

  • 증명 체인을 포함한 역방향 체인 추론

  • 진실 유지 및 모순 처리

  • ttl, validFrom, validUntil을 포함한 시간적 사실

  • X-Database 및 X-Tenant-ID를 통한 멀티 테넌시

  • 동일한 엔진 위에서 MCP, REST, Python SDK, TypeScript SDK 및 CLI 인터페이스 제공


퀵스타트

Docker (가장 빠름)

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

Ollama를 포함한 Docker (자연어 추출 활성화)

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

이 저장소에서

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

문서

전체 문서: nocturnus.ai

여기서 시작

턴 감소 워크플로우

컨텍스트 워크플로우

원시 턴 → 최적화 → 차이점 → 지우기

API 참조

REST 엔드포인트 및 응답 형태

SDK

Python 및 TypeScript 클라이언트 메서드

통합

LangChain, CrewAI, AutoGen, MCP 등

벤치마크

실제 API에서 측정된 토큰 감소량

계산 내역

모든 수치의 도출 근거

작동 원리

추출 → 추론 → 델타 파이프라인


Docker Compose (고급)

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

소스에서 빌드

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

기여

CONTRIBUTING.md를 참조하세요. good first issue 라벨이 붙은 이슈가 좋은 시작점입니다.

보안

취약점은 GitHub 보안 권고를 통해 비공개로 보고해 주세요. SECURITY.md를 참조하세요.

라이선스

Business Source License 1.1 (SPDX: BUSL-1.1). 귀하의 조직 내부에서 내부 프로덕션을 포함하여 무료로 사용할 수 있습니다. NocturnusAI 또는 상당한 기능을 제3자에게 제품/호스팅 서비스로 제공하려면 상업용 라이선스가 필요합니다(licensing@nocturnus.ai). 2030년 2월 19일에 Apache 2.0으로 전환됩니다. LICENSE 및 DISCLAIMER.md를 참조하세요.


법적 및 안전 고지

NocturnusAI는 결정론적 추론 엔진이지만, 그 출력은 제공된 사실만큼만 신뢰할 수 있습니다.

  1. 진실에 대한 보증 없음. "검증됨"은 추론의 논리적 일관성을 의미하며, 실제 주장의 정확성을 의미하지 않습니다.

  2. 자율적인 고위험 결정용이 아님. 독립적인 인간 검증 단계 없이 의료, 금융, 법률 또는 물리적 안전과 관련된 무감독 결정에 이 엔진을 사용하지 마십시오.

  3. 논리 계층 전용. NocturnusAI는 정보와 추론을 제공하며, 작업을 실행하지 않습니다.

  4. 책임 없음. DISCLAIMER.md 및 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