# 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 Classifier
  • load_knowledge(): Carica rules, responses e conversations
  • predict(text): Predice intent ed entitร  per un testo
  • get_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:

python
@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 vocabolario
  • KnowledgeLoader: 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ร :

  1. ML Mode: Usa un modello GRU addestrato (DialoguePolicy)
  2. 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:

  1. Se slot richiesto mancante โ†’ rispondi con wait
  2. Se slot fornito, cerca nei cases โ†’ risposta specifica
  3. Se non trovato โ†’ fallback
  4. 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 matematici
  • location_query: Query geografiche
  • geocoding: 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 predictions

Caratteristiche:

  • 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:

python
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

Pipeline di Training

Pipeline Completa

bash
python -m pipeline

Step Manuali

bash
# 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_policy

Dettagli 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/ e training_data/rules/
  • Unisce responses da knowledge/responses/ e training_data/responses/
  • Unisce conversations da knowledge/conversations/ e training_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'utente

Modalitร  di Conversazione

Predictable Mode (default):

  • Bot risponde normalmente agli intent rilevati

Inputable Mode:

  • Bot aspetta input per uno slot specifico
  • Utente puรฒ annullare con #exit o #annulla

Flow di Esecuzione

Avvio API Server

bash
uvicorn main:app --reload

Endpoints:

  • POST /auth/token: Autenticazione JWT
  • POST /chatbot/message: Invia messaggio al chatbot
  • GET /health: Health check

Avvio Agent Interattivo

bash
python -m agent.agent

Entra 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`)

python
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOPING_ACTIVE = False  # Data augmentation
MIN_INTENT_CONFIDENCE = 0.20  # Soglia minima per accettare intent

Design Patterns Utilizzati

  1. Singleton: Per SessionManager
  2. Factory: Per la creazione dei modelli
  3. Strategy: Per diversi tipi di risposte
  4. Observer: Per la gestione degli eventi conversazionali
  5. Multi-task Learning: Per Intent Classification + NER

Estendere il Sistema

Aggiungere un nuovo modulo Operations

  1. Crea il file in agent/operations/
  2. Implementa una classe Operation o una funzione action_*
  3. Il sistema farร  auto-discovery

Modificare l'Intent Classifier

Per modificare l'architettura:

  1. Modifica intellective/intent_classifier.py
  2. Riaddestra con python -m intellective.train_intent_classifier

Aggiungere nuovi tag NER

  1. Modifica classes/ner_tag_builder.py
  2. Aggiungi i tag nella lista
  3. Riaddestra il modello

Personalizzare la Dialogue Policy

Modifica iperparametri in intellective/dialogue_policy.py:

python
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