Linguaggio cognitivo ibrido con runtime Python, integrazione LLM e UI interattiva
Project description
๐ง ASPERA โ Linguaggio Cognitivo Ibrido
Un framework innovativo per sistemi cognitivi che unisce ragionamento simbolico e intelligenza artificiale
๐ 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:
- LLM puri: potenti ma opachi, non tracciabili, non deterministici
- 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
- Python 3.10+
- Node.js 18+ (per UI)
- Account Groq con API key (https://console.groq.com)
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:
- Symbolic Reasoner: Applica regole deterministiche (inferenze)
- LLM Adapter: Gestisce ragionamento complesso e spiegazioni naturali
- 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
- Intro (30s): Mostra editor con esempio empathetic.aspera
- Parse (30s): CLI parse โ mostra AST JSON
- Run Mock (1m): Esegui con mock LLM, mostra trace
- Run Groq (1m): Esegui con Groq, mostra spiegazione naturale
- UI Playground (1m): Editor interattivo, modifica signals live
- Audit & Safety (1m): Mostra log tracciabilitร
- Wrap-up (30s): Architettura e next steps
๐ค Contributing
ASPERA รจ un progetto in evoluzione. Per contribuire:
- Fork del repository
- Crea feature branch (
git checkout -b feature/amazing-feature) - Commit con messaggi descrittivi
- 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
491785de5bb80b28d720c99a6a9e15a000847cbb2aa32fffbd272db191ea664e
|
|
| MD5 |
1a469186e89530cd47e968f9daca76bc
|
|
| BLAKE2b-256 |
a0e589c3847f782add0bd3108cc544fe5497913b1e7aaff9ac8527d176a59503
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4e6da0a5b5577a2dfca0d5c31564e68330c54004343ecfc2a7afc23987431a35
|
|
| MD5 |
8c7c9c69b88fb2952992d7221c084d17
|
|
| BLAKE2b-256 |
ff813a5192c5299f0be24b02bd7021d5c0924d2da3e7947307fad7f713a367f7
|