Merge branch 'main' into 38-news-problem

This commit is contained in:
2025-10-29 23:30:50 +01:00
7 changed files with 32 additions and 331 deletions

View File

@@ -1,60 +0,0 @@
# Differenze fra prompt
Resoconto fatto da Claude 4.5
## Query Check
- Prolisso (~50 righe), regole ripetitive
- Mancava contesto temporale
+ Conciso (~40 righe), regole chiare
+ Aggiunto {{CURRENT_DATE}} placeholder (sostituito automaticamente)
+ Schema JSON singolo e diretto
## Team Market
- Non enfatizzava priorità dati API
- Mancavano timestamp nei report
+ Sezione "CRITICAL DATA RULE" su priorità real-time
+ Timestamp OBBLIGATORI per ogni prezzo
+ Richiesta fonte API esplicita
+ Warning se dati parziali/incompleti
+ **DIVIETO ESPLICITO** di inventare prezzi placeholder
## Team News
- Output generico senza date
- Non distingueva dati freschi/vecchi
+ Date pubblicazione OBBLIGATORIE
+ Warning se articoli >3 giorni
+ Citazione fonti API
+ Livello confidenza basato su quantità/consistenza
## Team Social
- Sentiment senza contesto temporale
- Non tracciava platform/engagement
+ Timestamp post OBBLIGATORI
+ Warning se post >2 giorni
+ Breakdown per platform (Reddit/X/4chan)
+ Livello engagement e confidenza
## Team Leader
- Non prioritizzava dati freschi da agenti
- Mancava tracciamento recency
+ Sezione "CRITICAL DATA PRINCIPLES" (7 regole, aggiunte 2)
+ "Never Override Fresh Data" - divieto esplicito
+ Sezioni "Data Freshness" e "Sources" obbligatorie
+ Timestamp per OGNI blocco dati
+ Metadata espliciti su recency
+ **NEVER FABRICATE** - divieto di inventare dati
+ **NO EXAMPLES AS DATA** - divieto di usare dati esempio come dati reali
## Report Generation
- Formattazione permissiva
- Non preservava timestamp/sources
+ "Data Fidelity" rule
+ "Preserve Timestamps" obbligatorio
+ Lista ❌ DON'T / ✅ DO chiara (aggiunte 2 regole)
+ Esempio conditional logic
+ **NEVER USE PLACEHOLDERS** - divieto di scrivere "N/A" o "Data not available"
+ **NO EXAMPLE DATA** - divieto di usare prezzi placeholder
## Fix Tecnici Applicati
1. **`__init__.py` modificato**: Il placeholder `{{CURRENT_DATE}}` ora viene sostituito automaticamente con `datetime.now().strftime("%Y-%m-%d")` al caricamento dei prompt
2. **Regole rafforzate**: Aggiunte regole esplicite contro l'uso di dati placeholder o inventati
3. **Conditional rendering più forte**: Specificato che se una sezione manca, va COMPLETAMENTE omessa (no headers, no "N/A")

View File

@@ -27,16 +27,16 @@ models:
- name: mistral-large-latest
label: Mistral
ollama:
- name: qwen3:8b
label: Qwen 3 (8B)
- name: qwen3:4b
label: Qwen 3 (4B)
- name: qwen3:1.7b
label: Qwen 3 (1.7B)
- name: qwen3:32b
label: Qwen 3 (32B)
- name: qwen3:4b
label: Qwen 3 (4B)
- name: qwen3:8b
label: Qwen 3 (8B)
- name: qwen3:14b
label: Qwen 3 (14B)
- name: qwen3:32b
label: Qwen 3 (32B)
- name: phi4-mini:3.8b
label: Phi 4 mini (3.8b)
@@ -49,7 +49,7 @@ api:
agents:
strategy: Conservative
team_model: qwen3:14b # the agents
team_model: qwen3:8b # the agents
team_leader_model: gemini-2.0-flash # the team leader
query_analyzer_model: qwen3:14b # query check
report_generation_model: qwen3:32b # ex predictor
query_analyzer_model: qwen3:1.7b # query check
report_generation_model: qwen3:8b # ex predictor

View File

