# Architettura del Sistema
Panoramica del Sistema
Cognitor Assistant รจ un assistente virtuale conversazionale basato su tecniche di Natural Language Understanding (NLU). Il sistema combina multiple tecnologie di Machine Learning per comprendere l'intenzione dell'utente e gestire conversazioni contestuali.
Caratteristiche Principali
- Classificazione Intent: Identifica l'intenzione dell'utente tramite una rete neurale BiGRU con Attention
- Riconoscimento Entitร (NER): Estrae entitร ๅฝๅๅฎไฝ dal testo usando tag BIO con CRF
- Gestione Stato Dialogo: Mantiene il contesto della conversazione e predice le azioni del bot
- Sistema a Slot: Gestisce informazioni strutturate necessarie per completare azioni
- Operazioni Personalizzate: Supporta azioni custom con auto-discovery
Stack Tecnologico
- PyTorch: Framework per il deep learning
- FastText: Word embeddings e tokenizzazione
- FastAPI: Web framework per l'API REST
- CRF (Conditional Random Fields): Per il riconoscimento delle entitร
- Uvicorn: Server ASGI
- Pandas: Manipolazione dati
- Scikit-learn: Utilitร ML
- NLTK: NLP utilities
- python-jose: JWT authentication
- PyYAML: Parsing YAML
- torchcrf: CRF layer per NER
Architettura Generale
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ API Layer (FastAPI) โ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ /auth/token โ โ /chatbot/message โ โ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Agent (agent/agent.py) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Prediction Pipeline โ โ
โ โ 1. Predict Intent + NER โ โ
โ โ 2. Extract Entities โ โ
โ โ 3. Update Session Slots โ โ
โ โ 4. Dialogue State Policy โ Next Action โ โ
โ โ 5. Generate Response โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Session โ โ Dialogue State โ โ Rule Interpreterโ
โ Manager โ โ Policy โ โ (DSL Runtime) โ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Entity โ โ DialoguePolicy (ML) โ โ Responses โ
โ Manager โ โ or Heuristic โ โ Templates โ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโ
โ Operations โ
โ Manager โ
โโโโโโโโโโโโโโโโโโโComponenti Principali
1. Agent (`agent/agent.py`)
ร il componente centrale che coordina tutti gli altri componenti.
Responsabilitร :
- Caricamento dei modelli ML
- Predizione di intent ed entitร
- Coordinamento della generazione delle risposte
- Gestione della pipeline di conversazione
Metodi principali:
load_models(): Carica il modello Intent Classifierload_knowledge(): Carica rules, responses e conversationspredict(text): Predice intent ed entitร per un testoget_response(intent_name, slots, history): Genera la risposta
2. Session Manager (`agent/session_manager.py`)
Gestisce le sessioni di conversazione.
Responsabilitร :
- Creazione e gestione di sessioni utente
- Mantenimento dello storico della conversazione
- Gestione del contesto (slot) per ogni sessione
- Timeout e cleanup delle sessioni inattive
Struttura dati:
@dataclass
class ConversationSession:
session_id: str
created_at: datetime
updated_at: datetime
history: list[dict] # [{role, content, intent, entities, timestamp}]
context: dict # Slot della conversazione
metadata: dict
waiting_for_slot: dict | None # Se il bot aspetta uno slot
agent_mode: str # "predictable" o "inputable"3. Entity Manager (`agent/entity_manager.py`)
Gestisce le entitร estratte dalla conversazione.
Responsabilitร :
- Storage delle entitร riconosciute
- Lookup per nome o etichetta
- Gestione della confidence delle entitร
4. Model Loader (`agent/model_loader.py`)
Carica i modelli ML e la knowledge base.
Componenti:
ModelLoader: Carica il modello Intent Classifier e il vocabolarioKnowledgeLoader: Carica rules, responses e conversations
5. Dialogue State Policy (`agent/dialogue_state_policy.py`)
Gestisce lo stato del dialogo e predice la prossima azione del bot.
Due modalitร :
- ML Mode: Usa un modello GRU addestrato (DialoguePolicy)
- Heuristic Mode: Usa longest-suffix match sulle storie YAML (fallback)
Ispirato a Rasa TED Policy:
- Addestrato su "storie" di conversazione
- Rappresenta lo stato come sequenza di intent utente recenti
- Predice la prossima azione tramite classificazione
6. Rule Interpreter (`agent/rule_interpreter.py`)
Runtime DSL che interpreta le regole dichiarative definite in YAML.
Responsabilitร :
- Interpretazione delle rules per generare risposte
- Gestione degli slot (required, optional)
- Matching dei casi (cases)
- Sostituzione dei placeholder
{SLOT_NAME}nelle risposte - Esecuzione delle operazioni (prefisso
__)
Logica di selezione risposta:
- Se slot richiesto mancante โ rispondi con
wait - Se slot fornito, cerca nei
casesโ risposta specifica - Se non trovato โ
fallback - Altrimenti โ
default
7. Operations Manager (`agent/operations/manager.py`)
Gestisce le operazioni personalizzate del bot.
Caratteristiche:
- Auto-discovery delle operations nella cartella
operations/ - Supporta classi che ereditano da
Operation - Supporta funzioni con pattern
action_*o*_action - Espone i manager (Session, Entity) alle operations
Operazioni disponibili:
calculate: Esegue calcoli matematicilocation_query: Query geografichegeocoding: Conversione indirizzi/coordinate
8. Slot Manager (`agent/slot_manager.py`)
Gestisce gli slot in modo data-driven basato sulle rules.
Responsabilitร :
- Validazione dei valori degli slot
- Aggiornamento del contesto della sessione
- Gestione delle entitร estratte dal NER
Modelli ML
1. FastText (Word Embeddings)
Scopo: Generare rappresentazioni vettoriali delle parole
Configurazione:
- Modello: Skip-gram
- Dimensione: 300
- Epoch: 25
- Learning rate: 0.1
- minCount: 1
- wordNgrams: 2
- minn: 2, maxn: 5 (subwords)
Output:
models/fasttext_model.bin: Modello completo.cognitor/wordvectors.vec: Matrice embeddings (word2vec format).cognitor/vocab.json: Vocabolario
2. Intent Classifier (PyTorch BiGRU + Attention)
Architettura:
Input Text
โ
โผ
Embedding Layer (FastText, freeze=True) โโโ 300 dim
โ
โผ
BiGRU (hidden_dim=256, bidirectional)
โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโ
โผ โผ โผ
Attention Layer NER Branch Intent Branch
โ โ โ
โผ โผ โผ
Dropout(0.3) Linear+CRF Dropout(0.3) โ Linear
โ โ โ
โผ โผ โผ
Intent logits NER tags Intent predictionsCaratteristiche:
- Embedding inizializzato con FastText (congelato)
- BiGRU bidirezionale per catturare contesto
- Attention per focalizzarsi su parti rilevanti
- CRF (Conditional Random Field) per NER sequence labeling
- Multi-task: Intent Classification + NER
3. Dialogue Policy (PyTorch GRU)
Scopo: Predire la prossima azione del bot dato lo storico
Architettura:
Context Intents [T] โโโ Embedding โโโ
Context Actions [T] โโโ Embedding โโโผโโโ Sum โโโ GRU โโโ Dropout
โ โ
โโโโโโโโโโโผโโโโ Concatenate โโโ Linear โ Action logits
โ
Current Intent โโโ Embedding โโโโโโโโโโโโโโโโโโโIperparametri:
- Embed dim: 64
- Hidden dim: 128
- Dropout: 0.3
Personalizzabili in intellective/dialogue_policy.py:
DIALOGUE_POLICY_EMBED_DIM: int = 64 # default: 64
DIALOGUE_POLICY_HIDDEN_DIM: int = 128 # default: 128
DIALOGUE_POLICY_DROPOUT: float = 0.3 # default: 0.3Pipeline di Training
Pipeline Completa
python -m pipelineStep Manuali
# 1. Genera corpus FastText
python -m pipeline.intent_builder
# 2. Allena FastText
python -m intellective.train_fast_text
# 3. Allena Intent Classifier
python -m intellective.train_intent_classifier
# 4. Allena Dialogue Policy (opzionale)
python -m intellective.train_dialogue_policyDettagli Pipeline
Step 0: Validazione Dataset
- Valida intents ed entitร NER
- Controlla consistenza dei file YAML
Step 1: Generazione Corpus FastText
- Legge intents da
knowledge/intents/*.yaml - Genera
.cognitor/fast-text.txt(raw text)
Step 1.5: Merge Knowledge
- Unisce rules da
knowledge/rules/etraining_data/rules/ - Unisce responses da
knowledge/responses/etraining_data/responses/ - Unisce conversations da
knowledge/conversations/etraining_data/conversations/ - Output in
.cognitor/
Step 2: Training FastText
- Train unsupervised su corpus
- Estrae word vectors
Step 3: Generazione Dataset NLU
- Tokenizza usando FastText
- Genera tag NER BIO
- Salva
.cognitor/tokenized_data.npy
Step 4: Training Intent Classifier
- BiGRU + Attention + CRF
- Early stopping con patience=10
- Salva
models/intent_model_fast.pth
Step 5: Training Dialogue Policy
- GRU encoder per sequence di intent
- Addestrato su conversazioni YAML
- Salva
models/dialogue_policy.pth
Gestione del Dialogo
Flow di Predizione
1. Utente invia messaggio
โ
โผ
2. Agent.predict() โ Intent + Entities
โ
โผ
3. SlotManager.update_session() โ Estrae slot da entitร
โ
โผ
4. DialogueStatePolicy.predict_next_action()
โโ ML Mode: Usa DialoguePolicy (se disponibile)
โโ Heuristic Mode: Longest-suffix match
โ
โผ
5. Se azione trovata โ Ritorna response dalla TED policy
Altrimenti โ RuleInterpreter.handle_intent()
โ
โโ Slot required mancante โ wait response
โโ Slot fornito โ cerca nei cases
โโ Valore non trovato โ fallback
โโ Default โ default response
โ
โผ
6. Applica bot_slots (set_slots dalla rule)
โ
โผ
7. Risposta all'utenteModalitร di Conversazione
Predictable Mode (default):
- Bot risponde normalmente agli intent rilevati
Inputable Mode:
- Bot aspetta input per uno slot specifico
- Utente puรฒ annullare con
#exito#annulla
Flow di Esecuzione
Avvio API Server
uvicorn main:app --reloadEndpoints:
POST /auth/token: Autenticazione JWTPOST /chatbot/message: Invia messaggio al chatbotGET /health: Health check
Avvio Agent Interattivo
python -m agent.agentEntra in un loop di conversazione testuale dove รจ possibile:
- Inviare messaggi
- Vedere intent predetti e confidenza
- Vedere entitร estratte
- Interagire con slot richiesti
Configurazione (`config.py`)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOPING_ACTIVE = False # Data augmentation
MIN_INTENT_CONFIDENCE = 0.20 # Soglia minima per accettare intentDesign Patterns Utilizzati
- Singleton: Per SessionManager
- Factory: Per la creazione dei modelli
- Strategy: Per diversi tipi di risposte
- Observer: Per la gestione degli eventi conversazionali
- Multi-task Learning: Per Intent Classification + NER
Estendere il Sistema
Aggiungere un nuovo modulo Operations
- Crea il file in
agent/operations/ - Implementa una classe
Operationo una funzioneaction_* - Il sistema farร auto-discovery
Modificare l'Intent Classifier
Per modificare l'architettura:
- Modifica
intellective/intent_classifier.py - Riaddestra con
python -m intellective.train_intent_classifier
Aggiungere nuovi tag NER
- Modifica
classes/ner_tag_builder.py - Aggiungi i tag nella lista
- Riaddestra il modello
Personalizzare la Dialogue Policy
Modifica iperparametri in intellective/dialogue_policy.py:
DIALOGUE_POLICY_EMBED_DIM: int = 64 # default: 64
DIALOGUE_POLICY_HIDDEN_DIM: int = 128 # default: 128
DIALOGUE_POLICY_DROPOUT: float = 0.3 # default: 0.3