Skip to main content

LEAI — Oracle Database Intelligence & Documentation Engine

Documentation Python Version License: MIT

Official Bilingual Documentation: https://lucasbral.github.io/leai/ (English & Português)

LEAI (Lê - Aí in PT-BR) is an enterprise reverse engineering, impact analysis, and autonomous AI copilot engine for Oracle Database, specifically designed to power Retrieval-Augmented Generation (RAG), LLMs, and software engineers maintaining complex database ecosystems.



📑 Table of Contents / Índice


📌 What Is It?

Enterprise Oracle databases accumulate years of business rules scattered across hundreds of tables, views, triggers, and massive PL/SQL packages (3,000 to 10,000+ lines of code).

Enabling developers or AI assistants to reliably understand such environments is challenging due to three main issues:

  1. Token Inefficiency & Hallucinations: Sending entire monolithic packages into an LLM context is expensive, slow, and triggers attention degradation ("Lost in the Middle").
  2. Hidden Dependencies: Altering a single column can silently break triggers, views, and procedures across multiple schemas.
  3. Synonyms and Aliases: Stored procedures frequently access tables via private or public synonyms (PUBLIC SYNONYM), creating the false impression that referenced objects do not exist or belong elsewhere.

LEAI solves this by extracting the Oracle data dictionary, constructing a cross-schema dependency graph, and providing an autonomous multi-step reasoning agent with offline database tools.


⚙️ How It Works

LEAI operates via a 3-stage decoupled pipeline:

flowchart LR
    subgraph S1 [1. RAW JSON]
        DB[(Oracle Database)] -->|leai extract| RAW[Technical Snapshots<br/>./raw/*.json]
    end

    subgraph S2 [2. YAML Annotations]
        RAW -->|leai annotate| YAML[Business Annotations<br/>./annotations/*.yml]
        HUMAN[Human DBA / Engineer] -.-> YAML
        AI[LLM Auto-Enrich] -.-> YAML
    end

    subgraph S3 [3. DOCS & RAG]
        RAW & YAML -->|leai compile| DOCS[Markdown + Mermaid<br/>./docs/*.md]
        DOCS --> RAG[Vector Stores & LLMs]
    end

🤖 Autonomous Agent & Tool Calling Engine

When running leai chat or leai ask, the assistant uses an autonomous Tool-Calling Reasoning Loop (AgentExecutionEngine) with up to 10 iterations per turn. Instead of guessing or hallucinating, the model invokes specialized in-memory database tools:

Tool Name Parameters Purpose
search_catalog query, object_types, schema Fast text and regex search across tables, views, procedures, packages, functions, and synonyms.
get_table_schema table_name, schema Full table/view DDL inspection: column data types, nullable constraints, PKs, FKs, unique keys, check constraints, and indexes.
get_subprogram_source package_name, subprogram_name Surgical extraction of standalone procedure/function or specific subprogram inside a package with semantic compression.
grep_plsql_code pattern, object_name, schema Fast regex code search across all stored PL/SQL bodies without reading entire packages.
trace_object_lineage object_name, schema, depth, direction Multi-level upstream/downstream dependency graph with automated refactoring risk score (LOW, MEDIUM, HIGH, CRITICAL).
explain_and_tune_sql sql_query, detailed Evaluates sargability, non-sargable functions (TRUNC, NVL, UPPER), FTS risks, NOT IN NULL pitfalls, compound index ordering, and AI query rewrites.
validate_oracle_sql sql_query, target_schema Validates Oracle dialect compliance, blocks non-Oracle constructs (LIMIT, BOOLEAN, ILIKE, IFNULL, + concat), and checks against schema catalog.
lookup_business_term query, tag Searches domain glossary for canonical business definitions, calculation rules, and canonical SQL predicates.

🔗 Transparent Synonym Resolution

Stored procedures often access objects via PUBLIC SYNONYM or remote database links (@dblink). LEAI snapshots ALL_SYNONYMS and transparently dereferences every alias to its authentic physical entity, avoiding broken chains and LLM hallucinations.


✂️ PL/SQL Semantic Compression

For massive 10,000-line packages, LEAI extracts only the specific subprogram body requested while producing a lightweight signature skeleton of the rest of the package. This reduces token consumption by up to 95% while eliminating prompt distraction.


🚀 Quickstart: Using LEAI in Any Project

Step 1: Install LEAI

# Via pip
pip install leai

# Or via uv (recommended)
uv tool install leai
# Or in an existing project
uv add leai

Step 2: Initialize Configuration

# In English (default)
leai init

# Or in Brazilian Portuguese
leai init --lang pt-BR

Configure your leai.yml:

language: "en-US"                 # "en-US" (default) or "pt-BR"
update_check: true                # true (default) or false (disable with --no-update-check)
dsn: "oracle://${DB_USER}:${DB_PASS}@${DB_HOST}:1521/${DB_SERVICE}"

schemas:
  - HR
  - SALES

rawPath: "./raw"
annotationsPath: "./annotations"
docPath: "./docs"

ai:
  default_provider: "ollama"      # ollama, local, openai, gemini, anthropic, deepseek, qwen, kimi, grok
  temperature: 0.2
  timeout: 300.0
  max_history_turns: 15           # Chat history turns retained in memory
  max_agent_iterations: 10        # Maximum reasoning tool iterations per turn
  max_subagent_iterations: 5      # Maximum iterations for specialized subagents
  providers:
    ollama:
      base_url: "http://localhost:11434/v1"
      model: "qwen2.5-coder:latest"
      temperature: 0.1
      num_ctx: 32768              # Context window size for Ollama (prevents truncation on large DDLs)
      keep_alive: "1h"            # Keep model memory resident
    local:
      base_url: "http://localhost:1234/v1" # LM Studio, vLLM, LocalAI
      model: "qwen2.5"
      num_ctx: 32768
      max_tokens: 4096
    openai:
      api_key: "${OPENAI_API_KEY}"
      model: "gpt-4o-mini"
      max_tokens: 4096
    gemini:
      api_key: "${GEMINI_API_KEY}"
      model: "gemini-2.5-flash"

Step 3: Run the Full Pipeline

# 1. Run complete pipeline (extract + annotate + compile)
leai

# 2. Trace impact of modifying a table
leai trace EMPLOYEES --depth 2

# 3. Launch interactive terminal copilot
leai chat

# 4. Or launch the Web Studio in browser
leai serve

📖 CLI Command Reference

1. Pipeline & Core Commands

leai (or leai generate)

Executes the full automated pipeline: technical extraction, business annotation synchronization, and final Markdown compilation.

Flag / Option Type Default Description
-L, --lang LOCALE Option en-US Interface language (en-US or pt-BR).
--no-update-check Flag False Disables remote PyPI check for newer versions on startup.
-c, --config PATH Option leai.yml Configuration file path.
-s, --schemas TEXT Option From config Specific schema(s) to process.
-t, --object-types TEXT Option From config Filter object types (e.g., -t tables -t packages).
--with-traces / --no-traces Flag True Include Mermaid dependency lineage and risk ratings.
--rag-json, --rag Flag False Also exports structured JSON chunks for Vector DBs.
-d, --depth INT Option 1 Traversal depth for dependency tree.
--seaweed Flag False Routes metadata through remote S3/SeaweedFS storage.
--no-cache Flag False 100% remote mode without local files.
--force-upload Flag False Forces re-upload to storage, bypassing SHA-256 cache.
leai -s HR -t tables -t packages --depth 2 --rag-json

leai extract

Extracts Oracle data dictionary definitions into raw JSON snapshots.

Flag / Option Type Default Description
-c, --config PATH Option leai.yml Path to leai.yml.
-s, --schemas TEXT Option From config Target schema(s).
-t, --object-types TEXT Option From config Object categories to extract.
-d, --days INT Option None Incremental: Extract only objects modified in the last N days via LAST_DDL_TIME.
--seaweed Flag False Stream snapshots directly to S3.
--no-cache Flag False Avoids saving files to local rawPath.
--force-upload Flag False Forces overwrite in storage bucket.
# Incremental extraction of objects modified in the last 30 days
leai extract --days 30

leai annotate

Synchronizes YAML business annotation stubs under annotations/ without overwriting existing human notes.

Flag / Option Type Default Description
-c, --config PATH Option leai.yml Path to leai.yml.
-s, --schemas TEXT Option From config Target schema(s).
-t, --object-types TEXT Option From config Object categories to synchronize.
--seaweed Flag False Syncs annotations directly in S3.
--no-cache Flag False Zero-cache remote execution.

leai doc <OBJECT>

Opens the in-terminal interactive documentation editor for a specific database entity.

leai doc EMPLOYEES
leai doc PKG_BILLING

leai compile

Recompiles the final Markdown documentation in docs/ with Mermaid.js diagrams.

Flag / Option Type Default Description
-c, --config PATH Option leai.yml Path to leai.yml.
-o, --object-name TEXT Option None Recompiles an isolated individual entity.
-s, --schemas TEXT Option From config Target schema(s).
-t, --object-types TEXT Option From config Filter object types.
--with-traces / --no-traces Flag True Include Mermaid lineage graphs.
--rag-json, --rag Flag False Export JSON chunks for Vector DBs.
-d, --depth INT Option 1 Traversal depth for dependency tree.
--seaweed Flag False Uses remote S3 snapshots.
--no-cache Flag False Pure remote mode.

2. Impact Analysis & Lineage (leai trace)

Generates multi-level upstream/downstream dependency trees, automated risk scores (LOW, MEDIUM, HIGH, CRITICAL), and Mermaid diagrams.

Flag / Option Type Default Description
OBJECT Argument Required Target entity name to trace.
-d, --depth INT Option 1 Maximum graph exploration depth.
-s, --schema TEXT Option None Schema of the object when resolving ambiguous names.
--offline Flag False Offline Mode: Resolves dependencies from local raw/ without Oracle connection.
-o, --output PATH Option None Custom path to save the generated Markdown dossier.
--rag-json, --rag Flag False Exports structured JSON chunks for RAG.
--seaweed Flag False Resolves metadata from remote S3.
--no-cache Flag False Pure remote execution.
leai trace CONTRACTS_TB --depth 3 --offline --output ./dossier.md

3. AI Copilot & Chat

leai ask <QUESTION>

Answers one-off natural language queries about database structure and business rules.

leai ask "Which procedures update customer status to INACTIVE?" -p gemini

leai chat

Launches the interactive terminal copilot console with conversation memory, syntax highlighting, and live tool execution.

Flag / Option Type Default Description
-p, --provider TEXT Option From config Active AI provider.
-m, --model TEXT Option From config Target AI model identifier.
-c, --config PATH Option leai.yml Path to leai.yml.
-w, --web Flag False Launches Web Studio server and opens chat in browser.
--seaweed Flag False Resolves metadata from remote S3.
--no-cache Flag False Pure in-memory execution.

In-Session Slash Commands:

  • /tune <sql>: Analyze query sargability, FTS risks, compound indexes, and get AI tuning proposals.
  • /validate <sql>: Validate Oracle SQL dialect compliance and cross-check against schema catalog.
  • /thoughts [on|off]: Toggle live reasoning/thought token streaming in the terminal.
  • /workflow <name> <obj>: Execute autonomous workflows (reverse-procedure, impact-analysis, safe-refactor).
  • /agent <role> <task>: Run specialized subagents (catalog_researcher, plsql_analyst, lineage_auditor, etc.).
  • /copy [all|code|N]: Copy response or code block directly to OS clipboard.
  • /doc [obj]: In-terminal YAML annotation & documentation editor.
  • /rule [list|add|del|find]: Manage global domain glossary and canonical rules.
  • /enrich [obj]: Auto-enrich business rules with LLM.
  • /compile [obj]: Recompile Markdown docs (supports single object).
  • /trace <obj>: Inline dependency & impact X-ray with Mermaid.
  • /tables: List all catalog tables with column counts and primary keys.
  • /schema [s]: Show full overview of schema objects.
  • /changes [d]: Audit objects modified in last N days (Default: 7).
  • /provider <p>: Switch AI provider dynamically (ollama, openai, gemini, anthropic, local, etc.).
  • /models [p]: List available AI models returned by provider API.
  • /model <p> [m]: Switch AI model dynamically.
  • /audit [last|session|export]: Inspect AI tool call trace and latency.
  • /tools: Quick viewer for last turn's tool execution inputs/outputs.
  • /save [file.md]: Export current conversation transcript to Markdown.
  • /clear: Clear conversation memory and reset screen.
  • /exit, /quit: Exit interactive copilot session.

Smart Autocompletion Prefixes:

  • @: Autocomplete catalog objects with icons (📋 TABLE, 📦 PACKAGE, ⚙️ PROCEDURE, 👁️ VIEW, ⚡ TRIGGER, 🔢 SEQUENCE, 🔗 SYNONYM).
  • #: Autocomplete business rules and canonical terms from the domain glossary.
  • /: Autocomplete slash commands and sub-arguments.

leai enrich

Invokes the LLM to inspect DDLs and draft automated business descriptions for undocumented entities.

leai enrich -o EMPLOYEES --overwrite -p gemini

leai models

Lists all configured AI providers, benchmarks network latency, and validates API keys.


4. Interactive Web Studio (leai serve)

Launches the visual LEAI Web Documentation & Annotation Studio daemon for in-browser collaborative annotation, instant Markdown compilation, and streaming AI copilot chat.

  • Real-time SeaweedFS S3 Sync: Annotation edits in the browser (POST /api/annotations) are saved locally and synced directly to the S3 bucket in real time.
  • Remote Fallback: Loads annotations directly from SeaweedFS S3 if not present on local disk.
Flag / Option Type Default Description
--port Option 8891 TCP port for local server.
--host Option 127.0.0.1 Network interface to bind.
--open-browser / --no-open-browser Flag True Launches default browser on startup.
-c, --config PATH Option leai.yml Path to configuration file.
-p, --provider TEXT Option From config AI provider override.
leai serve --host 0.0.0.0 --port 9000

5. Specialized Subagents (leai agent)

Executes isolated technical personas with restricted, laser-focused database toolsets:

  • leai agent list: Lists registered subagents.
  • leai agent run <ROLE> <TASK>: Executes a subagent.
Subagent Role Specialist Title Focus & Permitted Tools
catalog_researcher Catalog Researcher Explores schema entities, synonyms, column types. Tools: get_table_schema, search_catalog, lookup_business_term.
plsql_analyst PL/SQL Analyst Reverse engineers routines, algorithms, and SQL tuning. Tools: get_subprogram_source, grep_plsql_code, get_table_schema, explain_and_tune_sql, validate_oracle_sql.
lineage_auditor Lineage Auditor Evaluates cascading risk and impact before refactoring. Tools: trace_object_lineage, search_catalog, get_table_schema.
patch_generator Patch Engineer Generates zero-downtime DDL migration scripts and rollback plans. Tools: get_table_schema, get_subprogram_source, grep_plsql_code, validate_oracle_sql, explain_and_tune_sql.
doc_annotator Documentation Annotator Generates domain-aligned business annotations. Tools: get_table_schema, get_subprogram_source, lookup_business_term.
leai agent run plsql_analyst "Explain the interest calculation algorithm in PKG_BILLING and suggest index tuning"

6. Autonomous Workflows (leai workflow)

Multi-step orchestrated pipelines for high-risk engineering and reverse-engineering tasks:

  • leai workflow list: Lists available workflows (impact-analysis, safe-refactor, reverse-procedure).
  • leai workflow run <NAME> <TARGET>: Executes a workflow.
Workflow Name Aliases Description
impact-analysis impact, lineage 4-step impact assessment: entity resolution, graph exploration, risk calculation (LOW to CRITICAL), and Markdown dossier.
safe-refactor refactor, patch 4-step phased refactoring plan, backward compatibility checks, semantic patch generation, and rollback script.
reverse-procedure reverse, decomp 5-step PL/SQL reverse engineering: source extraction, CRUD access matrix (SELECT/INSERT/UPDATE/DELETE), outgoing routine/package calls, business validation rules, and Mermaid flowchart diagram.
# Comprehensive impact dossier before modifying a table
leai workflow run impact CUSTOMERS_TB --output ./customers_impact.md

# Safe phased refactoring plan and DDL patch
leai workflow run refactor PKG_BILLING -p claude

# Decompile and specify business rules of a PL/SQL procedure with Mermaid diagram
leai workflow run reverse-procedure PRC_ATUALIZA_SALARIO --output ./specs.md

7. Business Rules & Canonical Glossary (leai rule)

Codifies domain concepts and canonical SQL predicates so AI copilots generate accurate queries:

  • leai rule list: Lists codified business rules.
  • leai rule add <TERM>: Adds a canonical rule.
  • leai rule show <TERM>: Displays rule specifications.
leai rule add "ACTIVE_CUSTOMER" \
  --table "CUSTOMERS_TB" \
  --canonical-filter "RECORD_STATUS = 'A' AND IS_LOCKED = 0" \
  --definition "Customers eligible to place orders and receive billing invoices" \
  --tags "sales,compliance"

8. GitOps Version Control (leai git)

Treats documentation as first-class code (Docs-as-Code):

  • leai git status [--fetch]: Inspects repository status across tracked documentation paths.
  • leai git pull: Pulls latest annotations from remote Git repository.
  • leai git sync [-m "message"]: Stages, commits, and pushes modified annotations and docs.
leai git sync -m "docs(billing): update tax calculation business rules"

9. S3 / SeaweedFS Distributed Storage (leai seaweed)

Collaborative metadata persistence using S3-compatible Object Storage:

  • leai seaweed status: Verifies S3 connection and bucket health.
  • leai seaweed push: Uploads local snapshots to remote S3 bucket.
  • leai seaweed pull: Downloads snapshots from remote S3 bucket.
  • Web Studio Integration: Edits made in Web Studio (/serve) sync directly to SeaweedFS in real time.
  • Lifecycle Rules: Compatible with standard S3 lifecycle configurations (NoncurrentVersionExpiration on annotations/) to purge old non-current versions automatically.

10. Maintenance & Diagnostics

  • leai changes: Audits database objects modified in the last N days via Oracle's LAST_DDL_TIME (-d, --days, -u, --user).
  • leai doctor (or check): Pre-flight verification of Oracle connectivity, catalog permissions, pipeline directories, and AI credentials.
  • leai init: Generates a starter leai.yml (-L, --lang [en-US|pt-BR], -f, --force, -o, --output).

📁 Directory Structure

my_project/
├── leai.yml                  <-- Master configuration file
├── raw/                      <-- Raw technical JSON snapshots extracted from Oracle
│   └── HR.json
├── annotations/              <-- Human & AI business rules in YAML (non-destructive)
│   └── HR.yml
└── docs/                     <-- Final compiled Markdown documents for RAG and humans
    └── HR/
        ├── INDEX.md          <-- Master navigation index
        ├── tables/           <-- Tables with Mermaid diagrams and YAML frontmatter
        └── code_objects/     <-- Procedures, packages, functions, views

🧪 Automated Testing

To run the complete automated test suite:

# Run unit tests with test coverage reporting
uv run coverage run -m unittest discover tests
uv run coverage report -m

# Run code linter
uv run ruff check .

LEAI — Built for Oracle Engineers, Enterprise RAG, and Autonomous AI Copilots.

Release files for leai 0.3.11

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for leai 0.3.11
File Size Uploaded
leai-0.3.11.tar.gz 343.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for leai 0.3.11
File Interpreter ABI Platform
leai-0.3.11-py3-none-any.whl Python 3 none any Details

Total release size: 633.8 kB

Release files / leai-0.3.11.tar.gz

Download URL leai-0.3.11.tar.gz
Size 343.2 kB
Tags Source
SHA-256 checksum
How to use checksums
4dc97deaa5d782d7388e5fef6bacc60ef21629008680b308ba915a3fa374dae4
BLAKE2b-256 checksum
How to use checksums
defbfc8c550c2d0b35cc84a847bc225ebac4a743b91f307aa0b83ccddee4723b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / leai-0.3.11-py3-none-any.whl

Download URL leai-0.3.11-py3-none-any.whl
Size 290.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab864bcd3405a4c7957c5ed8473095784ea9c96f964d3ad41fd51a06247f4e9d
BLAKE2b-256 checksum
How to use checksums
847305c04724b45f36cfc86a2aee48f8769550a4b568e502332f4853e77d412c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page