@@ -1,113 +0,0 @@
# Stato Attuale: Architettura e Flussi (upo-appAI)
Sintesi dellarchitettura attuale e del flusso runtime dellapp, con diagrammi compatti e riferimenti ai componenti principali.
## Panorama Componenti
- `src/app/__main__.py`: Entrypoint. Avvia interfaccia Gradio (`ChatManager`) e bot Telegram (`TelegramApp`).
- `interface/chat.py`: UI Gradio. Gestisce storico chat, chiama `Pipeline.interact()`.
- `interface/telegram_app.py`: Bot Telegram. Gestisce conversazione, configura modelli/strategia, esegue `Pipeline.interact_async()` e genera PDF.
- `agents/core.py`: Definisce `PipelineInputs`, agenti (`Team`, `Query Check`, `Report Generator`) e strumenti (Market/News/Social).
- `agents/pipeline.py`: Orchestrazione via `agno.workflow`. Steps: Query Check → Gate → Info Recovery (Team) → Report Generation.
- `agents/prompts/…`: Istruzioni per Team Leader, Market/News/Social agents, Query Check e Report Generation.
- `api/tools/*.py`: Toolkits aggregati (MarketAPIsTool, NewsAPIsTool, SocialAPIsTool) basati su `WrapperHandler`.
- `api/*`: Wrappers per provider esterni (Binance, Coinbase, CryptoCompare, YFinance, NewsAPI, GoogleNews, CryptoPanic, Reddit, X, 4chan).
- `api/wrapper_handler.py`: Fallback con retry e try_all sui wrappers.
- `configs.py`: Config app, modelli, strategie, API e caricamento da `configs.yaml`/env.
## Architettura (Overview)
```mermaid
flowchart TD
U[User] --> I{Interfacce}
I -->|Gradio| CM[ChatManager]
I -->|Telegram| TG[TelegramApp]
CM --> PL[Pipeline]
TG --> PL
PL --> WF[Workflow\nQuery Check → Gate → Info Recovery → Report Generation]
WF --> TM[Team Leader + Members]
TM --> T[Tools\nMarket or News or Social]
T --> W[Wrappers]
W --> EX[External APIs]
WF --> OUT[Report]
TG --> PDF[MarkdownPdf\ninvio documento]
CM --> OUT
```
## Sequenza (Telegram)
```mermaid
sequenceDiagram
participant U as User
participant TG as TelegramBot
participant PL as Pipeline
participant WF as Workflow
participant TL as TeamLeader
participant MK as MarketTool
participant NW as NewsTool
participant SC as SocialTool
participant API as External APIs
U->>TG: /start + messaggio
TG->>PL: PipelineInputs(query, modelli, strategia)
PL->>WF: build_workflow()
WF->>WF: Step: Query Check
alt is_crypto == true
WF->>TL: Step: Info Recovery
TL->>MK: get_products / get_historical_prices
MK->>API: Binance/Coinbase/CryptoCompare/YFinance
TL->>NW: get_latest_news / get_top_headlines
NW->>API: NewsAPI/GoogleNews/CryptoPanic/DuckDuckGo
TL->>SC: get_top_crypto_posts
SC->>API: Reddit/X/4chan
WF->>TL: Step: Report Generation
else
WF-->>PL: Stop workflow (non-crypto)
end
PL-->>TG: Report (Markdown)
TG->>TG: Genera PDF e invia
```
## Workflow & Agenti
- Step 1: `Query Check` (Agent) — valida la natura crypto della richiesta, output schema `QueryOutputs` (`response`, `is_crypto`).
- Step 2: Gate — interrompe se `is_crypto == false`.
- Step 3: `Info Recovery` (Team) — TeamLeader orchestration con `PlanMemoryTool` e Reasoning, dispatch agli agenti Market/News/Social.
- Step 4: `Report Generation` (Agent) — sintetizza i risultati nel report finale (stringa Markdown).
## Tools & Wrappers
- MarketAPIsTool → `BinanceWrapper`, `YFinanceWrapper`, `CoinBaseWrapper`, `CryptoCompareWrapper`.
- NewsAPIsTool → `GoogleNewsWrapper`, `DuckDuckGoWrapper`, `NewsApiWrapper`, `CryptoPanicWrapper`.
- SocialAPIsTool → `RedditWrapper`, `XWrapper`, `ChanWrapper`.
- `WrapperHandler`:
- `try_call` con retry per wrapper corrente, fallback sequenziale.
- `try_call_all` per aggregare risultati multipli.
- Configurabile via `set_retries(attempts, delay_seconds)`.
## Configurazione & Modelli
- Modelli (default): `gemini-2.0-flash` per Team, Team Leader, Query Analyzer, Report Generator.
- Strategie: es. `Conservative` (descrizione testuale). Selezionabili da UI.
- `configs.yaml` e variabili env determinano modelli, porta server (`AppConfig.port`) e opzioni sharing Gradio.
## Variabili dAmbiente (usate dai wrappers)
- `TELEGRAM_BOT_TOKEN` — Bot Telegram.
- `COINBASE_API_KEY`, `COINBASE_API_SECRET` — Coinbase Advanced Trade.
- `CRYPTOCOMPARE_API_KEY` — CryptoCompare.
- `NEWS_API_KEY` — NewsAPI.
- `CRYPTOPANIC_API_KEY` (+ opzionale `CRYPTOPANIC_API_PLAN`) — CryptoPanic.
- `REDDIT_API_CLIENT_ID`, `REDDIT_API_CLIENT_SECRET` — Reddit (PRAW).
- `X_API_KEY` — rettiwt API key (CLI richiesto).
## Note di Implementazione
- I wrappers sono prevalentemente sincroni; la Pipeline usa esecuzione asincrona per il workflow (`interact_async`), con stream di eventi dai `agno.workflow` steps.
- Il Team Leader segue prompt comportamentale: ciclo di pianificazione/esecuzione/aggiornamento task con `PlanMemoryTool`.
- Loutput Telegram allega un PDF generato da `markdown_pdf`. La UI Gradio restituisce testo formattato.
## Test & Copertura (repo)
- Test unitari/integrati in `tests/` per wrappers (Market/News/Social), tools e handler.
- Esecuzione consigliata: `pytest -q` con variabili dambiente correttamente impostate (alcuni test richiedono API keys).

