Satty27/andi-ai

GitHub: Satty27/andi-ai

ANDI-AI 是一款企业级 MongoDB 自然语言查询网关,在确保敏感数据不外泄的前提下,将自然语言意图安全编译为可执行的只读 MongoDB 查询。

Stars: 5 | Forks: 1

# ANDI-AI:面向企业级 MongoDB 的安全 Agentic AI 数据网关 🤖🍃 [![PyPI version](https://img.shields.io/pypi/v/andi-ai.svg)](https://pypi.org/project/andi-ai/0.1.2/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/) **ANDI** 代表高级自然语言数据库接口(Advanced Natural Language Database Interface)。它是面向企业级 MongoDB 的安全 Agentic AI 数据网关。 我们提供一个确定性的 middleware 层,使 AI agent 和软件应用程序能够使用纯文本安全地在 MongoDB 集群上执行查询/聚合——而不会牺牲速度、安全性或可预测性。 通过利用 **Agentic workflow**,Andi 可以立即将纯英语翻译为精确的 MongoDB 标准查询或复杂的多阶段聚合 pipeline——并完整支持 **动态 runtime 变量**。 停止构建、维护和调试数十个僵化的、单一用途的 CRUD endpoint。将您的数据获取层整合为一个单一、高度灵活且智能的 NLP endpoint。 ``` graph TD classDef payload fill:#e2e8f0,stroke:#475569,stroke-width:2px,color:#0f172a,font-weight:bold; classDef stage fill:#f8fafc,stroke:#2563eb,stroke-width:2px,color:#1e3a8a; classDef output fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d,font-weight:bold; Input["📥 User Intent Payload
(Natural Language + Base Collections)"]:::payload subgraph andi_Engine ["andi Open-Source Compilation Engine"] S1["1. Prompt-to-Task Decomposition
• Deconstructs intent into filtering, grouping, & projection targets"]:::stage S2["2. Schema Resolver & Type Isolation
• Validates keys against schema & isolates BSON data types"]:::stage S3["3. Relationship-to-Schema Mapping
• Resolves multi-collection references & constructs $lookup joins"]:::stage S4["4. Deterministic Pipeline Construction
• Enforces optimal stage ordering ($match ➔ $lookup ➔ $group)"]:::stage S5["5. BSON Query Generator & Validator
• Binds dynamic kwargs & compiles executable BSON syntax"]:::stage end Output[("🚀 Executable MongoDB BSON Query
(PyMongo / Motor Driver)")]:::output Input --> S1 S1 --> S2 S2 --> S3 S3 --> S4 S4 --> S5 S5 --> Output ``` ## ✨ 功能 * 🗣️ **文本到 NoSQL 翻译:** 用纯英语编写复杂的数据库请求。Andi 负责繁重的工作,将意图翻译为原生的 MongoDB 查询语法。 * 🧠 **Agentic 查询规划:** 由 **OPENAPI** 驱动,Andi 深刻理解上下文、深度嵌套结构和关系,以构建高度准确的操作。 * 💾 持久化查询缓存(**新增**):添加一个强大的持久层,直接从缓存中获取编译后的查询,避免冗余的查询生成,并显著减少 token 消耗。 * 🔒 **隐私优先的 schema 隔离:** Andi 连接到您的数据库,推断您的 collection 的结构,并在本地缓存该结构。**只有 schema 元数据被发送给 LLM**——您的实际数据库记录永远不会暴露给 agent。 * ⚡ **安全的 runtime 变量:** 在 runtime 将动态输入安全地注入到您的自然语言 prompt 中,消除字符串拼接和 prompt 注入漏洞。 * 🛠️ **开箱即用的复杂聚合:** 无缝生成标准的 `find()` 查询以及高级的 `aggregate()` pipeline(`$lookup`、`$unwind`、`$group` 等)。 * 🎯 **单一 endpoint 架构:** 非常适合构建 AI agent、聊天机器人或高度动态的应用程序,无需为每个新的 UI 视图编写代码即可实现灵活的临时数据检索。 ## 📦 安装 Andi 可在 PyPI 上获取。使用 `pip` 干净地安装它: ``` pip install andi-ai ``` ## ⚙️ 前置条件 要运行 Andi,请确保您具备: 1. 有效的 MongoDB 连接字符串 URI。 2. 在您的环境变量中配置了 OpenAI API Key (OPENAI_API_KEY)。 ## 🚀 快速开始 以下是您可以如此轻松地初始化 Andi、映射您的 schema,并执行带有动态 runtime 绑定的自然语言查询: ### ⚡ Runtime 变量的工作原理(`**kwargs` 解析) 为了防止字符串拼接漏洞和 prompt 注入,Andi 使用了严格的声明式变量绑定系统。当您定义一个意图时,您需要使用 `${variable_name}` 语法来声明占位符。 当通过 `run_query_executor` 执行查询时,您必须将这些确切的变量作为 Python 关键字参数(`**kwargs`)传递。 ### 映射的黄金法则 在您的 **`runtime_inputs` 对象模板** 内定义的变量键标识符必须与 **Python 参数键**完全匹配。 | 位置 | 键语法 | 示例 | | :--- |:---------------------------------------------------------------| :--- | | **1. 在 Intent JSON 内:** | `"runtime_inputs": [{"email": "${target_email}"}]` | 使用 `${target_email}` 占位符 | | **2. 在 `run_query_executor` 内:** | `vector_agent.run_query_executor(plan, target_email=variable)` | `target_email=target_email` | ### 详细分解示例 以下是映射如何从您的 JSON 定义连接到执行的确切方式: ``` from andi import Andi class TestProject: def testing_nlp(self, db_session, analyzed_schemas): self.db = db_session self.analyzed_schemas = analyzed_schemas connection_string = "mongodb://localhost:27017" vector_agent = Andi(db_session=db_session, analyzed_schemas=analyzed_schemas) database_name = "test" vector_agent.initialize_connection(connection_string=connection_string, database_name=database_name) vector_agent.analyze_schemas(base_collections=["users", "wallets", "weekly_leaderboard"]) #Example 1 target_email = "test_user_8_fischertimothy@gmail.com" intent = { "intent": { "goal": "Find the preferred_language and name of the user where email=target_email", "runtime_inputs":[ { "email":"${target_email}", "datatype": "string" } ], "projection":["name", "preferred_language"] } } query = vector_agent.build_nlp_query(intent=intent, query_identifier=None, retry=False) print(query) output = vector_agent.run_query_executor(nlp_query=query, target_email=target_email) print(output) ``` ## 🏗️ 工作原理 ``` graph TD %% Styling and Color Palettes (Enterprise Vibe) classDef client fill:#eef2f7,stroke:#3b82f6,stroke-width:2px,color:#1e3a8a; classDef engine fill:#eff6ff,stroke:#2563eb,stroke-width:2px,color:#1e40af,font-weight:bold; classDef security fill:#fff1f2,stroke:#f43f5e,stroke-width:2px,color:#9f1239; classDef database fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d; classDef structural fill:#fafafa,stroke:#71717a,stroke-width:1px,color:#27272a; %% 1. Ingestion Layer subgraph Client_Layer ["Application Interface"] API_Call["POST /api/v1/nlp_query
(Payload: Intent + Base Collections)"]:::client end %% 2. Orchestration Layer subgraph Andi_Engine ["andi Agent Engine Core"] Init["VectorAgent Initialization
(Target Database Setup)"]:::engine SchemaAnalzer["vector_agent.analyze_schemas()
(Extracts Schemas)"]:::engine Builder["vector_agent.build_nlp_query()
(Deterministic Query Construction)"]:::engine end %% 3. Security & Validation Layer subgraph Security_Guardrails ["Enterprise Safety Controls"] IntentRouter{"Intent Routing
& Field Validation"}:::security Sanitize{"Injection Scanning
& Operator Isolation"}:::security end %% 4. Data Execution Target subgraph Infrastructure ["Enterprise Storage Target"] MongoCluster[("NoSQL Cluster
(MongoDB)")]:::database end %% Data Pipeline Connections Flow API_Call -->|1. Transmit Payload| Init Init -->|2. Scrape Structure Constraints| SchemaAnalzer SchemaAnalzer -->|3. Establish Pipeline Context Boundaries| Builder Builder -->|4. Inspect Fields Against Schema| IntentRouter IntentRouter -->|Passed: Valid Fields| Sanitize IntentRouter -.->|Failed: Reject Intent| API_Call Sanitize -->|5. Compile Secure BSON Native Pipeline| MongoCluster MongoCluster -->|6. Standard Isolated Output Cursor| API_Call %% Apply Styles to classes class Builder,SchemaAnalzer,Init engine; ``` ## 📖 支持的操作 Andi 具有严格的只读路由引擎。它仅将自然语言翻译为数据获取操作,确保您的生产数据完全免受 AI 幻觉或未经授权的修改的影响。 | 操作 | 状态 | 能力 | 自然语言示例 | 生成的原生语法 | | :--- | :--- | :--- | :--- | :--- | | **`find()`** | ✅ 支持 | 标准过滤、排序、限制和显式字段投影。 | *"查找在 2025 年之后注册的活跃用户,按最新排序。"* | `{ "status": "active", "reg_date": { "$gt": "2025-01-01" } }` | | **`aggregate()`** | ✅ 支持 | 多阶段转换、关系连接、展开数组以及分组。 | *"将每周排行榜与用户钱包连接,并获取前 10 名得分。"* | `[{ "$lookup": {...} }, { "$unwind": ... }, { "$sort": ... }]` | | **`insert()`** | ❌ 阻止 | 防止通过 NLP endpoint 进行动态数据插入。 | *"向数据库添加一个新用户..."* | **操作被拒绝**(只读防护) | | **`update() / delete()`** | ❌ 阻止 | 防止未经授权的修改、批量更新或意外的 collection 删除。 | *"删除所有未登录的用户..."* | **操作被拒绝**(只读防护) | ### 🔒 只读安全保证 ## 🤝 贡献 欢迎贡献、问题和功能请求!如果您想扩展对自定义数据库引擎的支持、优化 pipeline 构建路由或建议功能,请随时提交 pull request 或查看 Issues 页面。 ## 📄 许可证 本项目基于 MIT 许可证授权 - 详情请参阅 LICENSE 文件。
标签:AI代理, MongoDB, Petitpotam, 中间件, 人工智能, 数据库网关, 数据隐私, 用户模式Hook绕过, 逆向工具