自主AI代理构建框架

Omnigent是一个生产级自主AI代理框架,提供领域无关的智能架构,包括ReAct循环、多提供商LLM路由、结构化记忆、分层规划、推理图和插件系统,适用于安全、代码分析、DevOps、合规和研究等多种领域。

  • by FrancescoStabile
  • Python
  • 本地部署
  • 34 星标
  • 更新于
在 GitHub 查看 FrancescoStabile/omnigent

使用说明

全能型

构建自主AI代理的通用支架。

在经过生产验证的基础上构建任何人工智能代理——安全、代码分析、DevOps、合规性、研究。从具有17k+LOC和320个测试的真实世界代理中提取。

建筑 · 例子 · 贡献


什么是Omnigent?

大多数AI代理框架都为您提供了LLM API的包装器。Omnigent为您提供 整个大脑.

这是生产自主代理的领域无关架构——ReAct循环、多提供商LLM路由、结构化内存、分层规划、推理图、错误恢复、反射和插件系统。你需要建立一个 真实的 代理,而不是带有工具的聊天机器人。

你带来了域名。全能者带来智慧。

┌──────────────────────────────────────────────────────┐
│                   Agent Loop (ReAct)                 │
│         Reason → Act → Observe → Reflect             │
├──────────────┬────────────┬────────────┬─────────────┤
│   Router     │  Planner   │  Context   │   Graph     │
│  4 Providers │  Phases    │  Smart Trim│  Reasoning  │
├──────────────┴────────────┴────────────┴─────────────┤
│            Post-Processing Pipeline                  │
│    Extractors → Reflection → Error Recovery          │
├──────────────────────────────────────────────────────┤
│            Tool Registry + Plugin System             │
├──────────────────────────────────────────────────────┤
│  State │ DomainProfile │ Session │ Cost │ Knowledge  │
├──────────────────────────────────────────────────────┤
│          Config │ Logging │ MCP Integration          │
└──────────────────────────────────────────────────────┘

为什么是Omnigent?

问题 全能解决方案
永远循环的代理人 断路器 + 环路检测 (基于哈希,块在第一次重复时)+ 速率限制 (每次迭代和总上限)
上下文窗口溢出 三级智能修剪 保留原子消息组+ 语义压缩 通过LLM
“只是一个工具调用者” 推理图 将发现链接到多步升级路径中
无方法论 分层规划器 具有基于阶段的执行、LLM细化、跳过条件和 宏观反映 阶段结束时
盲目执行工具 提取器 自动解析结果→ 结构化存储器 → 异步反射
失败会使代理崩溃 错误恢复模式 具有重试策略和优雅降级
供应商锁定 4名法学硕士提供者 基于任务的路由和自动回退+ 可扩展提供者ABC
没有人为监督 循环中的人类 敏感工具调用的审批步骤
崩溃时失去进展 检查点/回放 执行中期,会话恢复
不受信任的插件 插件严格校验和 SHA-256验证模式
从零开始 生产证明 --从真实的代理中提取,而不是在周末构建

快速开始

安装

pip install -e .

设置API密钥

export DEEPSEEK_API_KEY="sk-..."  # Cheapest option (~$0.001 per analysis)
# or
export ANTHROPIC_API_KEY="sk-ant-..."
# or
export OPENAI_API_KEY="sk-..."

运行示例代理

# CodeLens — code quality analyzer (included example)
python -m examples.codelens.main /path/to/any/project

通过4个步骤构建自己的代理

步骤1:定义域内存

from dataclasses import dataclass, field
from omnigent.domain_profile import DomainProfile

@dataclass
class MyProfile(DomainProfile):
    items_analyzed: list[str] = field(default_factory=list)
    risk_score: float = 0.0

第二步:注册您的工具

from omnigent.tools import ToolRegistry

registry = ToolRegistry()
registry.register(
    name="my_scanner",
    schema={"description": "Scan a target", "parameters": {
        "type": "object",
        "properties": {"target": {"type": "string"}},
        "required": ["target"],
    }},
    handler=my_scanner_function,
)