View File

@@ -1,51 +0,0 @@
# Report Obsolescenza Documenti (docs/)
Valutazione dei documenti esistenti rispetto allo stato attuale del codice.
## Valutazione Documenti
- `App_Architecture_Diagrams.md`
- Stato: parzialmente aggiornato.
- Criticità: contiene sezioni su "Signers Architecture" (src/app/signers/…) che non esistono nel repo attuale; riferimenti a auto-detection provider non presenti esplicitamente nei wrappers (lattuale gestione usa `WrapperHandler` e assert su env). Alcuni numeri/esempi sono illustrativi.
- Azioni: mantenere i diagrammi generali; rimuovere/aggiornare la sezione Signers; allineare provider e flusso al workflow `Query Check → Info Recovery → Report Generation`.
- `Async_Implementation_Detail.md`
- Stato: aspirazionale/roadmap tecnica.
- Criticità: la Pipeline è già asincrona per il workflow (`interact_async`), ma i singoli wrappers sono sincroni; il documento descrive dettagli di async su MarketAgent che non esiste come classe separata, e prevede parallelizzazione sui provider non implementata nei wrappers.
- Azioni: mantenere come proposta di miglioramento; etichettare come "future work"; evitare di confondere con stato attuale.
- `Market_Data_Implementation_Plan.md`
- Stato: piano di lavoro (utile).
- Criticità: parla di Binance mock/signers; nel codice attuale esiste `BinanceWrapper` reale (autenticato) e non ci sono signers; la sezione aggregazione JSON è coerente come obiettivo ma non implementata nativamente dai tools (aggregazione base è gestita da `WrapperHandler.try_call_all`).
- Azioni: aggiornare riferimenti a `BinanceWrapper` reale; chiarire che laggregazione avanzata è un obiettivo; mantenere come guida.
- `Piano di Sviluppo.md`
- Stato: generico e parzialmente disallineato.
- Criticità: fa riferimento a stack (LangChain/LlamaIndex) non presente; ruoli degli agenti con naming differente; database/persistenza non esiste nel codice.
- Azioni: etichettare come documento legacy; mantenerlo solo se serve come ispirazione; altrimenti spostarlo in `docs/legacy/`.
- `Progetto Esame.md`
- Stato: descrizione obiettivo.
- Criticità: allineata come visione; non problematica.
- Azioni: mantenere.
## Raccomandazioni
- Aggiornare `App_Architecture_Diagrams.md` rimuovendo la sezione "Signers Architecture" e allineando i diagrammi al workflow reale (`agents/pipeline.py`).
- Aggiungere `Current_Architecture.md` (presente) come riferimento principale per lo stato attuale.
- Spostare `Piano di Sviluppo.md` in `docs/legacy/` o eliminarlo se non utile.
- Annotare `Async_Implementation_Detail.md` e `Market_Data_Implementation_Plan.md` come "proposals"/"future work".
## Elenco Documenti Obsoleti o Parzialmente Obsoleti
- Parzialmente Obsoleti:
- `App_Architecture_Diagrams.md` (sezione Signers, parti di provider detection)
- `Async_Implementation_Detail.md` (dettagli Async MarketAgent non implementati)
- `Market_Data_Implementation_Plan.md` (Binance mock/signers)
- Legacy/Non allineato:
- `Piano di Sviluppo.md` (stack e ruoli non corrispondenti al codice)
## Nota
Queste raccomandazioni non rimuovono immediatamente file: il mantenimento storico può essere utile. Se desideri, posso eseguire ora lo spostamento in `docs/legacy/` o la cancellazione mirata dei documenti non necessari.

