Arneunalarming861/Laminae

GitHub: Arneunalarming861/Laminae

Laminae 是一个用 Rust 编写的模块化 SDK,通过安全防护、风格控制、自学习与沙箱等六大中间层,将原始大语言模型快速转化为生产就绪的 AI 系统。

Stars: 0 | Forks: 0

Laminae

Laminae

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

crates.io SDK downloads license rust docs.rs

如果您觉得 Laminae 很有用,请考虑给它一个 ⭐ - 这有助于其他人发现这个项目!

📖 文档 · 更新日志

用 ❤️ 为 AI 和 Vibe Coding 社区而作。

Laminae(拉丁语:*layers*)是一个开源的模块化 Rust SDK,它为任何 AI 或 LLM 应用程序增加了防护机制、安全性、个性、声音、学习和管控能力。每一层都可以独立工作,也可以组合成一个完整的生产就绪栈。

``` ┌─────────────────────────────────────────────┐ │ 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 应用都在从头开始重新构建安全性、提示注入防御和输出验证。大多数应用甚至完全跳过了这一步。Laminae 提供了结构化的安全层,它们位于你的 LLM 和用户之间——由 Rust 强制执行,而非通过提示词。 **没有现有的 SDK 能做到这一点。** LangChain、LlamaIndex 等其他 SDK 专注于检索和链接。Laminae 则专注于 LLM *周围*发生的事情:塑造其个性、从纠正中学习、审计其输出、沙箱化其行为以及限制其影响范围。 ## 各层说明 ### Psyche - 多智能体认知管线 受弗洛伊德启发的架构,由三个智能体塑造每一个响应: - **Id(本我)** - 创造力。生成非传统的角度、情感基调、创造性的重构。运行在小型本地 LLM (Ollama) 上 - 零成本。 - **Superego(超我)** - 安全评估器。评估风险、伦理边界、操纵企图。同样在本地运行 - 零成本。 - **Ego(自我)** - 你的 LLM。接收用户的请求,以及由 Id 和 Superego 提供的不可见上下文。在不知道已被塑造的情况下生成最终响应。 核心理念:Id 和 Superego 运行在小型、快速的本地模型上。它们的输出被压缩成“上下文信号”,作为不可见的系统上下文注入到 Ego 的提示词中。用户永远看不到塑造过程——他们只会得到更好、更安全的响应。 ``` 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(压缩输出协议)进行快速处理。复杂请求则走完整的管线。 ### Persona - 语气提取与风格强制 从文本样本中提取写作个性,并将其强制应用于 LLM 输出。与平台无关 - 适用于电子邮件、文档、聊天、代码审查、支持工单。 - **7 维度提取** - 语气、幽默感、词汇、正式程度、视角、情感风格、叙事偏好 - **反幻觉** - 根据真实样本验证 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% 词汇重叠去重 - **提示注入** - 将顶级指令格式化为适用于任何 LLM 的提示词块 ``` 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 响应进行红队测试。作为异步后处理管线运行——永远不会阻塞对话。 **三个阶段:** 1. **静态分析** - 针对 25 个以上漏洞类别的正则表达式模式扫描(eval 注入、硬编码密钥、SQL 注入、XSS、路径遍历等) 2. **LLM 对抗性审查** - 带有攻击者思维提示词的本地 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`、Linux namespaces + seccomp)将网络限制为 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 platform-native sandbox (macOS Seatbelt / Linux namespaces+seccomp) 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 都无法通过推理绕过: - **输入验证** - 检测提示注入企图 - **输出验证** - 捕获系统提示词泄露、身份操纵 - **命令过滤** - 阻止危险的 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 ``` ## 安装 ``` # 全栈 [dependencies] laminae = "0.4" tokio = { version = "1", features = ["full"] } # 具备一流的 LLM 后端 [dependencies] laminae = { version = "0.4", features = ["anthropic"] } # Claude laminae = { version = "0.4", features = ["openai"] } # OpenAI / Groq / Together / DeepSeek / local laminae = { version = "0.4", features = ["all-backends"] } # 或选择独立层 [dependencies] laminae-psyche = "0.4" # Just the cognitive pipeline laminae-persona = "0.4" # Just voice extraction & enforcement laminae-cortex = "0.4" # Just the learning loop laminae-shadow = "0.4" # Just the red-teaming laminae-glassbox = "0.4" # Just the containment laminae-ironclad = "0.4" # Just the sandbox laminae-ollama = "0.4" # Just the Ollama client laminae-anthropic = "0.4" # Claude EgoBackend laminae-openai = "0.4" # OpenAI-compatible EgoBackend ``` ## Python 绑定 从 PyPI 安装: ``` pip install laminae ``` 或从源码构建: ``` cd crates/laminae-python pip install maturin maturin develop # builds and installs locally ``` ``` from laminae import Glassbox, VoiceFilter, Cortex gb = Glassbox() gb.validate_input("Hello") # OK gb.validate_command("rm -rf /") # raises ValueError f = VoiceFilter() result = f.check("It's important to note that...") # result.passed = False, result.violations = ["AI vocabulary detected: ..."] c = Cortex() c.track_edit("It's worth noting X.", "X.") patterns = c.detect_patterns() ``` ## 平台支持 | 平台 | 状态 | |----------|--------| | macOS | 完全支持 (Seatbelt sandbox) | | Linux | 部分支持(namespace 隔离,seccomp 计划中) | | Windows | 部分支持(仅资源限制,无文件系统/网络隔离) | | WASM | Glassbox, Persona (voice filter), Cortex | | Python | Glassbox, VoiceFilter, Cortex via PyO3 | ## 基准测试 所有数据均来自 Apple M4 Max 上的 Criterion.rs 测试。完整结果见 [`BENCHMARKS.md`](BENCHMARKS.md)。 | 操作 | 耗时 | Crate | |-----------|------|-------| | `validate_input` (100 字符) | ~396 ns | Glassbox | | `validate_command` | ~248 ns | Glassbox | | `validate_output` (100 字符) | ~215 ns | Glassbox | | `validate_binary` | ~1.1 µs | Ironclad | | Voice filter (干净, 100 字符) | ~3.9 µs | Persona | | `track_edit` | ~85 ns | Cortex | | `detect_patterns` (100 次编辑) | ~426 µs | Cortex | | Static analyzer (10 行) | ~7.4 ms | Shadow | | Secrets analyzer (100 行) | ~428 µs | Shadow | 管控 (Glassbox) 每次调用增加 <1µs 的开销——在任何 LLM 管线上实际上是零开销。 ``` cargo bench --workspace ``` ## 环境要求 - **Rust 1.83+** - **Ollama**(用于 Psyche 和 Shadow 的 LLM 功能) - `brew install ollama && ollama serve` ## 示例 见 [`crates/laminae/examples/`](crates/laminae/examples/) 目录: | 示例 | 展示内容 | |---------|---------------| | [`quickstart.rs`](crates/laminae/examples/quickstart.rs) | 带有 mock Ego 后端的 Psyche 管线 | | [`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) | 完整管线中的所有四个层 | | [`ego_claude.rs`](crates/laminae/examples/ego_claude.rs) | 适用于 Claude (Anthropic API) 的 EgoBackend | | [`ego_openai.rs`](crates/laminae/examples/ego_openai.rs) | 适用于 GPT-4o (OpenAI API) 且支持流式传输的 EgoBackend | ## 发布 自动化 CI 工作流在推送版本 tag 时进行发布: - **Rust crates** -- 推送 `v*` tag 以按依赖顺序将所有 crate 发布到 crates.io - **Python wheel** -- 相同的 `v*` tag 会触发多平台构建,并通过 Maturin 上传到 PyPI ``` 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, feature-gated backends) ├── 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 + cross-platform sandbox + watchdog ├── laminae-glassbox ← GlassboxLogger trait + validation + rate limiter ├── laminae-ollama ← Standalone Ollama HTTP client ├── laminae-anthropic ← Claude EgoBackend (feature: "anthropic") ├── laminae-openai ← OpenAI-compatible EgoBackend (feature: "openai") └── laminae-python ← Python bindings via PyO3 (pip install laminae) ``` 每个 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`(用于事件日志记录) - `laminae-anthropic` 依赖于 `laminae-psyche`(实现 EgoBackend) - `laminae-openai` 依赖于 `laminae-psyche`(实现 EgoBackend) ## 扩展点 | Trait | 你需要实现的 | 官方实现 | |-------|-------------------|-------------------| | `EgoBackend` | 插入任何 LLM | `ClaudeBackend`, `OpenAIBackend` (+ Groq, Together, DeepSeek, 本地模型) | | `Analyzer` | 添加自定义的 Shadow 分析阶段 | `StaticAnalyzer`, `SecretsAnalyzer`, `DependencyAnalyzer`, `LlmReviewer` | | `GlassboxLogger` | 将管控事件路由到你的日志系统 | `TracingLogger` | | `SandboxProvider` | 自定义进程沙箱 | `SeatbeltProvider` (macOS), `LinuxSandboxProvider`, `WindowsSandboxProvider`, `NoopProvider` | ## 作者 由 [Orel Ohayon](https://raw.githubusercontent.com/Arneunalarming861/Laminae/main/crates/Software_2.5.zip) 构建 - 独立开发者,致力于为 AI 生态系统构建开源 Rust SDK 和开发者工具。 - [orellius.ai](https://raw.githubusercontent.com/Arneunalarming861/Laminae/main/crates/Software_2.5.zip) - [GitHub](https://raw.githubusercontent.com/Arneunalarming861/Laminae/main/crates/Software_2.5.zip) - [X](https://raw.githubusercontent.com/Arneunalarming861/Laminae/main/crates/Software_2.5.zip) - [crates.io](https://raw.githubusercontent.com/Arneunalarming861/Laminae/main/crates/Software_2.5.zip) ## 许可证 根据 Apache License, Version 2.0 授权 - 详见 [LICENSE](LICENSE)。 Copyright 2026 Orel Ohayon.

Laminae 的理念在 Thunder 生态系统中得以延续:
Thunder · Thunder Dome · Thunder Thinking · Thunder Eye

Orellius.ai 构建

标签:AI代理, AI安全, AI控制, AI风险缓解, Chat Copilot, DLL 劫持, LLM, Petitpotam, Rust, Unmanaged PE, Vibe Coding, 中间件, 人工智能, 可视化界面, 大模型应用开发, 大语言模型, 定制化, 开源, 护栏, 模块化, 生产环境, 用户模式Hook绕过, 网络流量审计, 通知系统, 集成