步骤3:填充注册表 (计划模板、链、提取器、反射器、错误模式)

from omnigent.registry import DomainRegistry
from omnigent.chains import ChainStep

registry = DomainRegistry(
    plan_templates={
        "my_domain": [
            {"name": "Discovery", "objective": "Map the target", "steps": [
                ("Initial scan", "my_scanner"),
            ]},
        ],
    },
    chains={
        "high_risk": [
            ChainStep("Deep dive on flagged items", "deep_scanner"),
            ChainStep("Generate remediation plan", ""),
        ],
    },
    extractors={
        "my_scanner": lambda profile, result, args: setattr(
            profile, 'risk_score', 0.8
        ),
    },
)

第四步:将其连接并运行

import asyncio
from omnigent.agent import Agent
from omnigent.router import LLMRouter, Provider

async def main():
    agent = Agent(
        router=LLMRouter(primary=Provider.DEEPSEEK),
        tools=tool_registry,
        registry=registry,  # DomainRegistry with all domain-specific behavior
    )
    async for event in agent.run("Analyze this target"):
        if event.type == "text":
            print(event.content, end="")
        elif event.type == "finding":
            print(f"\n[{event.finding.severity}] {event.finding.title}")

asyncio.run(main())

你能建造什么?

Omnigent是 领域无关 --它提供了智能架构,你提供了领域知识:

域名 您添加了什么 Omnigent提供了什么
安全 Nmap、SQLMap、Burp工具+漏洞知识 ReAct循环、攻击链推理、会话持久性
代码质量 AST解析器、复杂性工具+重构模式 规划、结构化发现、升级链
开发运维 K8s、Terraform、监控工具+运行手册 错误恢复、多步骤事件链、成本跟踪
合规 文档扫描仪、政策工具+法规知识库 假设跟踪、证据收集、报告
研究 搜索、抓取、数据库工具+领域本体 上下文管理、迭代细化、反思

看 示例/代码镜头/ 以实现完整的工作实施。

组件

模块 目的 如何自定义
agent.py ReAct回路、断路器、回路检测、速率限制、批准 子类 Agent,覆盖步骤方法和钩子
注册表.py 集中化 DomainRegistry 所有域特定注册表的数据类 通过 DomainRegistry(...) 到 Agent
router.py 多提供商LLM路由 LLMProvider ABC和扩展思维 子类 LLMProvider 对于新供应商
reasoning_graph.py 多步推理链的有向图 子类 ReasoningGraph
planner.py 具有跳过条件和宏观反映的分层任务规划 填充 plan_templates 在 DomainRegistry
context.py 智能上下文修剪+基于LLM的语义压缩 按原样工作
domain_profile.py 有界假设跟踪的结构化记忆 子类 DomainProfile
state.py 具有Pydantic验证结果的代理状态 集 enrich_fn 钩子
提取器.py 将工具结果自动解析到DomainProfile 填充 extractors 在 DomainRegistry
反射py 每次工具调用后异步战略洞察 填充 reflectors 在 DomainRegistry
error_recovery.py 模式匹配的恢复指导 填充 error_patterns 在 DomainRegistry
chains.py 已确认发现的升级链 普及 chains 在 DomainRegistry
知识阅读器.py 使用预算进行部门级知识检索 填充 knowledge_map 在 DomainRegistry
few_shot_examples.py 提高准确性的工具使用示例 填充 examples 在 DomainRegistry
plugins.py 具有严格校验和模式的文件系统插件发现 插入 ~/.omnigent/plugins/
会话.py 会话持久化、恢复、导出、检查点/回放 按原样工作
cost_trackr.py 按提供商、按任务进行成本跟踪 按原样运行
config.py YAML+.env+env配置加载 按原样工作
工具/ 具有范围检查和模式缓存的工具注册表 注册域工具

关键设计模式

数据驱动注册表(核心零域代码)

所有领域特定的行为都存在于一个注射中 DomainRegistry 数据类。您的代理在启动时填充它:

from omnigent.registry import DomainRegistry

