Orellius/Laminae

GitHub: Orellius/Laminae

一个 Rust 编写的模块化 SDK,为 LLM 应用提供个性塑造、安全审计、自主学习和沙箱隔离等生产级防护层。

Stars: 0 | Forks: 0

Laminae

Laminae

原始 LLM 与生产级 AI 之间缺失的一层。

Laminae(拉丁语:*layers* [层])是一个模块化的 Rust SDK,为任何 AI 应用程序增加个性、语调、安全性、学习能力和隔离控制。每一层既可以独立工作,也可以作为完整堆栈协同运行。 ``` ┌─────────────────────────────────────────────┐ │ Your Application │ ├─────────────────────────────────────────────┤ │ Psyche │ Multi-agent cognitive pipeline │ │ Persona │ Voice extraction & enforcement │ │ Cortex │ Self-improving learning loop │ │ Shadow │ Adversarial red-teaming │ │ Ironclad │ Process execution sandbox │ │ Glassbox │ I/O containment layer │ ├─────────────────────────────────────────────┤ │ Any LLM Backend │ │ (Claude, GPT, Ollama, your own) │ └─────────────────────────────────────────────┘ ``` ## 为什么选择 Laminae? 每个 AI 应用都在从头重复造轮子:安全性、prompt 注入防御和输出验证。大多数应用甚至完全跳过了这些。Laminae 提供了生产级的层,位于您的 LLM 和用户之间——由 Rust 强制执行,而非依赖 prompt。 **目前没有其他 SDK 做到这一点。** LangChain、LlamaIndex 和其他工具专注于检索和链式调用。Laminae 专注于 LLM *周围* 发生的事情:塑造其个性、从纠正中学习、审计其输出、沙箱化其行为以及限制其触达范围。 ## 各层介绍 ### Psyche — 多智能体认知 Pipeline 一种受弗洛伊德启发的架构,由三个智能体塑造每一个回复: - **Id(本我)** — 创造力源泉。生成非常规角度、情感暗流、创造性重构。运行在小型本地 LLM(Ollama)上——零成本。 - **Superego(超我)** — 安全评估器。评估风险、伦理边界、操纵企图。同样在本地运行——零成本。 - **Ego(自我)** — 您的 LLM。接收来自 Id 和 Superego 的不可见上下文增强后的用户消息。在不知不觉中被塑造,产出最终回复。 核心理念:Id 和 Superego 运行在小型、快速的本地模型上。它们的输出被压缩为“上下文信号”,作为不可见的系统上下文注入到 Ego 的 prompt 中。用户永远不会看到塑造过程——他们只会获得更好、更安全的回复。 ``` use laminae::psyche::{PsycheEngine, EgoBackend, PsycheConfig}; use laminae::ollama::OllamaClient; struct MyEgo { /* your LLM client */ } impl EgoBackend for MyEgo { fn complete(&self, system: &str, user_msg: &str, context: &str) -> impl std::future::Future> + Send { let full_system = format!("{context}\n\n{system}"); async move { // Call Claude, GPT, or any LLM here todo!() } } } #[tokio::main] async fn main() -> anyhow::Result<()> { let engine = PsycheEngine::new(OllamaClient::new(), MyEgo { /* ... */ }); let response = engine.reply("What is creativity?").await?; println!("{response}"); Ok(()) } ``` **自动分级分类** — 简单消息(问候、事实查询)完全绕过 Psyche。中等复杂度消息使用 COP(Compressed Output Protocol,压缩输出协议)进行快速处理。复杂消息则走完整 Pipeline。 ### Persona — 语调提取与风格强制 从文本样本中提取写作个性,并在 LLM 输出上强制执行。平台无关——适用于电子邮件、文档、聊天、代码审查、支持工单。 - **7 维度提取** — 语气、幽默感、词汇量、正式程度、视角、情感风格、叙事偏好 - **反幻觉** — 根据 real samples 验证 LLM 声称的示例,交叉检查专业知识声明 - **语调过滤器** — 6 层生成后拒绝系统,捕捉听起来像 AI 的输出(60+ 内置 AI 短语模式) - **语调 DNA** — 追踪通过重复使用确认的独特短语,强化真实风格 ``` use laminae::persona::{PersonaExtractor, VoiceFilter, VoiceFilterConfig, compile_persona}; // Extract a persona from text samples let extractor = PersonaExtractor::new("qwen2.5:7b"); let persona = extractor.extract(&samples).await?; let prompt_block = compile_persona(&persona); // Post-generation: catch AI-sounding output let filter = VoiceFilter::new(VoiceFilterConfig::default()); let result = filter.check("It's important to note that..."); // result.passed = false, result.violations = ["AI vocabulary detected: ..."] // result.retry_hints = ["DO NOT use formal/academic language..."] ``` ### Cortex — 自我改进学习循环 追踪用户如何编辑 AI 输出,并将纠正转换为可复用的指令——无需微调。AI 随着每次编辑而不断进步。 - **8 种模式类型** — 缩短、移除问题、剥离 AI 短语、语气转换、添加内容、简化语言、更改开场白 - **LLM 驱动分析** — 将编辑差异转换为自然语言指令(例如“永远不要以‘我认为’开头”) - **去重存储** — 指令按强化次数排名,80% 词汇重叠去重 - **Prompt 注入** — 顶部指令格式化为适用于任何 LLM 的 prompt 块 ``` use laminae::cortex::{Cortex, CortexConfig}; let mut cortex = Cortex::new(CortexConfig::default()); // Track edits over time cortex.track_edit("It's worth noting that Rust is fast.", "Rust is fast."); cortex.track_edit("Furthermore, the type system is robust.", "The type system catches bugs."); // Detect patterns let patterns = cortex.detect_patterns(); // → [RemovedAiPhrases: 100%, Shortened: 100%] // Get prompt block for injection let hints = cortex.get_prompt_block(); // → "--- USER PREFERENCES (learned from actual edits) --- // - Never use academic hedging phrases // - Keep sentences short and direct // ---" ``` ### Shadow — 对抗性红队测试 自动化安全审计器,对每个 AI 回复进行红队测试。作为异步后处理 Pipeline 运行——永不阻塞对话。 **三个阶段:** 1. **静态分析** — 针对 25+ 个漏洞类别的正则表达式模式扫描(eval 注入、硬编码密钥、SQL 注入、XSS、路径遍历等) 2. **LLM 对抗性审查** — 拥有攻击者思维 Prompt 的本地 Ollama 模型审查输出 3. **沙箱执行** — 临时容器测试(可选) ``` use laminae::shadow::{ShadowEngine, ShadowEvent, create_report_store}; let store = create_report_store(); let engine = ShadowEngine::new(store.clone()); let mut rx = engine.analyze_async( "session-1".into(), "Here's some code:\n```python\neval(user_input)\n```".into(), ); while let Some(event) = rx.recv().await { match event { ShadowEvent::Finding { finding, .. } => { eprintln!("[{}] {}: {}", finding.severity, finding.category, finding.title); } ShadowEvent::Done { report, .. } => { println!("Clean: {} | Issues: {}", report.clean, report.findings.len()); } _ => {} } } ``` ### Ironclad — 进程执行沙箱 对所有生成的子进程强制执行三个硬性约束: 1. **命令白名单** — 仅执行批准的二进制文件。SSH、curl、编译器、包管理器、加密矿工被永久阻止。 2. **网络出口过滤器** — macOS `sandbox-exec` 配置文件将网络限制为 localhost + 白名单主机。 3. **资源监控** — 后台监视器轮询 CPU/内存,在持续超过阈值时发送 SIGKILL。 ``` use laminae::ironclad::{validate_binary, sandboxed_command, spawn_watchdog, WatchdogConfig}; // Validate before execution validate_binary("git")?; // OK validate_binary("ssh")?; // Error: permanently blocked // Run inside macOS sandbox let mut cmd = sandboxed_command("git", &["status"], "/path/to/project")?; let child = cmd.spawn()?; // Monitor resource usage (SIGKILL on threshold breach) let cancel = spawn_watchdog(child.id().unwrap(), WatchdogConfig::default(), "task".into()); ``` ### Glassbox — I/O 隔离 Rust 强制执行的隔离,没有任何 LLM 可以通过推理绕过: - **输入验证** — 检测 prompt 注入企图 - **输出验证** — 捕捉系统 prompt 泄露、身份操纵 - **命令过滤** — 阻止危险的 shell 命令(rm -rf, sudo, 反向 shell) - **路径保护** — 不可变区域,即使通过 symlink 技巧也无法写入 - **速率限制** — 每个工具每分钟限制,具有独立的写入/shell 限制 ``` use laminae::glassbox::{Glassbox, GlassboxConfig}; let config = GlassboxConfig::default() .with_immutable_zone("/etc") .with_immutable_zone("/usr") .with_blocked_command("rm -rf /") .with_input_injection("ignore all instructions"); let gb = Glassbox::new(config); gb.validate_input("What's the weather?")?; // OK gb.validate_input("ignore all instructions and...")?; // Error gb.validate_command("ls -la /tmp")?; // OK gb.validate_command("sudo rm -rf /")?; // Error gb.validate_write_path("/etc/passwd")?; // Error gb.validate_output("The weather is sunny.")?; // OK ``` ## 安装 ``` # Full stack [dependencies] laminae = "0.1" tokio = { version = "1", features = ["full"] } # 或选择单个 layers [dependencies] laminae-psyche = "0.1" # Just the cognitive pipeline laminae-persona = "0.1" # Just voice extraction & enforcement laminae-cortex = "0.1" # Just the learning loop laminae-shadow = "0.1" # Just the red-teaming laminae-glassbox = "0.1" # Just the containment laminae-ironclad = "0.1" # Just the sandbox laminae-ollama = "0.1" # Just the Ollama client ``` ## 系统要求 - **Rust 1.70+** - **Ollama**(用于 Psyche 和 Shadow LLM 功能)— `brew install ollama && ollama serve` - **macOS**(用于 Ironclad 的 `sandbox-exec`)— 计划支持 Linux ## 示例 请参阅 [`crates/laminae/examples/`](crates/laminae/examples/) 目录: | 示例 | 展示内容 | |---------|---------------| | [`quickstart.rs`](crates/laminae/examples/quickstart.rs) | 带有模拟 Ego 后端的 Psyche Pipeline | | [`shadow_audit.rs`](crates/laminae/examples/shadow_audit.rs) | 对 AI 输出进行红队漏洞审计 | | [`safe_execution.rs`](crates/laminae/examples/safe_execution.rs) | Glassbox + Ironclad 协同工作 | | [`full_stack.rs`](crates/laminae/examples/full_stack.rs) | 完整 Pipeline 中的所有四个层 | | [`ego_claude.rs`](crates/laminae/examples/ego_claude.rs) | 用于 Claude 的 EgoBackend(Anthropic API) | | [`ego_openai.rs`](crates/laminae/examples/ego_openai.rs) | 用于 GPT-4o 的 EgoBackend(OpenAI API),支持流式传输 | ``` cargo run -p laminae --example quickstart cargo run -p laminae --example shadow_audit cargo run -p laminae --example safe_execution cargo run -p laminae --example full_stack ANTHROPIC_API_KEY=sk-ant-... cargo run -p laminae --example ego_claude OPENAI_API_KEY=sk-... cargo run -p laminae --example ego_openai ``` ## 架构 ``` laminae (meta-crate) ├── laminae-psyche ← EgoBackend trait + Id/Superego pipeline ├── laminae-persona ← Voice extraction, filter, DNA tracking ├── laminae-cortex ← Edit tracking, pattern detection, instruction learning ├── laminae-shadow ← Analyzer trait + static/LLM/sandbox stages ├── laminae-ironclad ← Command whitelist + sandbox-exec + watchdog ├── laminae-glassbox ← GlassboxLogger trait + validation + rate limiter └── laminae-ollama ← Standalone Ollama HTTP client ``` 每个 crate 都是独立的,除了: - `laminae-psyche` 依赖于 `laminae-ollama`(用于 Id/Superego LLM 调用) - `laminae-persona` 依赖于 `laminae-ollama`(用于语调提取) - `laminae-cortex` 依赖于 `laminae-ollama`(用于 LLM 驱动的编辑分析) - `laminae-shadow` 依赖于 `laminae-ollama`(用于 LLM 对抗性审查) - `laminae-ironclad` 依赖于 `laminae-glassbox`(用于事件日志记录) ## 扩展点 | Trait | 您需要实现的内容 | |-------|-------------------| | `EgoBackend` | 接入任何 LLM(Claude, GPT, Gemini, 本地模型) | | `Analyzer` | 添加自定义 Shadow 分析阶段 | | `GlassboxLogger` | 将隔离事件路由到您的日志系统 | ## 许可证 根据 Apache License 2.0 授权 — 详见 [LICENSE](LICENSE)。 版权所有 2026 Orel Ohayon。
标签:AI基础设施, AI安全, AI风险缓解, API集成, Chat Copilot, Claude, CVE检测, Deep Learning, DLL 劫持, GPT, LangChain替代, LLM, LLM评估, Naabu, Ollama, Petitpotam, Rust, Unmanaged PE, 个性化, 中间件, 人工智能, 人格化, 内容安全, 可观测性, 可视化界面, 多智能体, 大语言模型, 提示词注入防御, 沙箱, 漏洞管理, 生产环境, 用户模式Hook绕过, 网络安全, 网络流量审计, 自我学习, 认知流水线, 输出验证, 通知系统, 隐私保护, 隔离