NocturnusAI
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 | |
每轮 Token 数 | ~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为什么开发者为本项目点赞
可复现的 Token 缩减 — 仓库内包含基准测试,方法论已公开,可在您自己的工作负载上运行
确定性推理 — 相同的查询,每次都得到相同的结果。没有嵌入漂移,没有余弦相似度抽奖
真实性维护 — 撤回一个事实,所有派生结论自动撤回。没有陈旧的上下文,不会对操作状态产生幻觉
接入现有技术栈 — LangChain, LlamaIndex, CrewAI, AutoGen, MCP, Vercel AI SDK, OpenAI Agents SDK, Mastra
可与原始重放进行基准对比 — 数据源于计算,而非编造。每一项声明都可追溯到 Notebook 单元格
框架快速入门
框架 | 集成方式 | 链接 |
LangChain / LangGraph | 即插即用 | |
CrewAI | 针对代理角色的任务级上下文 | |
AutoGen | 可由任何代理调用的上下文服务器 | |
MCP | 兼容 Claude Desktop, Cursor, Continue 的规范服务器 | |
OpenAI Agents SDK | 上下文中间件,无需修改工具 | |
Vercel AI SDK | 适用于 Next.js, Nuxt, SvelteKit 的边缘兼容适配器 | |
Python SDK |
| |
TypeScript SDK |
|
工作原理
三步走。每一轮对话。
提取 — 原始对话轮次 → 通过 LLM 提取结构化事实
推理 — 反向链式逻辑推理,仅查找从代理当前目标可达的事实
返回增量 — 包含自上一轮以来所有变更的
briefingDelta
这不是向量搜索。也不是摘要。这是逻辑引擎上的确定性推理 — Hexastore 索引、反向链式推理 和 真实性维护。
工作循环
自然语言轮次需要 LLM。 下面的示例将原始文本轮次发送给 LLM 以提取结构化事实。如果您在没有 LLM 提供程序的情况下启动服务器,自然语言轮次将返回零事实。请参阅 快速入门 获取设置选项,或使用谓词语法(例如
"customer_tier(acme_corp, enterprise)"),这无需任何 LLM 即可工作。
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:latestcurl 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 smokeCLI
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
轮次缩减工作流 | |
原始轮次 → 优化 → 差异 → 清除 | |
REST 端点和响应格式 | |
Python 和 TypeScript 客户端方法 | |
LangChain, CrewAI, AutoGen, MCP 等 | |
实时 API 上的 Token 缩减测量 | |
每个数字的推导过程 | |
提取 → 推理 → 增量流水线 |
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 或其核心功能作为产品/托管服务需要商业许可证 (licensing@nocturnus.ai)。将于 2030 年 2 月 19 日转换为 Apache 2.0。请参阅 LICENSE 和 DISCLAIMER.md。
法律与安全声明
NocturnusAI 是一个确定性推理引擎,但 其输出的可靠性仅取决于提供给它的事实。
无真实性保证。 “已验证”是指推理的逻辑一致性,而非现实世界声明的准确性。
不适用于自主高风险决策。 未经独立的人工验证步骤,请勿将此引擎用于无人监督的医疗、金融、法律或物理安全决策。
仅限逻辑层。 NocturnusAI 提供信息和推理;它不执行操作。
免责声明。 请参阅 DISCLAIMER.md 和 LICENSE。
Available Tools
16 toolsaggregateA
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
Scored across 16 tools
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 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.
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.
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
Related MCP Connectors
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
Agent FinOps Spend Guard, Deterministic Budget Passport, LLM Token Cost Router & VIP Discounts.
Up to 90% fewer tokens: deterministic, declared tool calls, each with a receipt and an audit trail.
Universal memory for AI agents and tools. Save, organize and search context anywhere.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn 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.1162JavaScriptMIT

RelayPlaneofficial
AlicenseAqualityDmaintenanceEnables 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.71MIT- FlicenseNot gradedqualityDmaintenanceA 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.-
- AlicenseAqualityDmaintenanceProvides 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.720 npm8Apache 2.0