View File

@@ -1,80 +0,0 @@
# Diagrammi di Flusso e Sequenza (Sintesi)
Documentazione breve con blocchi testuali e mermaid per flussi principali.
## Flusso Gradio Chat
```mermaid
flowchart LR
U[User] --> CH(ChatInterface)
CH --> RESP[gradio_respond]
RESP --> PL(Pipeline.interact)
PL --> WF(Workflow run)
WF --> OUT(Report)
CH --> HIST[history update]
```
## Flusso Telegram Bot
```
/start
├─> CONFIGS state
│ ├─ Model Team ↔ choose_team(index)
│ ├─ Model Output ↔ choose_team_leader(index)
│ └─ Strategy ↔ choose_strategy(index)
└─> Text message → __start_team
└─ run team → Pipeline.interact_async
├─ build_workflow
├─ stream events (Query Check → Gate → Info Recovery → Report)
└─ send PDF (markdown_pdf)
```
## Pipeline Steps (Workflow)
```mermaid
flowchart TD
A[QueryInputs] --> B[Query Check Agent]
B -->|is_crypto true| C[Team Info Recovery]
B -->|is_crypto false| STOP((Stop))
C --> D[Report Generation Agent]
D --> OUT[Markdown Report]
```
## Team Leader Loop (PlanMemoryTool)
```
Initialize Plan with tasks
Loop until no pending tasks:
- Get next pending task
- Dispatch to specific Agent (Market/News/Social)
- Update task status (completed/failed)
- If failed & scope comprehensive → add retry task
After loop:
- List all tasks & results
- Synthesize final report
```
## Tools Aggregazione
```mermaid
flowchart LR
TL[Team Leader] --> MT[MarketAPIsTool]
TL --> NT[NewsAPIsTool]
TL --> ST[SocialAPIsTool]
MT --> WH(WrapperHandler)
NT --> WH
ST --> WH
WH --> W1[Binance]
WH --> W2[Coinbase]
WH --> W3[CryptoCompare]
WH --> W4[YFinance]
WH --> N1[NewsAPI]
WH --> N2[GoogleNews]
WH --> N3[CryptoPanic]
WH --> N4[DuckDuckGo]
WH --> S1[Reddit]
WH --> S2[X]
WH --> S3[4chan]
```

View File

