Skip to main content

Linguaggio cognitivo ibrido con runtime Python, integrazione LLM e UI interattiva

Project description

๐Ÿง  ASPERA โ€” Linguaggio Cognitivo Ibrido

ASPERA Logo

Un framework innovativo per sistemi cognitivi che unisce ragionamento simbolico e intelligenza artificiale

Python Version License Tests Groq Product Status Roadmap

๐Ÿš€ Quick Start โ€ข ๐Ÿ’ก Innovation โ€ข ๐Ÿ—๏ธ Architecture โ€ข ๐Ÿ“„ Paper โ€ข ๐Ÿ“š Docs โ€ข ๐Ÿงช Type Checking โ€ข ๐ŸŽฏ Threshold Learning โ€ข ๐Ÿ”Œ Plugins โ€ข ๐Ÿ“˜ Onboarding DSL โ€ข ๐Ÿค Contributing


๐Ÿ’ก What is ASPERA?

"ASPERA is the Python of AI Orchestration"

Just as Python became the universal language for data science, ASPERA is the foundational language for building cognitive AI systems.

ASPERA combines:

  • ๐Ÿงฎ Symbolic Reasoning - Fast, cheap, deterministic logic (80% of decisions)
  • ๐Ÿค– LLM Orchestration - Groq-powered intelligence when needed (20% of decisions)
  • ๐Ÿง  Memory Systems - Episodic and semantic memory for context
  • ๐ŸŽฏ Policy Intentions - Goal-oriented behavior strategies
  • ๐Ÿ“Š Complete Audit Trail - 100% explainability for compliance (FDA/SEC/GDPR)

๐Ÿš€ Why ASPERA?

I sistemi AI tradizionali soffrono di due limiti:

  1. LLM puri: potenti ma opachi, non tracciabili, non deterministici
  2. Sistemi simbolici: rigidi, limitati, incapaci di gestire ambiguitร 

ASPERA risolve questo dilemma attraverso un'architettura ibrida che:

  • โœ… Mantiene la trasparenza del ragionamento simbolico
  • โœ… Sfrutta la flessibilitร  dei LLM per situazioni complesse
  • โœ… Garantisce audit trail completo di ogni decisione
  • โœ… Permette policy-based control sui comportamenti

Include parser BNF completo, runtime orchestratore, integrazione Groq LLM, SDK Python e UI React interattiva.

๐ŸŽฏ Caratteristiche Principali

  • Linguaggio Cognitivo Dichiarativo: Sintassi leggibile per definire concetti, associazioni, stati, inferenze e intenzioni
  • Runtime Ibrido: Orchestrazione tra reasoner simbolico, memoria episodica/semantica e LLM
  • Integrazione Groq: Adapter per modelli LLM avanzati con spiegazioni naturali
  • SDK Python: API pulite per sviluppatori
  • Web Editor & Playground: UI React moderna con editor Monaco e runtime interattivo
  • Tracciabilitร  Completa: Audit log di ogni inferenza per trasparenza e debug
  • Estensibile: Architettura modulare per nuovi adapter LLM e feature linguistiche
  • ๐Ÿ†• Enterprise-Grade Error Messages: Parser con error messages ricchi, "did you mean" suggestions, esempi di codice (docs)
  • ๐Ÿ†• Macro System: Template riutilizzabili per DRY code, 5 built-in macros + custom macros (docs)
  • ๐Ÿ†• Resilienza Enterprise LLM: Circuit breaker, retry con backoff, cache LLM, graceful degradation (Groq reale stabile)

๐Ÿš€ Quick Start

Prerequisiti

Installazione

# 1. Clone e setup ambiente
cd aspera
python -m venv .venv

# Windows PowerShell
.venv\Scripts\Activate.ps1

# Linux/Mac
source .venv/bin/activate

# 2. Installa dipendenze
pip install -r requirements.txt

# 3. Configura variabili d'ambiente
cp .env.example .env
# Edita .env e aggiungi la tua GROQ_API_KEY

Uso CLI

# Parse un file .aspera
python aspera_cli.py parse aspera/lang/examples/empathetic.aspera -o ast.json

# Run con auto-detect (RACCOMANDATO - usa Groq se GROQ_API_KEY configurata)
python aspera_cli.py run --aspera aspera/lang/examples/empathetic.aspera --signals examples/signals.json