registry = DomainRegistry(
    plan_templates={...},   # Task plan templates
    chains={...},           # Escalation chains
    extractors={...},       # Tool result parsers
    reflectors={...},       # Post-tool strategic analysis
    error_patterns={...},   # Failure recovery patterns
    knowledge_map={...},    # Knowledge file routing
    examples={...},         # Few-shot tool examples
    tool_timeouts={...},    # Per-tool timeouts
)

agent = Agent(registry=registry)

多个代理可以使用独立的注册表运行——没有全局状态泄漏。为了向后兼容性, DomainRegistry.default() 读取模块级字典。

复杂域的子类

对于不能表示为数据的行为,重写方法:

class MyAgent(Agent):
    # Domain hooks
    def _is_failure(self, tool_name, result): ...
    def _extract_finding(self, text): ...
    def _build_dynamic_system_prompt(self): ...

    # Overridable step methods (decomposed agent loop)
    def _do_context_management(self): ...
    async def _do_llm_call(self, system_prompt): ...
    async def _do_tool_execution(self, tool_calls): ...
    async def _do_post_tool_processing(self, tc, result): ...
    def _check_termination(self, text_buffer): ...

class MyGraph(ReasoningGraph):
    def _build_default_graph(self): ...

class MyProfile(DomainProfile):
    def to_prompt_summary(self): ...

推理图(微分器)

Omnigent与简单工具调用者的区别在于:当发现得到确认时,推理图会激活下游升级路径。代理人不仅发现问题 将它们束缚在多步骤推理中.

Security:    SQLi → DB Dump → Credential Extraction → Admin Access → RCE
Code:        God Object → High Coupling → Low Testability → Regression Risk
Incident:    Alert → Log Correlation → Root Cause → Blast Radius
Compliance:  Gap Found → Control Missing → Risk Assessment → Remediation

测试

# Run all tests
pytest

# Run with coverage
pytest --cov=omnigent --cov-report=term-missing

# Run specific module tests
pytest tests/test_reasoning_graph.py -v

# Run only unit tests
pytest -m unit

325项测试涵盖所有核心组件。每个测试都在没有LLM调用或网络访问的情况下运行。

项目结构

omnigent/
├── src/omnigent/         # Core framework
│   ├── agent.py           # The ReAct loop (1024 lines)
│   ├── registry.py        # DomainRegistry dataclass (97 lines)
│   ├── router.py          # Multi-provider LLM routing + LLMProvider ABC (700 lines)
│   ├── reasoning_graph.py # Chain reasoning engine (389 lines)
│   ├── planner.py         # Hierarchical task planner + macro-reflection (544 lines)
│   ├── context.py         # Smart context + semantic compression (358 lines)
│   ├── state.py           # State + Pydantic findings
│   ├── domain_profile.py  # Structured agent memory (bounded summaries)
│   ├── extractors.py      # Result parsing pipeline
│   ├── reflection.py      # Async post-tool strategic analysis
│   ├── error_recovery.py  # Failure recovery engine
│   ├── chains.py          # Escalation chain registry
│   ├── knowledge_loader.py # Knowledge base retrieval
│   ├── few_shot_examples.py # Tool usage examples
│   ├── plugins.py         # Plugin system + strict checksum mode (556 lines)
│   ├── session.py         # Session persistence + checkpoint/replay (546 lines)
│   ├── cost_tracker.py    # Cost tracking
│   ├── config.py          # Configuration management
│   ├── logging_config.py  # Structured JSON logging
│   ├── prompts/system.md  # Base system prompt
│   └── tools/             # Tool registry + schema caching (309 lines)
├── examples/codelens/     # Complete working example agent
├── tests/                 # 325 tests
├── ARCHITECTURE.md        # Deep technical architecture doc
├── CONTRIBUTING.md        # Contribution guide
└── CHANGELOG.md           # Version history

起源

Omnigent提取自 NumaSec,生产自主安全代理(17878 LOC,320测试)。

由...建造 弗朗切斯科·斯塔比尔

许可证

麻省理工学院 --把它用于任何事情。

贡献

看 贡献.md。我们欢迎域实现、错误修复和文档改进。