convez.ai
MCP ServerAutomaçãoAvançado
rulego

RuleGo Components AI

rulego/rulego-components-ai

Framework declarativo de agentes IA com orquestração por regras e MCP bidirecional

Ver no GitHub
BomPluginScore · de 0 a 100

Framework declarativo para desenvolvimento de agentes IA construído sobre o motor de regras RuleGo. Permite criar agentes standalone ou assistentes de código através de configuração JSON, orquestração baseada em eventos e suporte bidirecional ao protocolo MCP. Inclui 10 aspectos AOP, gerenciamento de sessão multidimensional e troca dinâmica de modelos em tempo de execução.

Instalação

$npx convez-ai rulego/rulego-components-ai

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
7
Forks
12
Acompanhando
1
Saúde
50%
Último commit
há 1 semana
Versão
—
Issues abertas
1
Contribuidores
2

Casos de uso

  • Desenvolvimento de assistentes de código AI (Claude Code/OpenClaw-like)
  • Agentes IA autônomos que integram raciocínio LLM com lógica de negócio
  • Pipelines híbridos combinando chamadas REST, filas de mensagens e decisões IA
  • Sistemas multi-agente com colaboração entre agentes via sub-tools

Veredito

Solução madura e bem-documentada para quem busca contrapeso aos frameworks Python tradicionais — oferece deployment em binário único, configuração declarativa quente-recarregável e integração nativa ao ecossistema RuleGo. Ideal para arquiteturas que precisam híbridas (IA + orquestração de processos) e ambientes com restrições de recursos.

README

A tradução para o português deste README ainda está na fila.

rulego-components-ai

A Declarative AI Agent Development Framework

A declarative AI agent development framework built on the RuleGo rule engine. It can be used to develop standalone AI agents or serve as the foundation for building AI coding assistants like Claude Code / OpenClaw. It adopts the rule chain as agent design philosophy, embedding LLM reasoning capabilities into event-driven rule chain workflows. Through JSON declarative configuration, 10 AOP aspects, unified abstraction of four tool categories, and multi-dimensional session management, it enables building production-grade agent applications.

Full Documentation: Docs

Differences from Mainstream Frameworks

DimensionLangChain / LangGraphAutoGen / CrewAIThis Framework
DefinitionPython codePython codeJSON declarative, hot-reloadable
Runtime ModelRequest-responseRequest-responseEvent-driven, rule chain orchestration
InterceptionSimple callback listNo unified mechanism10 AOP aspects with PointCut condition matching
Tool SourcesFunctionsFunctionsBuilt-in + Rule chain + Sub-agent + MCP bidirectional
Session ManagementBasic Memory classExternal storage required6 scopes, auto-compression/pruning, extensible storage
Business IntegrationDIY requiredDIY requiredNative access to rule engine 200+ nodes
Model SwitchingBuild-time bindingBuild-time bindingRuntime per-session dynamic switching
DeploymentPython runtimePython runtimeSingle binary, low resource usage

Core Features

  • Rule Chain as Agent — Agents are defined declaratively in JSON and can be freely composed with other rule engine nodes (REST calls, JS filters, message queues, etc.) to build hybrid pipelines of AI reasoning and business orchestration
  • 10 AOP Aspects — Covering the complete agent execution lifecycle (start/before/around/after/completed/pre-LLM/post-LLM/stream-chunk/pre-tool-call/post-tool-call), with PointCut condition matching and Order priority
  • Unified Abstraction of Four Tool Categories — 4 atomic tools (bash/read/write/edit) form the perception-creation-execution-evolution capability loop; rule chain tools (expose any business process as a tool), sub-agent tools (multi-agent collaboration), MCP bidirectional protocol (client + server)
  • Skill System — Compatible with the SKILL.md format used by Claude Code / OpenClaw and other AI coding assistants, supporting multi-directory aggregation, fingerprint caching, and automatic hot-reloading
  • Multi-dimensional Session Management — 6 scopes (global/per-user/per-channel/per-thread/per-task), automatic LLM compression and intelligent pruning
  • Runtime Model Switching — Session-level dynamic model switching via decorator chains; the same agent can use different models for different users
  • ReAct Reasoning Loop — Supports synchronous/streaming execution, multimodal input, automatic retry
  • MCP Bidirectional Protocol — Acts as both MCP client (consuming external tools) and MCP server (exposing rule chains as MCP tools)
  • Intent Recognition — LLM classification and embedding vector similarity approaches
  • OpenAI Compatible — Streaming response processor, standard Chat Completions API output

Module Structure