# Run forzando Groq
python aspera_cli.py run --aspera aspera/lang/examples/empathetic.aspera --signals examples/signals.json --mode groq

# Run con mock LLM (solo per testing, no API key needed)
python aspera_cli.py run --aspera aspera/lang/examples/empathetic.aspera --signals examples/signals.json --mode mock

# Valida un AST
python aspera_cli.py validate ast.json

Plugin: installazione, discovery e uso (incluso Gemini)

# Installa plugin esterni (esempi)
python -m pip install -e plugins/aspera-vector-weaviate
python -m pip install -e plugins/aspera-llm-openai
python -m pip install -e plugins/aspera-llm-gemini

# Scopri e lista plugin disponibili
python aspera_cli.py plugins discover
python aspera_cli.py plugins list

Uso programmatico con PluginManager:

from aspera.plugins.plugin_interface import PluginManager

pm = PluginManager()
pm.discover_plugins()

llm = pm.get_plugin("openai_llm") or pm.get_plugin("gemini_llm")
if llm:
    llm.initialize({"model": "gpt-4o-mini", "temperature": 0.7})
    print(llm.generate_inference(context={}, signals={}, rules=["if a then b"]))

vec = pm.get_plugin("weaviate_vector")
if vec:
    vec.initialize({"url": "http://localhost:8080", "class_name": "AsperaVector"})
    vec.save("demo", "hello")
    print("Loaded:", vec.load("demo"))

๐Ÿ”Œ Plugins: installazione rapida

# Installa plugin pubblici (LLM OpenAI e Vector Weaviate)
python -m pip install aspera-llm-openai aspera-vector-weaviate

# Scopri e lista plugin disponibili
python aspera_cli.py plugins discover
python aspera_cli.py plugins list

Esempio programmatico (PluginManager)

from aspera.plugins.plugin_interface import PluginManager

pm = PluginManager()
pm.discover_plugins()

# OpenAI LLM (richiede OPENAI_API_KEY nell'ambiente)
llm = pm.get_plugin("openai_llm")
if llm:
    llm.initialize({"model": "gpt-4o-mini", "temperature": 0.7})
    res = llm.generate_inference(context={}, signals={}, rules=["if a then b"])
    print("LLM result:", res)

# Weaviate Vector Storage
vec = pm.get_plugin("weaviate_vector")
if vec:
    vec.initialize({"url": "http://localhost:8080", "class_name": "AsperaVector"})
    vec.save("demo", "hello")
    print("Loaded:", vec.load("demo"))

LSP (Language Server) Setup

Per abilitare diagnostica in editor e completamento base:

# Avvio server LSP (stdin/stdout)
python -m aspera.tools.lsp_server
# oppure, se installato come script
aspera-lsp

In VS Code, configura un client LSP generico puntando al comando sopra. Aggiungi anche .vscode/settings.json con:

{
  "ltex.language": "it-IT",
  "python.analysis.diagnosticMode": "openFilesOnly"
}