@@ -1,12 +1,12 @@
**ROLE:** You are the Crypto Analysis Team Leader, coordinating a team of specialized agents to deliver comprehensive cryptocurrency reports.
You have the permission to act as a consultant.
**CONTEXT:** Current date is {{CURRENT\_DATE}}.
**CONTEXT:** Current date is {{CURRENT_DATE}}.
You orchestrate data retrieval and synthesis using a tool-driven execution plan.
**CRITICAL DATA PRINCIPLES:**
1. **Real-time Data Priority**: Your agents fetch LIVE data from APIs (prices, news, social posts)
2. **Timestamps Matter**: All data your agents provide is current (as of {{CURRENT\_DATE}})
2. **Timestamps Matter**: All data your agents provide is current (as of {{CURRENT_DATE}})
3. **Never Override Fresh Data**: If an agent returns data with today's timestamp, that data is authoritative
4. **No Pre-trained Knowledge for Data**: Don't use model knowledge for prices, dates, or current events
5. **Data Freshness Tracking**: Track and report the recency of all retrieved data
@@ -18,17 +18,11 @@ You orchestrate data retrieval and synthesis using a tool-driven execution plan.
- **NewsAgent**: Live news articles with sentiment analysis (NewsAPI, GoogleNews, CryptoPanic)
- **SocialAgent**: Current social media discussions (Reddit, X, 4chan)
**YOUR PERSONAL TOOLS (FOR PLANNING, SYNTHESIS & UTILITIES):**
*The framework will provide you with the exact functions for these tools. Your job is to use them according to these strategies.*
- **Planning & State (`PlanMemoryTool`)**:
This is your stateful memory. You MUST use it to build your plan (`add_tasks`) *before* delegating, execute the plan step-by-step (`get_next_pending_task`), and record all outcomes (`update_task_status`).
- **Cognition & Synthesis (`ReasoningTools`)**:
You MUST use this tool to reflect on the data gathered from your team and to synthesize the `Analysis` sections of your final report.
- **Data Utilities (`CryptoSymbolsTools`)**:
You MUST use this tool to find the correct ticker (e.g., "BTC-USD") when the user asks for a name (e.g., "Bitcoin"). Do this *before* you create a task for the `MarketAgent`.
**YOUR PERSONAL TOOLS (FOR PLANNING & SYNTHESIS):**
- **PlanMemoryTool**: MUST be used to manage your execution plan. You will use its functions (`add_tasks`, `get_next_pending_task`, `update_task_status`, `list_all_tasks`) to track all agent operations. This is your stateful memory.
- **ReasoningTools**: MUST be used for cognitive tasks like synthesizing data from multiple agents, reflecting on the plan's success, or deciding on retry strategies before writing your final analysis.
- **think(title, thought, action, confidence)**: Use this to reason through problems step-by-step before making decisions. Example: `think(title="Analyze BTC data quality", thought="Market data shows BTC at $45000 from Binance, news is 2h old", action="Proceed to synthesis", confidence=0.9)`
- **analyze(title, result, analysis, next_action, confidence)**: Use this to evaluate results and determine next steps. Example: `analyze(title="Market data evaluation", result="Received complete price data", analysis="Data is fresh and comprehensive", next_action="continue", confidence=0.95)`
**AGENT OUTPUT SCHEMAS (MANDATORY REFERENCE):**
You MUST parse the exact structures your agents provide:
@@ -239,7 +233,7 @@ Timestamp: Report generated at {{CURRENT_DATE}}
**CRITICAL REMINDERS:**
1. Data from agents is ALWAYS current (today is {{CURRENT\_DATE}})
1. Data from agents is ALWAYS current (today is {{CURRENT_DATE}})
2. Include timestamps and sources for EVERY data section
3. If no data for a section, OMIT it entirely (don't write "No data available")
4. Track and report data freshness explicitly

View File

@@ -75,19 +75,30 @@ class ChatManager:
with gr.Blocks() as interface:
gr.Markdown("# 🤖 Agente di Analisi e Consulenza Crypto (Chat)")
# --- Prepara le etichette di default per i dropdown
model_labels = self.inputs.list_models_names()
default_model_label = self.inputs.team_leader_model.label
if default_model_label not in model_labels:
default_model_label = model_labels[0] if model_labels else None
strategy_labels = self.inputs.list_strategies_names()
default_strategy_label = self.inputs.strategy.label
if default_strategy_label not in strategy_labels:
default_strategy_label = strategy_labels[0] if strategy_labels else None
# Dropdown provider e stile
with gr.Row():
provider = gr.Dropdown(
choices=self.inputs.list_models_names(),
value=self.inputs.team_leader_model.label,
choices=model_labels,
value=default_model_label,
type="index",
label="Modello da usare"
)
provider.change(fn=self.inputs.choose_team_leader, inputs=provider, outputs=None)
style = gr.Dropdown(
choices=self.inputs.list_strategies_names(),
value=self.inputs.strategy.label,
choices=strategy_labels,
value=default_strategy_label,
type="index",
label="Stile di investimento"
)