ai/
├── agent/          # Core ReAct agent node (type: ai/agent)
├── action/         # Simple LLM operation nodes
│                   #   - ai/llm       Text generation
│                   #   - ai/createImage Image generation
├── intent/         # Intent recognition nodes
│                   #   - ai/intent     LLM-based
│                   #   - ai/localIntent Embedding vector-based
├── aspect/         # AOP aspect framework
│   └── builtin/    #   Built-in aspects (logging, session, visualization)
├── config/         # Shared configuration types and model capability registry
├── constants/      # Constants (provider URLs, model names, timeouts)
├── embedding/      # Lightweight embedding client + cosine similarity
├── endpoint/       # MCP Server endpoint (rule chains exposed as MCP tools)
├── errors/         # Structured error codes (AgentError with Retryable)
├── mcp/            # MCP client node (calling remote MCP services)
├── processor/      # OpenAI-compatible streaming response processor
├── session/        # Session/conversation history management
├── tool/           # Tool registry + built-in tool implementations
│   ├── bash/       #   Shell command execution
│   ├── read/       #   File reading and search
│   ├── write/      #   File writing
│   ├── edit/       #   File editing (line-level, search-replace)
│   ├── browseruse/ #   Browser automation (chromedp)
│   ├── mcp/        #   MCP tool adapter (self + remote mode)
│   └── skill/      #   Skill invocation
├── utils/          # Utility functions
│   ├── contextx/   #   Type-safe Context Key
│   ├── image/      #   Image loading, Base64 conversion
│   ├── llm/        #   LLM response parsing
│   ├── token/      #   Token estimation and metrics collection
│   └── tool/       #   Tool parameter JSON Schema parsing
└── all/            # One-liner import for all components

Quick Start

Installation

go get github.com/rulego/rulego-components-ai

Import Components

Import all components in one line:

import _ "github.com/rulego/rulego-components-ai/all"

Import on demand:

import (
    _ "github.com/rulego/rulego-components-ai/agent"
    _ "github.com/rulego/rulego-components-ai/tool/bash"
    _ "github.com/rulego/rulego-components-ai/tool/read"
)

Minimal Example: Using an AI Agent in a Rule Chain

Here is a complete agent rule chain JSON configuration with the node type ai/agent:

{
  "ruleChain": {
    "id": "my-agent",
    "name": "My Assistant"
  },
  "nodes": [
    {
      "id": "s1",
      "type": "ai/agent",
      "configuration": {
        "url": "${global.llm.url}",
        "key": "${global.llm.key}",
        "model": "glm-5.1",
        "systemPrompt": "You are a helpful assistant.",
        "maxStep": 50,
        "params": {
          "temperature": 0.7
        },
        "tools": [
          {"type": "builtin", "name": "bash"},
          {"type": "builtin", "name": "read"},
          {"type": "builtin", "name": "write"}
        ]
      }
    }
  ]
}

Load and execute via Go code:

package main

import (
    "context"
    "fmt"

    _ "github.com/rulego/rulego-components-ai/all"
    "github.com/rulego/rulego/api/types"
    "github.com/rulego/rulego/rulego"
)

func main() {
    // 1. Create a RuleGo instance
    config := rulego.NewConfig()
    ruleEngine := rulego.NewRuleGo()

    // 2. Load the agent rule chain (JSON as above)
    chainJson := `{"ruleChain":{"id":"my-agent","name":"My Assistant"},"nodes":[{"id":"s1","type":"ai/agent","configuration":{"url":"https://open.bigmodel.cn/api/paas/v4","key":"your-api-key","model":"glm-5.1","systemPrompt":"You are a helpful assistant.","tools":[{"type":"builtin","name":"bash"}]}}]}`

    _, err := ruleEngine.OnLoad(chainJson, types.WithConfig(config))
    if err != nil {
        panic(err)
    }

    // 3. Send a message to the agent
    msg := rulego.NewMsg(0, "user", types.JSON, map[string]string{}, "What's the weather like today?")
    ruleEngine.OnMsg(msg, rulego.WithContext(context.Background()))

    // Note: In production, retrieve responses via callback or endpoint
    fmt.Println("Message sent")
}

Node Types

Node TypePackageDescription
ai/agentagentReAct agent with tool calling, streaming output, multimodal support
ai/llmactionSingle-shot text generation
ai/createImageactionImage generation (DALL-E 3)
ai/intentintentLLM-based intent recognition
ai/localIntentintentEmbedding vector-based intent recognition (low latency, zero LLM calls)
x/mcpClientmcpMCP client node

Agent Configuration (ai/agent)