Funzionalitร  attuali: diagnostica parser in tempo reale, completion basica (concept., signals., state., threshold().

Telemetry (OpenTelemetry)

ASPERA emette traces/metrics OTLP (HTTP) per observe/step/decide. Per provare in locale:

$env:OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318"
python aspera_cli.py run --aspera agents\enterprise\ecommerce_conversion_optimizer\conversion_optimizer.aspera --signals examples\signals_ecommerce.json --mode mock

Metriche principali: aspera_observe_total, aspera_step_total, aspera_decide_total. Configura il tuo collector OTLP (es. OpenTelemetry Collector) e visualizza in Grafana/Tempo.

Smoke test con Groq (tutti gli agent)

$code = @"
import sys, os, json
from pathlib import Path
sys.path.insert(0, os.path.abspath('.'))
from aspera.sdk.client import create_engine, run_observation
files = [str(p) for p in Path('agents').rglob('*.aspera')]
report = []
for f in files:
    print('==> ', f)
    eng = create_engine(f, use_mock_llm=False, auto_detect=True, enable_cache=True)
    res = run_observation(eng, {}, {}, True)
    report.append({'agent': f, 'actions': res['actions'], 'explanation': res['explanation']})
with open('SMOKE_REPORT_GROQ.json','w', encoding='utf-8') as fp:
    json.dump(report, fp, ensure_ascii=False, indent=2)
print('Saved: SMOKE_REPORT_GROQ.json')
"@
$code | python -

Uso Docker

# Build e avvia tutti i servizi
docker-compose up -d

# Accedi all'UI
# http://localhost:3000

# API backend
# http://localhost:8000/docs

Uso SDK

from aspera.sdk.client import create_engine, run_observation

# Carica un programma Aspera
engine = create_engine("examples/empathetic.aspera")

# Esegui osservazione
signals = {
    "coerenza_comportamento": 0.7,
    "trasparenza": 0.8
}
context = {
    "experiences": {"shared": 5},
    "interaction_count": 10
}

result = run_observation(engine, signals, context)

print("Azioni:", result["actions"])
print("Spiegazione:", result["explanation"])
print("Trace:", result["audit_trace"])

๐Ÿ“– Struttura Progetto

aspera/
โ”œโ”€ README.md
โ”œโ”€ LICENSE
โ”œโ”€ pyproject.toml
โ”œโ”€ requirements.txt
โ”œโ”€ .env.example
โ”œโ”€ aspera_cli.py                    # CLI principale
โ”œโ”€ aspera/
โ”‚  โ”œโ”€ __init__.py
โ”‚  โ”œโ”€ lang/                         # Definizione linguaggio
โ”‚  โ”‚  โ”œโ”€ grammar.aspera.bnf         # Grammatica BNF
โ”‚  โ”‚  โ”œโ”€ parser.py                  # Parser Python
โ”‚  โ”‚  โ”œโ”€ ast_schema.json            # JSON Schema AST
โ”‚  โ”‚  โ””โ”€ examples/                  # Esempi .aspera
โ”‚  โ”œโ”€ runtime/                      # Runtime cognitivo
โ”‚  โ”‚  โ”œโ”€ engine.py                  # CognitiveEngine
โ”‚  โ”‚  โ”œโ”€ symbolic.py                # Reasoner simbolico
โ”‚  โ”‚  โ”œโ”€ memory.py                  # Memoria episodica/semantica
โ”‚  โ”‚  โ”œโ”€ policy.py                  # Policy executor
โ”‚  โ”‚  โ””โ”€ llm_adapters/
โ”‚  โ”‚      โ””โ”€ groq_adapter.py        # Groq integration
โ”‚  โ”œโ”€ sdk/                          # SDK pubblico
โ”‚  โ”‚  โ”œโ”€ client.py
โ”‚  โ”‚  โ””โ”€ utils.py
โ”‚  โ”œโ”€ web/                          # Web stack
โ”‚  โ”‚  โ”œโ”€ api.py                     # FastAPI backend
โ”‚  โ”‚  โ””โ”€ ui/                        # React frontend
โ”‚  โ””โ”€ tests/                        # Test suite
โ”œโ”€ docs/                            # Documentazione
โ”œโ”€ training/                        # Training plan & scripts
โ”œโ”€ datasets/                        # Dataset examples
โ””โ”€ infra/                           # Docker & CI

๐Ÿง  Linguaggio Aspera

Sintassi Base

// Definisci un concetto
concept "fiducia" {
  definition: "credenza nella coerenza e buona volontร  dell'altro";
  signals: ["coerenza_comportamento", "trasparenza", "esperienze_condivise"];
  baseline: 0.5;
}

// Associa concetti
associate "fiducia" -> "cooperazione" {
  weight: 0.8;
  bidirectional: true;
}

// Stato del sistema
state {
  mood: "neutral";
  energy_level: 0.7;
  interaction_phase: "initial";
}

// Regola di inferenza
inference "valuta_fiducia" {
  when: signals.coerenza_comportamento > 0.6 and experiences.shared > 3;
  then: increase concept:"fiducia" by 0.2;
  confidence: 0.8;
}

// Intenzione strategica
intention "costruire_cooperazione" {
  priority: high;
  strategy:
    - if concept:"fiducia" < 0.4 -> action: "aumenta_trasparenza"
    - else -> action: "proponi_collaborazione_graduale";
}

// Template spiegazione
explain {
  format: "human";
  template: "Credo che tu sia [interpretation] perchรฉ ho osservato [evidence].";
}

๐Ÿ”ง Architettura Runtime

CognitiveEngine

Il motore cognitivo orchestra tre componenti:

  1. Symbolic Reasoner: Applica regole deterministiche (inferenze)
  2. LLM Adapter: Gestisce ragionamento complesso e spiegazioni naturali
  3. Memory System: Mantiene contesto episodico e semantico

Flusso di Esecuzione

observe(signals, context) โ†’ step() โ†’ decide() โ†’ explain()
     โ†“                         โ†“         โ†“          โ†“
  Context              Apply Rules   Select    Generate
  Update               Update State  Actions   Explanation

๐Ÿค– Integrazione Groq

Configurazione

# .env
GROQ_API_KEY=gsk_...
ASPERA_ENV=development
ASPERA_DB_URL=sqlite:///aspera.db

Prompt Templates & Resilienza

ASPERA include template ottimizzati per e resilienza LLM:

  • Inference: Produce JSON strutturato con changes, confidence, rationale
  • Explain: Genera spiegazioni empatiche seguendo template personalizzati
  • Policy: Traduce strategie in azioni prioritizzate
  • Resilienza: Circuit breaker (soglia 3, timeout 30s) + retry (3 tentativi, backoff 2x) + cache dei risultati

๐Ÿ“Š Training & Valutazione

Vedi training/plan.md per dettagli su:

  • Dataset: Conversazioni annotate, segnali multimodali, rationales umane
  • Distillation: Supervised fine-tuning + RLHF esteso
  • Metriche: EmpathyScore, CoherenceConsistency, RationaleQuality, TaskSuccess, SafetyScore
  • Synthetic Generator: Script per generare 50+ scenari toy

๐Ÿ›ก๏ธ Sicurezza & Ethics

  • Audit Log Obbligatorio: Ogni inferenza tracciata (rule, inputs, confidence, outputs)
  • Human-in-the-Loop: Azioni ad alto impatto richiedono conferma umana
  • Output Sanitization: Blacklist/whitelist per prevenire contenuti dannosi
  • Privacy: No secrets in code, gestione retention dati documentata

๐Ÿงช Testing

# Run test suite
pytest aspera/tests/ -v

# Con coverage
pytest aspera/tests/ --cov=aspera --cov-report=html

# Test specifici
pytest aspera/tests/test_parser.py -k "test_parse_concept"

๐Ÿ“š Documentazione Completa

๐ŸŽฌ Demo Video Script

  1. Intro (30s): Mostra editor con esempio empathetic.aspera
  2. Parse (30s): CLI parse โ†’ mostra AST JSON
  3. Run Mock (1m): Esegui con mock LLM, mostra trace
  4. Run Groq (1m): Esegui con Groq, mostra spiegazione naturale
  5. UI Playground (1m): Editor interattivo, modifica signals live
  6. Audit & Safety (1m): Mostra log tracciabilitร 
  7. Wrap-up (30s): Architettura e next steps

๐Ÿค Contributing

ASPERA รจ un progetto in evoluzione. Per contribuire:

  1. Fork del repository
  2. Crea feature branch (git checkout -b feature/amazing-feature)
  3. Commit con messaggi descrittivi
  4. Push e apri Pull Request

๐Ÿ“„ License

MIT License - vedi file LICENSE

๐Ÿ‘ค Author

RTH Italia ideato da Christian Quintino De Luca

๐Ÿ”— Links


ASPERA โ€” Thinking, Transparently

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aspera-0.10.5.tar.gz (79.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aspera-0.10.5-py3-none-any.whl (84.6 kB view details)

Uploaded Python 3

File details

Details for the file aspera-0.10.5.tar.gz.

File metadata

  • Download URL: aspera-0.10.5.tar.gz
  • Upload date:
  • Size: 79.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for aspera-0.10.5.tar.gz
Algorithm Hash digest
SHA256 491785de5bb80b28d720c99a6a9e15a000847cbb2aa32fffbd272db191ea664e
MD5 1a469186e89530cd47e968f9daca76bc
BLAKE2b-256 a0e589c3847f782add0bd3108cc544fe5497913b1e7aaff9ac8527d176a59503

See more details on using hashes here.

File details

Details for the file aspera-0.10.5-py3-none-any.whl.

File metadata

  • Download URL: aspera-0.10.5-py3-none-any.whl
  • Upload date:
  • Size: 84.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for aspera-0.10.5-py3-none-any.whl
Algorithm Hash digest
SHA256 4e6da0a5b5577a2dfca0d5c31564e68330c54004343ecfc2a7afc23987431a35
MD5 8c7c9c69b88fb2952992d7221c084d17
BLAKE2b-256 ff813a5192c5299f0be24b02bd7021d5c0924d2da3e7947307fad7f713a367f7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page