{
  "url": "https://open.bigmodel.cn/api/paas/v4",
  "key": "your-api-key",
  "model": "glm-5.1",
  "systemPrompt": "System prompt, supports ${variable} and ${include(\"/path/to/file\")} file references",
  "messages": [
    {"role": "user", "content": "Preset messages for scheduled task scenarios"}
  ],
  "images": ["https://example.com/image.png"],
  "params": {
    "temperature": 0.7,
    "topP": 0.9,
    "maxTokens": 4096,
    "responseFormat": "text",
    "extraFields": {
      "thinking_budget_tokens": 8192
    }
  },
  "maxStep": 50,
  "maxToolOutputLength": 5000,
  "maxRetries": 3,
  "tools": [
    {"type": "builtin", "name": "bash"},
    {"type": "rulechain", "name": "myChain", "targetId": "chain-001"},
    {"type": "agent", "name": "subAgent", "targetId": "sub-agent-001", "description": "Sub-agent"},
    {"type": "mcp", "name": "mcpTools", "config": {"serverUrl": "http://localhost:8080/mcp"}}
  ]
}

Tool Types

TypeDescription
builtinBuilt-in tools: bash, read, write, edit, browseruse, skill
rulechainCall another rule chain as a tool
agentCall a sub-agent (semantic alias of rulechain)
mcpMCP protocol tool, supports self (in-process) and remote (http/stdio) modes

4 Atomic Tools

ToolCapabilityDescription
bashExecuteShell command execution, HTTP requests; supports allow/deny security mode, timeout control, output truncation
readPerceiveFile reading, line-range reading, content search; supports memory reading and grep mode
writeCreateFile writing, memory writing, experience recording; supports safe path resolution
editEvolveFile editing (line-level, search-replace, insert/delete); supports backup history

These 4 atomic tools form the agent's capability loop: Perceive the environment → Create content → Execute operations → Evolve improvements.

Skill System

Skills are reusable capability units defined via SKILL.md files, compatible with the skill format used by Claude Code / OpenClaw and other mainstream AI coding assistants:

skills/
  code-review/
    SKILL.md
  refactor/
    SKILL.md

SKILL.md format (YAML frontmatter + Markdown):

---
name: code-review
description: Code review skill
---
Please perform a comprehensive code review, focusing on: security, performance, maintainability...

Features:

  • Mainstream Format Compatible — Fully compatible with Claude Code's SKILL.md format; reuse existing skill ecosystems directly
  • Multi-directory Aggregation — Supports priority overlay of user directory > global directory; higher-priority skills override lower-priority ones
  • Auto Hot-reload — FNV-1a fingerprint-based caching; automatically reloads on file changes without restart
  • Multiple Execution Modes — inline (execute in current agent), fork (execute in independent sub-agent), fork_with_context (sub-agent with context)

Aspect Framework (AOP)

The aspect framework allows inserting cross-cutting concerns (logging, sessions, visualization, etc.) without modifying the agent's core logic.

10 Aspect Interfaces

AspectInterception Point
AgentStartAspectAgent startup
AgentBeforeAspectBefore execution (can modify input)
AgentAroundAspectAround execution (can replace entire execution)
AgentAfterAspectAfter execution (can modify output)
AgentCompletedAspectAgent completion
MessageBeforeAspectBefore LLM call (can modify messages)
MessageAfterAspectAfter LLM call
StreamChunkAspectStreaming chunk
ToolCallBeforeAspectBefore tool call (can modify call parameters)
ToolCallAfterAspectAfter tool call

Built-in Aspects

AspectOrderDescription
SessionAspect50Session management (load history, save messages, auto-compress)
VizAspect100AG-UI visualization event push
LoggingAspect200Execution logging

Register Custom Aspects

import "github.com/rulego/rulego-components-ai/aspect"

// Register a global aspect
aspect.RegisterAspect("my_aspect", &MyAspect{})

Session Management

import agentsession "github.com/rulego/rulego-components-ai/session"

// Create an in-memory session manager
storage := agentsession.NewMemoryStorage()
manager := agentsession.NewManager(storage, &agentsession.SessionConfig{
    MaxMessages:   100,
    MaxTokenCount: 100000,
    Pruning: agentsession.PruningConfig{
        Enabled:         true,
        KeepRecentCount: 10,
    },
})

// Auto-integrate into agent via SessionAspect
sessionAspect := builtin.NewSessionAspect(manager, builtin.SessionAspectConfig{})
aspect.RegisterAspect("session", sessionAspect)

Session Scopes

ScopeKey FormatDescription
mainagent:{id}Default; one session per agent
per_peeragent:{id}:peer:{userId}Isolated per conversation peer
per_channel_peeragent:{id}:channel:{ch}:peer:{userId}Isolated per channel + peer
threadagent:{id}:thread:{threadId}Isolated per thread
taskagent:{id}:task:{taskId}Isolated per task

Related Documentation

License

Apache License 2.0

Ver o original no GitHub

Bom para

Relacionados